text
stringlengths 54
60.6k
|
---|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, 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 Image Engine Design 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>
#include "IECore/MeshPrimitiveShrinkWrapOp.h"
#include "IECore/Parameter.h"
#include "IECore/Object.h"
#include "IECore/CompoundObject.h"
#include "IECore/bindings/IntrusivePtrPatch.h"
#include "IECore/bindings/WrapperToPython.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/MeshPrimitiveShrinkWrapOpBinding.h"
using namespace boost;
using namespace boost::python;
namespace IECore
{
void bindMeshPrimitiveShrinkWrapOp()
{
typedef class_< MeshPrimitiveShrinkWrapOp, MeshPrimitiveShrinkWrapOpPtr, boost::noncopyable, bases<MeshPrimitiveOp> > MeshPrimitiveShrinkWrapOpPyClass;
MeshPrimitiveShrinkWrapOpPyClass( "MeshPrimitiveShrinkWrapOp", no_init )
.def( init< >() )
.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( MeshPrimitiveShrinkWrapOp )
;
INTRUSIVE_PTR_PATCH( MeshPrimitiveShrinkWrapOp, MeshPrimitiveShrinkWrapOpPyClass );
implicitly_convertible<MeshPrimitiveShrinkWrapOpPtr, MeshPrimitiveOpPtr>();
}
} // namespace IECore
<commit_msg>Bound enum<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, 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 Image Engine Design 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>
#include "IECore/MeshPrimitiveShrinkWrapOp.h"
#include "IECore/Parameter.h"
#include "IECore/Object.h"
#include "IECore/CompoundObject.h"
#include "IECore/bindings/IntrusivePtrPatch.h"
#include "IECore/bindings/WrapperToPython.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/MeshPrimitiveShrinkWrapOpBinding.h"
using namespace boost;
using namespace boost::python;
namespace IECore
{
void bindMeshPrimitiveShrinkWrapOp()
{
typedef class_< MeshPrimitiveShrinkWrapOp, MeshPrimitiveShrinkWrapOpPtr, boost::noncopyable, bases<MeshPrimitiveOp> > MeshPrimitiveShrinkWrapOpPyClass;
scope opScope = MeshPrimitiveShrinkWrapOpPyClass( "MeshPrimitiveShrinkWrapOp", no_init )
.def( init< >() )
.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( MeshPrimitiveShrinkWrapOp )
;
enum_< MeshPrimitiveShrinkWrapOp::Method >( "Method" )
.value( "Both", MeshPrimitiveShrinkWrapOp::Both )
.value( "Inside", MeshPrimitiveShrinkWrapOp::Inside )
.value( "Outside", MeshPrimitiveShrinkWrapOp::Outside )
;
INTRUSIVE_PTR_PATCH( MeshPrimitiveShrinkWrapOp, MeshPrimitiveShrinkWrapOpPyClass );
implicitly_convertible<MeshPrimitiveShrinkWrapOpPtr, MeshPrimitiveOpPtr>();
}
} // namespace IECore
<|endoftext|> |
<commit_before>#ifndef MATH_HPP
#define MATH_HPP
#include <algorithm>
#include <cmath>
#include <math.h>
#define PI 3.14159265358979323846f
#define TAU 6.28318530717958647692f
#define KAPPA90 0.5522847493f
// KAPPA90 = (4/3 * (sqrt(2) - 1))
// https://de.wikipedia.org/wiki/Datei:Circle-cbezier-method2.svg
#define OE_FLOAT_INFINITY std::numeric_limits<float>::infinity()
#define ARRAY_COUNT(arr) (sizeof(arr) / sizeof(0[arr]))
namespace OrbitEngine { namespace Math {
inline double deg2rad(double deg)
{
return deg * PI / 180.f;
}
inline double rad2deg(double rad)
{
return rad * 180.f / PI;
}
inline unsigned int nextPowerOfTwo(unsigned int x)
{
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
}
template<typename T>
inline T approximatelyEqual(T a, T b, T epsilon)
{
return std::abs(a - b) <= ((std::abs(a) < std::abs(b) ? std::abs(b) : std::abs(a)) * epsilon);
}
template<typename T>
inline T lerp(T v0, T v1, float t) {
return (1.f - t) * v0 + t * v1;
}
template<typename T>
inline T clamp(T input, T min_, T max_) {
return (std::max)(min_, (std::min)(input, max_));
}
template<typename T>
inline T sign(T input)
{
return input >= (T)0 ? (T)1 : (T)-1;
};
template<typename A, typename B>
A castMinMax(B in)
{
// only integer types
A retVal = 0;
if (in > 0)
retVal = static_cast<A>(in & std::numeric_limits<A>::max());
else if (in < 0)
retVal = static_cast<A>(in | std::numeric_limits<A>::min());
return retVal;
}
} }
#endif<commit_msg>isPowerOfTwo<commit_after>#ifndef MATH_HPP
#define MATH_HPP
#include <algorithm>
#include <cmath>
#include <math.h>
#define PI 3.14159265358979323846f
#define TAU 6.28318530717958647692f
#define KAPPA90 0.5522847493f
// KAPPA90 = (4/3 * (sqrt(2) - 1))
// https://de.wikipedia.org/wiki/Datei:Circle-cbezier-method2.svg
#define OE_FLOAT_INFINITY std::numeric_limits<float>::infinity()
#define ARRAY_COUNT(arr) (sizeof(arr) / sizeof(0[arr]))
namespace OrbitEngine { namespace Math {
inline double deg2rad(double deg)
{
return deg * PI / 180.f;
}
inline double rad2deg(double rad)
{
return rad * 180.f / PI;
}
inline unsigned int nextPowerOfTwo(unsigned int x)
{
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
}
inline bool isPowerOfTwo(unsigned int x) {
return x == 0 || (x & (x - 1)) == 0;
}
template<typename T>
inline T approximatelyEqual(T a, T b, T epsilon)
{
return std::abs(a - b) <= ((std::abs(a) < std::abs(b) ? std::abs(b) : std::abs(a)) * epsilon);
}
template<typename T>
inline T lerp(T v0, T v1, float t) {
return (1.f - t) * v0 + t * v1;
}
template<typename T>
inline T clamp(T input, T min_, T max_) {
return (std::max)(min_, (std::min)(input, max_));
}
template<typename T>
inline T sign(T input)
{
return input >= (T)0 ? (T)1 : (T)-1;
};
template<typename A, typename B>
A castMinMax(B in)
{
// only integer types
A retVal = 0;
if (in > 0)
retVal = static_cast<A>(in & std::numeric_limits<A>::max());
else if (in < 0)
retVal = static_cast<A>(in | std::numeric_limits<A>::min());
return retVal;
}
} }
#endif<|endoftext|> |
<commit_before>#include <sstream>
#include <pwd.h>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <string>
#include <errno.h>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <time.h>
#include <stdlib.h>
#include <fcntl.h>
using namespace std;
//PRINTING OUT VECTOR OF FILES
void print_files(vector<string>& x) {
unsigned z = 0;
for(unsigned i = 0; i < x.size(); ++i) {
if(z == 5)
cout << endl;
cout << setw(16) << left << x.at(i) << " ";
++z;
}
cout << endl;
return;
}
void print_l(vector<string>& x) {
struct stat club;
int intake;
string cow;
string now;
ssize_t g = 0;
for(unsigned i = 0; i < x.size(); ++i) {
now = x[i];
// int fd = open(now.c_str(), O_RDONLY);
// if(fd == -1)
// {
// perror("open");
// exit(1);
// }
if(stat(now.c_str(), &club) == -1) {
perror("stat");
exit(1);
}
g += club.st_size;
// int fo = close(fd);
// if(fo == -1)
// {
// perror("close");
// exit(1);
// }
}
cout << "total " << g << endl;
for(unsigned e = 0; e < x.size(); ++e) {
cow = x[e];
// int fd = open(now.c_str(), O_RDONLY);
// if(fd == -1)
// {
// perror("open");
// exit(1);
// }
if(stat(cow.c_str(), &club) == -1) {
perror("stat");
exit(-1);
}
if(S_ISDIR(club.st_mode))
cout << "d";
else
cout << "-";
if((intake = access(cow.c_str(), R_OK)) == 0)
cout << "r";
else
cout << "-";
if((intake = access(cow.c_str(), W_OK)) == 0)
cout << "w";
else
cout << "-";
if((intake = access(cow.c_str(), X_OK)) == 0)
cout << "x";
else
cout << "-";
cout << "------" << " ";
cout << club.st_nlink << " ";
cout << club.st_uid << " ";
cout << club.st_gid << " ";
cout << setw(5) << club.st_size << " ";
cout << setw(5) << club.st_mtime << "sec ";
cout << left << setw(0) << x[e] << endl;
// int fo = close(fd);
// if(fo == -1)
// {
// perror("close");
// exit(1);
// }
}
return;
}
//-a
void alphabetize2(vector<string>& x) {
unsigned i;
vector<string> ad;
vector<string> qw;
unsigned j;
unsigned k;
for(i = 0; i < x.size(); i++)
{
if(x[i][0] >= 65 && x[i][0] <= 90){
x[i][0] += 32;
qw.push_back(x[i]);
}
if(x[i][0] == '.' && x[i][1] != '.'){
x[i].erase(0,1);
ad.push_back(x[i]);
}
}
sort(x.begin(), x.end());
for(i = 0; i < x.size(); i++)
{
for(j = 0; j < qw.size(); j++)
{
if(qw[j] == x[i])
x[i][0] -= 32;
}
for(k = 0; k < ad.size(); k++)
{
if(ad[k] == x[i])
x[i].insert(0, ".");
}
}
}
//default alphabetize
void alphabetize(vector<string>& x) {
unsigned i;
vector<string> qw;
unsigned j;
for(i = 0; i < x.size(); i++)
{
if(x[i][0] >= 65 && x[i][0] <= 90){
x[i][0] += 32;
qw.push_back(x[i]);
}
}
sort(x.begin(), x.end());
for(i = 0; i < x.size(); i++)
{
for(j = 0; j < qw.size(); j++)
{
if(qw[j] == x[i])
x[i][0] -= 32;
}
}
}
//default
static void lookup()//ls (no flags)
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(".")) == NULL)
{
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
x = entry->d_name;
if(x[0] == '.')
continue;
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize(temp);
print_files(temp);
if(errno != 0)
perror("error reading directory");
closedir(start);
return;
}
//-a
static void lookup2()
{
vector<string> temp;
DIR *start;
struct dirent *entry;
if((start=opendir(".")) == NULL) {
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL) {
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize2(temp);
print_files(temp);
if(errno != 0)
perror("error reading directory");
closedir(start);
return;
}
//-la
static void lookup31()
{
vector<string> temp;
DIR *start;
struct dirent *entry;
if((start=opendir(".")) == NULL)
{
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize(temp);
print_l(temp);
if(errno != 0)
perror("error reading directory");
closedir(start);
return;
}
//-l
static void lookup3()
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(".")) == NULL)
{
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
x = entry->d_name;
if(x[0] == '.')
continue;
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize(temp);
print_l(temp);
if(errno != 0){
perror("error reading directory");
}
closedir(start);
return;
}
static void lookup_d1(char* q)
{
vector<string> temp;
DIR *start;
struct dirent *entry;
if((start=opendir(q)) == NULL)
{
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize(temp);
print_files(temp);
if(errno != 0)
perror("error reading directory");
closedir(start);
return;
}
//-lR
static void dlookup_d(char* q)
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(q)) == NULL)
{
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
x = entry->d_name;
if(x[0] == '.')
continue;
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize(temp);
print_l(temp);
if(errno != 0)
perror("error reading directory");
closedir(start);
return;
}
//ls (passed in directory
static void lookup_d(char* q)
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(q)) == NULL)
{
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
x = entry->d_name;
if(x[0] == '.')
continue;
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize(temp);
print_files(temp);
if(errno != 0)
perror("error reading directory");
closedir(start);
return;
}
//-Ra
static void lookup41()
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(".")) == NULL)
{
perror("opendir");
closedir(start);
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
if(entry->d_type == DT_DIR)
{
x = entry->d_name;
if(x[0] == '.' && x[1] == '.')
continue;
cout << x << ":" << endl;
lookup_d1(x);
}
}
} while(entry != NULL);
if(errno != 0)
{
perror("error reading directory");
closedir(start);
return;
}
closedir(start);
return;
}
//-R
static void lookup4()
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(".")) == NULL)
{
perror("opendir");
closedir(start);
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
if(entry->d_type == DT_DIR)
{
x = entry->d_name;
if(x[0] == '.' && x[1] == '.')
continue;
cout << x << ":" << endl;
lookup_d(x);
}
}
} while(entry != NULL);
if(errno != 0)
{
perror("error reading directory");
closedir(start);
return;
}
closedir(start);
return;
}
//-Rl
static void lookup42()
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(".")) == NULL)
{
perror("opendir");
closedir(start);
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
if(entry->d_type == DT_DIR)
{
x = entry->d_name;
if(x[0] == '.' && x[1] == '.')
continue;
cout << x << ":" << endl;
dlookup_d(x);
}
}
} while(entry != NULL);
if(errno != 0)
{
perror("error reading directory");
closedir(start);
return;
}
closedir(start);
return;
}
int main( int argc, char *argv[]) {
string flag = "-a";
string flag2 = "-l";
string flag3 = "-R";
stringstream d;
if(argc == 1)
{
lookup();
return 0;
}
//for(int k = 0; k < argc; ++k)
// d << argv[k] << " ";
int i = 1;
for(; i < argc; ++i) {
if(argv[i][0] != '-'){
lookup_d(argv[i]);
break;
}
else if(argv[i] == flag) {
if(argc >= 3) {
if(argv[2] == flag2)
lookup31();
else if(argv[2] == flag3)
lookup41();
}
else
lookup2();
}
else if(argv[i] == flag2) {
if(argc >= 3) {
if(argv[2] == flag)
lookup31();
else if(argv[2] == flag3)
lookup42();
}
else
lookup3();
}
else if(argv[i] == flag3){
if(argc >= 3) {
if(argv[2] == flag)
lookup41();
else if(argv[2] == flag2)
lookup42();
}
else
lookup4();
}
else if(strstr(argv[i], "a") != NULL)
{
if(strstr(argv[i], "l") != NULL)
lookup31();
if(strstr(argv[i], "R") != NULL)
lookup41();
}
else if(strstr(argv[i], "l") != NULL)
{
if(strstr(argv[i], "R") != NULL)
lookup42();
}
}
return 0;
}
<commit_msg>ls.cpp added<commit_after>#include <sstream>
#include <pwd.h>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <string>
#include <errno.h>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <time.h>
#include <stdlib.h>
#include <fcntl.h>
using namespace std;
//PRINTING OUT VECTOR OF FILES
void print_files(vector<string>& x) {
unsigned z = 0;
for(unsigned i = 0; i < x.size(); ++i) {
if(z == 5)
cout << endl;
cout << setw(16) << left << x.at(i) << " ";
++z;
}
cout << endl;
return;
}
void print_l(vector<string>& x) {
struct stat club;
int intake;
string cow;
string now;
ssize_t g = 0;
for(unsigned i = 0; i < x.size(); ++i) {
now = x[i];
// int fd = open(now.c_str(), O_RDONLY);
// if(fd == -1)
// {
// perror("open");
// exit(1);
// }
if(stat(now.c_str(), &club) == -1) {
perror("stat");
exit(1);
}
g += club.st_size;
// int fo = close(fd);
// if(fo == -1)
// {
// perror("close");
// exit(1);
// }
}
cout << "total " << g << endl;
for(unsigned e = 0; e < x.size(); ++e) {
cow = x[e];
// int fd = open(now.c_str(), O_RDONLY);
// if(fd == -1)
// {
// perror("open");
// exit(1);
// }
if(stat(cow.c_str(), &club) == -1) {
perror("stat");
exit(-1);
}
if(S_ISDIR(club.st_mode))
cout << "d";
else
cout << "-";
if((intake = access(cow.c_str(), R_OK)) == 0)
cout << "r";
else
cout << "-";
if((intake = access(cow.c_str(), W_OK)) == 0)
cout << "w";
else
cout << "-";
if((intake = access(cow.c_str(), X_OK)) == 0)
cout << "x";
else
cout << "-";
cout << "------" << " ";
cout << club.st_nlink << " ";
cout << club.st_uid << " ";
cout << club.st_gid << " ";
cout << setw(5) << club.st_size << " ";
cout << setw(5) << club.st_mtime << "sec ";
cout << left << setw(0) << x[e] << endl;
// int fo = close(fd);
// if(fo == -1)
// {
// perror("close");
// exit(1);
// }
}
return;
}
//-a
void alphabetize2(vector<string>& x) {
unsigned i;
vector<string> ad;
vector<string> qw;
unsigned j;
unsigned k;
for(i = 0; i < x.size(); i++)
{
if(x[i][0] >= 65 && x[i][0] <= 90){
x[i][0] += 32;
qw.push_back(x[i]);
}
if(x[i][0] == '.' && x[i][1] != '.'){
x[i].erase(0,1);
ad.push_back(x[i]);
}
}
sort(x.begin(), x.end());
for(i = 0; i < x.size(); i++)
{
for(j = 0; j < qw.size(); j++)
{
if(qw[j] == x[i])
x[i][0] -= 32;
}
for(k = 0; k < ad.size(); k++)
{
if(ad[k] == x[i])
x[i].insert(0, ".");
}
}
}
//default alphabetize
void alphabetize(vector<string>& x) {
unsigned i;
vector<string> qw;
unsigned j;
for(i = 0; i < x.size(); i++)
{
if(x[i][0] >= 65 && x[i][0] <= 90){
x[i][0] += 32;
qw.push_back(x[i]);
}
}
sort(x.begin(), x.end());
for(i = 0; i < x.size(); i++)
{
for(j = 0; j < qw.size(); j++)
{
if(qw[j] == x[i])
x[i][0] -= 32;
}
}
}
//default
static void lookup()//ls (no flags)
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(".")) == NULL)
{
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
x = entry->d_name;
if(x[0] == '.')
continue;
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize(temp);
print_files(temp);
if(errno != 0)
perror("error reading directory");
closedir(start);
return;
}
//-a
static void lookup2()
{
vector<string> temp;
DIR *start;
struct dirent *entry;
if((start=opendir(".")) == NULL) {
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL) {
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize2(temp);
print_files(temp);
if(errno != 0)
perror("error reading directory");
closedir(start);
return;
}
//-la
static void lookup31()
{
vector<string> temp;
DIR *start;
struct dirent *entry;
if((start=opendir(".")) == NULL)
{
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize(temp);
print_l(temp);
if(errno != 0)
perror("error reading directory");
closedir(start);
return;
}
//-l
static void lookup3()
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(".")) == NULL)
{
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
x = entry->d_name;
if(x[0] == '.')
continue;
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize(temp);
print_l(temp);
if(errno != 0){
perror("error reading directory");
}
closedir(start);
return;
}
static void lookup_d1(char* q)
{
vector<string> temp;
DIR *start;
struct dirent *entry;
if((start=opendir(q)) == NULL)
{
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize(temp);
print_files(temp);
if(errno != 0)
perror("error reading directory");
closedir(start);
return;
}
//-lR
static void dlookup_d(char* q)
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(q)) == NULL)
{
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
x = entry->d_name;
if(x[0] == '.')
continue;
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize(temp);
print_l(temp);
if(errno != 0)
perror("error reading directory");
closedir(start);
return;
}
//ls (passed in directory
static void lookup_d(char* q)
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(q)) == NULL)
{
perror("opendir");
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
x = entry->d_name;
if(x[0] == '.')
continue;
temp.push_back(entry->d_name);
}
} while(entry != NULL);
alphabetize(temp);
print_files(temp);
if(errno != 0)
perror("error reading directory");
closedir(start);
return;
}
//-Ra
static void lookup41()
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(".")) == NULL)
{
perror("opendir");
closedir(start);
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
if(entry->d_type == DT_DIR)
{
x = entry->d_name;
if(x[0] == '.' && x[1] == '.')
continue;
cout << x << ":" << endl;
lookup_d1(x);
}
}
} while(entry != NULL);
if(errno != 0)
{
perror("error reading directory");
closedir(start);
return;
}
closedir(start);
return;
}
//-R
static void lookup4()
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(".")) == NULL)
{
perror("opendir");
closedir(start);
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
if(entry->d_type == DT_DIR)
{
x = entry->d_name;
if(x[0] == '.' && x[1] == '.')
continue;
cout << x << ":" << endl;
lookup_d(x);
}
}
} while(entry != NULL);
if(errno != 0)
{
perror("error reading directory");
closedir(start);
return;
}
closedir(start);
return;
}
//-Rl
static void lookup42()
{
vector<string> temp;
DIR *start;
struct dirent *entry;
char* x;
if((start=opendir(".")) == NULL)
{
perror("opendir");
closedir(start);
return;
}
do {
errno = 0;
if((entry = readdir(start)) != NULL)
{
if(entry->d_type == DT_DIR)
{
x = entry->d_name;
if(x[0] == '.' && x[1] == '.')
continue;
cout << x << ":" << endl;
dlookup_d(x);
}
}
} while(entry != NULL);
if(errno != 0)
{
perror("error reading directory");
closedir(start);
return;
}
closedir(start);
return;
}
int main( int argc, char *argv[]) {
string flag = "-a";
string flag2 = "-l";
string flag3 = "-R";
if(argc == 1)
{
lookup();
return 0;
}
int i = 1;
for(; i < argc; ++i) {
if(argv[i][0] != '-'){
lookup_d(argv[i]);
}
else if(argv[i] == flag) {
if(argc >= 3) {
if(argv[2] == flag2)
lookup31();
else if(argv[2] == flag3)
lookup41();
}
else
lookup2();
}
else if(argv[i] == flag2) {
if(argc >= 3) {
if(argv[2] == flag)
lookup31();
else if(argv[2] == flag3)
lookup42();
}
else
lookup3();
}
else if(argv[i] == flag3){
if(argc >= 3) {
if(argv[2] == flag)
lookup41();
else if(argv[2] == flag2)
lookup42();
}
else
lookup4();
}
else if(strstr(argv[i], "a") != NULL)
{
if(strstr(argv[i], "l") != NULL)
lookup31();
if(strstr(argv[i], "R") != NULL)
lookup41();
}
else if(strstr(argv[i], "l") != NULL)
{
if(strstr(argv[i], "R") != NULL)
lookup42();
}
}
return 0;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2018 The nanoFramework project contributors
// Portions Copyright (c) 2006-2015, ARM Limited, All Rights Reserved
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include <ssl.h>
#include "mbedtls.h"
int ssl_connect_internal(int sd, const char* szTargetHost, int sslContextHandle)
{
mbedTLS_NFContext* context;
int ret = -1;
// Retrieve SSL struct from g_SSL_Driver
if((sslContextHandle >= (int)ARRAYSIZE(g_SSL_Driver.m_sslContextArray)) || (sslContextHandle < 0))
{
goto error;
}
// sd should already have been created
// Now do the SSL negotiation
context = (mbedTLS_NFContext*)g_SSL_Driver.m_sslContextArray[sslContextHandle].SslContext;
if (context == NULL) goto error;
// set socket
context->server_fd->fd = sd;
if(szTargetHost != NULL && szTargetHost[0] != 0)
{
if( (ret = mbedtls_ssl_set_hostname( context->ssl, szTargetHost )) != 0 )
{
// hostname_failed
goto error;
}
}
mbedtls_ssl_set_bio( context->ssl, context->server_fd, mbedtls_net_send, mbedtls_net_recv, mbedtls_net_recv_timeout );
while( ( ret = mbedtls_ssl_handshake( context->ssl ) ) != 0 )
{
if( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE )
{
// SSL handshake failed
//mbedtls_printf( " failed\n ! mbedtls_ssl_handshake returned -0x%x\n\n", -ret );
goto error;
}
}
SOCKET_DRIVER.SetSocketSslData(sd, (void*)context);
error:
return ret;
}
<commit_msg>Improve comments<commit_after>//
// Copyright (c) 2018 The nanoFramework project contributors
// Portions Copyright (c) 2006-2015, ARM Limited, All Rights Reserved
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include <ssl.h>
#include "mbedtls.h"
int ssl_connect_internal(int sd, const char* szTargetHost, int sslContextHandle)
{
mbedTLS_NFContext* context;
int ret = -1;
// Retrieve SSL struct from g_SSL_Driver
if((sslContextHandle >= (int)ARRAYSIZE(g_SSL_Driver.m_sslContextArray)) || (sslContextHandle < 0))
{
goto error;
}
// sd should already have been created
// Now do the SSL negotiation
context = (mbedTLS_NFContext*)g_SSL_Driver.m_sslContextArray[sslContextHandle].SslContext;
if (context == NULL) goto error;
// set socket in network context
context->server_fd->fd = sd;
if(szTargetHost != NULL && szTargetHost[0] != 0)
{
if( (ret = mbedtls_ssl_set_hostname( context->ssl, szTargetHost )) != 0 )
{
// hostname_failed
goto error;
}
}
// setup internal SSL context and calls to transport layer send, receive and receive with timeout
mbedtls_ssl_set_bio( context->ssl, context->server_fd, mbedtls_net_send, mbedtls_net_recv, mbedtls_net_recv_timeout );
// perform SSL handshake
while( ( ret = mbedtls_ssl_handshake( context->ssl ) ) != 0 )
{
if( ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE )
{
// SSL handshake failed
//mbedtls_printf( " failed\n ! mbedtls_ssl_handshake returned -0x%x\n\n", -ret );
goto error;
}
}
// store SSL context in sockets driver
SOCKET_DRIVER.SetSocketSslData(sd, (void*)context);
error:
return ret;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/memory_size.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file memory_size.C
/// @brief Return the effective memory size behind a target
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#include <fapi2.H>
#include <lib/mss_attribute_accessors.H>
#include <lib/shared/mss_const.H>
#include <lib/eff_config/memory_size.H>
#include <lib/utils/find.H>
namespace mss
{
///
/// @brief Return the total memory size behind an MCA
/// @param[in] i_target the MCA target
/// @param[out] o_size the size of memory in GB behind the target
/// @return FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode eff_memory_size( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, uint64_t& o_size )
{
// Don't try to get cute and read the attributes once and loop over the array.
// Cronus honors initToZero which would work, but HB might not and so we might get
// crap in some of the attributes (which we shouldn't access as there's no DIMM there)
uint32_t l_sizes = 0;
o_size = 0;
for (const auto& d : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(i_target))
{
FAPI_TRY( mss::eff_dimm_size(d, l_sizes) );
o_size += l_sizes;
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Return the total memory size behind an MBIST
/// @param[in] i_target the MCBIST target
/// @param[out] o_size the size of memory in GB behind the target
/// @return FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode eff_memory_size( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target, uint64_t& o_size )
{
o_size = 0;
for (const auto& p : mss::find_targets<fapi2::TARGET_TYPE_MCA>(i_target))
{
uint64_t l_size = 0;
FAPI_TRY( eff_memory_size(p, l_size) );
o_size += l_size;
}
fapi_try_exit:
return fapi2::current_err;
}
}
<commit_msg>Update mss_eff_config to L3<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/eff_config/memory_size.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file memory_size.C
/// @brief Return the effective memory size behind a target
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#include <fapi2.H>
#include <lib/mss_attribute_accessors.H>
#include <lib/shared/mss_const.H>
#include <lib/eff_config/memory_size.H>
#include <lib/utils/find.H>
namespace mss
{
///
/// @brief Return the total memory size behind an MCA
/// @param[in] i_target the MCA target
/// @param[out] o_size the size of memory in GB behind the target
/// @return FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode eff_memory_size( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, uint64_t& o_size )
{
// Don't try to get cute and read the attributes once and loop over the array.
// Cronus honors initToZero which would work, but HB might not and so we might get
// crap in some of the attributes (which we shouldn't access as there's no DIMM there)
uint32_t l_sizes = 0;
o_size = 0;
for (const auto& d : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(i_target))
{
FAPI_TRY( mss::eff_dimm_size(d, l_sizes) );
o_size += l_sizes;
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Return the total memory size behind an MBIST
/// @param[in] i_target the MCBIST target
/// @param[out] o_size the size of memory in GB behind the target
/// @return FAPI2_RC_SUCCESS if ok
///
template<>
fapi2::ReturnCode eff_memory_size( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target, uint64_t& o_size )
{
o_size = 0;
for (const auto& p : mss::find_targets<fapi2::TARGET_TYPE_MCA>(i_target))
{
uint64_t l_size = 0;
FAPI_TRY( eff_memory_size(p, l_size) );
o_size += l_size;
}
fapi_try_exit:
return fapi2::current_err;
}
}
<|endoftext|> |
<commit_before>// Copyright 2017 Global Phasing Ltd.
#include "gemmi/symmetry.hpp"
#include <stdio.h>
void print_symmetry_operations(const gemmi::GroupOps& ops) {
printf("%zu x %zu symmetry operations:\n",
ops.cen_ops.size(), ops.sym_ops.size());
for (const gemmi::Op& op : ops.all_ops_sorted())
printf(" %s\n", op.triplet().c_str());
}
void process_arg(const char* arg) {
const gemmi::SpaceGroup* sg = gemmi::find_spacegroup_by_name(arg);
if (sg == nullptr) {
try {
gemmi::GroupOps ops = gemmi::symops_from_hall(arg);
sg = gemmi::find_spacegroup_by_ops(ops);
if (sg == nullptr) {
printf("Hall symbol: %s\n", arg);
print_symmetry_operations(ops);
}
} catch (std::runtime_error&) {
}
}
if (sg == nullptr) {
fprintf(stderr, "Space group not found: %s\n", arg);
return;
}
printf("Number: %d\n", sg->number);
printf("CCP4 number: %d\n", sg->ccp4);
printf("Hermann–Mauguin: %s\n", sg->hm);
printf("extended H-M: %s\n", sg->xhm().c_str());
printf("Hall symbol: %s\n", sg->hall);
print_symmetry_operations(sg->operations());
printf("\n");
}
int main(int argc, char **argv) {
for (int i = 1; i < argc; ++i)
process_arg(argv[i]);
return 0;
}
// vim:sw=2:ts=2:et:path^=../include,../third_party
<commit_msg>gemmi-sg: don't sort operations<commit_after>// Copyright 2017 Global Phasing Ltd.
#include "gemmi/symmetry.hpp"
#include <stdio.h>
void print_symmetry_operations(const gemmi::GroupOps& ops) {
printf("%zu x %zu symmetry operations:\n",
ops.cen_ops.size(), ops.sym_ops.size());
for (const gemmi::Op& op : ops)
printf(" %s\n", op.triplet().c_str());
}
void process_arg(const char* arg) {
const gemmi::SpaceGroup* sg = gemmi::find_spacegroup_by_name(arg);
if (sg == nullptr) {
try {
gemmi::GroupOps ops = gemmi::symops_from_hall(arg);
sg = gemmi::find_spacegroup_by_ops(ops);
if (sg == nullptr) {
printf("Hall symbol: %s\n", arg);
print_symmetry_operations(ops);
}
} catch (std::runtime_error&) {
}
}
if (sg == nullptr) {
fprintf(stderr, "Space group not found: %s\n", arg);
return;
}
printf("Number: %d\n", sg->number);
printf("CCP4 number: %d\n", sg->ccp4);
printf("Hermann–Mauguin: %s\n", sg->hm);
printf("extended H-M: %s\n", sg->xhm().c_str());
printf("Hall symbol: %s\n", sg->hall);
print_symmetry_operations(sg->operations());
printf("\n");
}
int main(int argc, char **argv) {
for (int i = 1; i < argc; ++i)
process_arg(argv[i]);
return 0;
}
// vim:sw=2:ts=2:et:path^=../include,../third_party
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmlmodelview.h"
#include "qmlobjectnode.h"
#include "qmlitemnode.h"
#include "itemlibraryinfo.h"
#include "mathutils.h"
#include "invalididexception.h"
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <utils/fileutils.h>
#include "nodeabstractproperty.h"
#include "variantproperty.h"
#include "rewritingexception.h"
#include "rewriterview.h"
#include "plaintexteditmodifier.h"
#include "modelmerger.h"
#include "nodemetainfo.h"
#include <utils/qtcassert.h>
namespace QmlDesigner {
QmlModelView::QmlModelView(QObject *parent)
: AbstractView(parent)
{
}
void QmlModelView::setCurrentState(const QmlModelState &state)
{
if (!state.isValid())
return;
if (!model())
return;
if (actualStateNode() != state.modelNode())
setAcutalStateNode(state.modelNode());
}
QmlModelState QmlModelView::currentState() const
{
return QmlModelState(actualStateNode());
}
QmlModelState QmlModelView::baseState() const
{
return QmlModelState::createBaseState(this);
}
QmlModelStateGroup QmlModelView::rootStateGroup() const
{
return QmlModelStateGroup(rootModelNode());
}
QmlObjectNode QmlModelView::createQmlObjectNode(const TypeName &typeString,
int majorVersion,
int minorVersion,
const PropertyListType &propertyList)
{
return QmlObjectNode(createModelNode(typeString, majorVersion, minorVersion, propertyList));
}
QmlItemNode QmlModelView::createQmlItemNode(const TypeName &typeString,
int majorVersion,
int minorVersion,
const PropertyListType &propertyList)
{
return createQmlObjectNode(typeString, majorVersion, minorVersion, propertyList).toQmlItemNode();
}
QmlItemNode QmlModelView::createQmlItemNodeFromImage(const QString &imageName, const QPointF &position, QmlItemNode parentNode)
{
if (!parentNode.isValid())
parentNode = rootQmlItemNode();
if (!parentNode.isValid())
return QmlItemNode();
QmlItemNode newNode;
RewriterTransaction transaction = beginRewriterTransaction();
{
const QString newImportUrl = QLatin1String("QtQuick");
const QString newImportVersion = QLatin1String("1.1");
Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
foreach (const Import &import, model()->imports()) {
if (import.isLibraryImport()
&& import.url() == newImport.url()
&& import.version() == newImport.version()) {
// reuse this import
newImport = import;
break;
}
}
if (!model()->imports().contains(newImport))
model()->changeImports(QList<Import>() << newImport, QList<Import>());
QList<QPair<PropertyName, QVariant> > propertyPairList;
propertyPairList.append(qMakePair(PropertyName("x"), QVariant( round(position.x(), 4))));
propertyPairList.append(qMakePair(PropertyName("y"), QVariant( round(position.y(), 4))));
QString relativeImageName = imageName;
//use relative path
if (QFileInfo(model()->fileUrl().toLocalFile()).exists()) {
QDir fileDir(QFileInfo(model()->fileUrl().toLocalFile()).absolutePath());
relativeImageName = fileDir.relativeFilePath(imageName);
}
propertyPairList.append(qMakePair(PropertyName("source"), QVariant(relativeImageName)));
newNode = createQmlItemNode("QtQuick.Image", -1, -1, propertyPairList);
parentNode.nodeAbstractProperty("data").reparentHere(newNode);
Q_ASSERT(newNode.isValid());
QString id;
int i = 1;
QString name("image");
name.remove(QLatin1Char(' '));
do {
id = name + QString::number(i);
i++;
} while (hasId(id)); //If the name already exists count upwards
newNode.setId(id);
if (!currentState().isBaseState()) {
newNode.modelNode().variantProperty("opacity") = 0;
newNode.setVariantProperty("opacity", 1);
}
Q_ASSERT(newNode.isValid());
}
Q_ASSERT(newNode.isValid());
return newNode;
}
QmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, const QPointF &position, QmlItemNode parentNode)
{
if (!parentNode.isValid())
parentNode = rootQmlItemNode();
Q_ASSERT(parentNode.isValid());
QmlItemNode newNode;
try {
RewriterTransaction transaction = beginRewriterTransaction();
NodeMetaInfo metaInfo = model()->metaInfo(itemLibraryEntry.typeName());
int minorVersion = metaInfo.minorVersion();
int majorVersion = metaInfo.majorVersion();
if (itemLibraryEntry.typeName().contains('.')) {
const QString newImportUrl = itemLibraryEntry.requiredImport();
if (!itemLibraryEntry.requiredImport().isEmpty()) {
const QString newImportVersion = QString("%1.%2").arg(QString::number(itemLibraryEntry.majorVersion()), QString::number(itemLibraryEntry.minorVersion()));
Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
if (itemLibraryEntry.majorVersion() == -1 && itemLibraryEntry.minorVersion() == -1)
newImport = Import::createFileImport(newImportUrl, QString());
else
newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
foreach (const Import &import, model()->imports()) {
if (import.isLibraryImport()
&& import.url() == newImport.url()
&& import.version() == newImport.version()) {
// reuse this import
newImport = import;
break;
}
}
if (!model()->hasImport(newImport, true, true))
model()->changeImports(QList<Import>() << newImport, QList<Import>());
}
}
QList<QPair<PropertyName, QVariant> > propertyPairList;
propertyPairList.append(qMakePair(PropertyName("x"), QVariant(round(position.x(), 4))));
propertyPairList.append(qMakePair(PropertyName("y"), QVariant(round(position.y(), 4))));
if (itemLibraryEntry.qml().isEmpty()) {
foreach (const PropertyContainer &property, itemLibraryEntry.properties())
propertyPairList.append(qMakePair(property.name(), property.value()));
newNode = createQmlItemNode(itemLibraryEntry.typeName(), majorVersion, minorVersion, propertyPairList);
} else {
QScopedPointer<Model> inputModel(Model::create("QtQuick.Rectangle", 1, 0, model()));
inputModel->setFileUrl(model()->fileUrl());
QPlainTextEdit textEdit;
textEdit.setPlainText(Utils::FileReader::fetchQrc(itemLibraryEntry.qml()));
NotIndentingTextEditModifier modifier(&textEdit);
QScopedPointer<RewriterView> rewriterView(new RewriterView(RewriterView::Amend, 0));
rewriterView->setCheckSemanticErrors(false);
rewriterView->setTextModifier(&modifier);
inputModel->setRewriterView(rewriterView.data());
if (rewriterView->errors().isEmpty() && rewriterView->rootModelNode().isValid()) {
ModelNode rootModelNode = rewriterView->rootModelNode();
inputModel->detachView(rewriterView.data());
rootModelNode.variantProperty("x") = propertyPairList.first().second;
rootModelNode.variantProperty("y") = propertyPairList.at(1).second;
ModelMerger merger(this);
newNode = merger.insertModel(rootModelNode);
}
}
if (parentNode.hasDefaultProperty())
parentNode.nodeAbstractProperty(parentNode.defaultProperty()).reparentHere(newNode);
if (!newNode.isValid())
return newNode;
QString id;
int i = 1;
QString name(itemLibraryEntry.name().toLower());
//remove forbidden characters
name.replace(QRegExp(QLatin1String("[^a-zA-Z0-9_]")), QLatin1String("_"));
do {
id = name + QString::number(i);
i++;
} while (hasId(id)); //If the name already exists count upwards
newNode.setId(id);
if (!currentState().isBaseState()) {
newNode.modelNode().variantProperty("opacity") = 0;
newNode.setVariantProperty("opacity", 1);
}
Q_ASSERT(newNode.isValid());
}
catch (RewritingException &e) {
QMessageBox::warning(0, "Error", e.description());
}
catch (InvalidIdException &e) {
// should never happen
QMessageBox::warning(0, tr("Invalid Id"), e.description());
}
Q_ASSERT(newNode.isValid());
return newNode;
}
QmlObjectNode QmlModelView::rootQmlObjectNode() const
{
return QmlObjectNode(rootModelNode());
}
QmlItemNode QmlModelView::rootQmlItemNode() const
{
return rootQmlObjectNode().toQmlItemNode();
}
void QmlModelView::setSelectedQmlObjectNodes(const QList<QmlObjectNode> &selectedNodeList)
{
setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));
}
void QmlModelView::selectQmlObjectNode(const QmlObjectNode &node)
{
selectModelNode(node.modelNode());
}
void QmlModelView::deselectQmlObjectNode(const QmlObjectNode &node)
{
deselectModelNode(node.modelNode());
}
QList<QmlObjectNode> QmlModelView::selectedQmlObjectNodes() const
{
return toQmlObjectNodeList(selectedModelNodes());
}
QList<QmlItemNode> QmlModelView::selectedQmlItemNodes() const
{
return toQmlItemNodeList(selectedModelNodes());
}
void QmlModelView::setSelectedQmlItemNodes(const QList<QmlItemNode> &selectedNodeList)
{
return setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));
}
QmlObjectNode QmlModelView::fxObjectNodeForId(const QString &id)
{
return QmlObjectNode(modelNodeForId(id));
}
NodeInstance QmlModelView::instanceForModelNode(const ModelNode &modelNode)
{
return nodeInstanceView()->instanceForNode(modelNode);
}
bool QmlModelView::hasInstanceForModelNode(const ModelNode &modelNode)
{
return nodeInstanceView() && nodeInstanceView()->hasInstanceForNode(modelNode);
}
void QmlModelView::modelAttached(Model *model)
{
AbstractView::modelAttached(model);
}
void QmlModelView::modelAboutToBeDetached(Model *model)
{
AbstractView::modelAboutToBeDetached(model);
}
static bool isTransformProperty(const QString &name)
{
static QStringList transformProperties(QStringList() << "x"
<< "y"
<< "width"
<< "height"
<< "z"
<< "rotation"
<< "scale"
<< "transformOrigin"
<< "paintedWidth"
<< "paintedHeight"
<< "border.width");
return transformProperties.contains(name);
}
void QmlModelView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/)
{
}
void QmlModelView::nodeCreated(const ModelNode &/*createdNode*/) {}
void QmlModelView::nodeAboutToBeRemoved(const ModelNode &/*removedNode*/) {}
void QmlModelView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::nodeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::nodeIdChanged(const ModelNode& /*node*/, const QString& /*newId*/, const QString& /*oldId*/) {}
void QmlModelView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
void QmlModelView::propertiesRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
void QmlModelView::variantPropertiesChanged(const QList<VariantProperty>& /*propertyList*/, PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::bindingPropertiesChanged(const QList<BindingProperty>& /*propertyList*/, PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::rootNodeTypeChanged(const QString &/*type*/, int, int /*minorVersion*/) {}
void QmlModelView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/) {}
void QmlModelView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/) {}
void QmlModelView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/)
{
}
void QmlModelView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/)
{
}
void QmlModelView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/)
{
}
void QmlModelView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/)
{
}
void QmlModelView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/)
{
}
void QmlModelView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/)
{
}
void QmlModelView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/)
{
}
void QmlModelView::nodeSourceChanged(const ModelNode &, const QString & /*newNodeSource*/)
{
}
void QmlModelView::rewriterBeginTransaction()
{
}
void QmlModelView::rewriterEndTransaction()
{
}
void QmlModelView::actualStateChanged(const ModelNode & /*node*/)
{
}
void QmlModelView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > & /*propertyList*/)
{
}
ModelNode QmlModelView::createQmlState(const QmlDesigner::PropertyListType &propertyList)
{
QTC_CHECK(rootModelNode().majorQtQuickVersion() < 3);
if (rootModelNode().majorQtQuickVersion() > 1)
return createModelNode("QtQuick.State", 2, 0, propertyList);
else
return createModelNode("QtQuick.State", 1, 0, propertyList);
}
} //QmlDesigner
<commit_msg>QmlDesigner: remove unused function<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmlmodelview.h"
#include "qmlobjectnode.h"
#include "qmlitemnode.h"
#include "itemlibraryinfo.h"
#include "mathutils.h"
#include "invalididexception.h"
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <utils/fileutils.h>
#include "nodeabstractproperty.h"
#include "variantproperty.h"
#include "rewritingexception.h"
#include "rewriterview.h"
#include "plaintexteditmodifier.h"
#include "modelmerger.h"
#include "nodemetainfo.h"
#include <utils/qtcassert.h>
namespace QmlDesigner {
QmlModelView::QmlModelView(QObject *parent)
: AbstractView(parent)
{
}
void QmlModelView::setCurrentState(const QmlModelState &state)
{
if (!state.isValid())
return;
if (!model())
return;
if (actualStateNode() != state.modelNode())
setAcutalStateNode(state.modelNode());
}
QmlModelState QmlModelView::currentState() const
{
return QmlModelState(actualStateNode());
}
QmlModelState QmlModelView::baseState() const
{
return QmlModelState::createBaseState(this);
}
QmlModelStateGroup QmlModelView::rootStateGroup() const
{
return QmlModelStateGroup(rootModelNode());
}
QmlObjectNode QmlModelView::createQmlObjectNode(const TypeName &typeString,
int majorVersion,
int minorVersion,
const PropertyListType &propertyList)
{
return QmlObjectNode(createModelNode(typeString, majorVersion, minorVersion, propertyList));
}
QmlItemNode QmlModelView::createQmlItemNode(const TypeName &typeString,
int majorVersion,
int minorVersion,
const PropertyListType &propertyList)
{
return createQmlObjectNode(typeString, majorVersion, minorVersion, propertyList).toQmlItemNode();
}
QmlItemNode QmlModelView::createQmlItemNodeFromImage(const QString &imageName, const QPointF &position, QmlItemNode parentNode)
{
if (!parentNode.isValid())
parentNode = rootQmlItemNode();
if (!parentNode.isValid())
return QmlItemNode();
QmlItemNode newNode;
RewriterTransaction transaction = beginRewriterTransaction();
{
const QString newImportUrl = QLatin1String("QtQuick");
const QString newImportVersion = QLatin1String("1.1");
Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
foreach (const Import &import, model()->imports()) {
if (import.isLibraryImport()
&& import.url() == newImport.url()
&& import.version() == newImport.version()) {
// reuse this import
newImport = import;
break;
}
}
if (!model()->imports().contains(newImport))
model()->changeImports(QList<Import>() << newImport, QList<Import>());
QList<QPair<PropertyName, QVariant> > propertyPairList;
propertyPairList.append(qMakePair(PropertyName("x"), QVariant( round(position.x(), 4))));
propertyPairList.append(qMakePair(PropertyName("y"), QVariant( round(position.y(), 4))));
QString relativeImageName = imageName;
//use relative path
if (QFileInfo(model()->fileUrl().toLocalFile()).exists()) {
QDir fileDir(QFileInfo(model()->fileUrl().toLocalFile()).absolutePath());
relativeImageName = fileDir.relativeFilePath(imageName);
}
propertyPairList.append(qMakePair(PropertyName("source"), QVariant(relativeImageName)));
newNode = createQmlItemNode("QtQuick.Image", -1, -1, propertyPairList);
parentNode.nodeAbstractProperty("data").reparentHere(newNode);
Q_ASSERT(newNode.isValid());
QString id;
int i = 1;
QString name("image");
name.remove(QLatin1Char(' '));
do {
id = name + QString::number(i);
i++;
} while (hasId(id)); //If the name already exists count upwards
newNode.setId(id);
if (!currentState().isBaseState()) {
newNode.modelNode().variantProperty("opacity") = 0;
newNode.setVariantProperty("opacity", 1);
}
Q_ASSERT(newNode.isValid());
}
Q_ASSERT(newNode.isValid());
return newNode;
}
QmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, const QPointF &position, QmlItemNode parentNode)
{
if (!parentNode.isValid())
parentNode = rootQmlItemNode();
Q_ASSERT(parentNode.isValid());
QmlItemNode newNode;
try {
RewriterTransaction transaction = beginRewriterTransaction();
NodeMetaInfo metaInfo = model()->metaInfo(itemLibraryEntry.typeName());
int minorVersion = metaInfo.minorVersion();
int majorVersion = metaInfo.majorVersion();
if (itemLibraryEntry.typeName().contains('.')) {
const QString newImportUrl = itemLibraryEntry.requiredImport();
if (!itemLibraryEntry.requiredImport().isEmpty()) {
const QString newImportVersion = QString("%1.%2").arg(QString::number(itemLibraryEntry.majorVersion()), QString::number(itemLibraryEntry.minorVersion()));
Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
if (itemLibraryEntry.majorVersion() == -1 && itemLibraryEntry.minorVersion() == -1)
newImport = Import::createFileImport(newImportUrl, QString());
else
newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
foreach (const Import &import, model()->imports()) {
if (import.isLibraryImport()
&& import.url() == newImport.url()
&& import.version() == newImport.version()) {
// reuse this import
newImport = import;
break;
}
}
if (!model()->hasImport(newImport, true, true))
model()->changeImports(QList<Import>() << newImport, QList<Import>());
}
}
QList<QPair<PropertyName, QVariant> > propertyPairList;
propertyPairList.append(qMakePair(PropertyName("x"), QVariant(round(position.x(), 4))));
propertyPairList.append(qMakePair(PropertyName("y"), QVariant(round(position.y(), 4))));
if (itemLibraryEntry.qml().isEmpty()) {
foreach (const PropertyContainer &property, itemLibraryEntry.properties())
propertyPairList.append(qMakePair(property.name(), property.value()));
newNode = createQmlItemNode(itemLibraryEntry.typeName(), majorVersion, minorVersion, propertyPairList);
} else {
QScopedPointer<Model> inputModel(Model::create("QtQuick.Rectangle", 1, 0, model()));
inputModel->setFileUrl(model()->fileUrl());
QPlainTextEdit textEdit;
textEdit.setPlainText(Utils::FileReader::fetchQrc(itemLibraryEntry.qml()));
NotIndentingTextEditModifier modifier(&textEdit);
QScopedPointer<RewriterView> rewriterView(new RewriterView(RewriterView::Amend, 0));
rewriterView->setCheckSemanticErrors(false);
rewriterView->setTextModifier(&modifier);
inputModel->setRewriterView(rewriterView.data());
if (rewriterView->errors().isEmpty() && rewriterView->rootModelNode().isValid()) {
ModelNode rootModelNode = rewriterView->rootModelNode();
inputModel->detachView(rewriterView.data());
rootModelNode.variantProperty("x") = propertyPairList.first().second;
rootModelNode.variantProperty("y") = propertyPairList.at(1).second;
ModelMerger merger(this);
newNode = merger.insertModel(rootModelNode);
}
}
if (parentNode.hasDefaultProperty())
parentNode.nodeAbstractProperty(parentNode.defaultProperty()).reparentHere(newNode);
if (!newNode.isValid())
return newNode;
QString id;
int i = 1;
QString name(itemLibraryEntry.name().toLower());
//remove forbidden characters
name.replace(QRegExp(QLatin1String("[^a-zA-Z0-9_]")), QLatin1String("_"));
do {
id = name + QString::number(i);
i++;
} while (hasId(id)); //If the name already exists count upwards
newNode.setId(id);
if (!currentState().isBaseState()) {
newNode.modelNode().variantProperty("opacity") = 0;
newNode.setVariantProperty("opacity", 1);
}
Q_ASSERT(newNode.isValid());
}
catch (RewritingException &e) {
QMessageBox::warning(0, "Error", e.description());
}
catch (InvalidIdException &e) {
// should never happen
QMessageBox::warning(0, tr("Invalid Id"), e.description());
}
Q_ASSERT(newNode.isValid());
return newNode;
}
QmlObjectNode QmlModelView::rootQmlObjectNode() const
{
return QmlObjectNode(rootModelNode());
}
QmlItemNode QmlModelView::rootQmlItemNode() const
{
return rootQmlObjectNode().toQmlItemNode();
}
void QmlModelView::setSelectedQmlObjectNodes(const QList<QmlObjectNode> &selectedNodeList)
{
setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));
}
void QmlModelView::selectQmlObjectNode(const QmlObjectNode &node)
{
selectModelNode(node.modelNode());
}
void QmlModelView::deselectQmlObjectNode(const QmlObjectNode &node)
{
deselectModelNode(node.modelNode());
}
QList<QmlObjectNode> QmlModelView::selectedQmlObjectNodes() const
{
return toQmlObjectNodeList(selectedModelNodes());
}
QList<QmlItemNode> QmlModelView::selectedQmlItemNodes() const
{
return toQmlItemNodeList(selectedModelNodes());
}
void QmlModelView::setSelectedQmlItemNodes(const QList<QmlItemNode> &selectedNodeList)
{
return setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));
}
QmlObjectNode QmlModelView::fxObjectNodeForId(const QString &id)
{
return QmlObjectNode(modelNodeForId(id));
}
NodeInstance QmlModelView::instanceForModelNode(const ModelNode &modelNode)
{
return nodeInstanceView()->instanceForNode(modelNode);
}
bool QmlModelView::hasInstanceForModelNode(const ModelNode &modelNode)
{
return nodeInstanceView() && nodeInstanceView()->hasInstanceForNode(modelNode);
}
void QmlModelView::modelAttached(Model *model)
{
AbstractView::modelAttached(model);
}
void QmlModelView::modelAboutToBeDetached(Model *model)
{
AbstractView::modelAboutToBeDetached(model);
}
void QmlModelView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/)
{
}
void QmlModelView::nodeCreated(const ModelNode &/*createdNode*/) {}
void QmlModelView::nodeAboutToBeRemoved(const ModelNode &/*removedNode*/) {}
void QmlModelView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::nodeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::nodeIdChanged(const ModelNode& /*node*/, const QString& /*newId*/, const QString& /*oldId*/) {}
void QmlModelView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
void QmlModelView::propertiesRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
void QmlModelView::variantPropertiesChanged(const QList<VariantProperty>& /*propertyList*/, PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::bindingPropertiesChanged(const QList<BindingProperty>& /*propertyList*/, PropertyChangeFlags /*propertyChange*/) {}
void QmlModelView::rootNodeTypeChanged(const QString &/*type*/, int, int /*minorVersion*/) {}
void QmlModelView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/) {}
void QmlModelView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/) {}
void QmlModelView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/)
{
}
void QmlModelView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/)
{
}
void QmlModelView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/)
{
}
void QmlModelView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/)
{
}
void QmlModelView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/)
{
}
void QmlModelView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/)
{
}
void QmlModelView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/)
{
}
void QmlModelView::nodeSourceChanged(const ModelNode &, const QString & /*newNodeSource*/)
{
}
void QmlModelView::rewriterBeginTransaction()
{
}
void QmlModelView::rewriterEndTransaction()
{
}
void QmlModelView::actualStateChanged(const ModelNode & /*node*/)
{
}
void QmlModelView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > & /*propertyList*/)
{
}
ModelNode QmlModelView::createQmlState(const QmlDesigner::PropertyListType &propertyList)
{
QTC_CHECK(rootModelNode().majorQtQuickVersion() < 3);
if (rootModelNode().majorQtQuickVersion() > 1)
return createModelNode("QtQuick.State", 2, 0, propertyList);
else
return createModelNode("QtQuick.State", 1, 0, propertyList);
}
} //QmlDesigner
<|endoftext|> |
<commit_before>/*
Copyright 2015-2020 Igor Petrovic
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 "Nextion.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
bool Nextion::init()
{
rxBuffer.reset();
return hwa.init();
}
bool Nextion::setScreen(size_t screenID)
{
return writeCommand("page %u", screenID);
}
bool Nextion::update(size_t& buttonID, bool& state)
{
uint8_t data;
if (hwa.read(data))
rxBuffer.insert(data);
else
return false;
if (data == 0xFF)
{
endCounter++;
}
else
{
if (endCounter)
endCounter = 0;
}
if (endCounter == 3)
{
//new message received
endCounter = 0;
//handle only button messages for now
bool messageStart = true;
while (rxBuffer.count())
{
rxBuffer.remove(data);
if ((data == 0x65) && messageStart)
{
if (rxBuffer.count() >= 5)
{
//state
//1 - pressed, 0 - released
rxBuffer.remove(data);
state = data ? 1 : 0;
//button id
rxBuffer.remove(data);
buttonID = data;
rxBuffer.reset();
return true;
}
}
else
{
rxBuffer.reset();
}
messageStart = false;
}
}
return false;
}
void Nextion::setIconState(IO::Touchscreen::icon_t& icon, bool state)
{
writeCommand("picq %u,%u,%u,%u,%u", icon.xPos, icon.yPos, icon.width, icon.height, state ? 1 : 0);
}
bool Nextion::writeCommand(const char* line, ...)
{
va_list args;
va_start(args, line);
size_t retVal = vsnprintf(commandBuffer, bufferSize, line, args);
va_end(args);
if (retVal < 0)
return false;
for (size_t i = 0; i < strlen(commandBuffer); i++)
{
if (!hwa.write(commandBuffer[i]))
return false;
}
return endCommand();
}
bool Nextion::endCommand()
{
for (int i = 0; i < 3; i++)
{
if (!hwa.write(0xFF))
return false;
}
return true;
}<commit_msg>touchscreen: don't hardcode on/off screens when setting icon state<commit_after>/*
Copyright 2015-2020 Igor Petrovic
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 "Nextion.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
bool Nextion::init()
{
rxBuffer.reset();
return hwa.init();
}
bool Nextion::setScreen(size_t screenID)
{
return writeCommand("page %u", screenID);
}
bool Nextion::update(size_t& buttonID, bool& state)
{
uint8_t data;
if (hwa.read(data))
rxBuffer.insert(data);
else
return false;
if (data == 0xFF)
{
endCounter++;
}
else
{
if (endCounter)
endCounter = 0;
}
if (endCounter == 3)
{
//new message received
endCounter = 0;
//handle only button messages for now
bool messageStart = true;
while (rxBuffer.count())
{
rxBuffer.remove(data);
if ((data == 0x65) && messageStart)
{
if (rxBuffer.count() >= 5)
{
//state
//1 - pressed, 0 - released
rxBuffer.remove(data);
state = data ? 1 : 0;
//button id
rxBuffer.remove(data);
buttonID = data;
rxBuffer.reset();
return true;
}
}
else
{
rxBuffer.reset();
}
messageStart = false;
}
}
return false;
}
void Nextion::setIconState(IO::Touchscreen::icon_t& icon, bool state)
{
writeCommand("picq %u,%u,%u,%u,%u", icon.xPos, icon.yPos, icon.width, icon.height, state ? icon.onScreen : icon.offScreen);
}
bool Nextion::writeCommand(const char* line, ...)
{
va_list args;
va_start(args, line);
size_t retVal = vsnprintf(commandBuffer, bufferSize, line, args);
va_end(args);
if (retVal < 0)
return false;
for (size_t i = 0; i < strlen(commandBuffer); i++)
{
if (!hwa.write(commandBuffer[i]))
return false;
}
return endCommand();
}
bool Nextion::endCommand()
{
for (int i = 0; i < 3; i++)
{
if (!hwa.write(0xFF))
return false;
}
return true;
}<|endoftext|> |
<commit_before>#include <QSettings>
#include <QThread>
#include "canconnection.h"
CANConnection::CANConnection(QString pPort,
QString pDriver,
CANCon::type pType,
int pNumBuses,
int pQueueLen,
bool pUseThread) :
mNumBuses(pNumBuses),
mQueue(),
mPort(pPort),
mDriver(pDriver),
mType(pType),
mIsCapSuspended(false),
mStatus(CANCon::NOT_CONNECTED),
mStarted(false),
mThread_p(nullptr)
{
/* register types */
qRegisterMetaType<CANBus>("CANBus");
qRegisterMetaType<CANFrame>("CANFrame");
qRegisterMetaType<CANConStatus>("CANConStatus");
qRegisterMetaType<CANFltObserver>("CANFlt");
/* set queue size */
mQueue.setSize(pQueueLen); /*TODO add check on returned value */
/* allocate buses */
/* TODO: change those tables for a vector */
mBusData.resize(mNumBuses);
for(int i=0 ; i<mNumBuses ; i++) {
mBusData[i].mConfigured = false;
}
/* if needed, create a thread and move ourself into it */
if(pUseThread) {
mThread_p = new QThread();
}
}
CANConnection::~CANConnection()
{
/* stop and delete thread */
if(mThread_p) {
mThread_p->quit();
mThread_p->wait();
delete mThread_p;
mThread_p = nullptr;
}
mBusData.clear();
}
void CANConnection::start()
{
if( mThread_p && (mThread_p != QThread::currentThread()) )
{
/* move ourself to the thread */
moveToThread(mThread_p); /*TODO handle errors */
/* connect started() */
connect(mThread_p, SIGNAL(started()), this, SLOT(start()));
/* start the thread */
mThread_p->start(QThread::HighPriority);
return;
}
/* set started flag */
mStarted = true;
QSettings settings;
if (settings.value("Main/TimeClock", false).toBool())
{
useSystemTime = true;
}
else useSystemTime = false;
/* in multithread case, this will be called before entering thread event loop */
return piStarted();
}
void CANConnection::suspend(bool pSuspend)
{
/* execute in mThread_p context */
if( mThread_p && (mThread_p != QThread::currentThread()) ) {
QMetaObject::invokeMethod(this, "suspend",
Qt::BlockingQueuedConnection,
Q_ARG(bool, pSuspend));
return;
}
return piSuspend(pSuspend);
}
void CANConnection::stop()
{
/* 1) execute in mThread_p context */
if( mThread_p && mStarted && (mThread_p != QThread::currentThread()) )
{
/* if thread is finished, it means we call this function for the second time so we can leave */
if( !mThread_p->isFinished() )
{
/* we need to call piStop() */
QMetaObject::invokeMethod(this, "stop",
Qt::BlockingQueuedConnection);
/* 3) stop thread */
mThread_p->quit();
if(!mThread_p->wait()) {
qDebug() << "can't stop thread";
}
}
return;
}
/* 2) call piStop in mThread context */
return piStop();
}
bool CANConnection::getBusSettings(int pBusIdx, CANBus& pBus)
{
/* make sure we execute in mThread context */
if( mThread_p && (mThread_p != QThread::currentThread()) ) {
bool ret;
QMetaObject::invokeMethod(this, "getBusSettings",
Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, ret),
Q_ARG(int , pBusIdx),
Q_ARG(CANBus& , pBus));
return ret;
}
return piGetBusSettings(pBusIdx, pBus);
}
void CANConnection::setBusSettings(int pBusIdx, CANBus pBus)
{
/* make sure we execute in mThread context */
if( mThread_p && (mThread_p != QThread::currentThread()) ) {
QMetaObject::invokeMethod(this, "setBusSettings",
Qt::BlockingQueuedConnection,
Q_ARG(int, pBusIdx),
Q_ARG(CANBus, pBus));
return;
}
return piSetBusSettings(pBusIdx, pBus);
}
bool CANConnection::sendFrame(const CANFrame& pFrame)
{
/* make sure we execute in mThread context */
if( mThread_p && (mThread_p != QThread::currentThread()) )
{
bool ret;
QMetaObject::invokeMethod(this, "sendFrame",
Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, ret),
Q_ARG(const CANFrame&, pFrame));
return ret;
}
return piSendFrame(pFrame);
}
bool CANConnection::sendFrames(const QList<CANFrame>& pFrames)
{
/* make sure we execute in mThread context */
if( mThread_p && (mThread_p != QThread::currentThread()) )
{
bool ret;
QMetaObject::invokeMethod(this, "sendFrames",
Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, ret),
Q_ARG(const QList<CANFrame>&, pFrames));
return ret;
}
return piSendFrames(pFrames);
}
int CANConnection::getNumBuses() const{
return mNumBuses;
}
bool CANConnection::isConfigured(int pBusId) {
if( pBusId < 0 || pBusId >= getNumBuses())
return false;
return mBusData[pBusId].mConfigured;
}
void CANConnection::setConfigured(int pBusId, bool pConfigured) {
if( pBusId < 0 || pBusId >= getNumBuses())
return;
mBusData[pBusId].mConfigured = pConfigured;
}
bool CANConnection::getBusConfig(int pBusId, CANBus& pBus) {
if( pBusId < 0 || pBusId >= getNumBuses() || !isConfigured(pBusId))
return false;
qDebug() << "getBusConfig id: " << pBusId;
pBus = mBusData[pBusId].mBus;
return true;
}
void CANConnection::setBusConfig(int pBusId, CANBus& pBus) {
if( pBusId < 0 || pBusId >= getNumBuses())
return;
mBusData[pBusId].mConfigured = true;
mBusData[pBusId].mBus = pBus;
}
QString CANConnection::getPort() {
return mPort;
}
QString CANConnection::getDriver()
{
return mDriver;
}
LFQueue<CANFrame>& CANConnection::getQueue() {
return mQueue;
}
CANCon::type CANConnection::getType() {
return mType;
}
CANCon::status CANConnection::getStatus() {
return (CANCon::status) mStatus.load();
}
void CANConnection::setStatus(CANCon::status pStatus) {
mStatus.store(pStatus);
}
bool CANConnection::isCapSuspended() {
return mIsCapSuspended;
}
void CANConnection::setCapSuspended(bool pIsSuspended) {
mIsCapSuspended = pIsSuspended;
}
void CANConnection::debugInput(QByteArray bytes) {
Q_UNUSED(bytes)
}
bool CANConnection::addTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver)
{
/*
if( mThread_p && (mThread_p != QThread::currentThread()) ) {
bool ret;
QMetaObject::invokeMethod(this, "addTargettedFrame",
Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, ret),
Q_ARG(int, pBusId),
Q_ARG(uint32_t , ID),
Q_ARG(uint32_t , mask),
Q_ARG(QObject *, receiver));
return ret;
}
*/
/* sanity checks */
if(pBusId < -1 || pBusId >= getNumBuses())
return false;
qDebug() << "Connection is registering a new targetted frame filter, local bus " << pBusId;
CANFltObserver target;
target.id = ID;
target.mask = mask;
target.observer = receiver;
mBusData[pBusId].mTargettedFrames.append(target);
return true;
}
bool CANConnection::removeTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver)
{
/*
if( mThread_p && (mThread_p != QThread::currentThread()) ) {
bool ret;
QMetaObject::invokeMethod(this, "removeTargettedFrame",
Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, ret),
Q_ARG(int, pBusId),
Q_ARG(uint32_t , ID),
Q_ARG(uint32_t , mask),
Q_ARG(QObject *, receiver));
return ret;
}
*/
/* sanity checks */
if(pBusId < -1 || pBusId >= getNumBuses())
return false;
CANFltObserver target;
target.id = ID;
target.mask = mask;
target.observer = receiver;
mBusData[pBusId].mTargettedFrames.removeAll(target);
return true;
}
bool CANConnection::removeAllTargettedFrames(QObject *receiver)
{
for (int i = 0; i < getNumBuses(); i++) {
foreach (const CANFltObserver filt, mBusData[i].mTargettedFrames)
{
if (filt.observer == receiver) mBusData[i].mTargettedFrames.removeOne(filt);
}
}
return true;
}
void CANConnection::checkTargettedFrame(CANFrame &frame)
{
unsigned int maskedID;
//qDebug() << "Got frame with ID " << frame.ID << " on bus " << frame.bus;
if (mBusData.count() == 0) return;
int bus = frame.bus;
if (bus > (mBusData.length() - 1)) bus = mBusData.length() - 1;
if (mBusData[bus].mTargettedFrames.length() == 0) return;
foreach (const CANFltObserver filt, mBusData[frame.bus].mTargettedFrames)
{
//qDebug() << "Checking filter with id " << filt.id << " mask " << filt.mask;
maskedID = frame.frameId() & filt.mask;
if (maskedID == filt.id) {
qDebug() << "In connection object I got a targetted frame. Forwarding it.";
QMetaObject::invokeMethod(filt.observer, "gotTargettedFrame",Qt::QueuedConnection, Q_ARG(CANFrame, frame));
}
}
}
bool CANConnection::piSendFrames(const QList<CANFrame>& pFrames)
{
foreach(const CANFrame& frame, pFrames)
{
if(!piSendFrame(frame))
return false;
}
return true;
}
<commit_msg>replace QAtomicInt load()/store() with loadRelaxed()/storeRelaxed()<commit_after>#include <QSettings>
#include <QThread>
#include "canconnection.h"
CANConnection::CANConnection(QString pPort,
QString pDriver,
CANCon::type pType,
int pNumBuses,
int pQueueLen,
bool pUseThread) :
mNumBuses(pNumBuses),
mQueue(),
mPort(pPort),
mDriver(pDriver),
mType(pType),
mIsCapSuspended(false),
mStatus(CANCon::NOT_CONNECTED),
mStarted(false),
mThread_p(nullptr)
{
/* register types */
qRegisterMetaType<CANBus>("CANBus");
qRegisterMetaType<CANFrame>("CANFrame");
qRegisterMetaType<CANConStatus>("CANConStatus");
qRegisterMetaType<CANFltObserver>("CANFlt");
/* set queue size */
mQueue.setSize(pQueueLen); /*TODO add check on returned value */
/* allocate buses */
/* TODO: change those tables for a vector */
mBusData.resize(mNumBuses);
for(int i=0 ; i<mNumBuses ; i++) {
mBusData[i].mConfigured = false;
}
/* if needed, create a thread and move ourself into it */
if(pUseThread) {
mThread_p = new QThread();
}
}
CANConnection::~CANConnection()
{
/* stop and delete thread */
if(mThread_p) {
mThread_p->quit();
mThread_p->wait();
delete mThread_p;
mThread_p = nullptr;
}
mBusData.clear();
}
void CANConnection::start()
{
if( mThread_p && (mThread_p != QThread::currentThread()) )
{
/* move ourself to the thread */
moveToThread(mThread_p); /*TODO handle errors */
/* connect started() */
connect(mThread_p, SIGNAL(started()), this, SLOT(start()));
/* start the thread */
mThread_p->start(QThread::HighPriority);
return;
}
/* set started flag */
mStarted = true;
QSettings settings;
if (settings.value("Main/TimeClock", false).toBool())
{
useSystemTime = true;
}
else useSystemTime = false;
/* in multithread case, this will be called before entering thread event loop */
return piStarted();
}
void CANConnection::suspend(bool pSuspend)
{
/* execute in mThread_p context */
if( mThread_p && (mThread_p != QThread::currentThread()) ) {
QMetaObject::invokeMethod(this, "suspend",
Qt::BlockingQueuedConnection,
Q_ARG(bool, pSuspend));
return;
}
return piSuspend(pSuspend);
}
void CANConnection::stop()
{
/* 1) execute in mThread_p context */
if( mThread_p && mStarted && (mThread_p != QThread::currentThread()) )
{
/* if thread is finished, it means we call this function for the second time so we can leave */
if( !mThread_p->isFinished() )
{
/* we need to call piStop() */
QMetaObject::invokeMethod(this, "stop",
Qt::BlockingQueuedConnection);
/* 3) stop thread */
mThread_p->quit();
if(!mThread_p->wait()) {
qDebug() << "can't stop thread";
}
}
return;
}
/* 2) call piStop in mThread context */
return piStop();
}
bool CANConnection::getBusSettings(int pBusIdx, CANBus& pBus)
{
/* make sure we execute in mThread context */
if( mThread_p && (mThread_p != QThread::currentThread()) ) {
bool ret;
QMetaObject::invokeMethod(this, "getBusSettings",
Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, ret),
Q_ARG(int , pBusIdx),
Q_ARG(CANBus& , pBus));
return ret;
}
return piGetBusSettings(pBusIdx, pBus);
}
void CANConnection::setBusSettings(int pBusIdx, CANBus pBus)
{
/* make sure we execute in mThread context */
if( mThread_p && (mThread_p != QThread::currentThread()) ) {
QMetaObject::invokeMethod(this, "setBusSettings",
Qt::BlockingQueuedConnection,
Q_ARG(int, pBusIdx),
Q_ARG(CANBus, pBus));
return;
}
return piSetBusSettings(pBusIdx, pBus);
}
bool CANConnection::sendFrame(const CANFrame& pFrame)
{
/* make sure we execute in mThread context */
if( mThread_p && (mThread_p != QThread::currentThread()) )
{
bool ret;
QMetaObject::invokeMethod(this, "sendFrame",
Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, ret),
Q_ARG(const CANFrame&, pFrame));
return ret;
}
return piSendFrame(pFrame);
}
bool CANConnection::sendFrames(const QList<CANFrame>& pFrames)
{
/* make sure we execute in mThread context */
if( mThread_p && (mThread_p != QThread::currentThread()) )
{
bool ret;
QMetaObject::invokeMethod(this, "sendFrames",
Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, ret),
Q_ARG(const QList<CANFrame>&, pFrames));
return ret;
}
return piSendFrames(pFrames);
}
int CANConnection::getNumBuses() const{
return mNumBuses;
}
bool CANConnection::isConfigured(int pBusId) {
if( pBusId < 0 || pBusId >= getNumBuses())
return false;
return mBusData[pBusId].mConfigured;
}
void CANConnection::setConfigured(int pBusId, bool pConfigured) {
if( pBusId < 0 || pBusId >= getNumBuses())
return;
mBusData[pBusId].mConfigured = pConfigured;
}
bool CANConnection::getBusConfig(int pBusId, CANBus& pBus) {
if( pBusId < 0 || pBusId >= getNumBuses() || !isConfigured(pBusId))
return false;
qDebug() << "getBusConfig id: " << pBusId;
pBus = mBusData[pBusId].mBus;
return true;
}
void CANConnection::setBusConfig(int pBusId, CANBus& pBus) {
if( pBusId < 0 || pBusId >= getNumBuses())
return;
mBusData[pBusId].mConfigured = true;
mBusData[pBusId].mBus = pBus;
}
QString CANConnection::getPort() {
return mPort;
}
QString CANConnection::getDriver()
{
return mDriver;
}
LFQueue<CANFrame>& CANConnection::getQueue() {
return mQueue;
}
CANCon::type CANConnection::getType() {
return mType;
}
CANCon::status CANConnection::getStatus() {
return (CANCon::status) mStatus.loadRelaxed();
}
void CANConnection::setStatus(CANCon::status pStatus) {
mStatus.storeRelaxed(pStatus);
}
bool CANConnection::isCapSuspended() {
return mIsCapSuspended;
}
void CANConnection::setCapSuspended(bool pIsSuspended) {
mIsCapSuspended = pIsSuspended;
}
void CANConnection::debugInput(QByteArray bytes) {
Q_UNUSED(bytes)
}
bool CANConnection::addTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver)
{
/*
if( mThread_p && (mThread_p != QThread::currentThread()) ) {
bool ret;
QMetaObject::invokeMethod(this, "addTargettedFrame",
Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, ret),
Q_ARG(int, pBusId),
Q_ARG(uint32_t , ID),
Q_ARG(uint32_t , mask),
Q_ARG(QObject *, receiver));
return ret;
}
*/
/* sanity checks */
if(pBusId < -1 || pBusId >= getNumBuses())
return false;
qDebug() << "Connection is registering a new targetted frame filter, local bus " << pBusId;
CANFltObserver target;
target.id = ID;
target.mask = mask;
target.observer = receiver;
mBusData[pBusId].mTargettedFrames.append(target);
return true;
}
bool CANConnection::removeTargettedFrame(int pBusId, uint32_t ID, uint32_t mask, QObject *receiver)
{
/*
if( mThread_p && (mThread_p != QThread::currentThread()) ) {
bool ret;
QMetaObject::invokeMethod(this, "removeTargettedFrame",
Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, ret),
Q_ARG(int, pBusId),
Q_ARG(uint32_t , ID),
Q_ARG(uint32_t , mask),
Q_ARG(QObject *, receiver));
return ret;
}
*/
/* sanity checks */
if(pBusId < -1 || pBusId >= getNumBuses())
return false;
CANFltObserver target;
target.id = ID;
target.mask = mask;
target.observer = receiver;
mBusData[pBusId].mTargettedFrames.removeAll(target);
return true;
}
bool CANConnection::removeAllTargettedFrames(QObject *receiver)
{
for (int i = 0; i < getNumBuses(); i++) {
foreach (const CANFltObserver filt, mBusData[i].mTargettedFrames)
{
if (filt.observer == receiver) mBusData[i].mTargettedFrames.removeOne(filt);
}
}
return true;
}
void CANConnection::checkTargettedFrame(CANFrame &frame)
{
unsigned int maskedID;
//qDebug() << "Got frame with ID " << frame.ID << " on bus " << frame.bus;
if (mBusData.count() == 0) return;
int bus = frame.bus;
if (bus > (mBusData.length() - 1)) bus = mBusData.length() - 1;
if (mBusData[bus].mTargettedFrames.length() == 0) return;
foreach (const CANFltObserver filt, mBusData[frame.bus].mTargettedFrames)
{
//qDebug() << "Checking filter with id " << filt.id << " mask " << filt.mask;
maskedID = frame.frameId() & filt.mask;
if (maskedID == filt.id) {
qDebug() << "In connection object I got a targetted frame. Forwarding it.";
QMetaObject::invokeMethod(filt.observer, "gotTargettedFrame",Qt::QueuedConnection, Q_ARG(CANFrame, frame));
}
}
}
bool CANConnection::piSendFrames(const QList<CANFrame>& pFrames)
{
foreach(const CANFrame& frame, pFrames)
{
if(!piSendFrame(frame))
return false;
}
return true;
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2011 Juergen Riegel <[email protected]> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Standard_Failure.hxx>
# include <TopoDS_Solid.hxx>
# include <TopExp_Explorer.hxx>
# include <TopoDS.hxx>
# include <BRep_Tool.hxx>
# include <gp_Pnt.hxx>
# include <gp_Pln.hxx>
# include <BRepBuilderAPI_MakeFace.hxx>
#endif
#include <Base/Exception.h>
#include "App/Document.h"
#include "App/Plane.h"
#include <App/Line.h>
#include "Body.h"
#include "Feature.h"
#include "Mod/Part/App/DatumFeature.h"
#include <Base/Console.h>
namespace PartDesign {
PROPERTY_SOURCE(PartDesign::Feature,Part::Feature)
Feature::Feature()
{
ADD_PROPERTY(BaseFeature,(0));
Placement.StatusBits.set(2, true);
}
short Feature::mustExecute() const
{
if (BaseFeature.isTouched())
return 1;
return Part::Feature::mustExecute();
}
TopoDS_Shape Feature::getSolid(const TopoDS_Shape& shape)
{
if (shape.IsNull())
Standard_Failure::Raise("Shape is null");
TopExp_Explorer xp;
xp.Init(shape,TopAbs_SOLID);
for (;xp.More(); xp.Next()) {
return xp.Current();
}
return TopoDS_Shape();
}
const gp_Pnt Feature::getPointFromFace(const TopoDS_Face& f)
{
if (!f.Infinite()) {
TopExp_Explorer exp;
exp.Init(f, TopAbs_VERTEX);
if (exp.More())
return BRep_Tool::Pnt(TopoDS::Vertex(exp.Current()));
// Else try the other method
}
// TODO: Other method, e.g. intersect X,Y,Z axis with the (unlimited?) face?
// Or get a "corner" point if the face is limited?
throw Base::Exception("getPointFromFace(): Not implemented yet for this case");
}
const Part::Feature* Feature::getBaseObject() const {
App::DocumentObject* BaseLink = BaseFeature.getValue();
if (BaseLink == NULL) throw Base::Exception("Base property not set");
Part::Feature* BaseObject = NULL;
if (BaseLink->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
BaseObject = static_cast<Part::Feature*>(BaseLink);
if (BaseObject == NULL)
throw Base::Exception("No base feature linked");
return BaseObject;
}
const TopoDS_Shape& Feature::getBaseShape() const {
const Part::Feature* BaseObject = getBaseObject();
const TopoDS_Shape& result = BaseObject->Shape.getValue();
if (result.IsNull())
throw Base::Exception("Base feature's shape is invalid");
TopExp_Explorer xp (result, TopAbs_SOLID);
if (!xp.More())
throw Base::Exception("Base feature's shape is not a solid");
return result;
}
const Part::TopoShape Feature::getBaseTopoShape() const {
const Part::Feature* BaseObject = getBaseObject();
const Part::TopoShape& result = BaseObject->Shape.getShape();
if (result._Shape.IsNull())
throw Base::Exception("Base feature's TopoShape is invalid");
return result;
}
bool Feature::isDatum(const App::DocumentObject* feature)
{
return feature->getTypeId().isDerivedFrom(App::Plane::getClassTypeId()) ||
feature->getTypeId().isDerivedFrom(App::Line::getClassTypeId()) ||
feature->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId());
}
gp_Pln Feature::makePlnFromPlane(const App::DocumentObject* obj)
{
const App::Plane* plane = static_cast<const App::Plane*>(obj);
if (plane == NULL)
throw Base::Exception("Feature: Null object");
Base::Rotation rot = plane->Placement.getValue().getRotation();
Base::Vector3d normal(0,0,1);
rot.multVec(normal, normal);
return gp_Pln(gp_Pnt(0,0,0), gp_Dir(normal.x,normal.y,normal.z));
}
TopoDS_Shape Feature::makeShapeFromPlane(const App::DocumentObject* obj)
{
BRepBuilderAPI_MakeFace builder(makePlnFromPlane(obj));
if (!builder.IsDone())
throw Base::Exception("Feature: Could not create shape from base plane");
return builder.Shape();
}
}
<commit_msg>don't show placement for part design features<commit_after>/***************************************************************************
* Copyright (c) 2011 Juergen Riegel <[email protected]> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Standard_Failure.hxx>
# include <TopoDS_Solid.hxx>
# include <TopExp_Explorer.hxx>
# include <TopoDS.hxx>
# include <BRep_Tool.hxx>
# include <gp_Pnt.hxx>
# include <gp_Pln.hxx>
# include <BRepBuilderAPI_MakeFace.hxx>
#endif
#include <Base/Exception.h>
#include "App/Document.h"
#include "App/Plane.h"
#include <App/Line.h>
#include "Body.h"
#include "Feature.h"
#include "Mod/Part/App/DatumFeature.h"
#include <Base/Console.h>
namespace PartDesign {
PROPERTY_SOURCE(PartDesign::Feature,Part::Feature)
Feature::Feature()
{
ADD_PROPERTY(BaseFeature,(0));
Placement.StatusBits.set(3, true);
}
short Feature::mustExecute() const
{
if (BaseFeature.isTouched())
return 1;
return Part::Feature::mustExecute();
}
TopoDS_Shape Feature::getSolid(const TopoDS_Shape& shape)
{
if (shape.IsNull())
Standard_Failure::Raise("Shape is null");
TopExp_Explorer xp;
xp.Init(shape,TopAbs_SOLID);
for (;xp.More(); xp.Next()) {
return xp.Current();
}
return TopoDS_Shape();
}
const gp_Pnt Feature::getPointFromFace(const TopoDS_Face& f)
{
if (!f.Infinite()) {
TopExp_Explorer exp;
exp.Init(f, TopAbs_VERTEX);
if (exp.More())
return BRep_Tool::Pnt(TopoDS::Vertex(exp.Current()));
// Else try the other method
}
// TODO: Other method, e.g. intersect X,Y,Z axis with the (unlimited?) face?
// Or get a "corner" point if the face is limited?
throw Base::Exception("getPointFromFace(): Not implemented yet for this case");
}
const Part::Feature* Feature::getBaseObject() const {
App::DocumentObject* BaseLink = BaseFeature.getValue();
if (BaseLink == NULL) throw Base::Exception("Base property not set");
Part::Feature* BaseObject = NULL;
if (BaseLink->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
BaseObject = static_cast<Part::Feature*>(BaseLink);
if (BaseObject == NULL)
throw Base::Exception("No base feature linked");
return BaseObject;
}
const TopoDS_Shape& Feature::getBaseShape() const {
const Part::Feature* BaseObject = getBaseObject();
const TopoDS_Shape& result = BaseObject->Shape.getValue();
if (result.IsNull())
throw Base::Exception("Base feature's shape is invalid");
TopExp_Explorer xp (result, TopAbs_SOLID);
if (!xp.More())
throw Base::Exception("Base feature's shape is not a solid");
return result;
}
const Part::TopoShape Feature::getBaseTopoShape() const {
const Part::Feature* BaseObject = getBaseObject();
const Part::TopoShape& result = BaseObject->Shape.getShape();
if (result._Shape.IsNull())
throw Base::Exception("Base feature's TopoShape is invalid");
return result;
}
bool Feature::isDatum(const App::DocumentObject* feature)
{
return feature->getTypeId().isDerivedFrom(App::Plane::getClassTypeId()) ||
feature->getTypeId().isDerivedFrom(App::Line::getClassTypeId()) ||
feature->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId());
}
gp_Pln Feature::makePlnFromPlane(const App::DocumentObject* obj)
{
const App::Plane* plane = static_cast<const App::Plane*>(obj);
if (plane == NULL)
throw Base::Exception("Feature: Null object");
Base::Rotation rot = plane->Placement.getValue().getRotation();
Base::Vector3d normal(0,0,1);
rot.multVec(normal, normal);
return gp_Pln(gp_Pnt(0,0,0), gp_Dir(normal.x,normal.y,normal.z));
}
TopoDS_Shape Feature::makeShapeFromPlane(const App::DocumentObject* obj)
{
BRepBuilderAPI_MakeFace builder(makePlnFromPlane(obj));
if (!builder.IsDone())
throw Base::Exception("Feature: Could not create shape from base plane");
return builder.Shape();
}
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/common/utils/imageProcs/common_ringId.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef _COMMON_RINGID_H_
#define _COMMON_RINGID_H_
#include <stdint.h>
#include <stddef.h>
////////////////////////////////////////////////////////////////////////////////
// Declare assumptions - Begin
//
// Various data type defs for enums. Serves following purposes:
// - Reduces space since enum defaults to an int type.
// - Enables using these types without the scope operator for
// those enums that are namespaced, e.g. RingID.
// NB! DO NOT CHANGE THESE DEFS W/O EXPLICIT CONSENT FROM
// INFRASTRUCT TEAM. (These defs affect packing assumptions
// of ring structures that go into the image ringSections.)
typedef uint16_t RingId_t; // Type for RingID enum
typedef uint8_t ChipletType_t; // Type for CHIPLET_TYPE enum
typedef uint8_t PpeType_t; // Type for PpeType
typedef uint8_t ChipType_t; // Type for ChipType enum
typedef uint8_t RingType_t; // Type for RingType enum
typedef uint8_t RingVariant_t; // Type for RingVariant enum
typedef uint32_t TorCpltOffset_t; // Type for offset value to chiplet's CMN or INST section
#define UNDEFINED_RING_ID (RingId_t)0xffff
#define INVALID_RING_TYPE (RingType_t)0xff
#define INVALID_CHIPLET_TYPE (ChipletType_t)0xff
#define UNDEFINED_CHIP_TYPE (ChipType_t)0xff
#define MAX_TOR_RING_OFFSET (uint16_t)(256*256-1) // Max val of uint16
#define MAX_RING_NAME_LENGTH (uint8_t)50
#define UNDEFINED_DD_LEVEL (uint8_t)0xff
//
// Declare assumptions - End
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// TOR layout definitions - Begin
//
//
// TOR header field (appears in top of every HW, SBE, CEN, OVRD, etc ring section)
//
typedef struct
{
uint32_t magic;
uint8_t version;
ChipType_t chipType; // Value from ChipType enum
uint8_t ddLevel; // =0xff if MAGIC_HW, >0 all other MAGICs
uint8_t numDdLevels; // >0 if MAGIC_HW, =1 all other MAGICs
uint32_t size; // Size of the TOR ringSection.
} TorHeader_t;
//
// Subsequent TOR fields (listed in order they appear in TOR ringSections)
//
typedef struct
{
uint32_t offset;
uint32_t size;
uint8_t ddLevel;
uint8_t reserved[3];
} TorDdBlock_t;
typedef struct
{
uint32_t offset;
uint32_t size;
} TorPpeBlock_t;
typedef struct
{
TorCpltOffset_t cmnOffset;
TorCpltOffset_t instOffset;
} TorCpltBlock_t;
typedef uint16_t TorRingOffset_t; // Offset value to actual ring
//
// TOR layout definitions - End
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Key TOR constants - Begin
//
#define TOR_VERSION 4
// TOR Magic values for top-level TOR ringSection and sub-ringSections
enum TorMagicNum
{
TOR_MAGIC = (uint32_t)0x544F52 , // "TOR"
TOR_MAGIC_HW = (uint32_t)0x544F5248, // "TORH"
TOR_MAGIC_SBE = (uint32_t)0x544F5242, // "TORB"
TOR_MAGIC_SGPE = (uint32_t)0x544F5247, // "TORG"
TOR_MAGIC_CME = (uint32_t)0x544F524D, // "TORM"
TOR_MAGIC_OVRD = (uint32_t)0x544F5252, // "TORR"
TOR_MAGIC_OVLY = (uint32_t)0x544F524C, // "TORL"
TOR_MAGIC_CEN = (uint32_t)0x544F524E, // "TORN"
};
//
// Key TOR constants - End
///////////////////////////////////////////////////////////////////////////////
//
// Chip types and List to represent p9n, p9c, p9a, cen (centaur)
// NB! There's a matching CHIP_TYPE_LIST definition in common_ringId.C
//
enum ChipType
{
CT_P9N, // ==P9 for now
CT_P9C, // ==P9 for now
CT_P9A,
CT_CEN,
NUM_CHIP_TYPES
};
typedef struct
{
const char* name;
ChipType_t type;
} ChipTypeList_t;
static const ChipTypeList_t CHIP_TYPE_LIST[] =
{
{"p9n", CT_P9N},
{"p9c", CT_P9C},
{"p9a", CT_P9A},
{"cen", CT_CEN},
};
//
// Ring related data structs and types
//
typedef enum RingClass
{
EKB_RING,
EKB_FSM_RING,
EKB_STUMPED_RING,
EKB_CMSK_RING,
EKB_NONFLUSH_RING,
VPD_RING,
CEN_RING,
NUM_RING_CLASSES
} RingClass_t;
//
// General Ring ID list structure
//
typedef struct
{
const char* ringName;
RingId_t ringId;
uint8_t instanceIdMin;
uint8_t instanceIdMax;
RingClass_t ringClass;
uint32_t scanScomAddress;
} GenRingIdList;
// PPE types supported. Note that this enum also reflects the
// order with which they appear in the HW image's .rings section.
enum PpeType
{
PT_SBE = 0x00,
PT_CME = 0x01,
PT_SGPE = 0x02,
NUM_PPE_TYPES = 0x03
};
// Do NOT make changes to the values or order of this enum. Some user
// codes, like xip_tool, make assumptions about range and order.
enum RingVariant
{
BASE = 0x00,
CC = 0x01,
RL = 0x02,
OVERRIDE = 0x03,
OVERLAY = 0x04,
NUM_RING_VARIANTS = 0x05,
NOT_VALID = 0xff
};
extern const char* ppeTypeName[];
extern const char* ringVariantName[];
typedef struct
{
RingVariant_t variant[3];
} RingVariantOrder;
enum RingType
{
COMMON_RING = 0,
INSTANCE_RING = 1,
ALLRING = 2
};
typedef struct
{
// This is the chiplet-ID of the first instance of the Chiplet
uint8_t iv_base_chiplet_number;
// The no.of common rings for the Chiplet
uint8_t iv_num_common_rings;
// The no.of instance rings for the Chiplet (w/different ringId values)
uint8_t iv_num_instance_rings;
// The no.of instance rings for the Chiplet (w/different ringId values
// AND different scanAddress values)
uint8_t iv_num_instance_rings_scan_addrs;
// The no.of ring variants
uint8_t iv_num_ring_variants;
} ChipletData_t;
// This is used to Set (Mark) the left-most bit
#define INSTANCE_RING_MARK (uint8_t)0x80
//
// This is used to Set (Mark) the left-most bit
#define INSTANCE_RING_MASK (uint8_t)0x7F
// This is used to mark an invalid ring in the ring properties list
#define INVALID_RING_OFFSET (uint8_t)0xFF
// This structure is needed for mapping a RingID to it's corresponding name.
// The names will be used by the build scripts when generating the TOR.
typedef struct
{
uint8_t iv_torOffSet;
#ifndef __PPE__
char iv_name[50];
#endif
ChipletType_t iv_type;
} RingProperties_t;
//
// Universal infrastructure error codes
//
#define INFRASTRUCT_RC_SUCCESS 0
#define INFRASTRUCT_RC_FAILURE 1
#define INFRASTRUCT_RC_CODE_BUG 2
#define INFRASTRUCT_RC_USER_ERROR 3
#define INFRASTRUCT_RC_NOOF_CODES 5 // Do not use as RC code
//
// TOR specific error codes
//
#define TOR_SUCCESS INFRASTRUCT_RC_SUCCESS
#define TOR_FAILURE INFRASTRUCT_RC_FAILURE
#define TOR_CODE_BUG INFRASTRUCT_RC_CODE_BUG
#define TOR_USER_ERROR INFRASTRUCT_RC_USER_ERROR
#define TOR_INVALID_MAGIC_NUMBER INFRASTRUCT_RC_NOOF_CODES + 1
#define TOR_INVALID_CHIPTYPE INFRASTRUCT_RC_NOOF_CODES + 3
#define TOR_INVALID_CHIPLET INFRASTRUCT_RC_NOOF_CODES + 4
#define TOR_INVALID_VARIANT INFRASTRUCT_RC_NOOF_CODES + 5
#define TOR_INVALID_RING_ID INFRASTRUCT_RC_NOOF_CODES + 6
#define TOR_INVALID_INSTANCE_ID INFRASTRUCT_RC_NOOF_CODES + 7
#define TOR_INVALID_RING_BLOCK_TYPE INFRASTRUCT_RC_NOOF_CODES + 8
#define TOR_UNSUPPORTED_RING_SECTION INFRASTRUCT_RC_NOOF_CODES + 9
#define TOR_RING_NOT_FOUND INFRASTRUCT_RC_NOOF_CODES + 10
#define TOR_AMBIGUOUS_API_PARMS INFRASTRUCT_RC_NOOF_CODES + 11
#define TOR_SECTION_NOT_FOUND INFRASTRUCT_RC_NOOF_CODES + 12
#define TOR_DD_LEVEL_NOT_FOUND INFRASTRUCT_RC_NOOF_CODES + 13
#define TOR_OP_BUFFER_INVALID INFRASTRUCT_RC_NOOF_CODES + 14
#define TOR_OP_BUFFER_SIZE_EXCEEDED INFRASTRUCT_RC_NOOF_CODES + 15
#define TOR_IMAGE_DOES_NOT_SUPPORT_CME INFRASTRUCT_RC_NOOF_CODES + 16
#define TOR_IMAGE_DOES_NOT_SUPPORT_SGPE INFRASTRUCT_RC_NOOF_CODES + 17
#define TOR_IMAGE_DOES_NOT_SUPPORT_DD_LEVEL INFRASTRUCT_RC_NOOF_CODES + 18
#define TOR_IMAGE_DOES_NOT_SUPPORT_PPE_LEVEL INFRASTRUCT_RC_NOOF_CODES + 19
#define TOR_RING_AVAILABLE_IN_RINGSECTION INFRASTRUCT_RC_NOOF_CODES + 20
#define TOR_BUFFER_TOO_SMALL INFRASTRUCT_RC_NOOF_CODES + 21
#define TOR_TOO_MANY_DD_LEVELS INFRASTRUCT_RC_NOOF_CODES + 22
#define TOR_OFFSET_TOO_BIG INFRASTRUCT_RC_NOOF_CODES + 23
int ringid_get_noof_chiplets( ChipType_t i_chipType,
uint32_t i_torMagic,
uint8_t* o_numChiplets );
int ringid_get_properties( ChipType_t i_chipType,
uint32_t i_torMagic,
ChipletType_t i_chiplet,
ChipletData_t** o_chipletData,
GenRingIdList** o_ringIdListCommon,
GenRingIdList** o_ringIdListInstance,
RingVariantOrder** o_ringVariantOrder,
RingProperties_t** o_ringProps,
uint8_t* o_numVariants );
#endif // _COMMON_RINGID_H_
<commit_msg>Revert "Adding p9a support."<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/common/utils/imageProcs/common_ringId.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef _COMMON_RINGID_H_
#define _COMMON_RINGID_H_
#include <stdint.h>
#include <stddef.h>
////////////////////////////////////////////////////////////////////////////////
// Declare assumptions - Begin
//
// Various data type defs for enums. Serves following purposes:
// - Reduces space since enum defaults to an int type.
// - Enables using these types without the scope operator for
// those enums that are namespaced, e.g. RingID.
// NB! DO NOT CHANGE THESE DEFS W/O EXPLICIT CONSENT FROM
// INFRASTRUCT TEAM. (These defs affect packing assumptions
// of ring structures that go into the image ringSections.)
typedef uint16_t RingId_t; // Type for RingID enum
typedef uint8_t ChipletType_t; // Type for CHIPLET_TYPE enum
typedef uint8_t PpeType_t; // Type for PpeType
typedef uint8_t ChipType_t; // Type for ChipType enum
typedef uint8_t RingType_t; // Type for RingType enum
typedef uint8_t RingVariant_t; // Type for RingVariant enum
typedef uint32_t TorCpltOffset_t; // Type for offset value to chiplet's CMN or INST section
#define UNDEFINED_RING_ID (RingId_t)0xffff
#define INVALID_RING_TYPE (RingType_t)0xff
#define INVALID_CHIPLET_TYPE (ChipletType_t)0xff
#define UNDEFINED_CHIP_TYPE (ChipType_t)0xff
#define MAX_TOR_RING_OFFSET (uint16_t)(256*256-1) // Max val of uint16
#define MAX_RING_NAME_LENGTH (uint8_t)50
#define UNDEFINED_DD_LEVEL (uint8_t)0xff
//
// Declare assumptions - End
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// TOR layout definitions - Begin
//
//
// TOR header field (appears in top of every HW, SBE, CEN, OVRD, etc ring section)
//
typedef struct
{
uint32_t magic;
uint8_t version;
ChipType_t chipType; // Value from ChipType enum
uint8_t ddLevel; // =0xff if MAGIC_HW, >0 all other MAGICs
uint8_t numDdLevels; // >0 if MAGIC_HW, =1 all other MAGICs
uint32_t size; // Size of the TOR ringSection.
} TorHeader_t;
//
// Subsequent TOR fields (listed in order they appear in TOR ringSections)
//
typedef struct
{
uint32_t offset;
uint32_t size;
uint8_t ddLevel;
uint8_t reserved[3];
} TorDdBlock_t;
typedef struct
{
uint32_t offset;
uint32_t size;
} TorPpeBlock_t;
typedef struct
{
TorCpltOffset_t cmnOffset;
TorCpltOffset_t instOffset;
} TorCpltBlock_t;
typedef uint16_t TorRingOffset_t; // Offset value to actual ring
//
// TOR layout definitions - End
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Key TOR constants - Begin
//
#define TOR_VERSION 4
// TOR Magic values for top-level TOR ringSection and sub-ringSections
enum TorMagicNum
{
TOR_MAGIC = (uint32_t)0x544F52 , // "TOR"
TOR_MAGIC_HW = (uint32_t)0x544F5248, // "TORH"
TOR_MAGIC_SBE = (uint32_t)0x544F5242, // "TORB"
TOR_MAGIC_SGPE = (uint32_t)0x544F5247, // "TORG"
TOR_MAGIC_CME = (uint32_t)0x544F524D, // "TORM"
TOR_MAGIC_OVRD = (uint32_t)0x544F5252, // "TORR"
TOR_MAGIC_OVLY = (uint32_t)0x544F524C, // "TORL"
TOR_MAGIC_CEN = (uint32_t)0x544F524E, // "TORN"
};
//
// Key TOR constants - End
///////////////////////////////////////////////////////////////////////////////
//
// Chip types and List to represent p9n, p9c, cen (centaur)
// NB! There's a matching CHIP_TYPE_LIST definition in common_ringId.C
//
enum ChipType
{
CT_P9N, // ==P9 for now
CT_P9C, // ==P9 for now
CT_CEN,
NUM_CHIP_TYPES
};
typedef struct
{
const char* name;
ChipType_t type;
} ChipTypeList_t;
static const ChipTypeList_t CHIP_TYPE_LIST[] =
{
{"p9n", CT_P9N},
{"p9c", CT_P9C},
{"cen", CT_CEN},
};
//
// Ring related data structs and types
//
typedef enum RingClass
{
EKB_RING,
EKB_FSM_RING,
EKB_STUMPED_RING,
EKB_CMSK_RING,
EKB_NONFLUSH_RING,
VPD_RING,
CEN_RING,
NUM_RING_CLASSES
} RingClass_t;
//
// General Ring ID list structure
//
typedef struct
{
const char* ringName;
RingId_t ringId;
uint8_t instanceIdMin;
uint8_t instanceIdMax;
RingClass_t ringClass;
uint32_t scanScomAddress;
} GenRingIdList;
// PPE types supported. Note that this enum also reflects the
// order with which they appear in the HW image's .rings section.
enum PpeType
{
PT_SBE = 0x00,
PT_CME = 0x01,
PT_SGPE = 0x02,
NUM_PPE_TYPES = 0x03
};
// Do NOT make changes to the values or order of this enum. Some user
// codes, like xip_tool, make assumptions about range and order.
enum RingVariant
{
BASE = 0x00,
CC = 0x01,
RL = 0x02,
OVERRIDE = 0x03,
OVERLAY = 0x04,
NUM_RING_VARIANTS = 0x05,
NOT_VALID = 0xff
};
extern const char* ppeTypeName[];
extern const char* ringVariantName[];
typedef struct
{
RingVariant_t variant[3];
} RingVariantOrder;
enum RingType
{
COMMON_RING = 0,
INSTANCE_RING = 1,
ALLRING = 2
};
typedef struct
{
// This is the chiplet-ID of the first instance of the Chiplet
uint8_t iv_base_chiplet_number;
// The no.of common rings for the Chiplet
uint8_t iv_num_common_rings;
// The no.of instance rings for the Chiplet (w/different ringId values)
uint8_t iv_num_instance_rings;
// The no.of instance rings for the Chiplet (w/different ringId values
// AND different scanAddress values)
uint8_t iv_num_instance_rings_scan_addrs;
// The no.of ring variants
uint8_t iv_num_ring_variants;
} ChipletData_t;
// This is used to Set (Mark) the left-most bit
#define INSTANCE_RING_MARK (uint8_t)0x80
//
// This is used to Set (Mark) the left-most bit
#define INSTANCE_RING_MASK (uint8_t)0x7F
// This is used to mark an invalid ring in the ring properties list
#define INVALID_RING_OFFSET (uint8_t)0xFF
// This structure is needed for mapping a RingID to it's corresponding name.
// The names will be used by the build scripts when generating the TOR.
typedef struct
{
uint8_t iv_torOffSet;
#ifndef __PPE__
char iv_name[50];
#endif
ChipletType_t iv_type;
} RingProperties_t;
//
// Universal infrastructure error codes
//
#define INFRASTRUCT_RC_SUCCESS 0
#define INFRASTRUCT_RC_FAILURE 1
#define INFRASTRUCT_RC_CODE_BUG 2
#define INFRASTRUCT_RC_USER_ERROR 3
#define INFRASTRUCT_RC_NOOF_CODES 5 // Do not use as RC code
//
// TOR specific error codes
//
#define TOR_SUCCESS INFRASTRUCT_RC_SUCCESS
#define TOR_FAILURE INFRASTRUCT_RC_FAILURE
#define TOR_CODE_BUG INFRASTRUCT_RC_CODE_BUG
#define TOR_USER_ERROR INFRASTRUCT_RC_USER_ERROR
#define TOR_INVALID_MAGIC_NUMBER INFRASTRUCT_RC_NOOF_CODES + 1
#define TOR_INVALID_CHIPTYPE INFRASTRUCT_RC_NOOF_CODES + 3
#define TOR_INVALID_CHIPLET INFRASTRUCT_RC_NOOF_CODES + 4
#define TOR_INVALID_VARIANT INFRASTRUCT_RC_NOOF_CODES + 5
#define TOR_INVALID_RING_ID INFRASTRUCT_RC_NOOF_CODES + 6
#define TOR_INVALID_INSTANCE_ID INFRASTRUCT_RC_NOOF_CODES + 7
#define TOR_INVALID_RING_BLOCK_TYPE INFRASTRUCT_RC_NOOF_CODES + 8
#define TOR_UNSUPPORTED_RING_SECTION INFRASTRUCT_RC_NOOF_CODES + 9
#define TOR_RING_NOT_FOUND INFRASTRUCT_RC_NOOF_CODES + 10
#define TOR_AMBIGUOUS_API_PARMS INFRASTRUCT_RC_NOOF_CODES + 11
#define TOR_SECTION_NOT_FOUND INFRASTRUCT_RC_NOOF_CODES + 12
#define TOR_DD_LEVEL_NOT_FOUND INFRASTRUCT_RC_NOOF_CODES + 13
#define TOR_OP_BUFFER_INVALID INFRASTRUCT_RC_NOOF_CODES + 14
#define TOR_OP_BUFFER_SIZE_EXCEEDED INFRASTRUCT_RC_NOOF_CODES + 15
#define TOR_IMAGE_DOES_NOT_SUPPORT_CME INFRASTRUCT_RC_NOOF_CODES + 16
#define TOR_IMAGE_DOES_NOT_SUPPORT_SGPE INFRASTRUCT_RC_NOOF_CODES + 17
#define TOR_IMAGE_DOES_NOT_SUPPORT_DD_LEVEL INFRASTRUCT_RC_NOOF_CODES + 18
#define TOR_IMAGE_DOES_NOT_SUPPORT_PPE_LEVEL INFRASTRUCT_RC_NOOF_CODES + 19
#define TOR_RING_AVAILABLE_IN_RINGSECTION INFRASTRUCT_RC_NOOF_CODES + 20
#define TOR_BUFFER_TOO_SMALL INFRASTRUCT_RC_NOOF_CODES + 21
#define TOR_TOO_MANY_DD_LEVELS INFRASTRUCT_RC_NOOF_CODES + 22
#define TOR_OFFSET_TOO_BIG INFRASTRUCT_RC_NOOF_CODES + 23
int ringid_get_noof_chiplets( ChipType_t i_chipType,
uint32_t i_torMagic,
uint8_t* o_numChiplets );
int ringid_get_properties( ChipType_t i_chipType,
uint32_t i_torMagic,
ChipletType_t i_chiplet,
ChipletData_t** o_chipletData,
GenRingIdList** o_ringIdListCommon,
GenRingIdList** o_ringIdListInstance,
RingVariantOrder** o_ringVariantOrder,
RingProperties_t** o_ringProps,
uint8_t* o_numVariants );
#endif // _COMMON_RINGID_H_
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_scrub.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_scrub.C
/// @brief Begin background scrub
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mss_scrub.H>
#include <lib/dimm/rank.H>
#include <lib/mcbist/address.H>
#include <lib/mcbist/mcbist.H>
#include <lib/mcbist/patterns.H>
#include <lib/mcbist/memdiags.H>
#include <lib/mcbist/sim.H>
#include <lib/utils/count_dimm.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_SYSTEM;
using fapi2::FAPI2_RC_SUCCESS;
///
/// @brief Begin background scrub
/// @param[in] i_target MCBIST
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_scrub( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
FAPI_INF("Start mss scrub");
// If we're running in the simulator, we want to only touch the addresses which training touched
uint8_t is_sim = 0;
// If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
// attributes for the PHY, etc.
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping scrub for %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_IS_SIMULATION, fapi2::Target<TARGET_TYPE_SYSTEM>(), is_sim) );
if (is_sim)
{
// Use some sort of pattern in sim in case the verification folks need to look for something
// TK. Need a verification pattern. This is a not-good pattern for verification ... We don't really
// have a good pattern for verification defined.
FAPI_INF("running mss sim init in place of scrub");
return mss::mcbist::sim::sf_init(i_target, mss::mcbist::PATTERN_2);
}
// TK do we want these to be arguments to the wrapper?
return memdiags::background_scrub(i_target, mss::mcbist::stop_conditions(),
mss::mcbist::speed::LUDICROUS, mss::mcbist::address());
fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>Change p9_mss_scrub to do a sf_write/sf_read on hardware<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_scrub.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_scrub.C
/// @brief Begin background scrub
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mss_scrub.H>
#include <lib/dimm/rank.H>
#include <lib/mcbist/address.H>
#include <lib/mcbist/mcbist.H>
#include <lib/mcbist/patterns.H>
#include <lib/mcbist/memdiags.H>
#include <lib/mcbist/sim.H>
#include <lib/utils/count_dimm.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_SYSTEM;
using fapi2::FAPI2_RC_SUCCESS;
///
/// @brief Begin background scrub
/// @param[in] i_target MCBIST
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_scrub( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
FAPI_INF("Start mss scrub");
// If we're running in the simulator, we want to only touch the addresses which training touched
uint8_t is_sim = 0;
// If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
// attributes for the PHY, etc.
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping scrub for %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_IS_SIMULATION, fapi2::Target<TARGET_TYPE_SYSTEM>(), is_sim) );
if (is_sim)
{
// Use some sort of pattern in sim in case the verification folks need to look for something
// TK. Need a verification pattern. This is a not-good pattern for verification ... We don't really
// have a good pattern for verification defined.
FAPI_INF("running mss sim init in place of scrub");
return mss::mcbist::sim::sf_init(i_target, mss::mcbist::PATTERN_0);
}
// In Cronus on hardware (which is how we got here - f/w doesn't call this) we want
// to call sf_init (0's) and then a sf_read.
// TK we need to check FIR given the way this is right now, we should adjust with better stop
// conditions when we learn more about what we want to find in the lab
FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) );
return memdiags::sf_read(i_target, mss::mcbist::stop_conditions(), mss::mcbist::end_boundary::STOP_AFTER_ADDRESS);
fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_attr_update.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_attr_update.C
///
/// @brief Stub HWP for FW to override attributes programmatically
///
//
// *HWP HW Owner : Michael Dye <[email protected]>
// *HWP FW Owner : Thi N. Tran <[email protected]>
// *HWP Team : Nest
// *HWP Level : 1
// *HWP Consumed by : HB
//
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "p9_attr_update.H"
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
fapi2::ReturnCode
p9_attr_update(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
FAPI_DBG("Entering ...");
FAPI_DBG("Exiting ...");
//fapi_try_exit:
return fapi2::current_err;
}
<commit_msg>Checking in change of HWP level from 1 to 2<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_attr_update.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_attr_update.C
///
/// @brief Stub HWP for FW to override attributes programmatically
///
//
// *HWP HW Owner : Michael Dye <[email protected]>
// *HWP FW Owner : Thi N. Tran <[email protected]>
// *HWP Team : Nest
// *HWP Level : 2
// *HWP Consumed by : HB
//
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "p9_attr_update.H"
//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------
fapi2::ReturnCode
p9_attr_update(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
FAPI_DBG("Entering ...");
FAPI_DBG("Exiting ...");
//fapi_try_exit:
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>#include "ImGuiEntitySelectorSystem.hpp"
#include "data/ImGuiComponent.hpp"
#include "data/ImGuiToolComponent.hpp"
#include "data/NameComponent.hpp"
#include "data/SelectedComponent.hpp"
#include "helpers/typeHelper.hpp"
#include "helpers/sortHelper.hpp"
#include "meta/Has.hpp"
#include "meta/MatchString.hpp"
#include "helpers/imguiHelper.hpp"
#include "imgui.h"
#include "string.hpp"
#include "to_string.hpp"
namespace kengine {
#pragma region declarations
static bool matches(const Entity & e, const char * str, EntityManager & em);
#pragma endregion
EntityCreatorFunctor<64> ImGuiEntitySelectorSystem(EntityManager & em) {
return [&](Entity & e) {
e += NameComponent{ "Entity selector" };
auto & tool = e.attach<ImGuiToolComponent>();
tool.enabled = true;
e += ImGuiComponent([&] {
if (!tool.enabled)
return;
if (ImGui::Begin("Entity selector", &tool.enabled)) {
static char nameSearch[1024];
ImGui::InputText("Search", nameSearch, sizeof(nameSearch));
ImGui::SameLine();
if (ImGui::Button("New"))
em += [](Entity & e) { e += SelectedComponent{}; };
ImGui::Separator();
ImGui::BeginChild("child");
for (auto & e : em.getEntities())
if (matches(e, nameSearch, em)) {
if (e.has<SelectedComponent>())
e.detach<SelectedComponent>();
else
e.attach<SelectedComponent>();
}
ImGui::EndChild();
}
ImGui::End();
});
};
}
static bool matches(const Entity & e, const char * str, EntityManager & em) {
putils::string<1024> displayText("[%d]", e.id);
if (strlen(str) != 0) {
displayText += " Matches in ";
bool matches = false;
if (str[0] >= '0' && str[0] <= '9' && putils::parse<Entity::ID>(str) == e.id) {
matches = true;
displayText += "ID";
}
else {
const auto types = sortHelper::getNameSortedEntities<KENGINE_COMPONENT_COUNT,
meta::Has, meta::MatchString
>(em);
for (const auto & [_, type, has, matchFunc] : types) {
if (!has->call(e) || !matchFunc->call(e, str))
continue;
if (displayText.size() + type->name.size() + 2 < decltype(displayText)::max_size) {
if (matches) // Isn't the first time
displayText += ", ";
displayText += type->name;
}
matches = true;
}
}
if (!matches)
return false;
}
bool ret = false;
if (ImGui::Button(putils::string<64>("Select##") + e.id))
ret = true;
ImGui::SameLine();
if (ImGui::Button(putils::string<64>("Remove##") + e.id)) {
em.removeEntity(e);
return false;
}
if (ImGui::TreeNode(displayText + "##" + e.id)) {
imguiHelper::displayEntity(em, e);
ImGui::TreePop();
}
return ret;
}
}<commit_msg>improve imgui entity selector layout<commit_after>#include "ImGuiEntitySelectorSystem.hpp"
#include "data/ImGuiComponent.hpp"
#include "data/ImGuiToolComponent.hpp"
#include "data/NameComponent.hpp"
#include "data/SelectedComponent.hpp"
#include "helpers/typeHelper.hpp"
#include "helpers/sortHelper.hpp"
#include "meta/Has.hpp"
#include "meta/MatchString.hpp"
#include "helpers/imguiHelper.hpp"
#include "imgui.h"
#include "string.hpp"
#include "to_string.hpp"
namespace kengine {
#pragma region declarations
static bool matches(const Entity & e, const char * str, EntityManager & em);
#pragma endregion
EntityCreatorFunctor<64> ImGuiEntitySelectorSystem(EntityManager & em) {
return [&](Entity & e) {
e += NameComponent{ "Entity selector" };
auto & tool = e.attach<ImGuiToolComponent>();
tool.enabled = true;
e += ImGuiComponent([&] {
if (!tool.enabled)
return;
if (ImGui::Begin("Entity selector", &tool.enabled)) {
static char nameSearch[1024];
ImGui::InputText("Search", nameSearch, sizeof(nameSearch));
ImGui::Separator();
ImGui::BeginChild("child");
for (auto & e : em.getEntities())
if (matches(e, nameSearch, em)) {
if (e.has<SelectedComponent>())
e.detach<SelectedComponent>();
else
e.attach<SelectedComponent>();
}
ImGui::EndChild();
}
ImGui::End();
});
};
}
static bool matches(const Entity & e, const char * str, EntityManager & em) {
putils::string<1024> displayText("[%d]", e.id);;
if (e.has<NameComponent>()) {
displayText += " ";
displayText += e.get<NameComponent>().name;
}
if (strlen(str) != 0) {
displayText += " -- ";
bool matches = false;
if (str[0] >= '0' && str[0] <= '9' && putils::parse<Entity::ID>(str) == e.id) {
matches = true;
displayText += "ID";
}
else {
const auto types = sortHelper::getNameSortedEntities<KENGINE_COMPONENT_COUNT,
meta::Has, meta::MatchString
>(em);
for (const auto & [_, type, has, matchFunc] : types) {
if (!has->call(e) || !matchFunc->call(e, str))
continue;
if (displayText.size() + type->name.size() + 2 < decltype(displayText)::max_size) {
if (matches) // Isn't the first time
displayText += ", ";
displayText += type->name;
}
matches = true;
}
}
if (!matches)
return false;
}
bool ret = false;
const auto openTreeNode = ImGui::TreeNode(displayText + "##" + e.id);
if (ImGui::BeginPopupContextItem()) {
if (ImGui::MenuItem("Select"))
ret = true;
if (ImGui::MenuItem("Remove")) {
em.removeEntity(e);
return false;
}
ImGui::EndPopup();
}
if (openTreeNode) {
imguiHelper::displayEntity(em, e);
ImGui::TreePop();
}
return ret;
}
}<|endoftext|> |
<commit_before>// Copyright 2020 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "rcutils/allocator.h"
#include "rosidl_typesupport_cpp/message_type_support.hpp"
#include "rmw/rmw.h"
#include "rmw/error_handling.h"
#include "test_msgs/msg/basic_types.h"
#include "test_msgs/msg/basic_types.hpp"
#include "./allocator_testing_utils.h"
#ifdef RMW_IMPLEMENTATION
# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX
# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)
#else
# define CLASSNAME(NAME, SUFFIX) NAME
#endif
class CLASSNAME (TestSerializeDeserialize, RMW_IMPLEMENTATION) : public ::testing::Test
{
};
TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), serialize_with_bad_arguments) {
const rosidl_message_type_support_t * ts{
ROSIDL_GET_MSG_TYPE_SUPPORT(test_msgs, msg, BasicTypes)};
test_msgs__msg__BasicTypes input_message{};
ASSERT_TRUE(test_msgs__msg__BasicTypes__init(&input_message));
rcutils_allocator_t failing_allocator = get_failing_allocator();
rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message();
ASSERT_EQ(
RMW_RET_OK, rmw_serialized_message_init(
&serialized_message, 0lu, &failing_allocator)) << rmw_get_error_string().str;
EXPECT_NE(RMW_RET_OK, rmw_serialize(&input_message, ts, &serialized_message));
rmw_reset_error();
EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) <<
rmw_get_error_string().str;
}
TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), clean_round_trip_for_c_message) {
const rosidl_message_type_support_t * ts{
ROSIDL_GET_MSG_TYPE_SUPPORT(test_msgs, msg, BasicTypes)};
test_msgs__msg__BasicTypes input_message{};
test_msgs__msg__BasicTypes output_message{};
ASSERT_TRUE(test_msgs__msg__BasicTypes__init(&input_message));
ASSERT_TRUE(test_msgs__msg__BasicTypes__init(&output_message));
rcutils_allocator_t default_allocator = rcutils_get_default_allocator();
rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message();
ASSERT_EQ(
RMW_RET_OK, rmw_serialized_message_init(
&serialized_message, 0lu, &default_allocator)) << rmw_get_error_string().str;
// Make input_message not equal to output_message.
input_message.bool_value = !output_message.bool_value;
input_message.int16_value = output_message.int16_value - 1;
input_message.uint32_value = output_message.uint32_value + 1000000;
rmw_ret_t ret = rmw_serialize(&input_message, ts, &serialized_message);
EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
EXPECT_NE(nullptr, serialized_message.buffer);
EXPECT_GT(serialized_message.buffer_length, 0lu);
ret = rmw_deserialize(&serialized_message, ts, &output_message);
EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
EXPECT_EQ(input_message.bool_value, output_message.bool_value);
EXPECT_EQ(input_message.int16_value, output_message.int16_value);
EXPECT_EQ(input_message.uint32_value, output_message.uint32_value);
EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) <<
rmw_get_error_string().str;
}
TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), clean_round_trip_for_cpp_message) {
const rosidl_message_type_support_t * ts =
rosidl_typesupport_cpp::get_message_type_support_handle<test_msgs::msg::BasicTypes>();
test_msgs::msg::BasicTypes input_message{};
test_msgs::msg::BasicTypes output_message{};
rcutils_allocator_t default_allocator = rcutils_get_default_allocator();
rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message();
ASSERT_EQ(
RMW_RET_OK, rmw_serialized_message_init(
&serialized_message, 0lu, &default_allocator)) << rmw_get_error_string().str;
// Make input_message not equal to output_message.
input_message.bool_value = !output_message.bool_value;
input_message.int16_value = output_message.int16_value - 1;
input_message.uint32_value = output_message.uint32_value + 1000000;
rmw_ret_t ret = rmw_serialize(&input_message, ts, &serialized_message);
EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
EXPECT_NE(nullptr, serialized_message.buffer);
EXPECT_GT(serialized_message.buffer_length, 0lu);
ret = rmw_deserialize(&serialized_message, ts, &output_message);
EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
EXPECT_EQ(input_message, output_message);
EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) <<
rmw_get_error_string().str;
}
<commit_msg>Add rmw_get_serialization_format() smoke test. (#133)<commit_after>// Copyright 2020 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "rcutils/allocator.h"
#include "rosidl_typesupport_cpp/message_type_support.hpp"
#include "rmw/rmw.h"
#include "rmw/error_handling.h"
#include "test_msgs/msg/basic_types.h"
#include "test_msgs/msg/basic_types.hpp"
#include "./allocator_testing_utils.h"
#ifdef RMW_IMPLEMENTATION
# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX
# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)
#else
# define CLASSNAME(NAME, SUFFIX) NAME
#endif
class CLASSNAME (TestSerializeDeserialize, RMW_IMPLEMENTATION) : public ::testing::Test
{
};
TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), get_serialization_format) {
const char * serialization_format = rmw_get_serialization_format();
EXPECT_NE(nullptr, serialization_format);
EXPECT_STREQ(serialization_format, rmw_get_serialization_format());
}
TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), serialize_with_bad_arguments) {
const rosidl_message_type_support_t * ts{
ROSIDL_GET_MSG_TYPE_SUPPORT(test_msgs, msg, BasicTypes)};
test_msgs__msg__BasicTypes input_message{};
ASSERT_TRUE(test_msgs__msg__BasicTypes__init(&input_message));
rcutils_allocator_t failing_allocator = get_failing_allocator();
rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message();
ASSERT_EQ(
RMW_RET_OK, rmw_serialized_message_init(
&serialized_message, 0lu, &failing_allocator)) << rmw_get_error_string().str;
EXPECT_NE(RMW_RET_OK, rmw_serialize(&input_message, ts, &serialized_message));
rmw_reset_error();
EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) <<
rmw_get_error_string().str;
}
TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), clean_round_trip_for_c_message) {
const rosidl_message_type_support_t * ts{
ROSIDL_GET_MSG_TYPE_SUPPORT(test_msgs, msg, BasicTypes)};
test_msgs__msg__BasicTypes input_message{};
test_msgs__msg__BasicTypes output_message{};
ASSERT_TRUE(test_msgs__msg__BasicTypes__init(&input_message));
ASSERT_TRUE(test_msgs__msg__BasicTypes__init(&output_message));
rcutils_allocator_t default_allocator = rcutils_get_default_allocator();
rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message();
ASSERT_EQ(
RMW_RET_OK, rmw_serialized_message_init(
&serialized_message, 0lu, &default_allocator)) << rmw_get_error_string().str;
// Make input_message not equal to output_message.
input_message.bool_value = !output_message.bool_value;
input_message.int16_value = output_message.int16_value - 1;
input_message.uint32_value = output_message.uint32_value + 1000000;
rmw_ret_t ret = rmw_serialize(&input_message, ts, &serialized_message);
EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
EXPECT_NE(nullptr, serialized_message.buffer);
EXPECT_GT(serialized_message.buffer_length, 0lu);
ret = rmw_deserialize(&serialized_message, ts, &output_message);
EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
EXPECT_EQ(input_message.bool_value, output_message.bool_value);
EXPECT_EQ(input_message.int16_value, output_message.int16_value);
EXPECT_EQ(input_message.uint32_value, output_message.uint32_value);
EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) <<
rmw_get_error_string().str;
}
TEST_F(CLASSNAME(TestSerializeDeserialize, RMW_IMPLEMENTATION), clean_round_trip_for_cpp_message) {
const rosidl_message_type_support_t * ts =
rosidl_typesupport_cpp::get_message_type_support_handle<test_msgs::msg::BasicTypes>();
test_msgs::msg::BasicTypes input_message{};
test_msgs::msg::BasicTypes output_message{};
rcutils_allocator_t default_allocator = rcutils_get_default_allocator();
rmw_serialized_message_t serialized_message = rmw_get_zero_initialized_serialized_message();
ASSERT_EQ(
RMW_RET_OK, rmw_serialized_message_init(
&serialized_message, 0lu, &default_allocator)) << rmw_get_error_string().str;
// Make input_message not equal to output_message.
input_message.bool_value = !output_message.bool_value;
input_message.int16_value = output_message.int16_value - 1;
input_message.uint32_value = output_message.uint32_value + 1000000;
rmw_ret_t ret = rmw_serialize(&input_message, ts, &serialized_message);
EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
EXPECT_NE(nullptr, serialized_message.buffer);
EXPECT_GT(serialized_message.buffer_length, 0lu);
ret = rmw_deserialize(&serialized_message, ts, &output_message);
EXPECT_EQ(RMW_RET_OK, ret) << rmw_get_error_string().str;
EXPECT_EQ(input_message, output_message);
EXPECT_EQ(RMW_RET_OK, rmw_serialized_message_fini(&serialized_message)) <<
rmw_get_error_string().str;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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.
****************************************************************************/
#ifndef INCLUDED_LIBLASREADER_HPP
#define INCLUDED_LIBLASREADER_HPP
#include "libpc/Reader.hpp"
#include <iostream>
#include "header.hpp"
// fwd decls
namespace liblas
{
class Reader;
enum PointFormatName;
}
namespace libpc
{
class LIBPC_DLL LiblasReader : public Reader
{
public:
LiblasReader(std::istream&);
~LiblasReader();
virtual boost::uint32_t readPoints(PointData&);
// default is to reset() and then read N points manually
// override this if you can
virtual void seekToPoint(boost::uint64_t pointNum);
// default just resets the point index
virtual void reset();
const LiblasHeader& getLiblasHeader() const;
private:
LiblasHeader& getLiblasHeader();
void setLiblasHeader(const LiblasHeader&);
void processExternalHeader();
void registerFields();
std::istream& m_istream;
liblas::Reader *m_externalReader;
// LAS header properties of interest to us
boost::uint8_t m_versionMajor;
boost::uint8_t m_versionMinor;
double m_scaleX;
double m_scaleY;
double m_scaleZ;
double m_offsetX;
double m_offsetY;
double m_offsetZ;
bool m_isCompressed;
liblas::PointFormatName m_pointFormat;
bool m_hasTimeData;
bool m_hasColorData;
bool m_hasWaveData;
LiblasReader& operator=(const LiblasReader&); // not implemented
LiblasReader(const LiblasReader&); // not implemented
};
} // namespace libpc
#endif
<commit_msg>you can't forward declare enums<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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.
****************************************************************************/
#ifndef INCLUDED_LIBLASREADER_HPP
#define INCLUDED_LIBLASREADER_HPP
#include "libpc/Reader.hpp"
#include <iostream>
#include "header.hpp"
#include <liblas/version.hpp>
// fwd decls
namespace liblas
{
class Reader;
// enum PointFormatName;
}
namespace libpc
{
class LIBPC_DLL LiblasReader : public Reader
{
public:
LiblasReader(std::istream&);
~LiblasReader();
virtual boost::uint32_t readPoints(PointData&);
// default is to reset() and then read N points manually
// override this if you can
virtual void seekToPoint(boost::uint64_t pointNum);
// default just resets the point index
virtual void reset();
const LiblasHeader& getLiblasHeader() const;
private:
LiblasHeader& getLiblasHeader();
void setLiblasHeader(const LiblasHeader&);
void processExternalHeader();
void registerFields();
std::istream& m_istream;
liblas::Reader *m_externalReader;
// LAS header properties of interest to us
boost::uint8_t m_versionMajor;
boost::uint8_t m_versionMinor;
double m_scaleX;
double m_scaleY;
double m_scaleZ;
double m_offsetX;
double m_offsetY;
double m_offsetZ;
bool m_isCompressed;
liblas::PointFormatName m_pointFormat;
bool m_hasTimeData;
bool m_hasColorData;
bool m_hasWaveData;
LiblasReader& operator=(const LiblasReader&); // not implemented
LiblasReader(const LiblasReader&); // not implemented
};
} // namespace libpc
#endif
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS warnings01 (1.3.30); FILE MERGED 2006/01/25 20:57:58 sb 1.3.30.4: RESYNC: (1.3-1.5); FILE MERGED 2005/12/22 11:44:53 fs 1.3.30.3: #i57457# warning-free code 2005/11/21 10:07:53 fs 1.3.30.2: #i57457# warning-free code on unx* 2005/11/07 14:43:49 fs 1.3.30.1: #i57457# warning-free code<commit_after><|endoftext|> |
<commit_before>/* Copyright 2017 Istio Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/common/enum_to_int.h"
#include "common/common/logger.h"
#include "envoy/network/connection.h"
#include "envoy/network/filter.h"
#include "envoy/registry/registry.h"
#include "envoy/server/instance.h"
#include "server/config/network/http_connection_manager.h"
#include "src/envoy/mixer/config.h"
#include "src/envoy/mixer/mixer_control.h"
using ::google::protobuf::util::Status;
using StatusCode = ::google::protobuf::util::error::Code;
namespace Envoy {
namespace Http {
namespace Mixer {
class TcpConfig : public Logger::Loggable<Logger::Id::filter> {
private:
Upstream::ClusterManager& cm_;
MixerConfig mixer_config_;
ThreadLocal::SlotPtr tls_;
public:
TcpConfig(const Json::Object& config,
Server::Configuration::FactoryContext& context)
: cm_(context.clusterManager()),
tls_(context.threadLocal().allocateSlot()) {
mixer_config_.Load(config);
Runtime::RandomGenerator& random = context.random();
tls_->set(
[this, &random](Event::Dispatcher& dispatcher)
-> ThreadLocal::ThreadLocalObjectSharedPtr {
return ThreadLocal::ThreadLocalObjectSharedPtr(
new MixerControl(mixer_config_, cm_, dispatcher, random));
});
}
MixerControl& mixer_control() { return tls_->getTyped<MixerControl>(); }
};
typedef std::shared_ptr<TcpConfig> TcpConfigPtr;
class TcpInstance : public Network::Filter,
public Network::ConnectionCallbacks,
public Logger::Loggable<Logger::Id::filter> {
private:
enum class State { NotStarted, Calling, Completed, Closed };
istio::mixer_client::CancelFunc cancel_check_;
MixerControl& mixer_control_;
std::shared_ptr<HttpRequestData> request_data_;
Network::ReadFilterCallbacks* filter_callbacks_{};
State state_{State::NotStarted};
bool calling_check_{};
uint64_t received_bytes_{};
uint64_t send_bytes_{};
int check_status_code_{};
std::chrono::time_point<std::chrono::system_clock> start_time_;
public:
TcpInstance(TcpConfigPtr config) : mixer_control_(config->mixer_control()) {
ENVOY_LOG(debug, "Called TcpInstance: {}", __func__);
}
~TcpInstance() {
if (state_ != State::Calling) {
cancel_check_ = nullptr;
}
state_ = State::Closed;
if (cancel_check_) {
ENVOY_LOG(debug, "Cancelling check call");
cancel_check_();
}
ENVOY_LOG(debug, "Called TcpInstance : {}", __func__);
}
void initializeReadFilterCallbacks(
Network::ReadFilterCallbacks& callbacks) override {
ENVOY_LOG(debug, "Called TcpInstance: {}", __func__);
filter_callbacks_ = &callbacks;
filter_callbacks_->connection().addConnectionCallbacks(*this);
start_time_ = std::chrono::system_clock::now();
}
// Network::ReadFilter
Network::FilterStatus onData(Buffer::Instance& data) override {
ENVOY_CONN_LOG(debug, "Called TcpInstance onRead bytes: {}",
filter_callbacks_->connection(), data.length());
received_bytes_ += data.length();
return Network::FilterStatus::Continue;
}
// Network::WriteFilter
Network::FilterStatus onWrite(Buffer::Instance& data) override {
ENVOY_CONN_LOG(debug, "Called TcpInstance onWrite bytes: {}",
filter_callbacks_->connection(), data.length());
send_bytes_ += data.length();
return Network::FilterStatus::Continue;
}
Network::FilterStatus onNewConnection() override {
ENVOY_CONN_LOG(debug,
"Called TcpInstance onNewConnection: remote {}, local {}",
filter_callbacks_->connection(),
filter_callbacks_->connection().remoteAddress().asString(),
filter_callbacks_->connection().localAddress().asString());
// Reports are always enabled.. And TcpReport uses attributes
// extracted by BuildTcpCheck
request_data_ = std::make_shared<HttpRequestData>();
std::string origin_user;
Ssl::Connection* ssl = filter_callbacks_->connection().ssl();
if (ssl != nullptr) {
origin_user = ssl->uriSanPeerCertificate();
}
mixer_control_.BuildTcpCheck(request_data_, filter_callbacks_->connection(),
origin_user);
if (state_ == State::NotStarted &&
!mixer_control_.MixerTcpCheckDisabled()) {
state_ = State::Calling;
filter_callbacks_->connection().readDisable(true);
calling_check_ = true;
cancel_check_ = mixer_control_.SendCheck(
request_data_, nullptr,
[this](const Status& status) { completeCheck(status); });
calling_check_ = false;
}
return state_ == State::Calling ? Network::FilterStatus::StopIteration
: Network::FilterStatus::Continue;
}
void completeCheck(const Status& status) {
ENVOY_LOG(debug, "Called TcpInstance completeCheck: {}", status.ToString());
if (state_ == State::Closed) {
return;
}
state_ = State::Completed;
filter_callbacks_->connection().readDisable(false);
if (!status.ok()) {
check_status_code_ = status.error_code();
filter_callbacks_->connection().close(
Network::ConnectionCloseType::NoFlush);
} else {
if (!calling_check_) {
filter_callbacks_->continueReading();
}
}
}
// Network::ConnectionCallbacks
void onEvent(Network::ConnectionEvent event) override {
if (filter_callbacks_->upstreamHost()) {
ENVOY_LOG(debug, "Called TcpInstance onEvent: {} upstream {}",
enumToInt(event),
filter_callbacks_->upstreamHost()->address()->asString());
} else {
ENVOY_LOG(debug, "Called TcpInstance onEvent: {}", enumToInt(event));
}
if (event == Network::ConnectionEvent::RemoteClose ||
event == Network::ConnectionEvent::LocalClose) {
if (state_ != State::Closed && request_data_) {
mixer_control_.BuildTcpReport(
request_data_, received_bytes_, send_bytes_, check_status_code_,
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now() - start_time_),
filter_callbacks_->upstreamHost());
mixer_control_.SendReport(request_data_);
}
state_ = State::Closed;
}
}
void onAboveWriteBufferHighWatermark() override {}
void onBelowWriteBufferLowWatermark() override {}
};
} // namespace Mixer
} // namespace Http
namespace Server {
namespace Configuration {
class TcpMixerFilterFactory : public NamedNetworkFilterConfigFactory {
public:
NetworkFilterFactoryCb createFilterFactory(const Json::Object& config,
FactoryContext& context) override {
Http::Mixer::TcpConfigPtr tcp_config(
new Http::Mixer::TcpConfig(config, context));
return [tcp_config](Network::FilterManager& filter_manager) -> void {
std::shared_ptr<Http::Mixer::TcpInstance> instance =
std::make_shared<Http::Mixer::TcpInstance>(tcp_config);
filter_manager.addReadFilter(Network::ReadFilterSharedPtr(instance));
filter_manager.addWriteFilter(Network::WriteFilterSharedPtr(instance));
};
}
std::string name() override { return "mixer"; }
NetworkFilterType type() override { return NetworkFilterType::Both; }
};
static Registry::RegisterFactory<TcpMixerFilterFactory,
NamedNetworkFilterConfigFactory>
register_;
} // namespace Configuration
} // namespace Server
} // namespace Envoy
<commit_msg>Fix a tcp filter crash. (#460)<commit_after>/* Copyright 2017 Istio Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/common/enum_to_int.h"
#include "common/common/logger.h"
#include "envoy/network/connection.h"
#include "envoy/network/filter.h"
#include "envoy/registry/registry.h"
#include "envoy/server/instance.h"
#include "server/config/network/http_connection_manager.h"
#include "src/envoy/mixer/config.h"
#include "src/envoy/mixer/mixer_control.h"
using ::google::protobuf::util::Status;
using StatusCode = ::google::protobuf::util::error::Code;
namespace Envoy {
namespace Http {
namespace Mixer {
class TcpConfig : public Logger::Loggable<Logger::Id::filter> {
private:
Upstream::ClusterManager& cm_;
MixerConfig mixer_config_;
ThreadLocal::SlotPtr tls_;
public:
TcpConfig(const Json::Object& config,
Server::Configuration::FactoryContext& context)
: cm_(context.clusterManager()),
tls_(context.threadLocal().allocateSlot()) {
mixer_config_.Load(config);
Runtime::RandomGenerator& random = context.random();
tls_->set(
[this, &random](Event::Dispatcher& dispatcher)
-> ThreadLocal::ThreadLocalObjectSharedPtr {
return ThreadLocal::ThreadLocalObjectSharedPtr(
new MixerControl(mixer_config_, cm_, dispatcher, random));
});
}
MixerControl& mixer_control() { return tls_->getTyped<MixerControl>(); }
};
typedef std::shared_ptr<TcpConfig> TcpConfigPtr;
class TcpInstance : public Network::Filter,
public Network::ConnectionCallbacks,
public Logger::Loggable<Logger::Id::filter> {
private:
enum class State { NotStarted, Calling, Completed, Closed };
istio::mixer_client::CancelFunc cancel_check_;
MixerControl& mixer_control_;
std::shared_ptr<HttpRequestData> request_data_;
Network::ReadFilterCallbacks* filter_callbacks_{};
State state_{State::NotStarted};
bool calling_check_{};
uint64_t received_bytes_{};
uint64_t send_bytes_{};
int check_status_code_{};
std::chrono::time_point<std::chrono::system_clock> start_time_;
public:
TcpInstance(TcpConfigPtr config) : mixer_control_(config->mixer_control()) {
ENVOY_LOG(debug, "Called TcpInstance: {}", __func__);
}
void cancelCheck() {
if (state_ != State::Calling) {
cancel_check_ = nullptr;
}
state_ = State::Closed;
if (cancel_check_) {
ENVOY_LOG(debug, "Cancelling check call");
cancel_check_();
cancel_check_ = nullptr;
}
}
~TcpInstance() {
cancelCheck();
ENVOY_LOG(debug, "Called TcpInstance : {}", __func__);
}
void initializeReadFilterCallbacks(
Network::ReadFilterCallbacks& callbacks) override {
ENVOY_LOG(debug, "Called TcpInstance: {}", __func__);
filter_callbacks_ = &callbacks;
filter_callbacks_->connection().addConnectionCallbacks(*this);
start_time_ = std::chrono::system_clock::now();
}
// Network::ReadFilter
Network::FilterStatus onData(Buffer::Instance& data) override {
ENVOY_CONN_LOG(debug, "Called TcpInstance onRead bytes: {}",
filter_callbacks_->connection(), data.length());
received_bytes_ += data.length();
return Network::FilterStatus::Continue;
}
// Network::WriteFilter
Network::FilterStatus onWrite(Buffer::Instance& data) override {
ENVOY_CONN_LOG(debug, "Called TcpInstance onWrite bytes: {}",
filter_callbacks_->connection(), data.length());
send_bytes_ += data.length();
return Network::FilterStatus::Continue;
}
Network::FilterStatus onNewConnection() override {
ENVOY_CONN_LOG(debug,
"Called TcpInstance onNewConnection: remote {}, local {}",
filter_callbacks_->connection(),
filter_callbacks_->connection().remoteAddress().asString(),
filter_callbacks_->connection().localAddress().asString());
// Reports are always enabled.. And TcpReport uses attributes
// extracted by BuildTcpCheck
request_data_ = std::make_shared<HttpRequestData>();
std::string origin_user;
Ssl::Connection* ssl = filter_callbacks_->connection().ssl();
if (ssl != nullptr) {
origin_user = ssl->uriSanPeerCertificate();
}
mixer_control_.BuildTcpCheck(request_data_, filter_callbacks_->connection(),
origin_user);
if (state_ == State::NotStarted &&
!mixer_control_.MixerTcpCheckDisabled()) {
state_ = State::Calling;
filter_callbacks_->connection().readDisable(true);
calling_check_ = true;
cancel_check_ = mixer_control_.SendCheck(
request_data_, nullptr,
[this](const Status& status) { completeCheck(status); });
calling_check_ = false;
}
return state_ == State::Calling ? Network::FilterStatus::StopIteration
: Network::FilterStatus::Continue;
}
void completeCheck(const Status& status) {
ENVOY_LOG(debug, "Called TcpInstance completeCheck: {}", status.ToString());
cancel_check_ = nullptr;
if (state_ == State::Closed) {
return;
}
state_ = State::Completed;
filter_callbacks_->connection().readDisable(false);
if (!status.ok()) {
check_status_code_ = status.error_code();
filter_callbacks_->connection().close(
Network::ConnectionCloseType::NoFlush);
} else {
if (!calling_check_) {
filter_callbacks_->continueReading();
}
}
}
// Network::ConnectionCallbacks
void onEvent(Network::ConnectionEvent event) override {
if (filter_callbacks_->upstreamHost()) {
ENVOY_LOG(debug, "Called TcpInstance onEvent: {} upstream {}",
enumToInt(event),
filter_callbacks_->upstreamHost()->address()->asString());
} else {
ENVOY_LOG(debug, "Called TcpInstance onEvent: {}", enumToInt(event));
}
if (event == Network::ConnectionEvent::RemoteClose ||
event == Network::ConnectionEvent::LocalClose) {
if (state_ != State::Closed && request_data_) {
mixer_control_.BuildTcpReport(
request_data_, received_bytes_, send_bytes_, check_status_code_,
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now() - start_time_),
filter_callbacks_->upstreamHost());
mixer_control_.SendReport(request_data_);
}
cancelCheck();
}
}
void onAboveWriteBufferHighWatermark() override {}
void onBelowWriteBufferLowWatermark() override {}
};
} // namespace Mixer
} // namespace Http
namespace Server {
namespace Configuration {
class TcpMixerFilterFactory : public NamedNetworkFilterConfigFactory {
public:
NetworkFilterFactoryCb createFilterFactory(const Json::Object& config,
FactoryContext& context) override {
Http::Mixer::TcpConfigPtr tcp_config(
new Http::Mixer::TcpConfig(config, context));
return [tcp_config](Network::FilterManager& filter_manager) -> void {
std::shared_ptr<Http::Mixer::TcpInstance> instance =
std::make_shared<Http::Mixer::TcpInstance>(tcp_config);
filter_manager.addReadFilter(Network::ReadFilterSharedPtr(instance));
filter_manager.addWriteFilter(Network::WriteFilterSharedPtr(instance));
};
}
std::string name() override { return "mixer"; }
NetworkFilterType type() override { return NetworkFilterType::Both; }
};
static Registry::RegisterFactory<TcpMixerFilterFactory,
NamedNetworkFilterConfigFactory>
register_;
} // namespace Configuration
} // namespace Server
} // namespace Envoy
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2015 Felix Rieseberg <[email protected]> and Jason Poon <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/win/notification_presenter_win.h"
#include "base/files/file_util.h"
#include "base/md5.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "browser/win/windows_toast_notification.h"
#include "content/public/browser/desktop_notification_delegate.h"
#include "content/public/common/platform_notification_data.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"
#pragma comment(lib, "runtimeobject.lib")
namespace brightray {
namespace {
bool SaveIconToPath(const SkBitmap& bitmap, const base::FilePath& path) {
std::vector<unsigned char> png_data;
if (!gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &png_data))
return false;
char* data = reinterpret_cast<char*>(&png_data[0]);
int size = static_cast<int>(png_data.size());
return base::WriteFile(path, data, size) == size;
}
} // namespace
// static
NotificationPresenter* NotificationPresenter::Create() {
if (!WindowsToastNotification::Initialize())
return nullptr;
std::unique_ptr<NotificationPresenterWin> presenter(new NotificationPresenterWin);
if (!presenter->Init())
return nullptr;
return presenter.release();
}
NotificationPresenterWin::NotificationPresenterWin() {
}
NotificationPresenterWin::~NotificationPresenterWin() {
}
bool NotificationPresenterWin::Init() {
return temp_dir_.CreateUniqueTempDir();
}
base::string16 NotificationPresenterWin::SaveIconToFilesystem(
const SkBitmap& icon, const GURL& origin) {
std::string filename = base::MD5String(origin.spec()) + ".png";
base::FilePath path = temp_dir_.path().Append(base::UTF8ToUTF16(filename));
if (base::PathExists(path))
return path.value();
if (SaveIconToPath(icon, path))
return path.value();
return base::UTF8ToUTF16(origin.spec());
}
} // namespace brightray
<commit_msg>Apply changes to "//base: Make ScopedTempDir::path() a GetPath() with a DCHECK" https://chromium.googlesource.com/chromium/src.git/+/411f4fc60df3a256dd2d15ab39c540228ed66e7f<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2015 Felix Rieseberg <[email protected]> and Jason Poon <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/win/notification_presenter_win.h"
#include "base/files/file_util.h"
#include "base/md5.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/windows_version.h"
#include "browser/win/windows_toast_notification.h"
#include "content/public/browser/desktop_notification_delegate.h"
#include "content/public/common/platform_notification_data.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"
#pragma comment(lib, "runtimeobject.lib")
namespace brightray {
namespace {
bool SaveIconToPath(const SkBitmap& bitmap, const base::FilePath& path) {
std::vector<unsigned char> png_data;
if (!gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false, &png_data))
return false;
char* data = reinterpret_cast<char*>(&png_data[0]);
int size = static_cast<int>(png_data.size());
return base::WriteFile(path, data, size) == size;
}
} // namespace
// static
NotificationPresenter* NotificationPresenter::Create() {
if (!WindowsToastNotification::Initialize())
return nullptr;
std::unique_ptr<NotificationPresenterWin> presenter(new NotificationPresenterWin);
if (!presenter->Init())
return nullptr;
return presenter.release();
}
NotificationPresenterWin::NotificationPresenterWin() {
}
NotificationPresenterWin::~NotificationPresenterWin() {
}
bool NotificationPresenterWin::Init() {
return temp_dir_.CreateUniqueTempDir();
}
base::string16 NotificationPresenterWin::SaveIconToFilesystem(
const SkBitmap& icon, const GURL& origin) {
std::string filename = base::MD5String(origin.spec()) + ".png";
base::FilePath path = temp_dir_.GetPath().Append(base::UTF8ToUTF16(filename));
if (base::PathExists(path))
return path.value();
if (SaveIconToPath(icon, path))
return path.value();
return base::UTF8ToUTF16(origin.spec());
}
} // namespace brightray
<|endoftext|> |
<commit_before><commit_msg>Bug Hunting<commit_after><|endoftext|> |
<commit_before>#include <ShaderReflection.h>
#include <ShaderMeta/USMShaderMeta.h>
#include <LogDelegate.h>
#include <cassert>
#include <map>
#define WIN32_LEAN_AND_MEAN
#include <d3dcompiler.h>
// StructCache stores D3D11 type to metadata index mapping, where metadata index is an index in the Out.Structs array
static bool ProcessStructure(CUSMShaderMeta& Meta, ID3D11ShaderReflectionType* pType, uint32_t StructSize, std::map<ID3D11ShaderReflectionType*, size_t>& StructCache)
{
if (!pType) return false;
// Already processed
if (StructCache.find(pType) != StructCache.cend()) return true;
D3D11_SHADER_TYPE_DESC D3DTypeDesc;
pType->GetDesc(&D3DTypeDesc);
// Has no members
if (D3DTypeDesc.Members == 0) return true;
// Add and fill new structure layout metadata
StructCache.emplace(pType, Meta.Structs.size());
CUSMStructMeta StructMeta;
StructMeta.Name = D3DTypeDesc.Name ? D3DTypeDesc.Name : std::string();
StructMeta.Members.reserve(D3DTypeDesc.Members);
for (UINT MemberIdx = 0; MemberIdx < D3DTypeDesc.Members; ++MemberIdx)
{
LPCSTR pMemberName = pType->GetMemberTypeName(MemberIdx);
ID3D11ShaderReflectionType* pMemberType = pType->GetMemberTypeByIndex(MemberIdx);
D3D11_SHADER_TYPE_DESC D3DMemberTypeDesc;
pMemberType->GetDesc(&D3DMemberTypeDesc);
CUSMConstMetaBase MemberMeta;
MemberMeta.Name = pMemberName;
MemberMeta.Offset = D3DMemberTypeDesc.Offset;
MemberMeta.Flags = 0;
uint32_t MemberSize;
if (MemberIdx + 1 < D3DTypeDesc.Members)
{
ID3D11ShaderReflectionType* pNextMemberType = pType->GetMemberTypeByIndex(MemberIdx + 1);
D3D11_SHADER_TYPE_DESC D3DNextMemberTypeDesc;
pNextMemberType->GetDesc(&D3DNextMemberTypeDesc);
MemberSize = D3DNextMemberTypeDesc.Offset - D3DMemberTypeDesc.Offset;
}
else MemberSize = StructSize - D3DMemberTypeDesc.Offset;
if (D3DMemberTypeDesc.Elements > 1)
{
// Arrays
MemberMeta.ElementSize = MemberSize / D3DMemberTypeDesc.Elements;
MemberMeta.ElementCount = D3DMemberTypeDesc.Elements;
}
else
{
// Non-arrays and arrays [1]
MemberMeta.ElementSize = MemberSize;
MemberMeta.ElementCount = 1;
}
if (D3DMemberTypeDesc.Class == D3D_SVC_STRUCT)
{
MemberMeta.Type = USMConst_Struct; // D3DTypeDesc.Type is 'void'
if (!ProcessStructure(Meta, pMemberType, MemberMeta.ElementSize, StructCache)) continue;
MemberMeta.StructIndex = StructCache[pMemberType];
}
else
{
MemberMeta.StructIndex = (uint32_t)(-1);
switch (D3DMemberTypeDesc.Type)
{
case D3D_SVT_BOOL: MemberMeta.Type = USMConst_Bool; break;
case D3D_SVT_INT:
case D3D_SVT_UINT: MemberMeta.Type = USMConst_Int; break;
case D3D_SVT_FLOAT: MemberMeta.Type = USMConst_Float; break;
default:
{
//Messages += "Unsupported constant '";
//Messages += pMemberName;
//Messages += "' type '";
//Messages += std::to_string(D3DMemberTypeDesc.Type);
//Messages += "' in a structure '";
//Messages += (D3DTypeDesc.Name ? D3DTypeDesc.Name : "");
//Messages += "'\n";
return false;
}
}
MemberMeta.Columns = D3DMemberTypeDesc.Columns;
MemberMeta.Rows = D3DMemberTypeDesc.Rows;
if (D3DMemberTypeDesc.Class == D3D_SVC_MATRIX_COLUMNS)
MemberMeta.Flags |= USMShaderConst_ColumnMajor;
}
StructMeta.Members.push_back(std::move(MemberMeta));
}
Meta.Structs.push_back(std::move(StructMeta));
return true;
}
//---------------------------------------------------------------------
bool ExtractUSMMetaFromBinary(const void* pData, size_t Size, CUSMShaderMeta& OutMeta, uint32_t& OutMinFeatureLevel, uint64_t& OutRequiresFlags, DEMShaderCompiler::ILogDelegate* pLog)
{
ID3D11ShaderReflection* pReflector = nullptr;
if (FAILED(D3DReflect(pData, Size, IID_ID3D11ShaderReflection, (void**)&pReflector))) return false;
D3D_FEATURE_LEVEL D3DFeatureLevel;
if (FAILED(pReflector->GetMinFeatureLevel(&D3DFeatureLevel)))
{
pReflector->Release();
return false;
}
switch (D3DFeatureLevel)
{
case D3D_FEATURE_LEVEL_9_1: OutMinFeatureLevel = GPU_Level_D3D9_1; break;
case D3D_FEATURE_LEVEL_9_2: OutMinFeatureLevel = GPU_Level_D3D9_2; break;
case D3D_FEATURE_LEVEL_9_3: OutMinFeatureLevel = GPU_Level_D3D9_3; break;
case D3D_FEATURE_LEVEL_10_0: OutMinFeatureLevel = GPU_Level_D3D10_0; break;
case D3D_FEATURE_LEVEL_10_1: OutMinFeatureLevel = GPU_Level_D3D10_1; break;
case D3D_FEATURE_LEVEL_11_0: OutMinFeatureLevel = GPU_Level_D3D11_0; break;
//case D3D_FEATURE_LEVEL_11_1:
default: OutMinFeatureLevel = GPU_Level_D3D11_1; break;
}
OutRequiresFlags = pReflector->GetRequiresFlags();
D3D11_SHADER_DESC D3DDesc;
if (FAILED(pReflector->GetDesc(&D3DDesc)))
{
pReflector->Release();
return false;
}
std::map<ID3D11ShaderReflectionType*, size_t> StructCache;
for (UINT RsrcIdx = 0; RsrcIdx < D3DDesc.BoundResources; ++RsrcIdx)
{
D3D11_SHADER_INPUT_BIND_DESC RsrcDesc;
if (FAILED(pReflector->GetResourceBindingDesc(RsrcIdx, &RsrcDesc)))
{
pReflector->Release();
return false;
}
// D3D_SIF_USERPACKED - may fail assertion if not set!
switch (RsrcDesc.Type)
{
case D3D_SIT_TEXTURE:
{
CUSMRsrcMeta Meta;
Meta.Name = RsrcDesc.Name;
Meta.RegisterStart = RsrcDesc.BindPoint;
Meta.RegisterCount = RsrcDesc.BindCount;
switch (RsrcDesc.Dimension)
{
case D3D_SRV_DIMENSION_TEXTURE1D: Meta.Type = USMRsrc_Texture1D; break;
case D3D_SRV_DIMENSION_TEXTURE1DARRAY: Meta.Type = USMRsrc_Texture1DArray; break;
case D3D_SRV_DIMENSION_TEXTURE2D: Meta.Type = USMRsrc_Texture2D; break;
case D3D_SRV_DIMENSION_TEXTURE2DARRAY: Meta.Type = USMRsrc_Texture2DArray; break;
case D3D_SRV_DIMENSION_TEXTURE2DMS: Meta.Type = USMRsrc_Texture2DMS; break;
case D3D_SRV_DIMENSION_TEXTURE2DMSARRAY: Meta.Type = USMRsrc_Texture2DMSArray; break;
case D3D_SRV_DIMENSION_TEXTURE3D: Meta.Type = USMRsrc_Texture3D; break;
case D3D_SRV_DIMENSION_TEXTURECUBE: Meta.Type = USMRsrc_TextureCUBE; break;
case D3D_SRV_DIMENSION_TEXTURECUBEARRAY: Meta.Type = USMRsrc_TextureCUBEArray; break;
default: Meta.Type = USMRsrc_Unknown; break;
}
OutMeta.Resources.push_back(std::move(Meta));
break;
}
case D3D_SIT_SAMPLER:
{
// D3D_SIF_COMPARISON_SAMPLER
CUSMSamplerMeta Meta;
Meta.Name = RsrcDesc.Name;
Meta.RegisterStart = RsrcDesc.BindPoint;
Meta.RegisterCount = RsrcDesc.BindCount;
OutMeta.Samplers.push_back(std::move(Meta));
break;
}
case D3D_SIT_CBUFFER:
case D3D_SIT_TBUFFER:
case D3D_SIT_STRUCTURED:
{
// Can't violate this condition (can't define cbuffer / tbuffer array)
assert(RsrcDesc.BindCount == 1);
// There can be cbuffer and tbuffer with the same name, so search by name and type
D3D_CBUFFER_TYPE DesiredType;
switch (RsrcDesc.Type)
{
case D3D_SIT_CBUFFER: DesiredType = D3D_CT_CBUFFER; break;
case D3D_SIT_TBUFFER: DesiredType = D3D_CT_TBUFFER; break;
case D3D_SIT_STRUCTURED: DesiredType = D3D_CT_RESOURCE_BIND_INFO; break;
}
ID3D11ShaderReflectionConstantBuffer* pCB = nullptr;
D3D11_SHADER_BUFFER_DESC D3DBufDesc;
for (size_t BufIdx = 0; BufIdx < D3DDesc.ConstantBuffers; ++BufIdx)
{
ID3D11ShaderReflectionConstantBuffer* pCurrCB = pReflector->GetConstantBufferByIndex(BufIdx);
pCurrCB->GetDesc(&D3DBufDesc);
if (!strcmp(RsrcDesc.Name, D3DBufDesc.Name) && D3DBufDesc.Type == DesiredType)
{
pCB = pCurrCB;
break;
}
}
if (!pCB || !D3DBufDesc.Variables) continue;
//D3DBufDesc.uFlags & D3D_CBF_USERPACKED
DWORD TypeMask;
if (RsrcDesc.Type == D3D_SIT_TBUFFER) TypeMask = USMBuffer_Texture;
else if (RsrcDesc.Type == D3D_SIT_STRUCTURED) TypeMask = USMBuffer_Structured;
else TypeMask = 0;
CUSMBufferMeta Meta;
Meta.Name = RsrcDesc.Name;
Meta.Register = (RsrcDesc.BindPoint | TypeMask);
Meta.Size = D3DBufDesc.Size;
OutMeta.Buffers.push_back(std::move(Meta));
if (RsrcDesc.Type != D3D_SIT_STRUCTURED)
{
for (UINT VarIdx = 0; VarIdx < D3DBufDesc.Variables; ++VarIdx)
{
ID3D11ShaderReflectionVariable* pVar = pCB->GetVariableByIndex(VarIdx);
if (!pVar) continue;
D3D11_SHADER_VARIABLE_DESC D3DVarDesc;
pVar->GetDesc(&D3DVarDesc);
//D3D_SVF_USERPACKED = 1,
//D3D_SVF_USED = 2,
ID3D11ShaderReflectionType* pVarType = pVar->GetType();
if (!pVarType) continue;
D3D11_SHADER_TYPE_DESC D3DTypeDesc;
pVarType->GetDesc(&D3DTypeDesc);
CUSMConstMeta ConstMeta;
ConstMeta.Name = D3DVarDesc.Name;
ConstMeta.BufferIndex = OutMeta.Buffers.size() - 1;
ConstMeta.Offset = D3DVarDesc.StartOffset;
ConstMeta.Flags = 0;
if (D3DTypeDesc.Elements > 1)
{
// Arrays
ConstMeta.ElementSize = D3DVarDesc.Size / D3DTypeDesc.Elements;
ConstMeta.ElementCount = D3DTypeDesc.Elements;
}
else
{
// Non-arrays and arrays [1]
ConstMeta.ElementSize = D3DVarDesc.Size;
ConstMeta.ElementCount = 1;
}
if (D3DTypeDesc.Class == D3D_SVC_STRUCT)
{
ConstMeta.Type = USMConst_Struct; // D3DTypeDesc.Type is 'void'
if (!ProcessStructure(OutMeta, pVarType, ConstMeta.ElementSize, StructCache)) continue;
ConstMeta.StructIndex = StructCache[pVarType];
}
else
{
ConstMeta.StructIndex = (uint32_t)(-1);
switch (D3DTypeDesc.Type)
{
case D3D_SVT_BOOL: ConstMeta.Type = USMConst_Bool; break;
case D3D_SVT_INT:
case D3D_SVT_UINT: ConstMeta.Type = USMConst_Int; break;
case D3D_SVT_FLOAT: ConstMeta.Type = USMConst_Float; break;
default:
{
if (pLog)
pLog->LogInfo((std::string("Unsupported constant '") + D3DVarDesc.Name + "' type '" +
std::to_string(D3DTypeDesc.Type) + "' in USM buffer '" + RsrcDesc.Name).c_str());
return false;
}
}
ConstMeta.Columns = D3DTypeDesc.Columns;
ConstMeta.Rows = D3DTypeDesc.Rows;
if (D3DTypeDesc.Class == D3D_SVC_MATRIX_COLUMNS)
ConstMeta.Flags |= USMShaderConst_ColumnMajor;
OutMeta.Consts.push_back(std::move(ConstMeta));
}
}
}
break;
}
}
}
pReflector->Release();
return true;
}
//---------------------------------------------------------------------
<commit_msg>Minor changes<commit_after>#include <ShaderReflection.h>
#include <ShaderMeta/USMShaderMeta.h>
#include <LogDelegate.h>
#include <cassert>
#include <map>
#define WIN32_LEAN_AND_MEAN
#include <d3dcompiler.h>
// StructCache stores D3D11 type to metadata index mapping, where metadata index is an index in the Out.Structs array
static bool ProcessStructure(CUSMShaderMeta& Meta, ID3D11ShaderReflectionType* pType, uint32_t StructSize,
std::map<ID3D11ShaderReflectionType*, size_t>& StructCache, DEMShaderCompiler::ILogDelegate* pLog)
{
if (!pType) return false;
// Already processed
if (StructCache.find(pType) != StructCache.cend()) return true;
D3D11_SHADER_TYPE_DESC D3DTypeDesc;
pType->GetDesc(&D3DTypeDesc);
// Has no members
if (D3DTypeDesc.Members == 0) return true;
// Add and fill new structure layout metadata
StructCache.emplace(pType, Meta.Structs.size());
CUSMStructMeta StructMeta;
StructMeta.Name = D3DTypeDesc.Name ? D3DTypeDesc.Name : std::string();
StructMeta.Members.reserve(D3DTypeDesc.Members);
for (UINT MemberIdx = 0; MemberIdx < D3DTypeDesc.Members; ++MemberIdx)
{
LPCSTR pMemberName = pType->GetMemberTypeName(MemberIdx);
ID3D11ShaderReflectionType* pMemberType = pType->GetMemberTypeByIndex(MemberIdx);
D3D11_SHADER_TYPE_DESC D3DMemberTypeDesc;
pMemberType->GetDesc(&D3DMemberTypeDesc);
CUSMConstMetaBase MemberMeta;
MemberMeta.Name = pMemberName;
MemberMeta.Offset = D3DMemberTypeDesc.Offset;
MemberMeta.Flags = 0;
uint32_t MemberSize;
if (MemberIdx + 1 < D3DTypeDesc.Members)
{
ID3D11ShaderReflectionType* pNextMemberType = pType->GetMemberTypeByIndex(MemberIdx + 1);
D3D11_SHADER_TYPE_DESC D3DNextMemberTypeDesc;
pNextMemberType->GetDesc(&D3DNextMemberTypeDesc);
MemberSize = D3DNextMemberTypeDesc.Offset - D3DMemberTypeDesc.Offset;
}
else MemberSize = StructSize - D3DMemberTypeDesc.Offset;
if (D3DMemberTypeDesc.Elements > 1)
{
// Arrays
MemberMeta.ElementSize = MemberSize / D3DMemberTypeDesc.Elements;
MemberMeta.ElementCount = D3DMemberTypeDesc.Elements;
}
else
{
// Non-arrays and arrays [1]
MemberMeta.ElementSize = MemberSize;
MemberMeta.ElementCount = 1;
}
if (D3DMemberTypeDesc.Class == D3D_SVC_STRUCT)
{
MemberMeta.Type = USMConst_Struct; // D3DTypeDesc.Type is 'void'
if (!ProcessStructure(Meta, pMemberType, MemberMeta.ElementSize, StructCache, pLog)) continue;
MemberMeta.StructIndex = StructCache[pMemberType];
}
else
{
MemberMeta.StructIndex = static_cast<uint32_t>(-1);
switch (D3DMemberTypeDesc.Type)
{
case D3D_SVT_BOOL: MemberMeta.Type = USMConst_Bool; break;
case D3D_SVT_INT:
case D3D_SVT_UINT: MemberMeta.Type = USMConst_Int; break;
case D3D_SVT_FLOAT: MemberMeta.Type = USMConst_Float; break;
default:
{
if (pLog)
pLog->LogInfo((std::string("Unsupported constant '") + pMemberName + "' type '" +
std::to_string(D3DMemberTypeDesc.Type) + "' in a structure '" + (D3DTypeDesc.Name ? D3DTypeDesc.Name : "")).c_str());
return false;
}
}
MemberMeta.Columns = D3DMemberTypeDesc.Columns;
MemberMeta.Rows = D3DMemberTypeDesc.Rows;
if (D3DMemberTypeDesc.Class == D3D_SVC_MATRIX_COLUMNS)
MemberMeta.Flags |= USMShaderConst_ColumnMajor;
}
StructMeta.Members.push_back(std::move(MemberMeta));
}
Meta.Structs.push_back(std::move(StructMeta));
return true;
}
//---------------------------------------------------------------------
bool ExtractUSMMetaFromBinary(const void* pData, size_t Size, CUSMShaderMeta& OutMeta, uint32_t& OutMinFeatureLevel, uint64_t& OutRequiresFlags, DEMShaderCompiler::ILogDelegate* pLog)
{
ID3D11ShaderReflection* pReflector = nullptr;
if (FAILED(D3DReflect(pData, Size, IID_ID3D11ShaderReflection, (void**)&pReflector))) return false;
D3D_FEATURE_LEVEL D3DFeatureLevel;
if (FAILED(pReflector->GetMinFeatureLevel(&D3DFeatureLevel)))
{
pReflector->Release();
return false;
}
switch (D3DFeatureLevel)
{
case D3D_FEATURE_LEVEL_9_1: OutMinFeatureLevel = GPU_Level_D3D9_1; break;
case D3D_FEATURE_LEVEL_9_2: OutMinFeatureLevel = GPU_Level_D3D9_2; break;
case D3D_FEATURE_LEVEL_9_3: OutMinFeatureLevel = GPU_Level_D3D9_3; break;
case D3D_FEATURE_LEVEL_10_0: OutMinFeatureLevel = GPU_Level_D3D10_0; break;
case D3D_FEATURE_LEVEL_10_1: OutMinFeatureLevel = GPU_Level_D3D10_1; break;
case D3D_FEATURE_LEVEL_11_0: OutMinFeatureLevel = GPU_Level_D3D11_0; break;
//case D3D_FEATURE_LEVEL_11_1:
default: OutMinFeatureLevel = GPU_Level_D3D11_1; break;
}
OutRequiresFlags = pReflector->GetRequiresFlags();
D3D11_SHADER_DESC D3DDesc;
if (FAILED(pReflector->GetDesc(&D3DDesc)))
{
pReflector->Release();
return false;
}
std::map<ID3D11ShaderReflectionType*, size_t> StructCache;
for (UINT RsrcIdx = 0; RsrcIdx < D3DDesc.BoundResources; ++RsrcIdx)
{
D3D11_SHADER_INPUT_BIND_DESC RsrcDesc;
if (FAILED(pReflector->GetResourceBindingDesc(RsrcIdx, &RsrcDesc)))
{
pReflector->Release();
return false;
}
// D3D_SIF_USERPACKED - may fail assertion if not set!
switch (RsrcDesc.Type)
{
case D3D_SIT_TEXTURE:
{
CUSMRsrcMeta Meta;
Meta.Name = RsrcDesc.Name;
Meta.RegisterStart = RsrcDesc.BindPoint;
Meta.RegisterCount = RsrcDesc.BindCount;
switch (RsrcDesc.Dimension)
{
case D3D_SRV_DIMENSION_TEXTURE1D: Meta.Type = USMRsrc_Texture1D; break;
case D3D_SRV_DIMENSION_TEXTURE1DARRAY: Meta.Type = USMRsrc_Texture1DArray; break;
case D3D_SRV_DIMENSION_TEXTURE2D: Meta.Type = USMRsrc_Texture2D; break;
case D3D_SRV_DIMENSION_TEXTURE2DARRAY: Meta.Type = USMRsrc_Texture2DArray; break;
case D3D_SRV_DIMENSION_TEXTURE2DMS: Meta.Type = USMRsrc_Texture2DMS; break;
case D3D_SRV_DIMENSION_TEXTURE2DMSARRAY: Meta.Type = USMRsrc_Texture2DMSArray; break;
case D3D_SRV_DIMENSION_TEXTURE3D: Meta.Type = USMRsrc_Texture3D; break;
case D3D_SRV_DIMENSION_TEXTURECUBE: Meta.Type = USMRsrc_TextureCUBE; break;
case D3D_SRV_DIMENSION_TEXTURECUBEARRAY: Meta.Type = USMRsrc_TextureCUBEArray; break;
default: Meta.Type = USMRsrc_Unknown; break;
}
OutMeta.Resources.push_back(std::move(Meta));
break;
}
case D3D_SIT_SAMPLER:
{
// D3D_SIF_COMPARISON_SAMPLER
CUSMSamplerMeta Meta;
Meta.Name = RsrcDesc.Name;
Meta.RegisterStart = RsrcDesc.BindPoint;
Meta.RegisterCount = RsrcDesc.BindCount;
OutMeta.Samplers.push_back(std::move(Meta));
break;
}
case D3D_SIT_CBUFFER:
case D3D_SIT_TBUFFER:
case D3D_SIT_STRUCTURED:
{
// Can't violate this condition (can't define cbuffer / tbuffer array)
assert(RsrcDesc.BindCount == 1);
// There can be cbuffer and tbuffer with the same name, so search by name and type
D3D_CBUFFER_TYPE DesiredType;
switch (RsrcDesc.Type)
{
case D3D_SIT_CBUFFER: DesiredType = D3D_CT_CBUFFER; break;
case D3D_SIT_TBUFFER: DesiredType = D3D_CT_TBUFFER; break;
case D3D_SIT_STRUCTURED: DesiredType = D3D_CT_RESOURCE_BIND_INFO; break;
}
ID3D11ShaderReflectionConstantBuffer* pCB = nullptr;
D3D11_SHADER_BUFFER_DESC D3DBufDesc;
for (size_t BufIdx = 0; BufIdx < D3DDesc.ConstantBuffers; ++BufIdx)
{
ID3D11ShaderReflectionConstantBuffer* pCurrCB = pReflector->GetConstantBufferByIndex(BufIdx);
pCurrCB->GetDesc(&D3DBufDesc);
if (!strcmp(RsrcDesc.Name, D3DBufDesc.Name) && D3DBufDesc.Type == DesiredType)
{
pCB = pCurrCB;
break;
}
}
if (!pCB || !D3DBufDesc.Variables) continue;
//D3DBufDesc.uFlags & D3D_CBF_USERPACKED
DWORD TypeMask;
if (RsrcDesc.Type == D3D_SIT_TBUFFER) TypeMask = USMBuffer_Texture;
else if (RsrcDesc.Type == D3D_SIT_STRUCTURED) TypeMask = USMBuffer_Structured;
else TypeMask = 0;
CUSMBufferMeta Meta;
Meta.Name = RsrcDesc.Name;
Meta.Register = (RsrcDesc.BindPoint | TypeMask);
Meta.Size = D3DBufDesc.Size;
OutMeta.Buffers.push_back(std::move(Meta));
if (RsrcDesc.Type != D3D_SIT_STRUCTURED)
{
for (UINT VarIdx = 0; VarIdx < D3DBufDesc.Variables; ++VarIdx)
{
ID3D11ShaderReflectionVariable* pVar = pCB->GetVariableByIndex(VarIdx);
if (!pVar) continue;
D3D11_SHADER_VARIABLE_DESC D3DVarDesc;
pVar->GetDesc(&D3DVarDesc);
//D3D_SVF_USERPACKED = 1,
//D3D_SVF_USED = 2,
ID3D11ShaderReflectionType* pVarType = pVar->GetType();
if (!pVarType) continue;
D3D11_SHADER_TYPE_DESC D3DTypeDesc;
pVarType->GetDesc(&D3DTypeDesc);
CUSMConstMeta ConstMeta;
ConstMeta.Name = D3DVarDesc.Name;
ConstMeta.BufferIndex = OutMeta.Buffers.size() - 1;
ConstMeta.Offset = D3DVarDesc.StartOffset;
ConstMeta.Flags = 0;
if (D3DTypeDesc.Elements > 1)
{
// Arrays
ConstMeta.ElementSize = D3DVarDesc.Size / D3DTypeDesc.Elements;
ConstMeta.ElementCount = D3DTypeDesc.Elements;
}
else
{
// Non-arrays and arrays [1]
ConstMeta.ElementSize = D3DVarDesc.Size;
ConstMeta.ElementCount = 1;
}
if (D3DTypeDesc.Class == D3D_SVC_STRUCT)
{
ConstMeta.Type = USMConst_Struct; // D3DTypeDesc.Type is 'void'
if (!ProcessStructure(OutMeta, pVarType, ConstMeta.ElementSize, StructCache, pLog)) continue;
ConstMeta.StructIndex = StructCache[pVarType];
}
else
{
ConstMeta.StructIndex = static_cast<uint32_t>(-1);
switch (D3DTypeDesc.Type)
{
case D3D_SVT_BOOL: ConstMeta.Type = USMConst_Bool; break;
case D3D_SVT_INT:
case D3D_SVT_UINT: ConstMeta.Type = USMConst_Int; break;
case D3D_SVT_FLOAT: ConstMeta.Type = USMConst_Float; break;
default:
{
if (pLog)
pLog->LogInfo((std::string("Unsupported constant '") + D3DVarDesc.Name + "' type '" +
std::to_string(D3DTypeDesc.Type) + "' in USM buffer '" + RsrcDesc.Name).c_str());
return false;
}
}
ConstMeta.Columns = D3DTypeDesc.Columns;
ConstMeta.Rows = D3DTypeDesc.Rows;
if (D3DTypeDesc.Class == D3D_SVC_MATRIX_COLUMNS)
ConstMeta.Flags |= USMShaderConst_ColumnMajor;
OutMeta.Consts.push_back(std::move(ConstMeta));
}
}
}
break;
}
}
}
pReflector->Release();
return true;
}
//---------------------------------------------------------------------
<|endoftext|> |
<commit_before>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008-2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "boot.h"
#include "popup_dialog_win32.h"
#include <process.h>
#include <windows.h>
using std::wstring;
#ifndef MAX_PATH
#define MAX_PATH 512
#endif
#ifdef USE_BREAKPAD
#include "client/windows/handler/exception_handler.h"
#include "common/windows/http_upload.h"
#endif
namespace KrollBoot
{
extern string applicationHome;
extern string updateFile;
extern SharedApplication app;
extern int argc;
extern const char** argv;
inline void ShowError(string msg, bool fatal)
{
std::cerr << "Error: " << msg << std::endl;
MessageBoxA(NULL, msg.c_str(), GetApplicationName().c_str(), MB_OK|MB_ICONERROR|MB_SYSTEMMODAL);
if (fatal)
exit(1);
}
std::string GetApplicationHomePath()
{
char path[MAX_PATH];
int size = GetModuleFileNameA(GetModuleHandle(NULL), (char*)path, MAX_PATH);
if (size>0)
{
path[size] = '\0';
}
return FileUtils::Dirname(string(path));
}
bool IsWindowsXP()
{
OSVERSIONINFO osVersion;
osVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
::GetVersionEx(&osVersion);
return osVersion.dwMajorVersion == 5;
}
void BootstrapPlatformSpecific(string path)
{
// Add runtime path and all module paths to PATH
path = app->runtime->path + ";" + path;
string currentPath = EnvironmentUtils::Get("PATH");
if (!currentPath.empty())
{
path = path + ":" + currentPath;
}
EnvironmentUtils::Set("PATH", path);
}
string Blastoff()
{
if (!IsWindowsXP())
{
// Windows boot does not normally need to restart itself, so just
// launch the host here and exit with the appropriate return value.
EnvironmentUtils::Unset(BOOTSTRAP_ENV);
exit(KrollBoot::StartHost());
}
// TODO: Fix manual activation context setup for Windows XP so we don't need
// to do the thing below any longer.
// We are on Windows XP. We need to reboot ourselves, but using the kboot.exe
// that is included with the runtime. The manifest embedded in kboot points
// to a DLL named "WebKit.dll" relative to the exe -- we need that path to
// resolve for registration-free COM to work.
string allArgs;
for (int i = 0; i < argc; i++)
{
string arg = argv[i];
size_t quotePos = arg.find('\"');
if (quotePos == string::npos)
{
allArgs.append("\"");
allArgs.append(arg);
allArgs.append("\" ");
}
else
{
allArgs.append(arg + " ");
}
}
string appName = app->runtime->path + "\\kboot.exe";
STARTUPINFOA startupInfo = {0};
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION processInformation;
char* applicationName = _strdup(appName.c_str());
char* allArguments = _strdup(allArgs.c_str());
int success = CreateProcessA(
applicationName, allArguments,
NULL, NULL, FALSE, 0, NULL, NULL,
&startupInfo, &processInformation);
free(applicationName);
free(allArguments);
if (success == 0)
{
string errorString = string("Could not bootstrap into ");
errorString.append(appName);
errorString.append(": ");
errorString.append(KrollUtils::Win32Utils::QuickFormatMessage(GetLastError()));
ShowError(errorString);
}
else
{
CloseHandle(processInformation.hThread);
WaitForSingleObject(processInformation.hProcess, INFINITE);
DWORD retCode;
if (GetExitCodeProcess(processInformation.hProcess, &retCode))
{
exit(retCode);
}
return "Could not retrieve the exit code.";
}
}
typedef int Executor(HINSTANCE, int, const char **);
int StartHost()
{
string runtimePath = EnvironmentUtils::Get("KR_RUNTIME");
std::string khost = FileUtils::Join(runtimePath.c_str(), "khost.dll", NULL);
// now we need to load the host and get 'er booted
if (!FileUtils::IsFile(khost))
{
ShowError(string("Couldn't find required file: ") + khost);
return __LINE__;
}
HMODULE dll = LoadLibraryA(khost.c_str());
if (!dll)
{
char msg[MAX_PATH];
sprintf_s(msg,"Couldn't load file: %s, error: %d", khost.c_str(), GetLastError());
ShowError(msg);
return __LINE__;
}
Executor *executor = (Executor*)GetProcAddress(dll, "Execute");
if (!executor)
{
ShowError(string("Invalid entry point for") + khost);
return __LINE__;
}
return executor(::GetModuleHandle(NULL), argc,(const char**)argv);
}
bool RunInstaller(vector<SharedDependency> missing, bool forceInstall)
{
string exec = FileUtils::Join(
app->path.c_str(), "installer", "Installer.exe", NULL);
if (!FileUtils::IsFile(exec))
{
ShowError("Missing installer and application has additional modules that are needed.");
return false;
}
bool result = BootUtils::RunInstaller(missing, app, updateFile, "", false, forceInstall);
// Ugh. Now we need to figure out where the app installer installed
// to. We would normally use stdout, but we had to execute with
// an expensive call to ShellExecuteEx, so we're just going to read
// the information from a file.
if (!app->IsInstalled())
{
string installedToFile = FileUtils::Join(app->GetDataPath().c_str(), ".installedto", NULL);
// The user probably cancelled -- don't show an error
if (!FileUtils::IsFile(installedToFile))
return true;
std::ifstream file(installedToFile.c_str());
if (file.bad() || file.fail() || file.eof())
{
DeleteFileA(installedToFile.c_str());
ShowError("Could not determine where installer installed application.");
return false; // Don't show further errors
}
string appInstallPath;
std::getline(file, appInstallPath);
appInstallPath = FileUtils::Trim(appInstallPath);
SharedApplication newapp = Application::NewApplication(appInstallPath);
if (newapp.isNull())
{
return false; // Don't show further errors
}
else
{
app = newapp;
}
DeleteFileA(installedToFile.c_str());
}
return result;
}
string GetApplicationName()
{
if (!app.isNull())
{
return app->name.c_str();
}
return PRODUCT_NAME;
}
#ifdef USE_BREAKPAD
static google_breakpad::ExceptionHandler* breakpad;
extern string dumpFilePath;
char breakpadCallBuffer[MAX_PATH];
bool HandleCrash(
const wchar_t* dumpPath,
const wchar_t* id,
void* context,
EXCEPTION_POINTERS* exinfo,
MDRawAssertionInfo* assertion,
bool succeeded)
{
if (succeeded)
{
STARTUPINFOA startupInfo = {0};
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION processInformation;
_snprintf_s(breakpadCallBuffer, MAX_PATH, MAX_PATH - 1,
"\"%s\" \"%s\" %S %S", argv[0], CRASH_REPORT_OPT, dumpPath, id);
CreateProcessA(
NULL,
breakpadCallBuffer,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&startupInfo,
&processInformation);
}
// We would not normally need to do this, but on Windows XP it
// seems that this callback is called multiple times for a crash.
// We should probably try to remove the following line the next
// time we update breakpad.
exit(__LINE__);
return true;
}
wstring StringToWString(string in)
{
wstring out(in.length(), L' ');
copy(in.begin(), in.end(), out.begin());
return out;
}
map<wstring, wstring> GetCrashReportParametersW()
{
map<wstring, wstring> paramsW;
map<string, string> params = GetCrashReportParameters();
map<string, string>::iterator i = params.begin();
while (i != params.end())
{
wstring key = StringToWString(i->first);
wstring val = StringToWString(i->second);
i++;
paramsW[key] = val;
}
return paramsW;
}
int SendCrashReport()
{
InitCrashDetection();
std::string title = GetCrashDetectionTitle();
std::string msg = GetCrashDetectionHeader();
msg.append("\n\n");
msg.append(GetCrashDetectionMessage());
Win32PopupDialog popupDialog(NULL);
popupDialog.SetTitle(title);
popupDialog.SetMessage(msg);
popupDialog.SetShowCancelButton(true);
if (popupDialog.Show() != IDYES)
{
return __LINE__;
}
wstring url = L"https://";
url += StringToWString(CRASH_REPORT_URL);
const std::map<wstring, wstring> parameters = GetCrashReportParametersW();
wstring dumpFilePathW = StringToWString(dumpFilePath);
wstring responseBody;
int responseCode;
bool success = google_breakpad::HTTPUpload::SendRequest(
url,
parameters,
dumpFilePathW.c_str(),
L"dump",
NULL,
&responseBody,
&responseCode);
if (!success)
{
#ifdef DEBUG
ShowError("Error uploading crash dump.");
#endif
return __LINE__;
}
#ifdef DEBUG
else
{
MessageBoxW(NULL,L"Your crash report has been submitted. Thank You!",L"Error Reporting Status",MB_OK | MB_ICONINFORMATION);
}
#endif
return 0;
}
#endif
}
#if defined(OS_WIN32) && !defined(WIN32_CONSOLE)
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR command_line, int)
#else
int main(int __argc, const char* __argv[])
#endif
{
KrollBoot::argc = __argc;
KrollBoot::argv = (const char**) __argv;
#ifdef USE_BREAKPAD
// Don't install a handler if we are just handling an error.
if (__argc > 2 && !strcmp(CRASH_REPORT_OPT, __argv[1]))
{
return KrollBoot::SendCrashReport();
}
wchar_t tempPath[MAX_PATH];
GetTempPathW(MAX_PATH, tempPath);
KrollBoot::breakpad = new google_breakpad::ExceptionHandler(
tempPath,
NULL,
KrollBoot::HandleCrash,
NULL,
google_breakpad::ExceptionHandler::HANDLER_ALL);
#endif
// Only Windows XP systems will need to restart the host.
if (EnvironmentUtils::Has(BOOTSTRAP_ENV))
{
EnvironmentUtils::Unset(BOOTSTRAP_ENV);
return KrollBoot::StartHost();
}
else
{
return KrollBoot::Bootstrap();
}
}
<commit_msg>use QuickFormatMessage when khost.dll fails to load<commit_after>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008-2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "boot.h"
#include "popup_dialog_win32.h"
#include <process.h>
#include <windows.h>
using std::wstring;
#ifndef MAX_PATH
#define MAX_PATH 512
#endif
#ifdef USE_BREAKPAD
#include "client/windows/handler/exception_handler.h"
#include "common/windows/http_upload.h"
#endif
namespace KrollBoot
{
extern string applicationHome;
extern string updateFile;
extern SharedApplication app;
extern int argc;
extern const char** argv;
inline void ShowError(string msg, bool fatal)
{
std::cerr << "Error: " << msg << std::endl;
MessageBoxA(NULL, msg.c_str(), GetApplicationName().c_str(), MB_OK|MB_ICONERROR|MB_SYSTEMMODAL);
if (fatal)
exit(1);
}
std::string GetApplicationHomePath()
{
char path[MAX_PATH];
int size = GetModuleFileNameA(GetModuleHandle(NULL), (char*)path, MAX_PATH);
if (size>0)
{
path[size] = '\0';
}
return FileUtils::Dirname(string(path));
}
bool IsWindowsXP()
{
OSVERSIONINFO osVersion;
osVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
::GetVersionEx(&osVersion);
return osVersion.dwMajorVersion == 5;
}
void BootstrapPlatformSpecific(string path)
{
// Add runtime path and all module paths to PATH
path = app->runtime->path + ";" + path;
string currentPath = EnvironmentUtils::Get("PATH");
if (!currentPath.empty())
{
path = path + ":" + currentPath;
}
EnvironmentUtils::Set("PATH", path);
}
string Blastoff()
{
if (!IsWindowsXP())
{
// Windows boot does not normally need to restart itself, so just
// launch the host here and exit with the appropriate return value.
EnvironmentUtils::Unset(BOOTSTRAP_ENV);
exit(KrollBoot::StartHost());
}
// TODO: Fix manual activation context setup for Windows XP so we don't need
// to do the thing below any longer.
// We are on Windows XP. We need to reboot ourselves, but using the kboot.exe
// that is included with the runtime. The manifest embedded in kboot points
// to a DLL named "WebKit.dll" relative to the exe -- we need that path to
// resolve for registration-free COM to work.
string allArgs;
for (int i = 0; i < argc; i++)
{
string arg = argv[i];
size_t quotePos = arg.find('\"');
if (quotePos == string::npos)
{
allArgs.append("\"");
allArgs.append(arg);
allArgs.append("\" ");
}
else
{
allArgs.append(arg + " ");
}
}
string appName = app->runtime->path + "\\kboot.exe";
STARTUPINFOA startupInfo = {0};
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION processInformation;
char* applicationName = _strdup(appName.c_str());
char* allArguments = _strdup(allArgs.c_str());
int success = CreateProcessA(
applicationName, allArguments,
NULL, NULL, FALSE, 0, NULL, NULL,
&startupInfo, &processInformation);
free(applicationName);
free(allArguments);
if (success == 0)
{
string errorString = string("Could not bootstrap into ");
errorString.append(appName);
errorString.append(": ");
errorString.append(KrollUtils::Win32Utils::QuickFormatMessage(GetLastError()));
ShowError(errorString);
}
else
{
CloseHandle(processInformation.hThread);
WaitForSingleObject(processInformation.hProcess, INFINITE);
DWORD retCode;
if (GetExitCodeProcess(processInformation.hProcess, &retCode))
{
exit(retCode);
}
return "Could not retrieve the exit code.";
}
}
typedef int Executor(HINSTANCE, int, const char **);
int StartHost()
{
string runtimePath = EnvironmentUtils::Get("KR_RUNTIME");
std::string khost = FileUtils::Join(runtimePath.c_str(), "khost.dll", NULL);
// now we need to load the host and get 'er booted
if (!FileUtils::IsFile(khost))
{
ShowError(string("Couldn't find required file: ") + khost);
return __LINE__;
}
HMODULE dll = LoadLibraryA(khost.c_str());
if (!dll)
{
char msg[MAX_PATH];
sprintf_s(msg,"Couldn't load file: %s, error: %s", khost.c_str(),
KrollUtils::Win32Utils::QuickFormatMessage(GetLastError()).c_str());
ShowError(msg);
return __LINE__;
}
Executor *executor = (Executor*)GetProcAddress(dll, "Execute");
if (!executor)
{
ShowError(string("Invalid entry point for") + khost);
return __LINE__;
}
return executor(::GetModuleHandle(NULL), argc,(const char**)argv);
}
bool RunInstaller(vector<SharedDependency> missing, bool forceInstall)
{
string exec = FileUtils::Join(
app->path.c_str(), "installer", "Installer.exe", NULL);
if (!FileUtils::IsFile(exec))
{
ShowError("Missing installer and application has additional modules that are needed.");
return false;
}
bool result = BootUtils::RunInstaller(missing, app, updateFile, "", false, forceInstall);
// Ugh. Now we need to figure out where the app installer installed
// to. We would normally use stdout, but we had to execute with
// an expensive call to ShellExecuteEx, so we're just going to read
// the information from a file.
if (!app->IsInstalled())
{
string installedToFile = FileUtils::Join(app->GetDataPath().c_str(), ".installedto", NULL);
// The user probably cancelled -- don't show an error
if (!FileUtils::IsFile(installedToFile))
return true;
std::ifstream file(installedToFile.c_str());
if (file.bad() || file.fail() || file.eof())
{
DeleteFileA(installedToFile.c_str());
ShowError("Could not determine where installer installed application.");
return false; // Don't show further errors
}
string appInstallPath;
std::getline(file, appInstallPath);
appInstallPath = FileUtils::Trim(appInstallPath);
SharedApplication newapp = Application::NewApplication(appInstallPath);
if (newapp.isNull())
{
return false; // Don't show further errors
}
else
{
app = newapp;
}
DeleteFileA(installedToFile.c_str());
}
return result;
}
string GetApplicationName()
{
if (!app.isNull())
{
return app->name.c_str();
}
return PRODUCT_NAME;
}
#ifdef USE_BREAKPAD
static google_breakpad::ExceptionHandler* breakpad;
extern string dumpFilePath;
char breakpadCallBuffer[MAX_PATH];
bool HandleCrash(
const wchar_t* dumpPath,
const wchar_t* id,
void* context,
EXCEPTION_POINTERS* exinfo,
MDRawAssertionInfo* assertion,
bool succeeded)
{
if (succeeded)
{
STARTUPINFOA startupInfo = {0};
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION processInformation;
_snprintf_s(breakpadCallBuffer, MAX_PATH, MAX_PATH - 1,
"\"%s\" \"%s\" %S %S", argv[0], CRASH_REPORT_OPT, dumpPath, id);
CreateProcessA(
NULL,
breakpadCallBuffer,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&startupInfo,
&processInformation);
}
// We would not normally need to do this, but on Windows XP it
// seems that this callback is called multiple times for a crash.
// We should probably try to remove the following line the next
// time we update breakpad.
exit(__LINE__);
return true;
}
wstring StringToWString(string in)
{
wstring out(in.length(), L' ');
copy(in.begin(), in.end(), out.begin());
return out;
}
map<wstring, wstring> GetCrashReportParametersW()
{
map<wstring, wstring> paramsW;
map<string, string> params = GetCrashReportParameters();
map<string, string>::iterator i = params.begin();
while (i != params.end())
{
wstring key = StringToWString(i->first);
wstring val = StringToWString(i->second);
i++;
paramsW[key] = val;
}
return paramsW;
}
int SendCrashReport()
{
InitCrashDetection();
std::string title = GetCrashDetectionTitle();
std::string msg = GetCrashDetectionHeader();
msg.append("\n\n");
msg.append(GetCrashDetectionMessage());
Win32PopupDialog popupDialog(NULL);
popupDialog.SetTitle(title);
popupDialog.SetMessage(msg);
popupDialog.SetShowCancelButton(true);
if (popupDialog.Show() != IDYES)
{
return __LINE__;
}
wstring url = L"https://";
url += StringToWString(CRASH_REPORT_URL);
const std::map<wstring, wstring> parameters = GetCrashReportParametersW();
wstring dumpFilePathW = StringToWString(dumpFilePath);
wstring responseBody;
int responseCode;
bool success = google_breakpad::HTTPUpload::SendRequest(
url,
parameters,
dumpFilePathW.c_str(),
L"dump",
NULL,
&responseBody,
&responseCode);
if (!success)
{
#ifdef DEBUG
ShowError("Error uploading crash dump.");
#endif
return __LINE__;
}
#ifdef DEBUG
else
{
MessageBoxW(NULL,L"Your crash report has been submitted. Thank You!",L"Error Reporting Status",MB_OK | MB_ICONINFORMATION);
}
#endif
return 0;
}
#endif
}
#if defined(OS_WIN32) && !defined(WIN32_CONSOLE)
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR command_line, int)
#else
int main(int __argc, const char* __argv[])
#endif
{
KrollBoot::argc = __argc;
KrollBoot::argv = (const char**) __argv;
#ifdef USE_BREAKPAD
// Don't install a handler if we are just handling an error.
if (__argc > 2 && !strcmp(CRASH_REPORT_OPT, __argv[1]))
{
return KrollBoot::SendCrashReport();
}
wchar_t tempPath[MAX_PATH];
GetTempPathW(MAX_PATH, tempPath);
KrollBoot::breakpad = new google_breakpad::ExceptionHandler(
tempPath,
NULL,
KrollBoot::HandleCrash,
NULL,
google_breakpad::ExceptionHandler::HANDLER_ALL);
#endif
// Only Windows XP systems will need to restart the host.
if (EnvironmentUtils::Has(BOOTSTRAP_ENV))
{
EnvironmentUtils::Unset(BOOTSTRAP_ENV);
return KrollBoot::StartHost();
}
else
{
return KrollBoot::Bootstrap();
}
}
<|endoftext|> |
<commit_before>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ inlcludes
// Local includes
#include "fe.h"
#include "elem.h"
template <>
Real FE<0,LAGRANGE>::shape(const ElemType,
const Order,
const unsigned int i,
const Point&)
{
libmesh_assert (i < 1);
return 1.;
}
template <>
Real FE<0,LAGRANGE>::shape(const Elem*,
const Order,
const unsigned int i,
const Point&)
{
libmesh_assert (i < 1);
return 1.;
}
template <>
Real FE<0,LAGRANGE>::shape_deriv(const ElemType,
const Order,
const unsigned int,
const unsigned int,
const Point&)
{
// No spatial derivatives in 0D!
libmesh_error();
return 0.;
}
template <>
Real FE<0,LAGRANGE>::shape_deriv(const Elem*,
const Order,
const unsigned int,
const unsigned int,
const Point&)
{
// No spatial derivatives in 0D!
libmesh_error();
return 0.;
}
template <>
Real FE<0,LAGRANGE>::shape_second_deriv(const ElemType,
const Order,
const unsigned int,
const unsigned int,
const Point&)
{
// No spatial derivatives in 0D!
libmesh_error();
return 0.;
}
template <>
Real FE<0,LAGRANGE>::shape_second_deriv(const Elem*,
const Order,
const unsigned int,
const unsigned int,
const Point&)
{
// No spatial derivatives in 0D!
libmesh_error();
return 0.;
}
<commit_msg>comment typo fix<commit_after>// $Id$
// The libMesh Finite Element Library.
// Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
// Local includes
#include "fe.h"
#include "elem.h"
template <>
Real FE<0,LAGRANGE>::shape(const ElemType,
const Order,
const unsigned int i,
const Point&)
{
libmesh_assert (i < 1);
return 1.;
}
template <>
Real FE<0,LAGRANGE>::shape(const Elem*,
const Order,
const unsigned int i,
const Point&)
{
libmesh_assert (i < 1);
return 1.;
}
template <>
Real FE<0,LAGRANGE>::shape_deriv(const ElemType,
const Order,
const unsigned int,
const unsigned int,
const Point&)
{
// No spatial derivatives in 0D!
libmesh_error();
return 0.;
}
template <>
Real FE<0,LAGRANGE>::shape_deriv(const Elem*,
const Order,
const unsigned int,
const unsigned int,
const Point&)
{
// No spatial derivatives in 0D!
libmesh_error();
return 0.;
}
template <>
Real FE<0,LAGRANGE>::shape_second_deriv(const ElemType,
const Order,
const unsigned int,
const unsigned int,
const Point&)
{
// No spatial derivatives in 0D!
libmesh_error();
return 0.;
}
template <>
Real FE<0,LAGRANGE>::shape_second_deriv(const Elem*,
const Order,
const unsigned int,
const unsigned int,
const Point&)
{
// No spatial derivatives in 0D!
libmesh_error();
return 0.;
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/visualization/software-license/
*
* 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 "GaussianDistribution.h"
#include <cmath>
#include "boost/math/distributions/normal.hpp"
namespace madai {
struct GaussianDistribution::GaussianDistributionPrivate {
/** Underlying class from Boost library that computes the things we want. */
boost::math::normal m_InternalDistribution;
GaussianDistributionPrivate(double mean, double standardDeviation);
};
GaussianDistribution::GaussianDistributionPrivate
::GaussianDistributionPrivate(double mean, double standardDeviation) :
m_InternalDistribution(mean, standardDeviation)
{
}
GaussianDistribution
::GaussianDistribution() :
m_Mean( 0.0 ),
m_StandardDeviation( 1.0 ),
m_GaussianDistributionImplementation(
new GaussianDistribution::GaussianDistributionPrivate(
m_Mean, m_StandardDeviation))
{
}
GaussianDistribution
::~GaussianDistribution()
{
delete m_GaussianDistributionImplementation;
}
Distribution *
GaussianDistribution
::Clone() const
{
GaussianDistribution * d = new GaussianDistribution();
d->SetMean(this->GetMean());
d->SetStandardDeviation(this->GetStandardDeviation());
return d;
}
void
GaussianDistribution
::SetMean( double mean )
{
m_Mean = mean;
delete m_GaussianDistributionImplementation;
m_GaussianDistributionImplementation =
new GaussianDistribution::GaussianDistributionPrivate(
m_Mean, m_StandardDeviation);
}
double
GaussianDistribution
::GetMean() const
{
return m_Mean;
}
void
GaussianDistribution
::SetStandardDeviation( double standardDeviation )
{
m_StandardDeviation = standardDeviation;
delete m_GaussianDistributionImplementation;
m_GaussianDistributionImplementation =
new GaussianDistribution::GaussianDistributionPrivate(
m_Mean, m_StandardDeviation);
}
double
GaussianDistribution
::GetStandardDeviation() const
{
return m_StandardDeviation;
}
double
GaussianDistribution
::GetLogProbabilityDensity( double x ) const
{
return log( this->GetNormalizationFactor() ) + this->GetExponent( x );
}
double
GaussianDistribution
::GetGradientLogProbabilityDensity( double x ) const
{
double diff = x - m_Mean;
double variance = m_StandardDeviation * m_StandardDeviation;
return ( - diff / variance );
}
double
GaussianDistribution
::GetProbabilityDensity( double x ) const
{
//return this->GetNormalizationFactor() * exp( this->GetExponent( x ) );
return boost::math::pdf(
m_GaussianDistributionImplementation->m_InternalDistribution, x );
}
double
GaussianDistribution
::GetPercentile( double percentile ) const
{
return boost::math::quantile(
m_GaussianDistributionImplementation->m_InternalDistribution,
percentile );
}
double
GaussianDistribution
::GetSample(madai::Random & r) const
{
return r.Gaussian(this->m_Mean, this->m_StandardDeviation);
}
double
GaussianDistribution
::GetNormalizationFactor() const
{
double variance = m_StandardDeviation * m_StandardDeviation;
return (1.0 / sqrt( 2.0 * M_PI * variance ) );
}
double
GaussianDistribution
::GetExponent( double x ) const
{
double variance = m_StandardDeviation * m_StandardDeviation;
double exponent = -( x - m_Mean ) * ( x - m_Mean ) / ( 2.0 * variance );
return exponent;
}
double
GaussianDistribution
::GetExpectedValue() const
{
return m_Mean;
}
} // end namespace madai
<commit_msg>Enabled defintion of M_PI by defining _USE_MATH_DEFINES<commit_after>/*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/visualization/software-license/
*
* 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 "GaussianDistribution.h"
#define _USE_MATH_DEFINES // Needed for M_PI to be defined on Windows
#include <cmath>
#undef _USE_MATH_DEFINES
#include "boost/math/distributions/normal.hpp"
namespace madai {
struct GaussianDistribution::GaussianDistributionPrivate {
/** Underlying class from Boost library that computes the things we want. */
boost::math::normal m_InternalDistribution;
GaussianDistributionPrivate(double mean, double standardDeviation);
};
GaussianDistribution::GaussianDistributionPrivate
::GaussianDistributionPrivate(double mean, double standardDeviation) :
m_InternalDistribution(mean, standardDeviation)
{
}
GaussianDistribution
::GaussianDistribution() :
m_Mean( 0.0 ),
m_StandardDeviation( 1.0 ),
m_GaussianDistributionImplementation(
new GaussianDistribution::GaussianDistributionPrivate(
m_Mean, m_StandardDeviation))
{
}
GaussianDistribution
::~GaussianDistribution()
{
delete m_GaussianDistributionImplementation;
}
Distribution *
GaussianDistribution
::Clone() const
{
GaussianDistribution * d = new GaussianDistribution();
d->SetMean(this->GetMean());
d->SetStandardDeviation(this->GetStandardDeviation());
return d;
}
void
GaussianDistribution
::SetMean( double mean )
{
m_Mean = mean;
delete m_GaussianDistributionImplementation;
m_GaussianDistributionImplementation =
new GaussianDistribution::GaussianDistributionPrivate(
m_Mean, m_StandardDeviation);
}
double
GaussianDistribution
::GetMean() const
{
return m_Mean;
}
void
GaussianDistribution
::SetStandardDeviation( double standardDeviation )
{
m_StandardDeviation = standardDeviation;
delete m_GaussianDistributionImplementation;
m_GaussianDistributionImplementation =
new GaussianDistribution::GaussianDistributionPrivate(
m_Mean, m_StandardDeviation);
}
double
GaussianDistribution
::GetStandardDeviation() const
{
return m_StandardDeviation;
}
double
GaussianDistribution
::GetLogProbabilityDensity( double x ) const
{
return log( this->GetNormalizationFactor() ) + this->GetExponent( x );
}
double
GaussianDistribution
::GetGradientLogProbabilityDensity( double x ) const
{
double diff = x - m_Mean;
double variance = m_StandardDeviation * m_StandardDeviation;
return ( - diff / variance );
}
double
GaussianDistribution
::GetProbabilityDensity( double x ) const
{
//return this->GetNormalizationFactor() * exp( this->GetExponent( x ) );
return boost::math::pdf(
m_GaussianDistributionImplementation->m_InternalDistribution, x );
}
double
GaussianDistribution
::GetPercentile( double percentile ) const
{
return boost::math::quantile(
m_GaussianDistributionImplementation->m_InternalDistribution,
percentile );
}
double
GaussianDistribution
::GetSample(madai::Random & r) const
{
return r.Gaussian(this->m_Mean, this->m_StandardDeviation);
}
double
GaussianDistribution
::GetNormalizationFactor() const
{
double variance = m_StandardDeviation * m_StandardDeviation;
return (1.0 / sqrt( 2.0 * M_PI * variance ) );
}
double
GaussianDistribution
::GetExponent( double x ) const
{
double variance = m_StandardDeviation * m_StandardDeviation;
double exponent = -( x - m_Mean ) * ( x - m_Mean ) / ( 2.0 * variance );
return exponent;
}
double
GaussianDistribution
::GetExpectedValue() const
{
return m_Mean;
}
} // end namespace madai
<|endoftext|> |
<commit_before>// Copyright (c) 2010 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 "webkit/tools/test_shell/test_shell_webmimeregistry_impl.h"
#include "base/string_util.h"
#include "net/base/mime_util.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
using WebKit::WebString;
using WebKit::WebMimeRegistry;
namespace {
// Convert a WebString to ASCII, falling back on an empty string in the case
// of a non-ASCII string.
std::string ToASCIIOrEmpty(const WebString& string) {
if (!IsStringASCII(string))
return std::string();
return UTF16ToASCII(string);
}
} // namespace
TestShellWebMimeRegistryImpl::TestShellWebMimeRegistryImpl() {
media_map_.insert("video/ogg");
media_map_.insert("audio/ogg");
media_map_.insert("application/ogg");
codecs_map_.insert("theora");
codecs_map_.insert("vorbis");
}
WebMimeRegistry::SupportsType
TestShellWebMimeRegistryImpl::supportsMediaMIMEType(
const WebString& mime_type, const WebString& codecs) {
// Not supporting the container is a flat-out no.
if (!IsSupportedMediaMimeType(ToASCIIOrEmpty(mime_type).c_str()))
return IsNotSupported;
// If we don't recognize the codec, it's possible we support it.
std::vector<std::string> parsed_codecs;
net::ParseCodecString(ToASCIIOrEmpty(codecs).c_str(), &parsed_codecs, true);
if (!AreSupportedMediaCodecs(parsed_codecs))
return MayBeSupported;
// Otherwise we have a perfect match.
return IsSupported;
}
bool TestShellWebMimeRegistryImpl::IsSupportedMediaMimeType(
const std::string& mime_type) {
return media_map_.find(mime_type) != media_map_.end();
}
bool TestShellWebMimeRegistryImpl::AreSupportedMediaCodecs(
const std::vector<std::string>& codecs) {
for (size_t i = 0; i < codecs.size(); ++i) {
if (codecs_map_.find(codecs[i]) == codecs_map_.end()) {
return false;
}
}
return true;
}
<commit_msg>Add audio/wav and audio/x-wav to TestShellWebMimeRegistryImpl.<commit_after>// Copyright (c) 2010 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 "webkit/tools/test_shell/test_shell_webmimeregistry_impl.h"
#include "base/string_util.h"
#include "net/base/mime_util.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
using WebKit::WebString;
using WebKit::WebMimeRegistry;
namespace {
// Convert a WebString to ASCII, falling back on an empty string in the case
// of a non-ASCII string.
std::string ToASCIIOrEmpty(const WebString& string) {
if (!IsStringASCII(string))
return std::string();
return UTF16ToASCII(string);
}
} // namespace
TestShellWebMimeRegistryImpl::TestShellWebMimeRegistryImpl() {
// Claim we support Ogg+Theora/Vorbis.
media_map_.insert("video/ogg");
media_map_.insert("audio/ogg");
media_map_.insert("application/ogg");
codecs_map_.insert("theora");
codecs_map_.insert("vorbis");
// Claim we support WAV.
media_map_.insert("audio/wav");
media_map_.insert("audio/x-wav");
codecs_map_.insert("1"); // PCM for WAV.
}
WebMimeRegistry::SupportsType
TestShellWebMimeRegistryImpl::supportsMediaMIMEType(
const WebString& mime_type, const WebString& codecs) {
// Not supporting the container is a flat-out no.
if (!IsSupportedMediaMimeType(ToASCIIOrEmpty(mime_type).c_str()))
return IsNotSupported;
// If we don't recognize the codec, it's possible we support it.
std::vector<std::string> parsed_codecs;
net::ParseCodecString(ToASCIIOrEmpty(codecs).c_str(), &parsed_codecs, true);
if (!AreSupportedMediaCodecs(parsed_codecs))
return MayBeSupported;
// Otherwise we have a perfect match.
return IsSupported;
}
bool TestShellWebMimeRegistryImpl::IsSupportedMediaMimeType(
const std::string& mime_type) {
return media_map_.find(mime_type) != media_map_.end();
}
bool TestShellWebMimeRegistryImpl::AreSupportedMediaCodecs(
const std::vector<std::string>& codecs) {
for (size_t i = 0; i < codecs.size(); ++i) {
if (codecs_map_.find(codecs[i]) == codecs_map_.end()) {
return false;
}
}
return true;
}
<|endoftext|> |
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/logging.h"
#include <asl.h>
#include <sys/types.h>
#include <unistd.h>
#include "base/logging.h"
#include "base/scoped_generic.h"
#include "base/strings/string_number_conversions.h"
namespace remoting {
namespace {
const char kChromotingLoggingFacility[] = "org.chromium.chromoting";
// Define a scoper for objects allocated by asl_new.
struct ScopedAslMsgTraits {
static aslmsg InvalidValue() {
return nullptr;
}
static void Free(aslmsg msg) {
asl_free(msg);
}
};
typedef base::ScopedGeneric<aslmsg, ScopedAslMsgTraits> ScopedAslMsg;
// Logging message handler that writes to syslog.
// The log can be obtained by running the following in a terminal:
// syslog -k Facility org.chromium.chromoting
bool LogMessageToAsl(
logging::LogSeverity severity,
const char* file,
int line,
size_t message_start,
const std::string& message) {
int level;
switch(severity) {
case logging::LOG_INFO:
level = ASL_LEVEL_NOTICE;
break;
case logging::LOG_WARNING:
level = ASL_LEVEL_WARNING;
break;
case logging::LOG_ERROR:
level = ASL_LEVEL_ERR;
break;
case logging::LOG_FATAL:
level = ASL_LEVEL_EMERG;
break;
default:
// 'notice' is the lowest priority that the asl libraries will log by
// default.
level = ASL_LEVEL_NOTICE;
break;
}
ScopedAslMsg asl_message(asl_new(ASL_TYPE_MSG));
if (!asl_message.is_valid())
return false;
if (asl_set(asl_message.get(), ASL_KEY_FACILITY,
kChromotingLoggingFacility) != 0)
return false;
if (asl_set(asl_message.get(), ASL_KEY_LEVEL,
base::IntToString(level).c_str()) != 0)
return false;
// Restrict read access to the message to root and the current user.
if (asl_set(asl_message.get(), ASL_KEY_READ_UID,
base::IntToString(geteuid()).c_str()) != 0)
return false;
if (asl_set(asl_message.get(), ASL_KEY_MSG,
message.c_str() + message_start) != 0)
return false;
asl_send(nullptr, asl_message.get());
// Don't prevent message from being logged by traditional means.
return false;
}
} // namespace
void InitHostLogging() {
// Write logs to the system debug log.
logging::LoggingSettings settings;
settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
logging::InitLogging(settings);
// Write logs to syslog as well.
logging::SetLogMessageHandler(LogMessageToAsl);
}
} // namespace remoting
<commit_msg>Fix terminal spam caused by host crashes<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/logging.h"
#include <asl.h>
#include <sys/types.h>
#include <unistd.h>
#include "base/logging.h"
#include "base/scoped_generic.h"
#include "base/strings/string_number_conversions.h"
namespace remoting {
namespace {
const char kChromotingLoggingFacility[] = "org.chromium.chromoting";
// Define a scoper for objects allocated by asl_new.
struct ScopedAslMsgTraits {
static aslmsg InvalidValue() {
return nullptr;
}
static void Free(aslmsg msg) {
asl_free(msg);
}
};
typedef base::ScopedGeneric<aslmsg, ScopedAslMsgTraits> ScopedAslMsg;
// Logging message handler that writes to syslog.
// The log can be obtained by running the following in a terminal:
// syslog -k Facility org.chromium.chromoting
bool LogMessageToAsl(
logging::LogSeverity severity,
const char* file,
int line,
size_t message_start,
const std::string& message) {
int level;
switch(severity) {
case logging::LOG_INFO:
level = ASL_LEVEL_NOTICE;
break;
case logging::LOG_WARNING:
level = ASL_LEVEL_WARNING;
break;
case logging::LOG_ERROR:
case logging::LOG_FATAL:
level = ASL_LEVEL_ERR;
break;
default:
// 'notice' is the lowest priority that the asl libraries will log by
// default.
level = ASL_LEVEL_NOTICE;
break;
}
ScopedAslMsg asl_message(asl_new(ASL_TYPE_MSG));
if (!asl_message.is_valid())
return false;
if (asl_set(asl_message.get(), ASL_KEY_FACILITY,
kChromotingLoggingFacility) != 0)
return false;
if (asl_set(asl_message.get(), ASL_KEY_LEVEL,
base::IntToString(level).c_str()) != 0)
return false;
// Restrict read access to the message to root and the current user.
if (asl_set(asl_message.get(), ASL_KEY_READ_UID,
base::IntToString(geteuid()).c_str()) != 0)
return false;
if (asl_set(asl_message.get(), ASL_KEY_MSG,
message.c_str() + message_start) != 0)
return false;
asl_send(nullptr, asl_message.get());
// Don't prevent message from being logged by traditional means.
return false;
}
} // namespace
void InitHostLogging() {
// Write logs to the system debug log.
logging::LoggingSettings settings;
settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
logging::InitLogging(settings);
// Write logs to syslog as well.
logging::SetLogMessageHandler(LogMessageToAsl);
}
} // namespace remoting
<|endoftext|> |
<commit_before>// Copyright (c) 2011 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/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
class NotificationsPermissionTest : public UITest {
public:
NotificationsPermissionTest() {
dom_automation_enabled_ = true;
show_window_ = true;
}
};
// Flaky, http://crbug.com/62311.
TEST_F(NotificationsPermissionTest, FLAKY_TestUserGestureInfobar) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab(browser->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/notifications/notifications_request_function.html")));
WaitUntilTabCount(1);
// Request permission by calling request() while eval'ing an inline script;
// That's considered a user gesture to webkit, and should produce an infobar.
bool result;
ASSERT_TRUE(tab->ExecuteAndExtractBool(
L"",
L"window.domAutomationController.send(request());",
&result));
EXPECT_TRUE(result);
EXPECT_TRUE(tab->WaitForInfoBarCount(1));
}
// Flaky, http://crbug.com/62311.
TEST_F(NotificationsPermissionTest, FLAKY_TestNoUserGestureInfobar) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab(browser->GetActiveTab());
ASSERT_TRUE(tab.get());
// Load a page which just does a request; no user gesture should result
// in no infobar.
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/notifications/notifications_request_inline.html")));
WaitUntilTabCount(1);
size_t info_bar_count;
ASSERT_TRUE(tab->GetInfoBarCount(&info_bar_count));
EXPECT_EQ(0U, info_bar_count);
}
<commit_msg>Disable test that's timing out BUG=74428 TEST=none Review URL: http://codereview.chromium.org/6598038<commit_after>// Copyright (c) 2011 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/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
class NotificationsPermissionTest : public UITest {
public:
NotificationsPermissionTest() {
dom_automation_enabled_ = true;
show_window_ = true;
}
};
// Flaky, http://crbug.com/62311 and http://crbug.com/74428.
TEST_F(NotificationsPermissionTest, DISABLED_TestUserGestureInfobar) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab(browser->GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/notifications/notifications_request_function.html")));
WaitUntilTabCount(1);
// Request permission by calling request() while eval'ing an inline script;
// That's considered a user gesture to webkit, and should produce an infobar.
bool result;
ASSERT_TRUE(tab->ExecuteAndExtractBool(
L"",
L"window.domAutomationController.send(request());",
&result));
EXPECT_TRUE(result);
EXPECT_TRUE(tab->WaitForInfoBarCount(1));
}
// Flaky, http://crbug.com/62311.
TEST_F(NotificationsPermissionTest, FLAKY_TestNoUserGestureInfobar) {
net::TestServer test_server(net::TestServer::TYPE_HTTP,
FilePath(FILE_PATH_LITERAL("chrome/test/data")));
ASSERT_TRUE(test_server.Start());
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab(browser->GetActiveTab());
ASSERT_TRUE(tab.get());
// Load a page which just does a request; no user gesture should result
// in no infobar.
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURL(test_server.GetURL(
"files/notifications/notifications_request_inline.html")));
WaitUntilTabCount(1);
size_t info_bar_count;
ASSERT_TRUE(tab->GetInfoBarCount(&info_bar_count));
EXPECT_EQ(0U, info_bar_count);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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 <stdlib.h> // required by _set_abort_behavior
#include <gtk/gtk.h>
#include "base/command_line.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"
void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
gtk_init(argc, argv);
}
void TestShellPlatformDelegate::SelectUnifiedTheme() {
// Pick a theme that uses Cairo for drawing, since we:
// 1) currently don't support GTK themes that use the GDK drawing APIs, and
// 2) need to use a unified theme for layout tests anyway.
g_object_set(gtk_settings_get_default(),
"gtk-theme-name", "Mist",
NULL);
}
TestShellPlatformDelegate::TestShellPlatformDelegate(
const CommandLine& command_line)
: command_line_(command_line) {
}
bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
return true;
}
void TestShellPlatformDelegate::SuppressErrorReporting() {
}
void TestShellPlatformDelegate::InitializeGUI() {
}
void TestShellPlatformDelegate::SetWindowPositionForRecording(TestShell *) {
}
TestShellPlatformDelegate::~TestShellPlatformDelegate() {
}
<commit_msg>Do no use custom gtkrc files in layout test mode.<commit_after>// Copyright (c) 2009 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 <stdlib.h> // required by _set_abort_behavior
#include <gtk/gtk.h>
#include "base/command_line.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"
void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
gtk_init(argc, argv);
}
void TestShellPlatformDelegate::SelectUnifiedTheme() {
// Stop custom gtkrc files from messing with the theme.
gchar* default_gtkrc_files[] = { NULL };
gtk_rc_set_default_files(default_gtkrc_files);
gtk_rc_reparse_all_for_settings(gtk_settings_get_default(), TRUE);
// Pick a theme that uses Cairo for drawing, since we:
// 1) currently don't support GTK themes that use the GDK drawing APIs, and
// 2) need to use a unified theme for layout tests anyway.
g_object_set(gtk_settings_get_default(),
"gtk-theme-name", "Mist",
NULL);
}
TestShellPlatformDelegate::TestShellPlatformDelegate(
const CommandLine& command_line)
: command_line_(command_line) {
}
bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
return true;
}
void TestShellPlatformDelegate::SuppressErrorReporting() {
}
void TestShellPlatformDelegate::InitializeGUI() {
}
void TestShellPlatformDelegate::SetWindowPositionForRecording(TestShell *) {
}
TestShellPlatformDelegate::~TestShellPlatformDelegate() {
}
<|endoftext|> |
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "process_memory_stats.h"
#include <vespa/vespalib/stllike/asciistream.h>
#include <algorithm>
#include <vespa/log/log.h>
LOG_SETUP(".vespalib.util.process_memory_stats");
namespace vespalib {
namespace {
#ifdef __linux__
/*
* Check if line specifies an address range.
*
* address perms offset dev inode pathname
*
* 00400000-00420000 r-xp 00000000 fd:04 16545041 /usr/bin/less
*/
bool
isRange(vespalib::stringref line) {
for (char c : line) {
if (c == ' ') {
return true;
}
if (c == ':') {
return false;
}
}
return false;
}
/*
* Check if address range is anonymous, e.g. not mapped from file.
* inode number is 0 in that case.
*
* address perms offset dev inode pathname
*
* 00400000-00420000 r-xp 00000000 fd:04 16545041 /usr/bin/less
* 00625000-00628000 rw-p 00000000 00:00 0
*
* The range starting at 00400000 is not anonymous.
* The range starting at 00625000 is anonymous.
*/
bool
isAnonymous(vespalib::stringref line) {
int delims = 0;
for (char c : line) {
if (delims >= 4) {
return (c == '0');
}
if (c == ' ') {
++delims;
}
}
return true;
}
/*
* Lines not containing an address range contains a header and a
* value, e.g.
*
* Size: 128 kB
* Rss: 96 kB
* Anonymous: 0 kB
*
* The lines with header Anonymous are ignored, thus anonymous pages
* caused by mmap() of a file with MAP_PRIVATE flags are counted as
* mapped pages.
*/
vespalib::stringref
getLineHeader(vespalib::stringref line)
{
return line.substr(0, line.find(':'));
}
#endif
}
ProcessMemoryStats
ProcessMemoryStats::createStatsFromSmaps()
{
ProcessMemoryStats ret;
#ifdef __linux__
asciistream smaps = asciistream::createFromDevice("/proc/self/smaps");
bool anonymous = true;
uint64_t lineVal = 0;
while (!smaps.eof()) {
string backedLine = smaps.getline();
stringref line(backedLine);
if (isRange(line)) {
ret._mappings_count += 1;
anonymous = isAnonymous(line);
} else if (!line.empty()) {
stringref lineHeader = getLineHeader(line);
if (lineHeader == "Size") {
asciistream is(line.substr(lineHeader.size() + 1));
is >> lineVal;
if (anonymous) {
ret._anonymous_virt += lineVal * 1024;
} else {
ret._mapped_virt += lineVal * 1024;
}
} else if (lineHeader == "Rss") {
asciistream is(line.substr(lineHeader.size() + 1));
is >> lineVal;
if (anonymous) {
ret._anonymous_rss += lineVal * 1024;
} else {
ret._mapped_rss += lineVal * 1024;
}
}
}
}
#endif
return ret;
}
ProcessMemoryStats::ProcessMemoryStats()
: _mapped_virt(0),
_mapped_rss(0),
_anonymous_virt(0),
_anonymous_rss(0),
_mappings_count(0)
{
}
ProcessMemoryStats::ProcessMemoryStats(uint64_t mapped_virt,
uint64_t mapped_rss,
uint64_t anonymous_virt,
uint64_t anonymous_rss,
uint64_t mappings_cnt)
: _mapped_virt(mapped_virt),
_mapped_rss(mapped_rss),
_anonymous_virt(anonymous_virt),
_anonymous_rss(anonymous_rss),
_mappings_count(mappings_cnt)
{
}
namespace {
bool
similar(uint64_t lhs, uint64_t rhs, uint64_t epsilon)
{
return (lhs < rhs) ? ((rhs - lhs) <= epsilon) : ((lhs - rhs) <= epsilon);
}
}
bool
ProcessMemoryStats::similarTo(const ProcessMemoryStats &rhs, uint64_t sizeEpsilon) const
{
return similar(_mapped_virt, rhs._mapped_virt, sizeEpsilon) &&
similar(_mapped_rss, rhs._mapped_rss, sizeEpsilon) &&
similar(_anonymous_virt, rhs._anonymous_virt, sizeEpsilon) &&
similar(_anonymous_rss, rhs._anonymous_rss, sizeEpsilon) &&
(_mappings_count == rhs._mappings_count);
}
vespalib::string
ProcessMemoryStats::toString() const
{
vespalib::asciistream stream;
stream << "_mapped_virt=" << _mapped_virt << ", "
<< "_mapped_rss=" << _mapped_rss << ", "
<< "_anonymous_virt=" << _anonymous_virt << ", "
<< "_anonymous_rss=" << _anonymous_rss << ", "
<< "_mappings_count=" << _mappings_count;
return stream.str();
}
ProcessMemoryStats
ProcessMemoryStats::create(uint64_t sizeEpsilon)
{
constexpr size_t NUM_TRIES = 10;
std::vector<ProcessMemoryStats> samples;
samples.reserve(NUM_TRIES);
samples.push_back(createStatsFromSmaps());
for (size_t i = 0; i < NUM_TRIES; ++i) {
samples.push_back(createStatsFromSmaps());
if (samples.back().similarTo(*(samples.rbegin()+1), sizeEpsilon)) {
return samples.back();
}
LOG(debug, "create(): Memory stats have changed, trying to read smaps file again: i=%zu, prevStats={%s}, currStats={%s}",
i, (samples.rbegin()+1)->toString().c_str(), samples.back().toString().c_str());
}
std::sort(samples.begin(), samples.end());
LOG(debug, "We failed to find 2 consecutive samples that where similar with epsilon of %" PRIu64 ".\nSmallest is '%s',\n median is '%s',\n largest is '%s'",
sizeEpsilon, samples.front().toString().c_str(), samples[samples.size()/2].toString().c_str(), samples.back().toString().c_str());
return samples[samples.size()/2];
}
}
<commit_msg>Reduce to 3 tries as this is a rather expensive operation with many smaps.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "process_memory_stats.h"
#include <vespa/vespalib/stllike/asciistream.h>
#include <algorithm>
#include <vespa/log/log.h>
LOG_SETUP(".vespalib.util.process_memory_stats");
namespace vespalib {
namespace {
#ifdef __linux__
/*
* Check if line specifies an address range.
*
* address perms offset dev inode pathname
*
* 00400000-00420000 r-xp 00000000 fd:04 16545041 /usr/bin/less
*/
bool
isRange(vespalib::stringref line) {
for (char c : line) {
if (c == ' ') {
return true;
}
if (c == ':') {
return false;
}
}
return false;
}
/*
* Check if address range is anonymous, e.g. not mapped from file.
* inode number is 0 in that case.
*
* address perms offset dev inode pathname
*
* 00400000-00420000 r-xp 00000000 fd:04 16545041 /usr/bin/less
* 00625000-00628000 rw-p 00000000 00:00 0
*
* The range starting at 00400000 is not anonymous.
* The range starting at 00625000 is anonymous.
*/
bool
isAnonymous(vespalib::stringref line) {
int delims = 0;
for (char c : line) {
if (delims >= 4) {
return (c == '0');
}
if (c == ' ') {
++delims;
}
}
return true;
}
/*
* Lines not containing an address range contains a header and a
* value, e.g.
*
* Size: 128 kB
* Rss: 96 kB
* Anonymous: 0 kB
*
* The lines with header Anonymous are ignored, thus anonymous pages
* caused by mmap() of a file with MAP_PRIVATE flags are counted as
* mapped pages.
*/
vespalib::stringref
getLineHeader(vespalib::stringref line)
{
return line.substr(0, line.find(':'));
}
#endif
}
ProcessMemoryStats
ProcessMemoryStats::createStatsFromSmaps()
{
ProcessMemoryStats ret;
#ifdef __linux__
asciistream smaps = asciistream::createFromDevice("/proc/self/smaps");
bool anonymous = true;
uint64_t lineVal = 0;
while (!smaps.eof()) {
string backedLine = smaps.getline();
stringref line(backedLine);
if (isRange(line)) {
ret._mappings_count += 1;
anonymous = isAnonymous(line);
} else if (!line.empty()) {
stringref lineHeader = getLineHeader(line);
if (lineHeader == "Size") {
asciistream is(line.substr(lineHeader.size() + 1));
is >> lineVal;
if (anonymous) {
ret._anonymous_virt += lineVal * 1024;
} else {
ret._mapped_virt += lineVal * 1024;
}
} else if (lineHeader == "Rss") {
asciistream is(line.substr(lineHeader.size() + 1));
is >> lineVal;
if (anonymous) {
ret._anonymous_rss += lineVal * 1024;
} else {
ret._mapped_rss += lineVal * 1024;
}
}
}
}
#endif
return ret;
}
ProcessMemoryStats::ProcessMemoryStats()
: _mapped_virt(0),
_mapped_rss(0),
_anonymous_virt(0),
_anonymous_rss(0),
_mappings_count(0)
{
}
ProcessMemoryStats::ProcessMemoryStats(uint64_t mapped_virt,
uint64_t mapped_rss,
uint64_t anonymous_virt,
uint64_t anonymous_rss,
uint64_t mappings_cnt)
: _mapped_virt(mapped_virt),
_mapped_rss(mapped_rss),
_anonymous_virt(anonymous_virt),
_anonymous_rss(anonymous_rss),
_mappings_count(mappings_cnt)
{
}
namespace {
bool
similar(uint64_t lhs, uint64_t rhs, uint64_t epsilon)
{
return (lhs < rhs) ? ((rhs - lhs) <= epsilon) : ((lhs - rhs) <= epsilon);
}
}
bool
ProcessMemoryStats::similarTo(const ProcessMemoryStats &rhs, uint64_t sizeEpsilon) const
{
return similar(_mapped_virt, rhs._mapped_virt, sizeEpsilon) &&
similar(_mapped_rss, rhs._mapped_rss, sizeEpsilon) &&
similar(_anonymous_virt, rhs._anonymous_virt, sizeEpsilon) &&
similar(_anonymous_rss, rhs._anonymous_rss, sizeEpsilon) &&
(_mappings_count == rhs._mappings_count);
}
vespalib::string
ProcessMemoryStats::toString() const
{
vespalib::asciistream stream;
stream << "_mapped_virt=" << _mapped_virt << ", "
<< "_mapped_rss=" << _mapped_rss << ", "
<< "_anonymous_virt=" << _anonymous_virt << ", "
<< "_anonymous_rss=" << _anonymous_rss << ", "
<< "_mappings_count=" << _mappings_count;
return stream.str();
}
ProcessMemoryStats
ProcessMemoryStats::create(uint64_t sizeEpsilon)
{
constexpr size_t NUM_TRIES = 3;
std::vector<ProcessMemoryStats> samples;
samples.reserve(NUM_TRIES);
samples.push_back(createStatsFromSmaps());
for (size_t i = 0; i < NUM_TRIES; ++i) {
samples.push_back(createStatsFromSmaps());
if (samples.back().similarTo(*(samples.rbegin()+1), sizeEpsilon)) {
return samples.back();
}
LOG(debug, "create(): Memory stats have changed, trying to read smaps file again: i=%zu, prevStats={%s}, currStats={%s}",
i, (samples.rbegin()+1)->toString().c_str(), samples.back().toString().c_str());
}
std::sort(samples.begin(), samples.end());
LOG(debug, "We failed to find 2 consecutive samples that where similar with epsilon of %" PRIu64 ".\nSmallest is '%s',\n median is '%s',\n largest is '%s'",
sizeEpsilon, samples.front().toString().c_str(), samples[samples.size()/2].toString().c_str(), samples.back().toString().c_str());
return samples[samples.size()/2];
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: UriSchemeParser_vndDOTsunDOTstarDOTexpand.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2007-03-12 10:55:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef \
INCLUDED_STOC_SOURCE_URIPROC_URISCHEMEPARSER_VNDDOTSUNDOTSTARDOTEXPAND_HXX
#define \
INCLUDED_STOC_SOURCE_URIPROC_URISCHEMEPARSER_VNDDOTSUNDOTSTARDOTEXPAND_HXX
#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif
#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_
#include "com/sun/star/uno/Exception.hpp"
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include "com/sun/star/uno/Reference.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include "com/sun/star/uno/Sequence.hxx"
#endif
#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
namespace com { namespace sun { namespace star { namespace uno {
class XComponentContext;
class XInterface;
} } } }
namespace rtl { class OUString; }
namespace stoc { namespace uriproc {
namespace UriSchemeParser_vndDOTsunDOTstarDOTexpand {
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
SAL_CALL create(
::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > const &)
SAL_THROW((::com::sun::star::uno::Exception));
::rtl::OUString SAL_CALL getImplementationName();
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getSupportedServiceNames();
}
} }
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.26); FILE MERGED 2008/04/01 15:42:29 thb 1.2.26.3: #i85898# Stripping all external header guards 2008/04/01 12:41:47 thb 1.2.26.2: #i85898# Stripping all external header guards 2008/03/31 07:26:13 rt 1.2.26.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: UriSchemeParser_vndDOTsunDOTstarDOTexpand.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef \
INCLUDED_STOC_SOURCE_URIPROC_URISCHEMEPARSER_VNDDOTSUNDOTSTARDOTEXPAND_HXX
#define \
INCLUDED_STOC_SOURCE_URIPROC_URISCHEMEPARSER_VNDDOTSUNDOTSTARDOTEXPAND_HXX
#include "sal/config.h"
#include "com/sun/star/uno/Exception.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Sequence.hxx"
#include "sal/types.h"
namespace com { namespace sun { namespace star { namespace uno {
class XComponentContext;
class XInterface;
} } } }
namespace rtl { class OUString; }
namespace stoc { namespace uriproc {
namespace UriSchemeParser_vndDOTsunDOTstarDOTexpand {
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
SAL_CALL create(
::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext > const &)
SAL_THROW((::com::sun::star::uno::Exception));
::rtl::OUString SAL_CALL getImplementationName();
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
getSupportedServiceNames();
}
} }
#endif
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/
#include "winscwtoolchain.h"
using namespace ProjectExplorer;
using namespace Qt4ProjectManager::Internal;
WINSCWToolChain::WINSCWToolChain(S60Devices::Device device, const QString &mwcDirectory)
: m_carbidePath(mwcDirectory),
m_deviceId(device.id),
m_deviceName(device.name),
m_deviceRoot(device.epocRoot)
{
}
ToolChain::ToolChainType WINSCWToolChain::type() const
{
return ToolChain::WINSCW;
}
QByteArray WINSCWToolChain::predefinedMacros()
{
// TODO
return m_predefinedMacros;
}
QList<HeaderPath> WINSCWToolChain::systemHeaderPaths()
{
if (m_systemHeaderPaths.isEmpty()) {
foreach (const QString &value, systemIncludes()) {
m_systemHeaderPaths.append(HeaderPath(value, HeaderPath::GlobalHeaderPath));
}
}
return m_systemHeaderPaths;
}
QStringList WINSCWToolChain::systemIncludes() const
{
QStringList symIncludes = QStringList()
<< "\\MSL\\MSL_C\\MSL_Common\\Include"
<< "\\MSL\\MSL_C\\MSL_Win32\\Include"
<< "\\MSL\\MSL_CMSL_X86"
<< "\\MSL\\MSL_C++\\MSL_Common\\Include"
<< "\\MSL\\MSL_Extras\\MSL_Common\\Include"
<< "\\MSL\\MSL_Extras\\MSL_Win32\\Include"
<< "\\Win32-x86 Support\\Headers\\Win32 SDK";
for (int i = 0; i < symIncludes.size(); ++i)
symIncludes[i].prepend(QString("%1\\x86Build\\Symbian_Support").arg(m_carbidePath));
return symIncludes;
}
void WINSCWToolChain::addToEnvironment(ProjectExplorer::Environment &env)
{
env.set("MWCSYM2INCLUDES", systemIncludes().join(";"));
QStringList symLibraries = QStringList()
<< "\\Win32-x86 Support\\Libraries\\Win32 SDK"
<< "\\Runtime\\Runtime_x86\\Runtime_Win32\\Libs";
for (int i = 0; i < symLibraries.size(); ++i)
symLibraries[i].prepend(QString("%1\\x86Build\\Symbian_Support").arg(m_carbidePath));
env.set("MWSYM2LIBRARIES", symLibraries.join(";"));
env.set("MWSYM2LIBRARYFILES", "MSL_All_MSE_Symbian_D.lib;gdi32.lib;user32.lib;kernel32.lib");
env.prependOrSetPath(QString("%1\\x86Build\\Symbian_Tools\\Command_Line_Tools").arg(m_carbidePath)); // compiler
env.prependOrSetPath(QString("%1\\epoc32\\tools").arg(m_deviceRoot)); // e.g. make.exe
env.prependOrSetPath(QString("%1\\epoc32\\gcc\\bin").arg(m_deviceRoot)); // e.g. gcc.exe
env.set("EPOCDEVICE", QString("%1:%2").arg(m_deviceId, m_deviceName));
env.set("EPOCROOT", S60Devices::cleanedRootPath(m_deviceRoot));
}
QString WINSCWToolChain::makeCommand() const
{
return "make";
}
QString WINSCWToolChain::defaultMakeTarget() const
{
return "debug-winscw";
}
bool WINSCWToolChain::equals(ToolChain *other) const
{
return (other->type() == type()
&& m_deviceId == static_cast<WINSCWToolChain *>(other)->m_deviceId
&& m_deviceName == static_cast<WINSCWToolChain *>(other)->m_deviceName);
}
<commit_msg>If no mwc path is set explicitly, still don't destroy working environment.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
**
**************************************************************************/
#include "winscwtoolchain.h"
#include <QtDebug>
using namespace ProjectExplorer;
using namespace Qt4ProjectManager::Internal;
WINSCWToolChain::WINSCWToolChain(S60Devices::Device device, const QString &mwcDirectory)
: m_carbidePath(mwcDirectory),
m_deviceId(device.id),
m_deviceName(device.name),
m_deviceRoot(device.epocRoot)
{
}
ToolChain::ToolChainType WINSCWToolChain::type() const
{
return ToolChain::WINSCW;
}
QByteArray WINSCWToolChain::predefinedMacros()
{
// TODO
return m_predefinedMacros;
}
QList<HeaderPath> WINSCWToolChain::systemHeaderPaths()
{
if (m_systemHeaderPaths.isEmpty()) {
foreach (const QString &value, systemIncludes()) {
m_systemHeaderPaths.append(HeaderPath(value, HeaderPath::GlobalHeaderPath));
}
}
return m_systemHeaderPaths;
}
QStringList WINSCWToolChain::systemIncludes() const
{
if (m_carbidePath.isEmpty()) {
qDebug() << "no carbide path set";
ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment();
QString symIncludesValue = env.value("MWCSYM2INCLUDES");
qDebug() << "includes:" << symIncludesValue.split(";");
if (!symIncludesValue.isEmpty())
return symIncludesValue.split(";");
} else {
QStringList symIncludes = QStringList()
<< "\\MSL\\MSL_C\\MSL_Common\\Include"
<< "\\MSL\\MSL_C\\MSL_Win32\\Include"
<< "\\MSL\\MSL_CMSL_X86"
<< "\\MSL\\MSL_C++\\MSL_Common\\Include"
<< "\\MSL\\MSL_Extras\\MSL_Common\\Include"
<< "\\MSL\\MSL_Extras\\MSL_Win32\\Include"
<< "\\Win32-x86 Support\\Headers\\Win32 SDK";
for (int i = 0; i < symIncludes.size(); ++i)
symIncludes[i].prepend(QString("%1\\x86Build\\Symbian_Support").arg(m_carbidePath));
return symIncludes;
}
return QStringList();
}
void WINSCWToolChain::addToEnvironment(ProjectExplorer::Environment &env)
{
if (!m_carbidePath.isEmpty()) {
env.set("MWCSYM2INCLUDES", systemIncludes().join(";"));
QStringList symLibraries = QStringList()
<< "\\Win32-x86 Support\\Libraries\\Win32 SDK"
<< "\\Runtime\\Runtime_x86\\Runtime_Win32\\Libs";
for (int i = 0; i < symLibraries.size(); ++i)
symLibraries[i].prepend(QString("%1\\x86Build\\Symbian_Support").arg(m_carbidePath));
env.set("MWSYM2LIBRARIES", symLibraries.join(";"));
env.set("MWSYM2LIBRARYFILES", "MSL_All_MSE_Symbian_D.lib;gdi32.lib;user32.lib;kernel32.lib");
env.prependOrSetPath(QString("%1\\x86Build\\Symbian_Tools\\Command_Line_Tools").arg(m_carbidePath)); // compiler
}
env.prependOrSetPath(QString("%1\\epoc32\\tools").arg(m_deviceRoot)); // e.g. make.exe
env.prependOrSetPath(QString("%1\\epoc32\\gcc\\bin").arg(m_deviceRoot)); // e.g. gcc.exe
env.set("EPOCDEVICE", QString("%1:%2").arg(m_deviceId, m_deviceName));
env.set("EPOCROOT", S60Devices::cleanedRootPath(m_deviceRoot));
}
QString WINSCWToolChain::makeCommand() const
{
return "make";
}
QString WINSCWToolChain::defaultMakeTarget() const
{
return "debug-winscw";
}
bool WINSCWToolChain::equals(ToolChain *other) const
{
return (other->type() == type()
&& m_deviceId == static_cast<WINSCWToolChain *>(other)->m_deviceId
&& m_deviceName == static_cast<WINSCWToolChain *>(other)->m_deviceName);
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, 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 (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND 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.
*/
/**
* \file ir_mat_op_to_vec.cpp
*
* Breaks matrix operation expressions down to a series of vector operations.
*
* Generally this is how we have to codegen matrix operations for a
* GPU, so this gives us the chance to constant fold operations on a
* column or row.
*/
#include "ir.h"
#include "ir_expression_flattening.h"
#include "glsl_types.h"
class ir_mat_op_to_vec_visitor : public ir_hierarchical_visitor {
public:
ir_mat_op_to_vec_visitor()
{
this->made_progress = false;
}
ir_visitor_status visit_leave(ir_assignment *);
ir_rvalue *get_column(ir_variable *var, int i);
bool made_progress;
};
static bool
mat_op_to_vec_predicate(ir_instruction *ir)
{
ir_expression *expr = ir->as_expression();
unsigned int i;
if (!expr)
return false;
for (i = 0; i < expr->get_num_operands(); i++) {
if (expr->operands[i]->type->is_matrix())
return true;
}
return false;
}
bool
do_mat_op_to_vec(exec_list *instructions)
{
ir_mat_op_to_vec_visitor v;
/* Pull out any matrix expression to a separate assignment to a
* temp. This will make our handling of the breakdown to
* operations on the matrix's vector components much easier.
*/
do_expression_flattening(instructions, mat_op_to_vec_predicate);
visit_list_elements(&v, instructions);
return v.made_progress;
}
ir_rvalue *
ir_mat_op_to_vec_visitor::get_column(ir_variable *var, int i)
{
ir_dereference *deref;
if (!var->type->is_matrix()) {
deref = new(base_ir) ir_dereference_variable(var);
} else {
deref = new(base_ir) ir_dereference_variable(var);
deref = new(base_ir) ir_dereference_array(deref,
new(base_ir) ir_constant(i));
}
return deref;
}
ir_visitor_status
ir_mat_op_to_vec_visitor::visit_leave(ir_assignment *assign)
{
ir_expression *expr = assign->rhs->as_expression();
bool found_matrix = false;
unsigned int i, matrix_columns = 1;
ir_variable *op_var[2];
if (!expr)
return visit_continue;
for (i = 0; i < expr->get_num_operands(); i++) {
if (expr->operands[i]->type->is_matrix()) {
found_matrix = true;
matrix_columns = expr->operands[i]->type->matrix_columns;
break;
}
}
if (!found_matrix)
return visit_continue;
/* FINISHME: see below */
if (expr->operation == ir_binop_mul)
return visit_continue;
ir_dereference_variable *lhs_deref = assign->lhs->as_dereference_variable();
assert(lhs_deref);
ir_variable *result_var = lhs_deref->var;
/* Store the expression operands in temps so we can use them
* multiple times.
*/
for (i = 0; i < expr->get_num_operands(); i++) {
ir_assignment *assign;
op_var[i] = new(base_ir) ir_variable(expr->operands[i]->type,
"mat_op_to_vec");
base_ir->insert_before(op_var[i]);
lhs_deref = new(base_ir) ir_dereference_variable(op_var[i]);
assign = new(base_ir) ir_assignment(lhs_deref,
expr->operands[i],
NULL);
base_ir->insert_before(assign);
}
/* OK, time to break down this matrix operation. */
switch (expr->operation) {
case ir_binop_add:
case ir_binop_sub:
case ir_binop_div:
case ir_binop_mod:
/* For most operations, the matrix version is just going
* column-wise through and applying the operation to each column
* if available.
*/
for (i = 0; i < matrix_columns; i++) {
ir_rvalue *op0 = get_column(op_var[0], i);
ir_rvalue *op1 = get_column(op_var[1], i);
ir_rvalue *result = get_column(result_var, i);
ir_expression *column_expr;
ir_assignment *column_assign;
column_expr = new(base_ir) ir_expression(expr->operation,
result->type,
op0,
op1);
column_assign = new(base_ir) ir_assignment(result,
column_expr,
NULL);
base_ir->insert_before(column_assign);
}
break;
case ir_binop_mul:
/* FINISHME */
return visit_continue;
break;
default:
printf("FINISHME: Handle matrix operation for %s\n", expr->operator_string());
abort();
}
assign->remove();
this->made_progress = true;
return visit_continue;
}
<commit_msg>glsl2: Add matrix multiplication to ir_mat_op_to_vec.<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, 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 (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND 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.
*/
/**
* \file ir_mat_op_to_vec.cpp
*
* Breaks matrix operation expressions down to a series of vector operations.
*
* Generally this is how we have to codegen matrix operations for a
* GPU, so this gives us the chance to constant fold operations on a
* column or row.
*/
#include "ir.h"
#include "ir_expression_flattening.h"
#include "glsl_types.h"
class ir_mat_op_to_vec_visitor : public ir_hierarchical_visitor {
public:
ir_mat_op_to_vec_visitor()
{
this->made_progress = false;
}
ir_visitor_status visit_leave(ir_assignment *);
ir_rvalue *get_column(ir_variable *var, int col);
ir_rvalue *get_element(ir_variable *var, int col, int row);
void do_mul_mat_mat(ir_variable *result_var,
ir_variable *a_var, ir_variable *b_var);
void do_mul_mat_vec(ir_variable *result_var,
ir_variable *a_var, ir_variable *b_var);
void do_mul_vec_mat(ir_variable *result_var,
ir_variable *a_var, ir_variable *b_var);
void do_mul_mat_scalar(ir_variable *result_var,
ir_variable *a_var, ir_variable *b_var);
bool made_progress;
};
static bool
mat_op_to_vec_predicate(ir_instruction *ir)
{
ir_expression *expr = ir->as_expression();
unsigned int i;
if (!expr)
return false;
for (i = 0; i < expr->get_num_operands(); i++) {
if (expr->operands[i]->type->is_matrix())
return true;
}
return false;
}
bool
do_mat_op_to_vec(exec_list *instructions)
{
ir_mat_op_to_vec_visitor v;
/* Pull out any matrix expression to a separate assignment to a
* temp. This will make our handling of the breakdown to
* operations on the matrix's vector components much easier.
*/
do_expression_flattening(instructions, mat_op_to_vec_predicate);
visit_list_elements(&v, instructions);
return v.made_progress;
}
ir_rvalue *
ir_mat_op_to_vec_visitor::get_element(ir_variable *var, int col, int row)
{
ir_dereference *deref;
deref = new(base_ir) ir_dereference_variable(var);
if (var->type->is_matrix()) {
deref = new(base_ir) ir_dereference_array(var,
new(base_ir) ir_constant(col));
} else {
assert(col == 0);
}
return new(base_ir) ir_swizzle(deref, row, 0, 0, 0, 1);
}
ir_rvalue *
ir_mat_op_to_vec_visitor::get_column(ir_variable *var, int row)
{
ir_dereference *deref;
if (!var->type->is_matrix()) {
deref = new(base_ir) ir_dereference_variable(var);
} else {
deref = new(base_ir) ir_dereference_variable(var);
deref = new(base_ir) ir_dereference_array(deref,
new(base_ir) ir_constant(row));
}
return deref;
}
void
ir_mat_op_to_vec_visitor::do_mul_mat_mat(ir_variable *result_var,
ir_variable *a_var,
ir_variable *b_var)
{
int b_col, i;
ir_assignment *assign;
ir_expression *expr;
for (b_col = 0; b_col < b_var->type->matrix_columns; b_col++) {
ir_rvalue *a = get_column(a_var, 0);
ir_rvalue *b = get_element(b_var, b_col, 0);
/* first column */
expr = new(base_ir) ir_expression(ir_binop_mul,
a->type,
a,
b);
/* following columns */
for (i = 1; i < a_var->type->matrix_columns; i++) {
ir_expression *mul_expr;
a = get_column(a_var, i);
b = get_element(b_var, b_col, i);
mul_expr = new(base_ir) ir_expression(ir_binop_mul,
a->type,
a,
b);
expr = new(base_ir) ir_expression(ir_binop_add,
a->type,
expr,
mul_expr);
}
ir_rvalue *result = get_column(result_var, b_col);
assign = new(base_ir) ir_assignment(result,
expr,
NULL);
base_ir->insert_before(assign);
}
}
void
ir_mat_op_to_vec_visitor::do_mul_mat_vec(ir_variable *result_var,
ir_variable *a_var,
ir_variable *b_var)
{
int i;
ir_rvalue *a = get_column(a_var, 0);
ir_rvalue *b = get_element(b_var, 0, 0);
ir_assignment *assign;
ir_expression *expr;
/* first column */
expr = new(base_ir) ir_expression(ir_binop_mul,
result_var->type,
a,
b);
/* following columns */
for (i = 1; i < a_var->type->matrix_columns; i++) {
ir_expression *mul_expr;
a = get_column(a_var, i);
b = get_element(b_var, 0, i);
mul_expr = new(base_ir) ir_expression(ir_binop_mul,
result_var->type,
a,
b);
expr = new(base_ir) ir_expression(ir_binop_add,
result_var->type,
expr,
mul_expr);
}
ir_rvalue *result = new(base_ir) ir_dereference_variable(result_var);
assign = new(base_ir) ir_assignment(result,
expr,
NULL);
base_ir->insert_before(assign);
}
void
ir_mat_op_to_vec_visitor::do_mul_vec_mat(ir_variable *result_var,
ir_variable *a_var,
ir_variable *b_var)
{
int i;
for (i = 0; i < b_var->type->matrix_columns; i++) {
ir_rvalue *a = new(base_ir) ir_dereference_variable(a_var);
ir_rvalue *b = get_column(b_var, i);
ir_rvalue *result;
ir_expression *column_expr;
ir_assignment *column_assign;
result = new(base_ir) ir_dereference_variable(result_var);
result = new(base_ir) ir_swizzle(result, i, 0, 0, 0, 1);
column_expr = new(base_ir) ir_expression(ir_binop_dot,
result->type,
a,
b);
column_assign = new(base_ir) ir_assignment(result,
column_expr,
NULL);
base_ir->insert_before(column_assign);
}
}
void
ir_mat_op_to_vec_visitor::do_mul_mat_scalar(ir_variable *result_var,
ir_variable *a_var,
ir_variable *b_var)
{
int i;
for (i = 0; i < a_var->type->matrix_columns; i++) {
ir_rvalue *a = get_column(a_var, i);
ir_rvalue *b = new(base_ir) ir_dereference_variable(b_var);
ir_rvalue *result = get_column(result_var, i);
ir_expression *column_expr;
ir_assignment *column_assign;
column_expr = new(base_ir) ir_expression(ir_binop_mul,
result->type,
a,
b);
column_assign = new(base_ir) ir_assignment(result,
column_expr,
NULL);
base_ir->insert_before(column_assign);
}
}
ir_visitor_status
ir_mat_op_to_vec_visitor::visit_leave(ir_assignment *assign)
{
ir_expression *expr = assign->rhs->as_expression();
bool found_matrix = false;
unsigned int i, matrix_columns = 1;
ir_variable *op_var[2];
if (!expr)
return visit_continue;
for (i = 0; i < expr->get_num_operands(); i++) {
if (expr->operands[i]->type->is_matrix()) {
found_matrix = true;
matrix_columns = expr->operands[i]->type->matrix_columns;
break;
}
}
if (!found_matrix)
return visit_continue;
ir_dereference_variable *lhs_deref = assign->lhs->as_dereference_variable();
assert(lhs_deref);
ir_variable *result_var = lhs_deref->var;
/* Store the expression operands in temps so we can use them
* multiple times.
*/
for (i = 0; i < expr->get_num_operands(); i++) {
ir_assignment *assign;
op_var[i] = new(base_ir) ir_variable(expr->operands[i]->type,
"mat_op_to_vec");
base_ir->insert_before(op_var[i]);
lhs_deref = new(base_ir) ir_dereference_variable(op_var[i]);
assign = new(base_ir) ir_assignment(lhs_deref,
expr->operands[i],
NULL);
base_ir->insert_before(assign);
}
/* OK, time to break down this matrix operation. */
switch (expr->operation) {
case ir_binop_add:
case ir_binop_sub:
case ir_binop_div:
case ir_binop_mod:
/* For most operations, the matrix version is just going
* column-wise through and applying the operation to each column
* if available.
*/
for (i = 0; i < matrix_columns; i++) {
ir_rvalue *op0 = get_column(op_var[0], i);
ir_rvalue *op1 = get_column(op_var[1], i);
ir_rvalue *result = get_column(result_var, i);
ir_expression *column_expr;
ir_assignment *column_assign;
column_expr = new(base_ir) ir_expression(expr->operation,
result->type,
op0,
op1);
column_assign = new(base_ir) ir_assignment(result,
column_expr,
NULL);
base_ir->insert_before(column_assign);
}
break;
case ir_binop_mul:
if (op_var[0]->type->is_matrix()) {
if (op_var[1]->type->is_matrix()) {
do_mul_mat_mat(result_var, op_var[0], op_var[1]);
} else if (op_var[1]->type->is_vector()) {
do_mul_mat_vec(result_var, op_var[0], op_var[1]);
} else {
assert(op_var[1]->type->is_scalar());
do_mul_mat_scalar(result_var, op_var[0], op_var[1]);
}
} else {
assert(op_var[1]->type->is_matrix());
if (op_var[0]->type->is_vector()) {
do_mul_vec_mat(result_var, op_var[0], op_var[1]);
} else {
assert(op_var[0]->type->is_scalar());
do_mul_mat_scalar(result_var, op_var[1], op_var[0]);
}
}
break;
default:
printf("FINISHME: Handle matrix operation for %s\n", expr->operator_string());
abort();
}
assign->remove();
this->made_progress = true;
return visit_continue;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012-2015 Advanced Micro Devices, Inc.
* All rights reserved.
*
* For use for simulation and test purposes only
*
* 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 name of the copyright holder 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.
*
* Author: Steve Reinhardt
*/
#include "gpu-compute/hsail_code.hh"
#include "arch/gpu_types.hh"
#include "arch/hsail/Brig.h"
#include "arch/hsail/operand.hh"
#include "config/the_gpu_isa.hh"
#include "debug/BRIG.hh"
#include "debug/HSAILObject.hh"
#include "gpu-compute/brig_object.hh"
#include "gpu-compute/gpu_static_inst.hh"
#include "gpu-compute/kernel_cfg.hh"
using namespace Brig;
int getBrigDataTypeBytes(BrigType16_t t);
HsailCode::HsailCode(const std::string &name_str)
: HsaCode(name_str), private_size(-1), readonly_size(-1)
{
}
void
HsailCode::init(const BrigDirectiveExecutable *code_dir, const BrigObject *obj,
StorageMap *objStorageMap)
{
storageMap = objStorageMap;
// set pointer so that decoding process can find this kernel context when
// needed
obj->currentCode = this;
if (code_dir->base.kind != BRIG_KIND_DIRECTIVE_FUNCTION &&
code_dir->base.kind != BRIG_KIND_DIRECTIVE_KERNEL) {
fatal("unexpected directive kind %d inside kernel/function init\n",
code_dir->base.kind);
}
DPRINTF(HSAILObject, "Initializing code, first code block entry is: %d\n",
code_dir->firstCodeBlockEntry);
// clear these static vars so we can properly track the max index
// for this kernel
SRegOperand::maxRegIdx = 0;
DRegOperand::maxRegIdx = 0;
CRegOperand::maxRegIdx = 0;
setPrivateSize(0);
const BrigBase *entryPtr = brigNext((BrigBase*)code_dir);
const BrigBase *endPtr =
obj->getCodeSectionEntry(code_dir->nextModuleEntry);
// the instruction's byte address (relative to the base addr
// of the code section)
int inst_addr = 0;
// the index that points to the instruction in the instruction
// array
int inst_idx = 0;
std::vector<GPUStaticInst*> instructions;
int funcarg_size_scope = 0;
// walk through instructions in code section and directives in
// directive section in parallel, processing directives that apply
// when we reach the relevant code point.
while (entryPtr < endPtr) {
switch (entryPtr->kind) {
case BRIG_KIND_DIRECTIVE_VARIABLE:
{
const BrigDirectiveVariable *sym =
(const BrigDirectiveVariable*)entryPtr;
DPRINTF(HSAILObject,"Initializing code, directive is "
"kind_variable, symbol is: %s\n",
obj->getString(sym->name));
StorageElement *se = storageMap->addSymbol(sym, obj);
if (sym->segment == BRIG_SEGMENT_PRIVATE) {
setPrivateSize(se->size);
} else { // spill
funcarg_size_scope += se->size;
}
}
break;
case BRIG_KIND_DIRECTIVE_LABEL:
{
const BrigDirectiveLabel *lbl =
(const BrigDirectiveLabel*)entryPtr;
DPRINTF(HSAILObject,"Initializing code, directive is "
"kind_label, label is: %s \n",
obj->getString(lbl->name));
labelMap.addLabel(lbl, inst_addr, obj);
}
break;
case BRIG_KIND_DIRECTIVE_PRAGMA:
{
DPRINTF(HSAILObject, "Initializing code, directive "
"is kind_pragma\n");
}
break;
case BRIG_KIND_DIRECTIVE_COMMENT:
{
DPRINTF(HSAILObject, "Initializing code, directive is "
"kind_comment\n");
}
break;
case BRIG_KIND_DIRECTIVE_ARG_BLOCK_START:
{
DPRINTF(HSAILObject, "Initializing code, directive is "
"kind_arg_block_start\n");
storageMap->resetOffset(BRIG_SEGMENT_ARG);
funcarg_size_scope = 0;
}
break;
case BRIG_KIND_DIRECTIVE_ARG_BLOCK_END:
{
DPRINTF(HSAILObject, "Initializing code, directive is "
"kind_arg_block_end\n");
funcarg_size = funcarg_size < funcarg_size_scope ?
funcarg_size_scope : funcarg_size;
}
break;
case BRIG_KIND_DIRECTIVE_END:
DPRINTF(HSAILObject, "Initializing code, dircetive is "
"kind_end\n");
break;
default:
if (entryPtr->kind >= BRIG_KIND_INST_BEGIN &&
entryPtr->kind <= BRIG_KIND_INST_END) {
BrigInstBase *instPtr = (BrigInstBase*)entryPtr;
TheGpuISA::MachInst machInst = { instPtr, obj };
GPUStaticInst *iptr = decoder.decode(machInst);
if (iptr) {
DPRINTF(HSAILObject, "Initializing code, processing inst "
"byte addr #%d idx %d: OPCODE=%d\n", inst_addr,
inst_idx, instPtr->opcode);
TheGpuISA::RawMachInst raw_inst = decoder.saveInst(iptr);
iptr->instNum(inst_idx);
iptr->instAddr(inst_addr);
_insts.push_back(raw_inst);
instructions.push_back(iptr);
}
inst_addr += sizeof(TheGpuISA::RawMachInst);
++inst_idx;
} else if (entryPtr->kind >= BRIG_KIND_OPERAND_BEGIN &&
entryPtr->kind < BRIG_KIND_OPERAND_END) {
warn("unexpected operand entry in code segment\n");
} else {
// there are surely some more cases we will need to handle,
// but we'll deal with them as we find them.
fatal("unexpected directive kind %d inside kernel scope\n",
entryPtr->kind);
}
}
entryPtr = brigNext(entryPtr);
}
// compute Control Flow Graph for current kernel
ControlFlowInfo::assignImmediatePostDominators(instructions);
max_sreg = SRegOperand::maxRegIdx;
max_dreg = DRegOperand::maxRegIdx;
max_creg = CRegOperand::maxRegIdx;
obj->currentCode = nullptr;
}
HsailCode::HsailCode(const std::string &name_str,
const BrigDirectiveExecutable *code_dir,
const BrigObject *obj, StorageMap *objStorageMap)
: HsaCode(name_str), private_size(-1), readonly_size(-1)
{
init(code_dir, obj, objStorageMap);
}
void
LabelMap::addLabel(const Brig::BrigDirectiveLabel *lblDir, int inst_index,
const BrigObject *obj)
{
std::string lbl_name = obj->getString(lblDir->name);
Label &lbl = map[lbl_name];
if (lbl.defined()) {
fatal("Attempt to redefine existing label %s\n", lbl_name);
}
lbl.define(lbl_name, inst_index);
DPRINTF(HSAILObject, "label %s = %d\n", lbl_name, inst_index);
}
Label*
LabelMap::refLabel(const Brig::BrigDirectiveLabel *lblDir,
const BrigObject *obj)
{
std::string name = obj->getString(lblDir->name);
Label &lbl = map[name];
lbl.checkName(name);
return &lbl;
}
int
getBrigDataTypeBytes(BrigType16_t t)
{
switch (t) {
case BRIG_TYPE_S8:
case BRIG_TYPE_U8:
case BRIG_TYPE_B8:
return 1;
case BRIG_TYPE_S16:
case BRIG_TYPE_U16:
case BRIG_TYPE_B16:
case BRIG_TYPE_F16:
return 2;
case BRIG_TYPE_S32:
case BRIG_TYPE_U32:
case BRIG_TYPE_B32:
case BRIG_TYPE_F32:
return 4;
case BRIG_TYPE_S64:
case BRIG_TYPE_U64:
case BRIG_TYPE_B64:
case BRIG_TYPE_F64:
return 8;
case BRIG_TYPE_B1:
default:
fatal("unhandled symbol data type %d", t);
return 0;
}
}
StorageElement*
StorageSpace::addSymbol(const BrigDirectiveVariable *sym,
const BrigObject *obj)
{
const char *sym_name = obj->getString(sym->name);
uint64_t size = 0;
uint64_t offset = 0;
if (sym->type & BRIG_TYPE_ARRAY) {
size = getBrigDataTypeBytes(sym->type & ~BRIG_TYPE_ARRAY);
size *= (((uint64_t)sym->dim.hi) << 32 | (uint64_t)sym->dim.lo);
offset = roundUp(nextOffset, getBrigDataTypeBytes(sym->type &
~BRIG_TYPE_ARRAY));
} else {
size = getBrigDataTypeBytes(sym->type);
offset = roundUp(nextOffset, getBrigDataTypeBytes(sym->type));
}
nextOffset = offset + size;
DPRINTF(HSAILObject, "Adding SYMBOL %s size %d offset %#x, init: %d\n",
sym_name, size, offset, sym->init);
StorageElement* se = new StorageElement(sym_name, offset, size, sym);
elements.push_back(se);
elements_by_addr.insert(AddrRange(offset, offset + size - 1), se);
elements_by_brigptr[sym] = se;
return se;
}
StorageElement*
StorageSpace::findSymbol(std::string name)
{
for (auto it : elements) {
if (it->name == name) {
return it;
}
}
return nullptr;
}
StorageElement*
StorageSpace::findSymbol(uint64_t addr)
{
assert(elements_by_addr.size() > 0);
auto se = elements_by_addr.find(addr);
if (se == elements_by_addr.end()) {
return nullptr;
} else {
return se->second;
}
}
StorageElement*
StorageSpace::findSymbol(const BrigDirectiveVariable *brigptr)
{
assert(elements_by_brigptr.size() > 0);
auto se = elements_by_brigptr.find(brigptr);
if (se == elements_by_brigptr.end()) {
return nullptr;
} else {
return se->second;
}
}
StorageMap::StorageMap(StorageMap *outerScope)
: outerScopeMap(outerScope)
{
for (int i = 0; i < NumSegments; ++i)
space[i] = new StorageSpace((BrigSegment)i);
}
StorageElement*
StorageMap::addSymbol(const BrigDirectiveVariable *sym, const BrigObject *obj)
{
BrigSegment8_t segment = sym->segment;
assert(segment >= Brig::BRIG_SEGMENT_FLAT);
assert(segment < NumSegments);
return space[segment]->addSymbol(sym, obj);
}
int
StorageMap::getSize(Brig::BrigSegment segment)
{
assert(segment > Brig::BRIG_SEGMENT_GLOBAL);
assert(segment < NumSegments);
if (segment != Brig::BRIG_SEGMENT_GROUP &&
segment != Brig::BRIG_SEGMENT_READONLY) {
return space[segment]->getSize();
} else {
int ret = space[segment]->getSize();
if (outerScopeMap) {
ret += outerScopeMap->getSize(segment);
}
return ret;
}
}
void
StorageMap::resetOffset(Brig::BrigSegment segment)
{
space[segment]->resetOffset();
}
StorageElement*
StorageMap::findSymbol(BrigSegment segment, std::string name)
{
StorageElement *se = space[segment]->findSymbol(name);
if (se)
return se;
if (outerScopeMap)
return outerScopeMap->findSymbol(segment, name);
return nullptr;
}
StorageElement*
StorageMap::findSymbol(Brig::BrigSegment segment, uint64_t addr)
{
StorageSpace *sp = space[segment];
if (!sp) {
// there is no memory in segment?
return nullptr;
}
StorageElement *se = sp->findSymbol(addr);
if (se)
return se;
if (outerScopeMap)
return outerScopeMap->findSymbol(segment, addr);
return nullptr;
}
StorageElement*
StorageMap::findSymbol(Brig::BrigSegment segment,
const BrigDirectiveVariable *brigptr)
{
StorageSpace *sp = space[segment];
if (!sp) {
// there is no memory in segment?
return nullptr;
}
StorageElement *se = sp->findSymbol(brigptr);
if (se)
return se;
if (outerScopeMap)
return outerScopeMap->findSymbol(segment, brigptr);
return nullptr;
}
<commit_msg>hsail-x86: fix addr_range_map error<commit_after>/*
* Copyright (c) 2012-2015 Advanced Micro Devices, Inc.
* All rights reserved.
*
* For use for simulation and test purposes only
*
* 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 name of the copyright holder 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.
*
* Author: Steve Reinhardt
*/
#include "gpu-compute/hsail_code.hh"
#include "arch/gpu_types.hh"
#include "arch/hsail/Brig.h"
#include "arch/hsail/operand.hh"
#include "config/the_gpu_isa.hh"
#include "debug/BRIG.hh"
#include "debug/HSAILObject.hh"
#include "gpu-compute/brig_object.hh"
#include "gpu-compute/gpu_static_inst.hh"
#include "gpu-compute/kernel_cfg.hh"
using namespace Brig;
int getBrigDataTypeBytes(BrigType16_t t);
HsailCode::HsailCode(const std::string &name_str)
: HsaCode(name_str), private_size(-1), readonly_size(-1)
{
}
void
HsailCode::init(const BrigDirectiveExecutable *code_dir, const BrigObject *obj,
StorageMap *objStorageMap)
{
storageMap = objStorageMap;
// set pointer so that decoding process can find this kernel context when
// needed
obj->currentCode = this;
if (code_dir->base.kind != BRIG_KIND_DIRECTIVE_FUNCTION &&
code_dir->base.kind != BRIG_KIND_DIRECTIVE_KERNEL) {
fatal("unexpected directive kind %d inside kernel/function init\n",
code_dir->base.kind);
}
DPRINTF(HSAILObject, "Initializing code, first code block entry is: %d\n",
code_dir->firstCodeBlockEntry);
// clear these static vars so we can properly track the max index
// for this kernel
SRegOperand::maxRegIdx = 0;
DRegOperand::maxRegIdx = 0;
CRegOperand::maxRegIdx = 0;
setPrivateSize(0);
const BrigBase *entryPtr = brigNext((BrigBase*)code_dir);
const BrigBase *endPtr =
obj->getCodeSectionEntry(code_dir->nextModuleEntry);
// the instruction's byte address (relative to the base addr
// of the code section)
int inst_addr = 0;
// the index that points to the instruction in the instruction
// array
int inst_idx = 0;
std::vector<GPUStaticInst*> instructions;
int funcarg_size_scope = 0;
// walk through instructions in code section and directives in
// directive section in parallel, processing directives that apply
// when we reach the relevant code point.
while (entryPtr < endPtr) {
switch (entryPtr->kind) {
case BRIG_KIND_DIRECTIVE_VARIABLE:
{
const BrigDirectiveVariable *sym =
(const BrigDirectiveVariable*)entryPtr;
DPRINTF(HSAILObject,"Initializing code, directive is "
"kind_variable, symbol is: %s\n",
obj->getString(sym->name));
StorageElement *se = storageMap->addSymbol(sym, obj);
if (sym->segment == BRIG_SEGMENT_PRIVATE) {
setPrivateSize(se->size);
} else { // spill
funcarg_size_scope += se->size;
}
}
break;
case BRIG_KIND_DIRECTIVE_LABEL:
{
const BrigDirectiveLabel *lbl =
(const BrigDirectiveLabel*)entryPtr;
DPRINTF(HSAILObject,"Initializing code, directive is "
"kind_label, label is: %s \n",
obj->getString(lbl->name));
labelMap.addLabel(lbl, inst_addr, obj);
}
break;
case BRIG_KIND_DIRECTIVE_PRAGMA:
{
DPRINTF(HSAILObject, "Initializing code, directive "
"is kind_pragma\n");
}
break;
case BRIG_KIND_DIRECTIVE_COMMENT:
{
DPRINTF(HSAILObject, "Initializing code, directive is "
"kind_comment\n");
}
break;
case BRIG_KIND_DIRECTIVE_ARG_BLOCK_START:
{
DPRINTF(HSAILObject, "Initializing code, directive is "
"kind_arg_block_start\n");
storageMap->resetOffset(BRIG_SEGMENT_ARG);
funcarg_size_scope = 0;
}
break;
case BRIG_KIND_DIRECTIVE_ARG_BLOCK_END:
{
DPRINTF(HSAILObject, "Initializing code, directive is "
"kind_arg_block_end\n");
funcarg_size = funcarg_size < funcarg_size_scope ?
funcarg_size_scope : funcarg_size;
}
break;
case BRIG_KIND_DIRECTIVE_END:
DPRINTF(HSAILObject, "Initializing code, dircetive is "
"kind_end\n");
break;
default:
if (entryPtr->kind >= BRIG_KIND_INST_BEGIN &&
entryPtr->kind <= BRIG_KIND_INST_END) {
BrigInstBase *instPtr = (BrigInstBase*)entryPtr;
TheGpuISA::MachInst machInst = { instPtr, obj };
GPUStaticInst *iptr = decoder.decode(machInst);
if (iptr) {
DPRINTF(HSAILObject, "Initializing code, processing inst "
"byte addr #%d idx %d: OPCODE=%d\n", inst_addr,
inst_idx, instPtr->opcode);
TheGpuISA::RawMachInst raw_inst = decoder.saveInst(iptr);
iptr->instNum(inst_idx);
iptr->instAddr(inst_addr);
_insts.push_back(raw_inst);
instructions.push_back(iptr);
}
inst_addr += sizeof(TheGpuISA::RawMachInst);
++inst_idx;
} else if (entryPtr->kind >= BRIG_KIND_OPERAND_BEGIN &&
entryPtr->kind < BRIG_KIND_OPERAND_END) {
warn("unexpected operand entry in code segment\n");
} else {
// there are surely some more cases we will need to handle,
// but we'll deal with them as we find them.
fatal("unexpected directive kind %d inside kernel scope\n",
entryPtr->kind);
}
}
entryPtr = brigNext(entryPtr);
}
// compute Control Flow Graph for current kernel
ControlFlowInfo::assignImmediatePostDominators(instructions);
max_sreg = SRegOperand::maxRegIdx;
max_dreg = DRegOperand::maxRegIdx;
max_creg = CRegOperand::maxRegIdx;
obj->currentCode = nullptr;
}
HsailCode::HsailCode(const std::string &name_str,
const BrigDirectiveExecutable *code_dir,
const BrigObject *obj, StorageMap *objStorageMap)
: HsaCode(name_str), private_size(-1), readonly_size(-1)
{
init(code_dir, obj, objStorageMap);
}
void
LabelMap::addLabel(const Brig::BrigDirectiveLabel *lblDir, int inst_index,
const BrigObject *obj)
{
std::string lbl_name = obj->getString(lblDir->name);
Label &lbl = map[lbl_name];
if (lbl.defined()) {
fatal("Attempt to redefine existing label %s\n", lbl_name);
}
lbl.define(lbl_name, inst_index);
DPRINTF(HSAILObject, "label %s = %d\n", lbl_name, inst_index);
}
Label*
LabelMap::refLabel(const Brig::BrigDirectiveLabel *lblDir,
const BrigObject *obj)
{
std::string name = obj->getString(lblDir->name);
Label &lbl = map[name];
lbl.checkName(name);
return &lbl;
}
int
getBrigDataTypeBytes(BrigType16_t t)
{
switch (t) {
case BRIG_TYPE_S8:
case BRIG_TYPE_U8:
case BRIG_TYPE_B8:
return 1;
case BRIG_TYPE_S16:
case BRIG_TYPE_U16:
case BRIG_TYPE_B16:
case BRIG_TYPE_F16:
return 2;
case BRIG_TYPE_S32:
case BRIG_TYPE_U32:
case BRIG_TYPE_B32:
case BRIG_TYPE_F32:
return 4;
case BRIG_TYPE_S64:
case BRIG_TYPE_U64:
case BRIG_TYPE_B64:
case BRIG_TYPE_F64:
return 8;
case BRIG_TYPE_B1:
default:
fatal("unhandled symbol data type %d", t);
return 0;
}
}
StorageElement*
StorageSpace::addSymbol(const BrigDirectiveVariable *sym,
const BrigObject *obj)
{
const char *sym_name = obj->getString(sym->name);
uint64_t size = 0;
uint64_t offset = 0;
if (sym->type & BRIG_TYPE_ARRAY) {
size = getBrigDataTypeBytes(sym->type & ~BRIG_TYPE_ARRAY);
size *= (((uint64_t)sym->dim.hi) << 32 | (uint64_t)sym->dim.lo);
offset = roundUp(nextOffset, getBrigDataTypeBytes(sym->type &
~BRIG_TYPE_ARRAY));
} else {
size = getBrigDataTypeBytes(sym->type);
offset = roundUp(nextOffset, getBrigDataTypeBytes(sym->type));
}
nextOffset = offset + size;
DPRINTF(HSAILObject, "Adding SYMBOL %s size %d offset %#x, init: %d\n",
sym_name, size, offset, sym->init);
StorageElement* se = new StorageElement(sym_name, offset, size, sym);
elements.push_back(se);
elements_by_addr.insert(AddrRange(offset, offset + size - 1), se);
elements_by_brigptr[sym] = se;
return se;
}
StorageElement*
StorageSpace::findSymbol(std::string name)
{
for (auto it : elements) {
if (it->name == name) {
return it;
}
}
return nullptr;
}
StorageElement*
StorageSpace::findSymbol(uint64_t addr)
{
assert(elements_by_addr.size() > 0);
auto se = elements_by_addr.contains(addr);
if (se == elements_by_addr.end()) {
return nullptr;
} else {
return se->second;
}
}
StorageElement*
StorageSpace::findSymbol(const BrigDirectiveVariable *brigptr)
{
assert(elements_by_brigptr.size() > 0);
auto se = elements_by_brigptr.find(brigptr);
if (se == elements_by_brigptr.end()) {
return nullptr;
} else {
return se->second;
}
}
StorageMap::StorageMap(StorageMap *outerScope)
: outerScopeMap(outerScope)
{
for (int i = 0; i < NumSegments; ++i)
space[i] = new StorageSpace((BrigSegment)i);
}
StorageElement*
StorageMap::addSymbol(const BrigDirectiveVariable *sym, const BrigObject *obj)
{
BrigSegment8_t segment = sym->segment;
assert(segment >= Brig::BRIG_SEGMENT_FLAT);
assert(segment < NumSegments);
return space[segment]->addSymbol(sym, obj);
}
int
StorageMap::getSize(Brig::BrigSegment segment)
{
assert(segment > Brig::BRIG_SEGMENT_GLOBAL);
assert(segment < NumSegments);
if (segment != Brig::BRIG_SEGMENT_GROUP &&
segment != Brig::BRIG_SEGMENT_READONLY) {
return space[segment]->getSize();
} else {
int ret = space[segment]->getSize();
if (outerScopeMap) {
ret += outerScopeMap->getSize(segment);
}
return ret;
}
}
void
StorageMap::resetOffset(Brig::BrigSegment segment)
{
space[segment]->resetOffset();
}
StorageElement*
StorageMap::findSymbol(BrigSegment segment, std::string name)
{
StorageElement *se = space[segment]->findSymbol(name);
if (se)
return se;
if (outerScopeMap)
return outerScopeMap->findSymbol(segment, name);
return nullptr;
}
StorageElement*
StorageMap::findSymbol(Brig::BrigSegment segment, uint64_t addr)
{
StorageSpace *sp = space[segment];
if (!sp) {
// there is no memory in segment?
return nullptr;
}
StorageElement *se = sp->findSymbol(addr);
if (se)
return se;
if (outerScopeMap)
return outerScopeMap->findSymbol(segment, addr);
return nullptr;
}
StorageElement*
StorageMap::findSymbol(Brig::BrigSegment segment,
const BrigDirectiveVariable *brigptr)
{
StorageSpace *sp = space[segment];
if (!sp) {
// there is no memory in segment?
return nullptr;
}
StorageElement *se = sp->findSymbol(brigptr);
if (se)
return se;
if (outerScopeMap)
return outerScopeMap->findSymbol(segment, brigptr);
return nullptr;
}
<|endoftext|> |
<commit_before>/* Please refer to license.txt */
#include "window.hpp"
#include "../2d/2d.hpp"
#include <iostream>
#include <CEGUI/CEGUI.h>
#include <CEGUI/RendererModules/OpenGL/GLRenderer.h>
namespace GEngine
{
namespace mgfx
{
Window::Window()
{
parent_d2d = nullptr;
width = nullptr;
height = nullptr;
delete_width = false;
delete_height = false;
fullscreen = false;
windowname = "";
window2d = nullptr;
event = nullptr;
closed = true;
can_close = true;
focus = true;
}
Window::~Window()
{
if (width) //If the width exists.
{
if (delete_width) //If it should be deleted.
{
delete width; //Delete it.
width = nullptr; //Reset it.
}
else
{
width = nullptr; //Don't delete it, simply reset it.
}
}
if (height) //If the height exists.
{
if (delete_height) //Delete it.
{
delete height; //Delete it.
height = nullptr; //Reset it.
}
else
{
height = nullptr; //Don't delete it, only reset it.
}
}
if (window2d) //If the 2d window exists.
{
window2d->close(); //Close the window.
delete window2d; //Delete the window.
window2d = nullptr; //Reset it.
}
if (event) //If the event exists.
{
delete event; //Delete it.
event = nullptr; //Set to null.
}
}
bool Window::create(int _width, int _height, bool _fullscreen, std::string _windowname, bool use_opengl)
{
if (width) //Delete the width if it exists.
{
delete width;
}
width = new int; //Allocate memory for the width.
delete_width = true; //The width is to be deleted.
*width = _width; //Store the width.
if (height) //Delete the height if it exists.
{
delete height;
}
height = new int; //Allocate memory for the height.
delete_height = true; //The height is to be deleted.
*height = _height; //Store the height.
fullscreen = _fullscreen; //Store the fullscreen state.
windowname = _windowname; //Store the window name.
//TODO: Point the width and the height to the SFML window's width and height? Don't know if that's possible.
window2d = new sf::RenderWindow; //Create a new (2d) window.
if(fullscreen) //If it is to be fullscreen, do it.
{
window2d->create(sf::VideoMode(*width, *height), _windowname, sf::Style::Fullscreen); //Make the window fullscreen.
}
else
{
window2d->create(sf::VideoMode(*width, *height), _windowname, sf::Style::Default); //Nope, just a normal window.
}
closed = false; //Not closed.
if (event) //If it already exists.
{
delete event; //Delete it.
}
event = new sf::Event; //Allocate memory for it.
//TODO: Error checking?
return true; //Success.
}
void Window::update()
{
events.clear(); //Reset all events.
if (!closed && window2d && event) //If the window is open, the window exists, and event exists.
{
while (window2d->pollEvent(*event)) //Poll events. //TODO: Give access to these events to the game.
{
if (event->type == sf::Event::Closed && can_close) //Check if the event is a window close.
{
window2d->close(); //Close the window.
closed = true; //Update that it's closed.
}
else if (event->type == sf::Event::Resized && !closed && window2d) //Window resized. //TODO: Make a can_resize check.
{
window2d->setView(sf::View(sf::FloatRect(0, 0, event->size.width, event->size.height)));
//CEGUI::Sizef size(event->size.width, event->size.height);
//CEGUI::System::getSingleton().notifyDisplaySizeChanged(size); //Notify CEGUI of the changed size.
//CEGUI::System::getSingleton().notifyDisplaySizeChanged(CEGUI::Sizef(event->size.width, event->size.height)); //Notify CEGUI of the changed size. //TODO: Notify the GUI context involved.
if (parent_d2d && parent_d2d->cegui_renderer)
{
parent_d2d->cegui_renderer->setDisplaySize(CEGUI::Size<float>(event->size.width, event->size.height));
}
std::cout << "\n[GEngine::mgfx::Window::update()] Resized window.\n";
}
else if (event->type == sf::Event::LostFocus)
{
focus = false; //Lost focus.
}
else if (event->type == sf::Event::GainedFocus)
{
focus = true; //Gained focus.
}
else
{
events.push_back(*event); //Save the event for later processing.
}
}
}
}
void Window::draw()
{
if (!closed && window2d) //If the window was not closed.
{
window2d->display(); //Display the window.
window2d->clear();
}
}
int Window::getWidth()
{
if (!window2d)
{
std::cout << "\nNo 2d window, fool.\n";
return -1;
}
if (!width || !delete_width) //If width does not exist or if it should not be deleted (meaning it's pointing to some other int).
{
width = new int; //Allocate it.
delete_width = true; //It will be deleted.
}
sf::Vector2u vector = window2d->getSize(); //Get the size.
*width = vector.x; //Set/update the width.
return *width; //Return the width.
}
int Window::getHeight()
{
if (!window2d)
{
std::cout << "\nNo, seriously, there is no 2d window! Why don't you understand?\n";
return -1;
}
if (!height || !delete_height) //If height does not exist or if it should not be deleted (meaning it's pointing to some other int).
{
height = new int; //Allocate it.
delete_height = true; //It will be deleted.
}
sf::Vector2u vector = window2d->getSize(); //Get the size of the window.
*height = vector.y; //Set/update the height.
return *height; //Return the height.
}
int Window::getX()
{
return window2d->getPosition().x;
//return (using_opengl) ? /*3d*/window3d->getPosition().x /*window*/ : /*2d*/ window2d->getPosition().x /*window*/;
}
int Window::getY()
{
return window2d->getPosition().y;
//return (using_opengl) ? /*3d*/window3d->getPosition().y /*window*/ : /*2d*/ window2d->getPosition().y /*window*/;
}
void Window::drawSprite(mgfx::d2d::Sprite &sprite)
{
if (!window2d)
{
std::cout << "\nAnd just what are you trying to achieve with a window that does not exist?\n";
return;
}
window2d->draw(*sprite.sprite); //Draw the sprite.
}
void Window::renderText(std::string text, int _x, int _y, int font_size, sf::Font &font)
{
sf::Text _text(text, font);
_text.setCharacterSize(font_size);
_text.setPosition(_x, _y);
if (!window2d)
{
std::cout << "\nAnd just what are you trying to achieve with a 2D window that does not exist?\n";
return;
}
window2d->pushGLStates();
window2d->draw(_text);
window2d->popGLStates();
}
void Window::setFramerateLimit(int fps)
{
//Set the frames per second rate for the window.
if (!window2d)
{
std::cout << "I can't set the framerate limit -- window2d doesn't exist!\n"; //Error.
return; //Abort this function.
}
window2d->setFramerateLimit(fps);
}
void Window::showMouseCursor(bool show)
{
//Set the frames per second rate for the window.
if (!window2d)
{
std::cout << "I can't show or hide the mouse cursor -- window2d doesn't exist!\n"; //Error.
return; //Abort this function.
}
window2d->setMouseCursorVisible(show);
}
void Window::setActive()
{
window2d->setActive(true);
}
void Window::getMousePosition(int *x, int *y)
{
if (window2d)
{
if (x)
*x = sf::Mouse::getPosition(*window2d).x;
if (y)
*y = sf::Mouse::getPosition(*window2d).y;
}
}
} //namespace mgfx
} //namespace GEngine.
<commit_msg> * Uh, forgot to commit this forever ago.<commit_after>/* Please refer to license.txt */
#include "window.hpp"
#include "../2d/2d.hpp"
#include <iostream>
#include <CEGUI/CEGUI.h>
#include <CEGUI/RendererModules/OpenGL/GLRenderer.h>
namespace GEngine
{
namespace mgfx
{
Window::Window()
{
parent_d2d = nullptr;
width = nullptr;
height = nullptr;
delete_width = false;
delete_height = false;
fullscreen = false;
windowname = "";
window2d = nullptr;
event = nullptr;
closed = true;
can_close = true;
focus = true;
}
Window::~Window()
{
if (width) //If the width exists.
{
if (delete_width) //If it should be deleted.
{
delete width; //Delete it.
width = nullptr; //Reset it.
}
else
{
width = nullptr; //Don't delete it, simply reset it.
}
}
if (height) //If the height exists.
{
if (delete_height) //Delete it.
{
delete height; //Delete it.
height = nullptr; //Reset it.
}
else
{
height = nullptr; //Don't delete it, only reset it.
}
}
if (window2d) //If the 2d window exists.
{
window2d->close(); //Close the window.
delete window2d; //Delete the window.
window2d = nullptr; //Reset it.
}
if (event) //If the event exists.
{
delete event; //Delete it.
event = nullptr; //Set to null.
}
}
bool Window::create(int _width, int _height, bool _fullscreen, std::string _windowname, bool use_opengl)
{
if (width) //Delete the width if it exists.
{
delete width;
}
width = new int; //Allocate memory for the width.
delete_width = true; //The width is to be deleted.
*width = _width; //Store the width.
if (height) //Delete the height if it exists.
{
delete height;
}
height = new int; //Allocate memory for the height.
delete_height = true; //The height is to be deleted.
*height = _height; //Store the height.
fullscreen = _fullscreen; //Store the fullscreen state.
windowname = _windowname; //Store the window name.
//TODO: Point the width and the height to the SFML window's width and height? Don't know if that's possible.
window2d = new sf::RenderWindow; //Create a new (2d) window.
if(fullscreen) //If it is to be fullscreen, do it.
{
window2d->create(sf::VideoMode(*width, *height), _windowname, sf::Style::Fullscreen); //Make the window fullscreen.
}
else
{
window2d->create(sf::VideoMode(*width, *height), _windowname, sf::Style::Default); //Nope, just a normal window.
}
closed = false; //Not closed.
if (event) //If it already exists.
{
delete event; //Delete it.
}
event = new sf::Event; //Allocate memory for it.
//TODO: Error checking?
return true; //Success.
}
void Window::update()
{
events.clear(); //Reset all events.
if (!closed && window2d && event) //If the window is open, the window exists, and event exists.
{
while (window2d->pollEvent(*event)) //Poll events. //TODO: Give access to these events to the game.
{
if (event->type == sf::Event::Closed && can_close) //Check if the event is a window close.
{
window2d->close(); //Close the window.
closed = true; //Update that it's closed.
}
else if (event->type == sf::Event::Resized && !closed && window2d) //Window resized. //TODO: Make a can_resize check.
{
window2d->setView(sf::View(sf::FloatRect(0, 0, event->size.width, event->size.height)));
//CEGUI::Sizef size(event->size.width, event->size.height);
//CEGUI::System::getSingleton().notifyDisplaySizeChanged(size); //Notify CEGUI of the changed size.
//CEGUI::System::getSingleton().notifyDisplaySizeChanged(CEGUI::Sizef(event->size.width, event->size.height)); //Notify CEGUI of the changed size. //TODO: Notify the GUI context involved.
if (parent_d2d && parent_d2d->cegui_renderer)
{
parent_d2d->cegui_renderer->setDisplaySize(CEGUI::Size<float>(event->size.width, event->size.height));
}
//TODO: Maybe I need to do a bunch of OpenGL calls?
//TODO: At any rate, check out SFML's forums and wiki to see why it's not working properly. Maybe OpenGL mode needs special stuff.
std::cout << "\n[GEngine::mgfx::Window::update()] Resized window.\n";
}
else if (event->type == sf::Event::LostFocus)
{
focus = false; //Lost focus.
}
else if (event->type == sf::Event::GainedFocus)
{
focus = true; //Gained focus.
}
else
{
events.push_back(*event); //Save the event for later processing.
}
}
}
}
void Window::draw()
{
if (!closed && window2d) //If the window was not closed.
{
window2d->display(); //Display the window.
window2d->clear();
}
}
int Window::getWidth()
{
if (!window2d)
{
std::cout << "\nNo 2d window, fool.\n";
return -1;
}
if (!width || !delete_width) //If width does not exist or if it should not be deleted (meaning it's pointing to some other int).
{
width = new int; //Allocate it.
delete_width = true; //It will be deleted.
}
sf::Vector2u vector = window2d->getSize(); //Get the size.
*width = vector.x; //Set/update the width.
return *width; //Return the width.
}
int Window::getHeight()
{
if (!window2d)
{
std::cout << "\nNo, seriously, there is no 2d window! Why don't you understand?\n";
return -1;
}
if (!height || !delete_height) //If height does not exist or if it should not be deleted (meaning it's pointing to some other int).
{
height = new int; //Allocate it.
delete_height = true; //It will be deleted.
}
sf::Vector2u vector = window2d->getSize(); //Get the size of the window.
*height = vector.y; //Set/update the height.
return *height; //Return the height.
}
int Window::getX()
{
return window2d->getPosition().x;
//return (using_opengl) ? /*3d*/window3d->getPosition().x /*window*/ : /*2d*/ window2d->getPosition().x /*window*/;
}
int Window::getY()
{
return window2d->getPosition().y;
//return (using_opengl) ? /*3d*/window3d->getPosition().y /*window*/ : /*2d*/ window2d->getPosition().y /*window*/;
}
void Window::drawSprite(mgfx::d2d::Sprite &sprite)
{
if (!window2d)
{
std::cout << "\nAnd just what are you trying to achieve with a window that does not exist?\n";
return;
}
window2d->draw(*sprite.sprite); //Draw the sprite.
}
void Window::renderText(std::string text, int _x, int _y, int font_size, sf::Font &font)
{
sf::Text _text(text, font);
_text.setCharacterSize(font_size);
_text.setPosition(_x, _y);
if (!window2d)
{
std::cout << "\nAnd just what are you trying to achieve with a 2D window that does not exist?\n";
return;
}
window2d->pushGLStates();
window2d->draw(_text);
window2d->popGLStates();
}
void Window::setFramerateLimit(int fps)
{
//Set the frames per second rate for the window.
if (!window2d)
{
std::cout << "I can't set the framerate limit -- window2d doesn't exist!\n"; //Error.
return; //Abort this function.
}
window2d->setFramerateLimit(fps);
}
void Window::showMouseCursor(bool show)
{
//Set the frames per second rate for the window.
if (!window2d)
{
std::cout << "I can't show or hide the mouse cursor -- window2d doesn't exist!\n"; //Error.
return; //Abort this function.
}
window2d->setMouseCursorVisible(show);
}
void Window::setActive()
{
window2d->setActive(true);
}
void Window::getMousePosition(int *x, int *y)
{
if (window2d)
{
if (x)
*x = sf::Mouse::getPosition(*window2d).x;
if (y)
*y = sf::Mouse::getPosition(*window2d).y;
}
}
} //namespace mgfx
} //namespace GEngine.
<|endoftext|> |
<commit_before>#include "graphics/textureAtlas.h"
#include "graphics/opengl.h"
#include "textureManager.h"
#include <algorithm>
namespace sp {
AtlasTexture::AtlasTexture(glm::ivec2 size)
{
texture_size = size;
available_areas.push_back({{0, 0}, {size.x, size.y}});
gl_handle = 0;
smooth = textureManager.isDefaultSmoothFiltering();
}
AtlasTexture::~AtlasTexture()
{
if (gl_handle)
glDeleteTextures(1, &gl_handle);
}
void AtlasTexture::bind()
{
if (gl_handle == 0)
{
glGenTextures(1, &gl_handle);
glBindTexture(GL_TEXTURE_2D, gl_handle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture_size.x, texture_size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
//Put 1 white pixel in the {1,1} corner, which we can use to draw solid things.
glm::u8vec4 white{255,255,255,255};
glTexSubImage2D(GL_TEXTURE_2D, 0, texture_size.x - 1, texture_size.y - 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &white);
}
else
{
glBindTexture(GL_TEXTURE_2D, gl_handle);
}
if (!add_list.empty())
{
for(auto& add_item : add_list)
glTexSubImage2D(GL_TEXTURE_2D, 0, add_item.position.x, add_item.position.y, add_item.image.getSize().x, add_item.image.getSize().y, GL_RGBA, GL_UNSIGNED_BYTE, add_item.image.getPtr());
add_list.clear();
}
}
bool AtlasTexture::canAdd(const Image& image, int margin)
{
glm::ivec2 size = image.getSize() + glm::ivec2(margin * 2, margin * 2);
for(int n=int(available_areas.size()) - 1; n >= 0; n--)
{
if (available_areas[n].size.x >= size.x && available_areas[n].size.y >= size.y)
return true;
}
return false;
}
Rect AtlasTexture::add(Image&& image, int margin)
{
glm::ivec2 size = image.getSize() + glm::ivec2(margin * 2, margin * 2);
for(int n=int(available_areas.size()) - 1; n >= 0; n--)
{
if (available_areas[n].size.x >= size.x && available_areas[n].size.y >= size.y)
{
//Suitable area found, grab it, cut it, and put it in a stew.
RectInt full_area = available_areas[n];
available_areas.erase(available_areas.begin() + n);
if (full_area.size.x <= full_area.size.y)
{
//Split horizontal
addArea({{full_area.position.x + size.x, full_area.position.y}, {full_area.size.x - size.x, size.y}});
addArea({{full_area.position.x, full_area.position.y + size.y}, {full_area.size.x, full_area.size.y - size.y}});
}
else
{
//Split vertical
addArea({{full_area.position.x + size.x, full_area.position.y}, {full_area.size.x - size.x, full_area.size.y}});
addArea({{full_area.position.x, full_area.position.y + size.y}, {size.x, full_area.size.y - size.y}});
}
if (image.getSize().x > 0 && image.getSize().y > 0)
{
add_list.emplace_back();
add_list.back().image = std::move(image);
add_list.back().position.x = full_area.position.x + margin;
add_list.back().position.y = full_area.position.y + margin;
}
return Rect(
float(full_area.position.x + margin) / float(texture_size.x), float(full_area.position.y + margin) / float(texture_size.y),
float(size.x - margin * 2) / float(texture_size.x), float(size.y - margin * 2) / float(texture_size.y));
}
}
return Rect(0, 0, -1, -1);
}
float AtlasTexture::usageRate()
{
int all_texture_volume = texture_size.x * texture_size.y;
int unused_texture_volume = 0;
for(auto& area : available_areas)
unused_texture_volume += area.size.x * area.size.y;
return float(all_texture_volume - unused_texture_volume) / float(all_texture_volume);
}
void AtlasTexture::addArea(RectInt area)
{
//Ignore really slim areas, they are never really used and use up a lot of room in the available_areas otherwise.
if (area.size.x < 4 || area.size.y < 4)
return;
int area_volume = area.size.x * area.size.y;
auto it = std::lower_bound(available_areas.begin(), available_areas.end(), area_volume, [](const RectInt& r, int volume) -> bool
{
return r.size.x * r.size.y > volume;
});
available_areas.insert(it, area);
}
}//namespace sp
<commit_msg>Initialize atlas textures with default transparent black instead of undefined data. (which is white on some GPUs)<commit_after>#include "graphics/textureAtlas.h"
#include "graphics/opengl.h"
#include "textureManager.h"
#include <algorithm>
namespace sp {
AtlasTexture::AtlasTexture(glm::ivec2 size)
{
texture_size = size;
available_areas.push_back({{0, 0}, {size.x, size.y}});
gl_handle = 0;
smooth = textureManager.isDefaultSmoothFiltering();
}
AtlasTexture::~AtlasTexture()
{
if (gl_handle)
glDeleteTextures(1, &gl_handle);
}
void AtlasTexture::bind()
{
if (gl_handle == 0)
{
glGenTextures(1, &gl_handle);
glBindTexture(GL_TEXTURE_2D, gl_handle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, smooth ? GL_LINEAR : GL_NEAREST);
std::vector<glm::u8vec4> initial_data;
initial_data.resize(texture_size.x * texture_size.y, {0, 0, 0, 0});
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture_size.x, texture_size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, initial_data.data());
//Put 1 white pixel in the {1,1} corner, which we can use to draw solid things.
glm::u8vec4 white{255,255,255,255};
glTexSubImage2D(GL_TEXTURE_2D, 0, texture_size.x - 1, texture_size.y - 1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &white);
}
else
{
glBindTexture(GL_TEXTURE_2D, gl_handle);
}
if (!add_list.empty())
{
for(auto& add_item : add_list)
glTexSubImage2D(GL_TEXTURE_2D, 0, add_item.position.x, add_item.position.y, add_item.image.getSize().x, add_item.image.getSize().y, GL_RGBA, GL_UNSIGNED_BYTE, add_item.image.getPtr());
add_list.clear();
}
}
bool AtlasTexture::canAdd(const Image& image, int margin)
{
glm::ivec2 size = image.getSize() + glm::ivec2(margin * 2, margin * 2);
for(int n=int(available_areas.size()) - 1; n >= 0; n--)
{
if (available_areas[n].size.x >= size.x && available_areas[n].size.y >= size.y)
return true;
}
return false;
}
Rect AtlasTexture::add(Image&& image, int margin)
{
glm::ivec2 size = image.getSize() + glm::ivec2(margin * 2, margin * 2);
for(int n=int(available_areas.size()) - 1; n >= 0; n--)
{
if (available_areas[n].size.x >= size.x && available_areas[n].size.y >= size.y)
{
//Suitable area found, grab it, cut it, and put it in a stew.
RectInt full_area = available_areas[n];
available_areas.erase(available_areas.begin() + n);
if (full_area.size.x <= full_area.size.y)
{
//Split horizontal
addArea({{full_area.position.x + size.x, full_area.position.y}, {full_area.size.x - size.x, size.y}});
addArea({{full_area.position.x, full_area.position.y + size.y}, {full_area.size.x, full_area.size.y - size.y}});
}
else
{
//Split vertical
addArea({{full_area.position.x + size.x, full_area.position.y}, {full_area.size.x - size.x, full_area.size.y}});
addArea({{full_area.position.x, full_area.position.y + size.y}, {size.x, full_area.size.y - size.y}});
}
if (image.getSize().x > 0 && image.getSize().y > 0)
{
add_list.emplace_back();
add_list.back().image = std::move(image);
add_list.back().position.x = full_area.position.x + margin;
add_list.back().position.y = full_area.position.y + margin;
}
return Rect(
float(full_area.position.x + margin) / float(texture_size.x), float(full_area.position.y + margin) / float(texture_size.y),
float(size.x - margin * 2) / float(texture_size.x), float(size.y - margin * 2) / float(texture_size.y));
}
}
return Rect(0, 0, -1, -1);
}
float AtlasTexture::usageRate()
{
int all_texture_volume = texture_size.x * texture_size.y;
int unused_texture_volume = 0;
for(auto& area : available_areas)
unused_texture_volume += area.size.x * area.size.y;
return float(all_texture_volume - unused_texture_volume) / float(all_texture_volume);
}
void AtlasTexture::addArea(RectInt area)
{
//Ignore really slim areas, they are never really used and use up a lot of room in the available_areas otherwise.
if (area.size.x < 4 || area.size.y < 4)
return;
int area_volume = area.size.x * area.size.y;
auto it = std::lower_bound(available_areas.begin(), available_areas.end(), area_volume, [](const RectInt& r, int volume) -> bool
{
return r.size.x * r.size.y > volume;
});
available_areas.insert(it, area);
}
}//namespace sp
<|endoftext|> |
<commit_before>#include "packagemanagerplugin.h"
#include "dbsettings.h"
PackageManagerPlugin::PackageManagerPlugin(QObject *parent) :
QObject(parent)
{}
void PackageManagerPlugin::initialize()
{
}
bool PackageManagerPlugin::startGuiInstall(const QStringList &packages)
{
Q_UNUSED(packages);
return false;
}
bool PackageManagerPlugin::startGuiUninstall(const QStringList &packages)
{
Q_UNUSED(packages);
return false;
}
QSettings *PackageManagerPlugin::createSyncedSettings(QObject *parent) const
{
auto settings = DbSettings::create(parent);
settings->beginGroup(QStringLiteral("plugins/%1")
.arg(QString::fromUtf8(metaObject()->className())));
return settings;
}
QSettings *PackageManagerPlugin::createLocalSettings(QObject *parent) const
{
auto settings = new QSettings(parent);
settings->beginGroup(QStringLiteral("plugins/%1")
.arg(QString::fromUtf8(metaObject()->className())));
return settings;
}
void PackageManagerPlugin::settingsChanged() {}
QVariant PackageManagerPlugin::settingsValue(QSettings *settings, const QString &key) const
{
if(!settings->contains(key)) {
foreach(auto info, listSettings()) {
if(info.settingsKeys == key)
return info.defaultValue;
}
return QVariant();
} else
return settings->value(key);
}
PackageManagerPlugin::SettingsInfo::SettingsInfo(QString displayName, QString description, QString settingsKeys, int type, QVariant defaultValue, QByteArray widgetClassName) :
displayName(displayName),
description(description),
settingsKeys(settingsKeys),
type(type),
defaultValue(defaultValue),
widgetClassName(widgetClassName)
{
}
<commit_msg>combobocConfig<commit_after>#include "packagemanagerplugin.h"
#include "dbsettings.h"
#include "comboboxconfig.h"
PackageManagerPlugin::PackageManagerPlugin(QObject *parent) :
QObject(parent)
{}
void PackageManagerPlugin::initialize()
{
}
bool PackageManagerPlugin::startGuiInstall(const QStringList &packages)
{
Q_UNUSED(packages);
return false;
}
bool PackageManagerPlugin::startGuiUninstall(const QStringList &packages)
{
Q_UNUSED(packages);
return false;
}
QSettings *PackageManagerPlugin::createSyncedSettings(QObject *parent) const
{
auto settings = DbSettings::create(parent);
settings->beginGroup(QStringLiteral("plugins/%1")
.arg(QString::fromUtf8(metaObject()->className())));
return settings;
}
QSettings *PackageManagerPlugin::createLocalSettings(QObject *parent) const
{
auto settings = new QSettings(parent);
settings->beginGroup(QStringLiteral("plugins/%1")
.arg(QString::fromUtf8(metaObject()->className())));
return settings;
}
void PackageManagerPlugin::settingsChanged() {}
QVariant PackageManagerPlugin::settingsValue(QSettings *settings, const QString &key) const
{
if(!settings->contains(key)) {
foreach(auto info, listSettings()) {
if(info.settingsKeys == key){
if(qMetaTypeId<ComboboxConfig>() == info.defaultValue.userType())
return info.defaultValue.value<ComboboxConfig>().defaultValue;
else
return info.defaultValue;
}
}
return QVariant();
} else
return settings->value(key);
}
PackageManagerPlugin::SettingsInfo::SettingsInfo(QString displayName, QString description, QString settingsKeys, int type, QVariant defaultValue, QByteArray widgetClassName) :
displayName(displayName),
description(description),
settingsKeys(settingsKeys),
type(type),
defaultValue(defaultValue),
widgetClassName(widgetClassName)
{
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and 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 <Log.h>
#include <Debugger.h>
#include <processor/PageFaultHandler.h>
#include <process/Scheduler.h>
#include <panic.h>
#include <processor/PhysicalMemoryManager.h>
PageFaultHandler PageFaultHandler::m_Instance;
#define PAGE_FAULT_EXCEPTION 0x0E
#define PFE_PAGE_PRESENT 0x01
#define PFE_ATTEMPTED_WRITE 0x02
#define PFE_USER_MODE 0x04
#define PFE_RESERVED_BIT 0x08
#define PFE_INSTRUCTION_FETCH 0x10
bool PageFaultHandler::initialise()
{
InterruptManager &IntManager = InterruptManager::instance();
return(IntManager.registerInterruptHandler(PAGE_FAULT_EXCEPTION, this));
}
void PageFaultHandler::interrupt(size_t interruptNumber, InterruptState &state)
{
uint32_t cr2, code;
asm volatile("mov %%cr2, %%eax" : "=a" (cr2));
code = state.m_Errorcode;
uintptr_t page = cr2 & ~(PhysicalMemoryManager::instance().getPageSize()-1);
// Check for copy-on-write.
VirtualAddressSpace &va = Processor::information().getVirtualAddressSpace();
if (va.isMapped(reinterpret_cast<void*>(page)))
{
physical_uintptr_t phys;
size_t flags;
va.getMapping(reinterpret_cast<void*>(page), phys, flags);
if (flags & VirtualAddressSpace::CopyOnWrite)
{
#if 0
static uint8_t buffer[PhysicalMemoryManager::instance().getPageSize()];
memcpy(buffer, reinterpret_cast<uint8_t*>(page), PhysicalMemoryManager::instance().getPageSize());
// Now that we've saved the page content, we can make a new physical page and map it.
physical_uintptr_t p = PhysicalMemoryManager::instance().allocatePage();
if (!p)
{
FATAL("PageFaultHandler: Out of memory!");
return;
}
va.unmap(reinterpret_cast<void*>(page));
if (!va.map(p, reinterpret_cast<void*>(page), VirtualAddressSpace::Write))
{
FATAL("PageFaultHandler: map() failed.");
return;
}
memcpy(reinterpret_cast<uint8_t*>(page), buffer, PhysicalMemoryManager::instance().getPageSize());
return;
#endif
}
}
if (cr2 < 0xc0000000)
{
// Check our handler list.
for (List<MemoryTrapHandler*>::Iterator it = m_Handlers.begin();
it != m_Handlers.end();
it++)
{
if ((*it)->trap(cr2, code & PFE_ATTEMPTED_WRITE))
{
return;
}
}
}
// Get PFE location and error code
static LargeStaticString sError;
sError.clear();
sError.append("Page Fault Exception at 0x");
sError.append(cr2, 16, 8, '0');
sError.append(", error code 0x");
sError.append(code, 16, 8, '0');
sError.append(", EIP 0x");
sError.append(state.getInstructionPointer(), 16, 8, '0');
// Extract error code information
static LargeStaticString sCode;
sCode.clear();
sCode.append("Details: PID=");
sCode.append(Processor::information().getCurrentThread()->getParent()->getId());
sCode.append(" ");
if(!(code & PFE_PAGE_PRESENT)) sCode.append("NOT ");
sCode.append("PRESENT | ");
if(code & PFE_ATTEMPTED_WRITE)
sCode.append("WRITE | ");
else
sCode.append("READ | ");
if(code & PFE_USER_MODE) sCode.append("USER "); else sCode.append("KERNEL ");
sCode.append("MODE | ");
if(code & PFE_RESERVED_BIT) sCode.append("RESERVED BIT SET | ");
if(code & PFE_INSTRUCTION_FETCH) sCode.append("FETCH |");
// Ensure the log spinlock isn't going to die on us...
// Log::instance().m_Lock.release();
ERROR_NOLOCK(static_cast<const char*>(sError));
ERROR_NOLOCK(static_cast<const char*>(sCode));
//static LargeStaticString eCode;
#ifdef DEBUGGER
uintptr_t physAddr = 0, flags = 0;
if(va.isMapped(reinterpret_cast<void*>(state.getInstructionPointer())))
va.getMapping(reinterpret_cast<void*>(state.getInstructionPointer()), physAddr, flags);
// Page faults in usermode are usually useless to debug in the debugger (some exceptions exist)
if(!(code & PFE_USER_MODE))
Debugger::instance().start(state, sError);
#endif
Scheduler &scheduler = Scheduler::instance();
if(UNLIKELY(scheduler.getNumProcesses() == 0))
{
// We are in the early stages of the boot process (no processes started)
panic(sError);
}
else
{
// Unrecoverable PFE in a process - Kill the process and yield
//Processor::information().getCurrentThread()->getParent()->kill();
Thread *pThread = Processor::information().getCurrentThread();
Process *pProcess = pThread->getParent();
Subsystem *pSubsystem = pProcess->getSubsystem();
if(pSubsystem)
pSubsystem->threadException(pThread, Subsystem::PageFault, state);
else
pProcess->kill();
// kill member function also calls yield(), so shouldn't get here.
for(;;) ;
}
// Currently, no code paths return from a PFE.
}
PageFaultHandler::PageFaultHandler() :
m_Handlers()
{
}
<commit_msg>Replaced a hardcoded constant in the x86 PageFaultHandler with a defined constant.<commit_after>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and 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 <Log.h>
#include <Debugger.h>
#include <processor/PageFaultHandler.h>
#include <process/Scheduler.h>
#include <panic.h>
#include <processor/PhysicalMemoryManager.h>
#include "VirtualAddressSpace.h"
PageFaultHandler PageFaultHandler::m_Instance;
#define PAGE_FAULT_EXCEPTION 0x0E
#define PFE_PAGE_PRESENT 0x01
#define PFE_ATTEMPTED_WRITE 0x02
#define PFE_USER_MODE 0x04
#define PFE_RESERVED_BIT 0x08
#define PFE_INSTRUCTION_FETCH 0x10
bool PageFaultHandler::initialise()
{
InterruptManager &IntManager = InterruptManager::instance();
return(IntManager.registerInterruptHandler(PAGE_FAULT_EXCEPTION, this));
}
void PageFaultHandler::interrupt(size_t interruptNumber, InterruptState &state)
{
uint32_t cr2, code;
asm volatile("mov %%cr2, %%eax" : "=a" (cr2));
code = state.m_Errorcode;
uintptr_t page = cr2 & ~(PhysicalMemoryManager::instance().getPageSize()-1);
// Check for copy-on-write.
VirtualAddressSpace &va = Processor::information().getVirtualAddressSpace();
if (va.isMapped(reinterpret_cast<void*>(page)))
{
physical_uintptr_t phys;
size_t flags;
va.getMapping(reinterpret_cast<void*>(page), phys, flags);
if (flags & VirtualAddressSpace::CopyOnWrite)
{
#if 0
static uint8_t buffer[PhysicalMemoryManager::instance().getPageSize()];
memcpy(buffer, reinterpret_cast<uint8_t*>(page), PhysicalMemoryManager::instance().getPageSize());
// Now that we've saved the page content, we can make a new physical page and map it.
physical_uintptr_t p = PhysicalMemoryManager::instance().allocatePage();
if (!p)
{
FATAL("PageFaultHandler: Out of memory!");
return;
}
va.unmap(reinterpret_cast<void*>(page));
if (!va.map(p, reinterpret_cast<void*>(page), VirtualAddressSpace::Write))
{
FATAL("PageFaultHandler: map() failed.");
return;
}
memcpy(reinterpret_cast<uint8_t*>(page), buffer, PhysicalMemoryManager::instance().getPageSize());
return;
#endif
}
}
if (cr2 < reinterpret_cast<uintptr_t>(KERNEL_SPACE_START))
{
// Check our handler list.
for (List<MemoryTrapHandler*>::Iterator it = m_Handlers.begin();
it != m_Handlers.end();
it++)
{
if ((*it)->trap(cr2, code & PFE_ATTEMPTED_WRITE))
{
return;
}
}
}
// Get PFE location and error code
static LargeStaticString sError;
sError.clear();
sError.append("Page Fault Exception at 0x");
sError.append(cr2, 16, 8, '0');
sError.append(", error code 0x");
sError.append(code, 16, 8, '0');
sError.append(", EIP 0x");
sError.append(state.getInstructionPointer(), 16, 8, '0');
// Extract error code information
static LargeStaticString sCode;
sCode.clear();
sCode.append("Details: PID=");
sCode.append(Processor::information().getCurrentThread()->getParent()->getId());
sCode.append(" ");
if(!(code & PFE_PAGE_PRESENT)) sCode.append("NOT ");
sCode.append("PRESENT | ");
if(code & PFE_ATTEMPTED_WRITE)
sCode.append("WRITE | ");
else
sCode.append("READ | ");
if(code & PFE_USER_MODE) sCode.append("USER "); else sCode.append("KERNEL ");
sCode.append("MODE | ");
if(code & PFE_RESERVED_BIT) sCode.append("RESERVED BIT SET | ");
if(code & PFE_INSTRUCTION_FETCH) sCode.append("FETCH |");
// Ensure the log spinlock isn't going to die on us...
// Log::instance().m_Lock.release();
ERROR_NOLOCK(static_cast<const char*>(sError));
ERROR_NOLOCK(static_cast<const char*>(sCode));
//static LargeStaticString eCode;
#ifdef DEBUGGER
uintptr_t physAddr = 0, flags = 0;
if(va.isMapped(reinterpret_cast<void*>(state.getInstructionPointer())))
va.getMapping(reinterpret_cast<void*>(state.getInstructionPointer()), physAddr, flags);
// Page faults in usermode are usually useless to debug in the debugger (some exceptions exist)
if(!(code & PFE_USER_MODE))
Debugger::instance().start(state, sError);
#endif
Scheduler &scheduler = Scheduler::instance();
if(UNLIKELY(scheduler.getNumProcesses() == 0))
{
// We are in the early stages of the boot process (no processes started)
panic(sError);
}
else
{
// Unrecoverable PFE in a process - Kill the process and yield
//Processor::information().getCurrentThread()->getParent()->kill();
Thread *pThread = Processor::information().getCurrentThread();
Process *pProcess = pThread->getParent();
Subsystem *pSubsystem = pProcess->getSubsystem();
if(pSubsystem)
pSubsystem->threadException(pThread, Subsystem::PageFault, state);
else
pProcess->kill();
// kill member function also calls yield(), so shouldn't get here.
for(;;) ;
}
// Currently, no code paths return from a PFE.
}
PageFaultHandler::PageFaultHandler() :
m_Handlers()
{
}
<|endoftext|> |
<commit_before>/** @file gsFunctionExpr.hpp
@brief Provides implementation of FunctionExpr class.
This file is part of the G+Smo library.
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Author(s): A. Mantzaflaris
*/
#pragma once
#include <gsCore/gsLinearAlgebra.h>
#include <exprtk.hpp>// External file
namespace gismo
{
template<typename T> class gsFunctionExprPrivate
{
public:
T vars[6]; // const members can change this
exprtk::symbol_table<T> symbol_table;
exprtk::expression<T> expression;
exprtk::expression<T> der_exp[6];
bool der_flag[6];
std::string string;
int dim;
};
template<typename T>
gsFunctionExpr<T>::gsFunctionExpr() : my(new gsFunctionExprPrivate<T>) {};
template<typename T>
gsFunctionExpr<T>::gsFunctionExpr(std::string expression_string) : my(new gsFunctionExprPrivate<T>)
{
// Keep string data
my->string = expression_string;
my->string.erase(std::remove(my->string.begin(),my->string.end(),' '),my->string.end());
stringReplace(my->string, "**", "^");
init();
}
template<typename T>
gsFunctionExpr<T>::gsFunctionExpr(const gsFunctionExpr& other)
{
my = new gsFunctionExprPrivate<T>;
my->string = other.my->string;
init();
}
template<typename T>
gsFunctionExpr<T>& gsFunctionExpr<T>::operator=(const gsFunctionExpr& other)
{
if (this != &other)
{
my->string = other.my->string;
init();
}
return *this;
}
template<typename T>
gsFunctionExpr<T>::~gsFunctionExpr()
{
delete my;
}
template<typename T>
void gsFunctionExpr<T>::init()
{
my->symbol_table.clear();
my->expression.release();
// Identify symbol table
my->symbol_table.add_variable("x",my->vars[0]);
my->symbol_table.add_variable("y",my->vars[1]);
my->symbol_table.add_variable("z",my->vars[2]);
my->symbol_table.add_variable("w",my->vars[3]);
my->symbol_table.add_variable("u",my->vars[4]);
my->symbol_table.add_variable("v",my->vars[5]);
//my->symbol_table.remove_variable("w",my->vars[3]);
my->symbol_table.add_pi();
//my->symbol_table.add_constant("C", 1);
my->expression.register_symbol_table( my->symbol_table);
exprtk::parser<T> parser;
parser.cache_symbols() = true;
bool success = parser.compile(my->string, my->expression);
if ( ! success )
std::cout<<"gsFunctionExpr error: " <<parser.error() <<std::endl;
std::vector<std::string> varlist;
parser.expression_symbols(varlist);
varlist.erase(std::remove(varlist.begin(), varlist.end(), "pi"), varlist.end());
my->dim = varlist.size();
my->der_flag[0]=false;
my->der_flag[1]=false;
my->der_flag[2]=false;
my->der_flag[3]=false;
my->der_flag[4]=false;
my->der_flag[5]=false;
}
template<typename T>
int gsFunctionExpr<T>::domainDim() const
{
return my->dim;
}
template<typename T>
void gsFunctionExpr<T>::set_x (T const & v) const { my->vars[0]= v; }
template<typename T>
void gsFunctionExpr<T>::set_y (T const & v) const { my->vars[1]= v; }
template<typename T>
void gsFunctionExpr<T>::set_z (T const & v) const { my->vars[2]= v; }
template<typename T>
void gsFunctionExpr<T>::set_w (T const & v) const { my->vars[3]= v; }
template<typename T>
void gsFunctionExpr<T>::set_u (T const & v) const { my->vars[4]= v; }
template<typename T>
void gsFunctionExpr<T>::set_v (T const & v) const { my->vars[5]= v; }
template<typename T>
void gsFunctionExpr<T>::set_x_der (std::string expression_string)
{
my->der_exp[0].register_symbol_table(my->symbol_table);
exprtk::parser<T> parser;
bool success = parser.compile(expression_string, my->der_exp[0] );
if ( ! success )
std::cout<<"gsFunctionExpr set_x_der(.) error: " <<parser.error() <<std::endl;
else
my->der_flag[0]=true;
} ;
template<typename T>
void gsFunctionExpr<T>::set_y_der (std::string expression_string)
{
my->der_exp[1].register_symbol_table(my->symbol_table);
exprtk::parser<T> parser;
bool success = parser.compile(expression_string, my->der_exp[1] );
if ( ! success )
std::cout<<"gsFunctionExpr set_x_der(.) error: " <<parser.error() <<std::endl;
else
my->der_flag[1]=true;
} ;
template<typename T>
void gsFunctionExpr<T>::eval_into(const gsMatrix<T>& u, gsMatrix<T>& result) const
{
GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." );
result.resize(1, u.cols());
for ( int i = 0; i<u.cols(); i++ )
{
for ( int j = 0; j<u.rows(); j++ )
{
my->vars[j] =u(j,i);
}
result(0,i) = my->expression.value();
}
}
template<typename T>
void gsFunctionExpr<T>::eval_component_into(const gsMatrix<T>& u, const index_t comp, gsMatrix<T>& result) const
{
GISMO_ASSERT (comp == 0, "Given component number is too high. Only one component");
result.resize(1, u.cols());
for ( int i = 0; i<u.cols(); i++ )
{
for ( int j = 0; j<u.rows(); j++ )
{
my->vars[j] =u(j,i);
}
result(0,i) = my->expression.value();
}
}
template<typename T>
void gsFunctionExpr<T>::deriv_into(const gsMatrix<T>& u, gsMatrix<T>& result) const
{
int n = u.rows();
GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." );
result.resize(1, n * u.cols());
for( int i=0; i < u.cols(); ++i )
{
for ( int j = 0; j<n; j++ )
my->vars[j] =u(j,i);
for( int j=0; j< n; ++j )
if ( my->der_flag[j] )
result(n*i+j) = my->der_exp[j].value();
else
result(n*i+j) = exprtk::derivative<T>( my->expression, my->vars[j], 0.00001 ) ;
}
}
template<typename T>
typename gsFunction<T>::uMatrixPtr
gsFunctionExpr<T>::hess(const gsMatrix<T>& u, unsigned coord) const
{
GISMO_ENSURE(coord == 0, "Error, function is real");
// one column only..
int n = u.rows();
GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." );
gsMatrix<T> * res= new gsMatrix<T>(n,n) ;
for ( int j = 0; j<n; j++ )
my->vars[j] =u(j,0);
for( int j=0; j< n; ++j )
{
(*res)(j,j) = exprtk::second_derivative<T>( my->expression, my->vars[j], 0.00001 ) ;
for( int k=0; k<j; ++k )
(*res)(k,j) = (*res)(j,k) =
exprtk::mixed_derivative<T>( my->expression, my->vars[k], my->vars[j], 0.00001 ) ;
}
return typename gsFunction<T>::uMatrixPtr(res);
} ;
template<typename T>
gsMatrix<T> * gsFunctionExpr<T>::mderiv(const gsMatrix<T>& u, const index_t &k, const index_t &j ) const
{
gsMatrix<T> * res= new gsMatrix<T>(1,u.cols()) ;
for( index_t i=0; i< res->cols(); ++i )
{
for ( int t = 0; t<u.rows(); t++ )
my->vars[t] =u(t,i);
(*res)(0,i) =
exprtk::mixed_derivative<T>( my->expression, my->vars[k], my->vars[j], 0.00001 ) ;
}
return res;
} ;
template<typename T>
gsMatrix<T> * gsFunctionExpr<T>::laplacian(const gsMatrix<T>& u) const
{
gsMatrix<T> * res= new gsMatrix<T>(1,u.cols()) ;
res->setZero();
int n = u.rows();
for( index_t i=0; i< res->cols(); ++i )
for ( int j = 0; j<n; j++ )
{
my->vars[j] =u(j,i);
(*res)(0,i) +=
exprtk::second_derivative<T>( my->expression, my->vars[j], 0.00001 ) ;
}
return res;
}
template<typename T>
T gsFunctionExpr<T>::value() const
{
return my->expression.value() ;
}
template<typename T>
std::ostream & gsFunctionExpr<T>::print(std::ostream &os) const
{ os << my->string ; return os; }
}; // namespace gismo
<commit_msg>update exprtk<commit_after>/** @file gsFunctionExpr.hpp
@brief Provides implementation of FunctionExpr class.
This file is part of the G+Smo library.
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Author(s): A. Mantzaflaris
*/
#pragma once
#include <gsCore/gsLinearAlgebra.h>
#include <exprtk.hpp>// External file
namespace gismo
{
template<typename T> class gsFunctionExprPrivate
{
public:
T vars[6];
exprtk::symbol_table<T> symbol_table;
exprtk::expression<T> expression;
exprtk::expression<T> der_exp[6];
bool der_flag[6];
std::string string;
int dim;
};
/* / /AM: under construction
template<typename T> class gsSymbolListPrivate
{
public:
exprtk::symbol_table<T> symbol_table;
std::vector<T> vars ;
std::vector<T> params;
};
template<typename T>
gsSymbolList<T>::gsSymbolList() : my(new gsSymbolListPrivate<T>) {}
template<typename T>
gsSymbolList<T>::~gsSymbolList()
{
delete my;
}
template<typename T>
void gsSymbolList<T>::setDefault()
{
my->symbol_table.clear();
// Identify symbol table
my->symbol_table.add_variable("x",my->vars[0]);
my->symbol_table.add_variable("y",my->vars[1]);
my->symbol_table.add_variable("z",my->vars[2]);
my->symbol_table.add_variable("w",my->vars[3]);
my->symbol_table.add_variable("u",my->vars[4]);
my->symbol_table.add_variable("v",my->vars[5]);
//my->symbol_table.remove_variable("w",my->vars[3]);
my->symbol_table.add_pi();
//my->symbol_table.add_constant("C", 1);
}
template<typename T>
bool gsSymbolList<T>::addConstant(const std::string & constant_name, const T& value)
{
return my->symbol_table.add_constant(constant_name, value);
}
template<typename T>
bool gsSymbolList<T>::addVariable(const std::string & variable_name)
{
my->vars.push_back(0.0);
return my->symbol_table.add_variable(variable_name, my->vars.back() );
}
template<typename T>
bool gsSymbolList<T>::addParameter(const std::string & variable_name)
{
my->params.push_back(0.0);
return my->symbol_table.add_variable(variable_name, my->params.back() );
}
template<typename T>
bool gsSymbolList<T>::hasSymbol(const std::string& symbol_name)
{
return true;
}
//*/
template<typename T>
gsFunctionExpr<T>::gsFunctionExpr() : my(new gsFunctionExprPrivate<T>) {}
template<typename T>
gsFunctionExpr<T>::gsFunctionExpr(std::string expression_string, int ddim)
: my(new gsFunctionExprPrivate<T>)
{
// Keep string data
my->string = expression_string;
my->string.erase(std::remove(my->string.begin(),my->string.end(),' '),my->string.end());
stringReplace(my->string, "**", "^");
my->dim = ddim;
init();
}
template<typename T>
gsFunctionExpr<T>::gsFunctionExpr(const gsFunctionExpr& other)
{
my = new gsFunctionExprPrivate<T>;
my->string = other.my->string;
init();
}
template<typename T>
gsFunctionExpr<T>& gsFunctionExpr<T>::operator=(const gsFunctionExpr& other)
{
if (this != &other)
{
my->string = other.my->string;
init();
}
return *this;
}
template<typename T>
gsFunctionExpr<T>::~gsFunctionExpr()
{
delete my;
}
// template<typename T>
// void gsFunctionExpr<T>::init(variables,constants)
template<typename T>
void gsFunctionExpr<T>::init()
{
my->symbol_table.clear();
my->expression.release();
// Identify symbol table
my->symbol_table.add_variable("x",my->vars[0]);
my->symbol_table.add_variable("y",my->vars[1]);
my->symbol_table.add_variable("z",my->vars[2]);
my->symbol_table.add_variable("w",my->vars[3]);
my->symbol_table.add_variable("u",my->vars[4]);
my->symbol_table.add_variable("v",my->vars[5]);
//my->symbol_table.remove_variable("w",my->vars[3]);
my->symbol_table.add_pi();
//my->symbol_table.add_constant("C", 1);
my->expression.register_symbol_table(my->symbol_table);
exprtk::parser<T> parser;
//parser.cache_symbols() = true;
bool success = parser.compile(my->string, my->expression);
if ( ! success )
std::cout<<"gsFunctionExpr error: " <<parser.error() <<std::endl;
/*
AM: Changed in recent versions.
std::vector<std::string> varlist;
parser.expression_symbols(varlist);
varlist.erase(std::remove(varlist.begin(), varlist.end(), "pi"), varlist.end());
my->dim = varlist.size();
*/
my->der_flag[0]=false;
my->der_flag[1]=false;
my->der_flag[2]=false;
my->der_flag[3]=false;
my->der_flag[4]=false;
my->der_flag[5]=false;
}
template<typename T>
int gsFunctionExpr<T>::domainDim() const
{
return my->dim;
}
template<typename T>
void gsFunctionExpr<T>::set_x (T const & v) const { my->vars[0]= v; }
template<typename T>
void gsFunctionExpr<T>::set_y (T const & v) const { my->vars[1]= v; }
template<typename T>
void gsFunctionExpr<T>::set_z (T const & v) const { my->vars[2]= v; }
template<typename T>
void gsFunctionExpr<T>::set_w (T const & v) const { my->vars[3]= v; }
template<typename T>
void gsFunctionExpr<T>::set_u (T const & v) const { my->vars[4]= v; }
template<typename T>
void gsFunctionExpr<T>::set_v (T const & v) const { my->vars[5]= v; }
template<typename T>
void gsFunctionExpr<T>::set_x_der (std::string expression_string)
{
my->der_exp[0].register_symbol_table(my->symbol_table);
exprtk::parser<T> parser;
bool success = parser.compile(expression_string, my->der_exp[0] );
if ( ! success )
std::cout<<"gsFunctionExpr set_x_der(.) error: " <<parser.error() <<std::endl;
else
my->der_flag[0]=true;
}
template<typename T>
void gsFunctionExpr<T>::set_y_der (std::string expression_string)
{
my->der_exp[1].register_symbol_table(my->symbol_table);
exprtk::parser<T> parser;
bool success = parser.compile(expression_string, my->der_exp[1] );
if ( ! success )
std::cout<<"gsFunctionExpr set_x_der(.) error: " <<parser.error() <<std::endl;
else
my->der_flag[1]=true;
}
template<typename T>
void gsFunctionExpr<T>::eval_into(const gsMatrix<T>& u, gsMatrix<T>& result) const
{
GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." );
result.resize(1, u.cols());
for ( int i = 0; i<u.cols(); i++ )
{
for ( int j = 0; j<u.rows(); j++ )
{
my->vars[j] =u(j,i);
}
result(0,i) = my->expression.value();
}
}
template<typename T>
void gsFunctionExpr<T>::eval_component_into(const gsMatrix<T>& u, const index_t comp, gsMatrix<T>& result) const
{
GISMO_ASSERT (comp == 0, "Given component number is too high. Only one component");
result.resize(1, u.cols());
for ( int i = 0; i<u.cols(); i++ )
{
for ( int j = 0; j<u.rows(); j++ )
{
my->vars[j] =u(j,i);
}
result(0,i) = my->expression.value();
}
}
template<typename T>
void gsFunctionExpr<T>::deriv_into(const gsMatrix<T>& u, gsMatrix<T>& result) const
{
int n = u.rows();
GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." );
result.resize(1, n * u.cols());
for( int i=0; i < u.cols(); ++i )
{
for ( int j = 0; j<n; j++ )
my->vars[j] =u(j,i);
for( int j=0; j< n; ++j )
if ( my->der_flag[j] )
result(n*i+j) = my->der_exp[j].value();
else
result(n*i+j) = exprtk::derivative<T>( my->expression, my->vars[j], 0.00001 ) ;
}
}
template<typename T>
typename gsFunction<T>::uMatrixPtr
gsFunctionExpr<T>::hess(const gsMatrix<T>& u, unsigned coord) const
{
GISMO_ENSURE(coord == 0, "Error, function is real");
// one column only..
int n = u.rows();
GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." );
gsMatrix<T> * res= new gsMatrix<T>(n,n) ;
for ( int j = 0; j<n; j++ )
my->vars[j] =u(j,0);
for( int j=0; j< n; ++j )
{
(*res)(j,j) = exprtk::second_derivative<T>( my->expression, my->vars[j], 0.00001 ) ;
for( int k=0; k<j; ++k )
(*res)(k,j) = (*res)(j,k) =
exprtk::mixed_derivative<T>( my->expression, my->vars[k], my->vars[j], 0.00001 ) ;
}
return typename gsFunction<T>::uMatrixPtr(res);
} ;
template<typename T>
gsMatrix<T> * gsFunctionExpr<T>::mderiv(const gsMatrix<T>& u, const index_t &k, const index_t &j ) const
{
gsMatrix<T> * res= new gsMatrix<T>(1,u.cols()) ;
for( index_t i=0; i< res->cols(); ++i )
{
for ( int t = 0; t<u.rows(); t++ )
my->vars[t] =u(t,i);
(*res)(0,i) =
exprtk::mixed_derivative<T>( my->expression, my->vars[k], my->vars[j], 0.00001 ) ;
}
return res;
} ;
template<typename T>
gsMatrix<T> * gsFunctionExpr<T>::laplacian(const gsMatrix<T>& u) const
{
gsMatrix<T> * res= new gsMatrix<T>(1,u.cols()) ;
res->setZero();
int n = u.rows();
for( index_t i=0; i< res->cols(); ++i )
for ( int j = 0; j<n; j++ )
{
my->vars[j] =u(j,i);
(*res)(0,i) +=
exprtk::second_derivative<T>( my->expression, my->vars[j], 0.00001 ) ;
}
return res;
}
template<typename T>
T gsFunctionExpr<T>::value() const
{
return my->expression.value() ;
}
template<typename T>
std::ostream & gsFunctionExpr<T>::print(std::ostream &os) const
{ os << my->string ; return os; }
}; // namespace gismo
<|endoftext|> |
<commit_before>/* © 2010 David Given.
* LBW is licensed under the MIT open source license. See the COPYING
* file in this distribution for the full text.
*/
#include "globals.h"
#include "filesystem/RealFD.h"
#include "filesystem/InterixVFSNode.h"
#include "filesystem/PtsVFSNode.h"
#include "filesystem/FakeFile.h"
#include <stdlib.h>
#include <limits.h>
#include <sys/mkdev.h>
PtsVFSNode::PtsVFSNode(VFSNode* parent, const string& name):
FakeVFSNode(parent, name)
{
AddFile(new TunnelledFakeDirectory("ptms", "/dev/ptmx"));
}
PtsVFSNode::~PtsVFSNode()
{
}
static string findpty(const string& name)
{
u32 number = strtoul(name.c_str(), NULL, 10);
if ((number == 0) || (number == ULONG_MAX))
return "";
char buffer[16] = "/dev/tty";
*(u32*) (buffer+8) = number;
buffer[12] = '\0';
/* A brief gesture to security checking. */
if (!buffer[8])
return "";
for (int i = 8; i < 12; i++)
{
if (buffer[i] &&
((buffer[i] == '/') || (buffer[i] < 32) || (buffer[i] > 126)))
return "";
}
return buffer;
}
void PtsVFSNode::StatFile(const string& name, struct stat& st)
{
string f = findpty(name);
if (!f.empty())
{
int i = stat(f.c_str(), &st);
if (i == -1)
throw errno;
/* libc expects slave devices to have a particular rdev.
* So we have to fake it here.
*/
st.st_rdev = mkdev(3, 0);
return;
}
return FakeVFSNode::StatFile(name, st);
}
Ref<FD> PtsVFSNode::OpenFile(const string& name, int flags, int mode)
{
string f = findpty(name);
if (!f.empty())
{
int newfd = open(f.c_str(), flags, mode);
if (newfd == -1)
throw errno;
return new RealFD(newfd);
}
return FakeVFSNode::OpenFile(name, flags, mode);
}
int PtsVFSNode::Access(const string& name, int mode)
{
string f = findpty(name);
if (!f.empty())
{
int i = access(f.c_str(), mode);
if (i == -1)
throw errno;
return i;
}
return FakeVFSNode::Access(name, mode);
}
void PtsVFSNode::Chown(const string& name, uid_t owner, gid_t group)
{
string f = findpty(name);
if (!f.empty())
{
if (Options.FakeRoot)
return;
int i = chown(f.c_str(), owner, group);
if (i == -1)
throw errno;
return;
}
return FakeVFSNode::Chown(name, owner, group);
}
<commit_msg>Fixed typo in name of /dev/pts/ptmx.<commit_after>/* © 2010 David Given.
* LBW is licensed under the MIT open source license. See the COPYING
* file in this distribution for the full text.
*/
#include "globals.h"
#include "filesystem/RealFD.h"
#include "filesystem/InterixVFSNode.h"
#include "filesystem/PtsVFSNode.h"
#include "filesystem/FakeFile.h"
#include <stdlib.h>
#include <limits.h>
#include <sys/mkdev.h>
PtsVFSNode::PtsVFSNode(VFSNode* parent, const string& name):
FakeVFSNode(parent, name)
{
AddFile(new TunnelledFakeDirectory("ptmx", "/dev/ptmx"));
}
PtsVFSNode::~PtsVFSNode()
{
}
static string findpty(const string& name)
{
u32 number = strtoul(name.c_str(), NULL, 10);
if ((number == 0) || (number == ULONG_MAX))
return "";
char buffer[16] = "/dev/tty";
*(u32*) (buffer+8) = number;
buffer[12] = '\0';
/* A brief gesture to security checking. */
if (!buffer[8])
return "";
for (int i = 8; i < 12; i++)
{
if (buffer[i] &&
((buffer[i] == '/') || (buffer[i] < 32) || (buffer[i] > 126)))
return "";
}
return buffer;
}
void PtsVFSNode::StatFile(const string& name, struct stat& st)
{
string f = findpty(name);
if (!f.empty())
{
int i = stat(f.c_str(), &st);
if (i == -1)
throw errno;
/* libc expects slave devices to have a particular rdev.
* So we have to fake it here.
*/
st.st_rdev = mkdev(3, 0);
return;
}
return FakeVFSNode::StatFile(name, st);
}
Ref<FD> PtsVFSNode::OpenFile(const string& name, int flags, int mode)
{
string f = findpty(name);
if (!f.empty())
{
int newfd = open(f.c_str(), flags, mode);
if (newfd == -1)
throw errno;
return new RealFD(newfd);
}
return FakeVFSNode::OpenFile(name, flags, mode);
}
int PtsVFSNode::Access(const string& name, int mode)
{
string f = findpty(name);
if (!f.empty())
{
int i = access(f.c_str(), mode);
if (i == -1)
throw errno;
return i;
}
return FakeVFSNode::Access(name, mode);
}
void PtsVFSNode::Chown(const string& name, uid_t owner, gid_t group)
{
string f = findpty(name);
if (!f.empty())
{
if (Options.FakeRoot)
return;
int i = chown(f.c_str(), owner, group);
if (i == -1)
throw errno;
return;
}
return FakeVFSNode::Chown(name, owner, group);
}
<|endoftext|> |
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef ECL_LIB_UTILS_ERR_HPP_
#define ECL_LIB_UTILS_ERR_HPP_
namespace ecl
{
//! theCore system-wide errors
//! \details Rudely taken from http://en.cppreference.com/w/cpp/error/errno_macros
enum class err : int
{
ok = 0, //! Successfully completed
tobig = -1, //! Argument list too long
acces = -2, //! Permission denied
addrinuse = -3, //! Address in use
addrnotavail = -4, //! Address not available
afnosupport = -5, //! Address family not supported
again = -6, //! Resource unavailable
already = -7, //! Connection already in progress
badf = -8, //! Bad file descriptor
badmsg = -9, //! Bad message
busy = -10, //! Device or resource busy
canceled = -11, //! Operation canceled
child = -12, //! No child processes
connaborted = -13, //! Connection aborted
connrefused = -14, //! Connection refused
connreset = -15, //! Connection reset
deadlk = -16, //! Resource deadlock would occur
destaddrreq = -17, //! Destination address required
dom = -18, //! Mathematics argument out of domain of function
exist = -19, //! File exists
fault = -20, //! Bad address
fbig = -21, //! File too large
hostunreach = -22, //! Host is unreachable
idrm = -23, //! Identifier removed
ilseq = -24, //! Illegal byte sequence
inprogress = -25, //! Operation in progress
intr = -26, //! Interrupted function
inval = -27, //! Invalid argument
io = -28, //! I/O error
isconn = -29, //! Socket is connected
isdir = -30, //! Is a directory
loop = -31, //! Too many levels of symbolic links
mfile = -32, //! File descriptor value too large
mlink = -33, //! Too many links
msgsize = -34, //! Message too large
nametoolong = -35, //! Filename too long
netdown = -36, //! Network is down
netreset = -37, //! Connection aborted by network
netunreach = -38, //! Network unreachable
nfile = -39, //! Too many files open in system
nobufs = -40, //! No buffer space available
nodata = -41, //! No message is available on the STREAM head read queue
nodev = -42, //! No such device
noent = -43, //! No such file or directory
noexec = -44, //! Executable file format error
nolck = -45, //! No locks available
nolink = -46, //! Link has been severed
nomem = -47, //! Not enough space
nomsg = -48, //! No message of the desired type
noprotoopt = -49, //! Protocol not available
nospc = -50, //! No space left on device
nosr = -51, //! No STREAM resources
nostr = -52, //! Not a STREAM
nosys = -53, //! Function not supported
notconn = -54, //! The socket is not connected
notdir = -55, //! Not a directory
notempty = -56, //! Directory not empty
notrecoverable = -57, //! State not recoverable
notsock = -58, //! Not a socket
notsup = -59, //! Not supported
notty = -60, //! Inappropriate I/O control operation
nxio = -61, //! No such device or address
opnotsupp = -62, //! Operation not supported on socket
overflow = -63, //! Value too large to be stored in data type
ownerdead = -64, //! Previous owner died
perm = -65, //! Operation not permitted
pipe = -66, //! Broken pipe
proto = -67, //! Protocol error
protonosupport = -68, //! Protocol not supported
prototype = -69, //! Protocol wrong type for socket
range = -70, //! Result too large
rofs = -71, //! Read-only file system
spipe = -72, //! Invalid seek
srch = -73, //! No such process
time = -74, //! Stream ioctl() timeout
timedout = -75, //! Connection timed out
txtbsy = -76, //! Text file busy
wouldblock = -77, //! Operation would block
xdev = -78, //! Cross-device link
generic = -79, //! Generic error
};
static inline bool is_error(err error)
{
return error != err::ok;
}
static inline bool is_ok(err error)
{
return !is_error(error);
}
const char* err_to_str(err error);
} // namespace ecl
#ifdef CORE_TESTS_ENABLED
#include <CppUTest/SimpleString.h>
static inline SimpleString StringFrom(ecl::err err)
{
return SimpleString{ecl::err_to_str(err)};
}
#endif // CORE_TESTS_ENABLED
#endif // ECL_LIB_UTILS_ERR_HPP_
<commit_msg>lib/types: add err code to handle EOF condition<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef ECL_LIB_UTILS_ERR_HPP_
#define ECL_LIB_UTILS_ERR_HPP_
namespace ecl
{
//! theCore system-wide errors
//! \details Rudely taken from http://en.cppreference.com/w/cpp/error/errno_macros
enum class err : int
{
ok = 0, //! Successfully completed
tobig = -1, //! Argument list too long
acces = -2, //! Permission denied
addrinuse = -3, //! Address in use
addrnotavail = -4, //! Address not available
afnosupport = -5, //! Address family not supported
again = -6, //! Resource unavailable
already = -7, //! Connection already in progress
badf = -8, //! Bad file descriptor
badmsg = -9, //! Bad message
busy = -10, //! Device or resource busy
canceled = -11, //! Operation canceled
child = -12, //! No child processes
connaborted = -13, //! Connection aborted
connrefused = -14, //! Connection refused
connreset = -15, //! Connection reset
deadlk = -16, //! Resource deadlock would occur
destaddrreq = -17, //! Destination address required
dom = -18, //! Mathematics argument out of domain of function
exist = -19, //! File exists
fault = -20, //! Bad address
fbig = -21, //! File too large
hostunreach = -22, //! Host is unreachable
idrm = -23, //! Identifier removed
ilseq = -24, //! Illegal byte sequence
inprogress = -25, //! Operation in progress
intr = -26, //! Interrupted function
inval = -27, //! Invalid argument
io = -28, //! I/O error
isconn = -29, //! Socket is connected
isdir = -30, //! Is a directory
loop = -31, //! Too many levels of symbolic links
mfile = -32, //! File descriptor value too large
mlink = -33, //! Too many links
msgsize = -34, //! Message too large
nametoolong = -35, //! Filename too long
netdown = -36, //! Network is down
netreset = -37, //! Connection aborted by network
netunreach = -38, //! Network unreachable
nfile = -39, //! Too many files open in system
nobufs = -40, //! No buffer space available
nodata = -41, //! No message is available on the STREAM head read queue
nodev = -42, //! No such device
noent = -43, //! No such file or directory
noexec = -44, //! Executable file format error
nolck = -45, //! No locks available
nolink = -46, //! Link has been severed
nomem = -47, //! Not enough space
nomsg = -48, //! No message of the desired type
noprotoopt = -49, //! Protocol not available
nospc = -50, //! No space left on device
nosr = -51, //! No STREAM resources
nostr = -52, //! Not a STREAM
nosys = -53, //! Function not supported
notconn = -54, //! The socket is not connected
notdir = -55, //! Not a directory
notempty = -56, //! Directory not empty
notrecoverable = -57, //! State not recoverable
notsock = -58, //! Not a socket
notsup = -59, //! Not supported
notty = -60, //! Inappropriate I/O control operation
nxio = -61, //! No such device or address
opnotsupp = -62, //! Operation not supported on socket
overflow = -63, //! Value too large to be stored in data type
ownerdead = -64, //! Previous owner died
perm = -65, //! Operation not permitted
pipe = -66, //! Broken pipe
proto = -67, //! Protocol error
protonosupport = -68, //! Protocol not supported
prototype = -69, //! Protocol wrong type for socket
range = -70, //! Result too large
rofs = -71, //! Read-only file system
spipe = -72, //! Invalid seek
srch = -73, //! No such process
time = -74, //! Stream ioctl() timeout
timedout = -75, //! Connection timed out
txtbsy = -76, //! Text file busy
wouldblock = -77, //! Operation would block
xdev = -78, //! Cross-device link
generic = -79, //! Generic error
eof = -255, //! End-of-file reached
};
static inline bool is_error(err error)
{
return error != err::ok;
}
static inline bool is_ok(err error)
{
return !is_error(error);
}
const char* err_to_str(err error);
} // namespace ecl
#ifdef CORE_TESTS_ENABLED
#include <CppUTest/SimpleString.h>
static inline SimpleString StringFrom(ecl::err err)
{
return SimpleString{ecl::err_to_str(err)};
}
#endif // CORE_TESTS_ENABLED
#endif // ECL_LIB_UTILS_ERR_HPP_
<|endoftext|> |
<commit_before>
#include <cstring>
#include <cstdarg>
#include <cstdio>
#include <ctype.h>
#include "Assert.h"
#include "String.h"
String::Data String::emptyData("");
String::Data* String::firstFreeData = 0;
String::String(const char* str, int length)
{
if(length < 0)
length = strlen(str);
init(length, str, length);
}
String::~String()
{
free();
}
void String::init(unsigned int size, const char* str, unsigned int length)
{
ASSERT(size >= length);
if(firstFreeData)
{
data = firstFreeData;
firstFreeData = firstFreeData->next;
data->refs = 1;
if(data->size < size)
{
delete[] (char*)data->str;
data->size = size + 16 + (size >> 1); // badass growing strategy
data->str = new char[data->size + 1];
}
}
else
{
data = new Data;
data->refs = 1;
data->size = size + 16 + (size >> 1); // badass growing strategy
data->str = new char[data->size + 1];
}
if(length)
memcpy((char*)data->str, str, length);
((char*)data->str)[length] = '\0';
data->length = length;
}
void String::free()
{
--data->refs;
if(data->refs == 0)
{
data->next = firstFreeData;
firstFreeData = data;
}
}
void String::grow(unsigned int size, unsigned int length)
{
ASSERT(size >= length);
ASSERT(length <= data->size);
if(data->refs > 1)
{
Data* otherData = data;
--otherData->refs;
init(size, otherData->str, length);
}
else if(data->size < size)
{
char* otherStr = (char*)data->str;
data->size = size + 16 + (size >> 1); // badass growing strategy
data->str = new char[data->size + 1];
if(length)
memcpy((char*)data->str, otherStr, length);
delete[] otherStr;
data->length = length;
((char*)data->str)[length] = '\0';
}
}
String& String::operator=(const String& other)
{
free();
data = other.data;
++data->refs;
return *this;
}
bool String::operator==(const String& other) const
{
return data->length == other.data->length && memcmp(data->str, other.data->str, data->length) == 0;
}
bool String::operator!=(const String& other) const
{
return data->length != other.data->length || memcmp(data->str, other.data->str, data->length) != 0;
}
char* String::getData(unsigned int size)
{
grow(size, 0);
return (char*)data->str;
}
void String::setCapacity(unsigned int size)
{
grow(size < data->length ? data->length : size, data->length); // enforce detach
}
String& String::append(char c)
{
unsigned int newLength = data->length + 1;
grow(newLength, data->length);
((char*)data->str)[data->length] = c;
((char*)data->str)[newLength] = '\0';
data->length = newLength;
return *this;
}
String& String::append(const String& str)
{
unsigned int newLength = data->length + str.data->length;
grow(newLength, data->length);
memcpy(((char*)data->str) + data->length, str.data->str, str.data->length);
((char*)data->str)[newLength] = '\0';
data->length = newLength;
return *this;
}
String& String::append(const char* str, unsigned int length)
{
unsigned int newLength = data->length + length;
grow(newLength, data->length);
memcpy(((char*)data->str) + data->length, str, length);
((char*)data->str)[newLength] = '\0';
data->length = newLength;
return *this;
}
String& String::prepend(const String& str)
{
// TODO: optimize this using memmove when possible?
String old(*this);
unsigned int newLength = data->length + str.data->length;
grow(newLength, 0);
memcpy((char*)data->str, str.data->str, str.data->length);
memcpy(((char*)data->str) + str.data->length, old.data->str, old.data->length);
((char*)data->str)[newLength] = '\0';
data->length = newLength;
return *this;
}
void String::clear()
{
if(data->refs == 1)
{
*(char*)data->str = '\0';
data->length = 0;
}
else
{
free();
data = &emptyData;
++data->refs;
}
}
void String::setLength(unsigned int length)
{
grow(length, length); // detach
((char*)data->str)[length] = '\0';
data->length = length;
}
String& String::format(unsigned int size, const char* format, ...)
{
int length;
va_list ap;
va_start(ap, format);
#ifdef _MSC_VER
length = vsprintf_s(getData(size), size, format, ap);
#else
length = ::vsnprintf(getData(size), size, format, ap);
if(length < 0)
length = size;
#endif
va_end(ap);
((char*)data->str)[length] = '\0';
data->length = length;
return *this;
}
String String::substr(int start, int length) const
{
if(start < 0)
{
start = (int)data->length + start;
if(start < 0)
start = 0;
}
else if((unsigned int)start > data->length)
start = data->length;
int end;
if(length >= 0)
{
end = start + length;
if((unsigned int)end > data->length)
end = data->length;
}
else
end = data->length;
length = end - start;
String result(length);
memcpy((char*)result.data->str, data->str + start, length);
((char*)result.data->str)[length] = '\0';
result.data->length = length;
return result;
}
int String::subst(const String& from, const String& to)
{
String result(data->length + to.data->length * 2);
const char* str = data->str;
const char* f = from.data->str;
unsigned int flen = from.data->length;
const char* start = str;
int i = 0;
while(*str)
if(*str == *f && strncmp(str, f, flen) == 0)
{
if(str > start)
result.append(start, str - start);
result.append(to);
str += flen;
start = str;
++i;
}
else
++str;
if(str > start)
result.append(start, str - start);
*this = result;
return i;
}
static bool szWildMatch7(const char* pat, const char* str);
static bool szWildMatch1(const char* pat, const char* str, const char*& matchstart, const char*& matchend);
bool String::patmatch(const String& pattern) const
{
return szWildMatch7(pattern.data->str, data->str);
}
bool String::patsubst(const String& pattern, const String& replace)
{
const char* matchstart;
const char* matchend;
if(!szWildMatch1(pattern.data->str, data->str, matchstart, matchend))
return false;
unsigned int matchlen = matchend - matchstart;
String result(matchlen + replace.data->length);
char* dest = (char*)result.data->str;
for(const char* src = replace.data->str; *src; ++src)
if(*src == '\\' && (src[1] == '%' || (src[1] == '\\' && src[2] == '%')))
{
++src;
*(dest++) = *src;
}
else if(*src == '%')
{
memcpy(dest, matchstart, matchlen);
dest += matchlen;
++src;
unsigned int left = replace.data->length - (src - replace.data->str);
memcpy(dest, src, left);
dest += left;
break;
}
else
*(dest++) = *src;
*dest = '\0';
result.data->length = dest - result.data->str;
*this = result;
return true;
}
/*
slightly modified wildcard matching functions based on Alessandro Cantatore's algorithms
http://xoomer.virgilio.it/acantato/dev/wildcard/wildmatch.html
*/
static bool szWildMatch7(const char* pat, const char* str) {
const char* s, * p;
bool star = false;
loopStart:
for (s = str, p = pat; *s; ++s, ++p) {
switch (*p) {
case '%':
star = true;
str = s, pat = p;
do { ++pat; } while (*pat == '%');
if (!*++pat) return true;
goto loopStart;
default:
if (*s != *p) goto starCheck;
break;
}
}
while (*p == '%') ++p;
return !*p;
starCheck:
if (!star) return false;
str++;
goto loopStart;
}
static bool szWildMatch1(const char* pat, const char* str, const char*& matchstart, const char*& matchend)
{
while(*str)
{
switch(*pat)
{
case '%':
matchstart = str;
do { ++pat; } while(*pat == '%');
if(!*pat)
{
matchend = matchstart + strlen(matchstart);
return true;
}
while(*str)
if(szWildMatch7(pat, str++))
{
matchend = str - 1;
return true;
}
return false;
default:
if(*str != *pat)
return false;
break;
}
++pat, ++str;
}
while(*pat == '%')
++pat;
if(!*pat)
{
matchstart = matchend = str;
return true;
}
return false;
}
String& String::lowercase()
{
grow(data->length, data->length); // detach
for(char* str = (char*)data->str; *str; ++str)
*str = tolower(*(unsigned char*)str);
return *this;
}
String& String::uppercase()
{
grow(data->length, data->length); // detach
for(char* str = (char*)data->str; *str; ++str)
*str = toupper(*(unsigned char*)str);
return *this;
}
<commit_msg>Fix not working pattern matching and substitution (filter, patsubst)<commit_after>
#include <cstring>
#include <cstdarg>
#include <cstdio>
#include <ctype.h>
#include "Assert.h"
#include "String.h"
String::Data String::emptyData("");
String::Data* String::firstFreeData = 0;
String::String(const char* str, int length)
{
if(length < 0)
length = strlen(str);
init(length, str, length);
}
String::~String()
{
free();
}
void String::init(unsigned int size, const char* str, unsigned int length)
{
ASSERT(size >= length);
if(firstFreeData)
{
data = firstFreeData;
firstFreeData = firstFreeData->next;
data->refs = 1;
if(data->size < size)
{
delete[] (char*)data->str;
data->size = size + 16 + (size >> 1); // badass growing strategy
data->str = new char[data->size + 1];
}
}
else
{
data = new Data;
data->refs = 1;
data->size = size + 16 + (size >> 1); // badass growing strategy
data->str = new char[data->size + 1];
}
if(length)
memcpy((char*)data->str, str, length);
((char*)data->str)[length] = '\0';
data->length = length;
}
void String::free()
{
--data->refs;
if(data->refs == 0)
{
data->next = firstFreeData;
firstFreeData = data;
}
}
void String::grow(unsigned int size, unsigned int length)
{
ASSERT(size >= length);
ASSERT(length <= data->size);
if(data->refs > 1)
{
Data* otherData = data;
--otherData->refs;
init(size, otherData->str, length);
}
else if(data->size < size)
{
char* otherStr = (char*)data->str;
data->size = size + 16 + (size >> 1); // badass growing strategy
data->str = new char[data->size + 1];
if(length)
memcpy((char*)data->str, otherStr, length);
delete[] otherStr;
data->length = length;
((char*)data->str)[length] = '\0';
}
}
String& String::operator=(const String& other)
{
free();
data = other.data;
++data->refs;
return *this;
}
bool String::operator==(const String& other) const
{
return data->length == other.data->length && memcmp(data->str, other.data->str, data->length) == 0;
}
bool String::operator!=(const String& other) const
{
return data->length != other.data->length || memcmp(data->str, other.data->str, data->length) != 0;
}
char* String::getData(unsigned int size)
{
grow(size, 0);
return (char*)data->str;
}
void String::setCapacity(unsigned int size)
{
grow(size < data->length ? data->length : size, data->length); // enforce detach
}
String& String::append(char c)
{
unsigned int newLength = data->length + 1;
grow(newLength, data->length);
((char*)data->str)[data->length] = c;
((char*)data->str)[newLength] = '\0';
data->length = newLength;
return *this;
}
String& String::append(const String& str)
{
unsigned int newLength = data->length + str.data->length;
grow(newLength, data->length);
memcpy(((char*)data->str) + data->length, str.data->str, str.data->length);
((char*)data->str)[newLength] = '\0';
data->length = newLength;
return *this;
}
String& String::append(const char* str, unsigned int length)
{
unsigned int newLength = data->length + length;
grow(newLength, data->length);
memcpy(((char*)data->str) + data->length, str, length);
((char*)data->str)[newLength] = '\0';
data->length = newLength;
return *this;
}
String& String::prepend(const String& str)
{
// TODO: optimize this using memmove when possible?
String old(*this);
unsigned int newLength = data->length + str.data->length;
grow(newLength, 0);
memcpy((char*)data->str, str.data->str, str.data->length);
memcpy(((char*)data->str) + str.data->length, old.data->str, old.data->length);
((char*)data->str)[newLength] = '\0';
data->length = newLength;
return *this;
}
void String::clear()
{
if(data->refs == 1)
{
*(char*)data->str = '\0';
data->length = 0;
}
else
{
free();
data = &emptyData;
++data->refs;
}
}
void String::setLength(unsigned int length)
{
grow(length, length); // detach
((char*)data->str)[length] = '\0';
data->length = length;
}
String& String::format(unsigned int size, const char* format, ...)
{
int length;
va_list ap;
va_start(ap, format);
#ifdef _MSC_VER
length = vsprintf_s(getData(size), size, format, ap);
#else
length = ::vsnprintf(getData(size), size, format, ap);
if(length < 0)
length = size;
#endif
va_end(ap);
((char*)data->str)[length] = '\0';
data->length = length;
return *this;
}
String String::substr(int start, int length) const
{
if(start < 0)
{
start = (int)data->length + start;
if(start < 0)
start = 0;
}
else if((unsigned int)start > data->length)
start = data->length;
int end;
if(length >= 0)
{
end = start + length;
if((unsigned int)end > data->length)
end = data->length;
}
else
end = data->length;
length = end - start;
String result(length);
memcpy((char*)result.data->str, data->str + start, length);
((char*)result.data->str)[length] = '\0';
result.data->length = length;
return result;
}
int String::subst(const String& from, const String& to)
{
String result(data->length + to.data->length * 2);
const char* str = data->str;
const char* f = from.data->str;
unsigned int flen = from.data->length;
const char* start = str;
int i = 0;
while(*str)
if(*str == *f && strncmp(str, f, flen) == 0)
{
if(str > start)
result.append(start, str - start);
result.append(to);
str += flen;
start = str;
++i;
}
else
++str;
if(str > start)
result.append(start, str - start);
*this = result;
return i;
}
static bool szWildMatch7(const char* pat, const char* str);
static bool szWildMatch1(const char* pat, const char* str, const char*& matchstart, const char*& matchend);
bool String::patmatch(const String& pattern) const
{
return szWildMatch7(pattern.data->str, data->str);
}
bool String::patsubst(const String& pattern, const String& replace)
{
const char* matchstart;
const char* matchend;
if(!szWildMatch1(pattern.data->str, data->str, matchstart, matchend))
return false;
unsigned int matchlen = matchend - matchstart;
String result(matchlen + replace.data->length);
char* dest = (char*)result.data->str;
for(const char* src = replace.data->str; *src; ++src)
if(*src == '\\' && (src[1] == '%' || (src[1] == '\\' && src[2] == '%')))
{
++src;
*(dest++) = *src;
}
else if(*src == '%')
{
memcpy(dest, matchstart, matchlen);
dest += matchlen;
++src;
unsigned int left = replace.data->length - (src - replace.data->str);
memcpy(dest, src, left);
dest += left;
break;
}
else
*(dest++) = *src;
*dest = '\0';
result.data->length = dest - result.data->str;
*this = result;
return true;
}
/*
slightly modified wildcard matching functions based on Alessandro Cantatore's algorithms
http://xoomer.virgilio.it/acantato/dev/wildcard/wildmatch.html
*/
static bool szWildMatch7(const char* pat, const char* str) {
const char* s, * p;
bool star = false;
loopStart:
for (s = str, p = pat; *s; ++s, ++p) {
switch (*p) {
case '%':
star = true;
str = s, pat = p;
do { ++pat; } while (*pat == '%');
if (!*pat) return true;
goto loopStart;
default:
if (*s != *p) goto starCheck;
break;
}
}
while (*p == '%') ++p;
return !*p;
starCheck:
if (!star) return false;
str++;
goto loopStart;
}
static bool szWildMatch1(const char* pat, const char* str, const char*& matchstart, const char*& matchend)
{
while(*str)
{
switch(*pat)
{
case '%':
matchstart = str;
do { ++pat; } while(*pat == '%');
if(!*pat)
{
matchend = matchstart + strlen(matchstart);
return true;
}
while(*str)
if(szWildMatch7(pat, str++))
{
matchend = str - 1;
return true;
}
return false;
default:
if(*str != *pat)
return false;
break;
}
++pat, ++str;
}
while(*pat == '%')
++pat;
if(!*pat)
{
matchstart = matchend = str;
return true;
}
return false;
}
String& String::lowercase()
{
grow(data->length, data->length); // detach
for(char* str = (char*)data->str; *str; ++str)
*str = tolower(*(unsigned char*)str);
return *this;
}
String& String::uppercase()
{
grow(data->length, data->length); // detach
for(char* str = (char*)data->str; *str; ++str)
*str = toupper(*(unsigned char*)str);
return *this;
}
<|endoftext|> |
<commit_before>#include <SDL2/SDL.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <Vect2.h>
#include "Systems/RenderSystem.h"
#include "Systems/ComponentManager.h"
#include "Systems/EntitySystem.h"
#include "Components/Sprite.h"
#include "Components/Transform.h"
#include "Components/BoxCollider.h"
#include "Components/SpriteSheet.h"
#include "Components/Animation.h"
#include "Components/SlopeCollider.h"
#include "Systems/ECS.h"
#include "Core.h"
#include "Systems/MovementSystem.h"
#include "Input/KeyboardController.h"
#include "Input/GameController.h"
#include "Utility/TextureLoader.h"
#include "Utility/TextureStore.h"
#include "Utility/ImageStore.h"
#include "Utility/ImageMod.h"
#include "Utility/MapFileLoader.h"
using namespace std;
int main(int argc, char* argv[])
{
Core core;
SDL_Renderer* render = core.getRenderer();
//draw a grid - pre render a static image.
const float tileWidth = 56;
const float tileHeight = 56;
const int level_width = 800;
const int level_height = 600;
const int tiles_per_row = level_width / (int)tileWidth;
const int tiles_per_col = level_height / (int)tileHeight;
const int x_offset = 17 / 2;
const int y_offset = 41 / 2;
SDL_Texture* grid = SDL_CreateTexture(render, SDL_GetWindowPixelFormat(core.getWindow()), SDL_TEXTUREACCESS_TARGET, level_width, level_height);
SDL_SetTextureBlendMode(grid, SDL_BlendMode::SDL_BLENDMODE_BLEND);
SDL_SetRenderTarget(render, grid);
//transparent background
SDL_SetRenderDrawColor(render, 255, 255, 255, 0);
SDL_RenderClear(render);
//black
SDL_SetRenderDrawColor(render, 0, 0, 0, 255);
for (int r = 0;r < tiles_per_col;++r)
{
for (int c = 0;c < tiles_per_row;++c)
{
SDL_Rect gridBox;
gridBox.x = c * (int)tileWidth + x_offset;
gridBox.y = r * (int)tileHeight + y_offset;
gridBox.w = (int)tileWidth;
gridBox.h = (int)tileHeight;
SDL_RenderDrawRect(render,&gridBox);
}
}
SDL_RenderPresent(render);
//set the render target back to the window's screen.
SDL_SetRenderTarget(render, NULL);
//setup texture file paths
string mainPath(SDL_GetBasePath());
mainPath += string("resources\\");
string backgroundPath = mainPath + string("hills.png");
string tilePath = mainPath + string("box.png");
ImageStore store(render);
store.Load("hills.png", backgroundPath);
store.Load("box.png", tilePath);
ECS ecs;
int bgID = ecs.entitySystem.CreateEntity("Background");
auto bgTransform = new Transform();
bgTransform->position = Vect2(0.0f, 0.0f);
auto bgSprite = new Sprite(store.Get("hills.png"));
ecs.transforms.AddComponent(bgID, bgTransform);
ecs.sprites.AddComponent(bgID, bgSprite);
//initialize systems
RenderSystem renderSys(&ecs);
renderSys.Init(SCREEN_WIDTH, SCREEN_HEIGHT);
SDL_Point mousePos{ 0,0 };
//screen to game world coordinates as ints
SDL_Point gameCoords{ 0,0 };
//---------------- Game Loop ------------------//
//observedDeltaTime is measured in milliseconds
float observedDeltaTime = core.getTargetDeltaTime();
float deltaTime = observedDeltaTime / 1000.0f;//converts from milliseconds to seconds
//to avoid unnecessary context switches os might do (which I have no control over.. cache the target delta time)
float targetDeltaTime = core.getTargetDeltaTime();
Uint64 observedFPS = core.getTargetFPS();
float currentTime = 0.0f;
Uint64 performanceFrequency = SDL_GetPerformanceFrequency();
Uint64 startCount = SDL_GetPerformanceCounter();
Uint64 endCount;
bool running = true;
while (running)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
running = false;
if (event.type == SDL_MOUSEBUTTONDOWN)
{
if (event.button.button == SDL_BUTTON_LEFT)
{
printf("left mouse click (%d,%d)\n", mousePos.x, mousePos.y);
printf("game world coords(%d, %d)\n", gameCoords.x, gameCoords.y);
//if (mousePos.x > 0 && mousePos.x + (int)tileWidth < SCREEN_WIDTH)
//{
int tileID = ecs.entitySystem.CreateEntity("Tile");
Vect2 tilePosition;
// tilePosition.x = (float)gameCoords.x;
// tilePosition.y = (float)gameCoords.y;
//clamp tile position to grid.
int r = gameCoords.y / (int)tileHeight;
int c = gameCoords.x / (int)tileWidth;
tilePosition.x = c * tileWidth + x_offset;
tilePosition.y = r * tileHeight + y_offset;
ecs.transforms.AddComponent(tileID, new Transform(tilePosition));
Sprite* sprite = new Sprite(store.Get("box.png"));
sprite->width = (int)tileWidth;
sprite->height = (int)tileHeight;
ecs.sprites.AddComponent(tileID, sprite);
//}
}
}
else if (event.type == SDL_MOUSEMOTION)
{
mousePos.x = event.button.x;
mousePos.y = event.button.y;
gameCoords.x = renderSys.camera.x + mousePos.x;
gameCoords.y = renderSys.camera.y + mousePos.y;
}
}
//pixels per frame
int camSpeed = 2;
if (mousePos.x + 5 > SCREEN_WIDTH)
{
if (renderSys.camera.x + renderSys.camera.w < level_width)
{
renderSys.camera.x += camSpeed;
}
}
if (mousePos.x < 5)
{
if (renderSys.camera.x > 0)
renderSys.camera.x -= camSpeed;
}
if (mousePos.y + 5 > SCREEN_HEIGHT)
{
int level_height = 600;
if (renderSys.camera.y + renderSys.camera.h < level_height)
renderSys.camera.y += camSpeed;
}
if (mousePos.y < 5)
{
if (renderSys.camera.y > 0)
renderSys.camera.y -= camSpeed;
}
renderSys.Update(render);
SDL_RenderCopy(render, grid, &renderSys.camera, NULL);
renderSys.Draw(render);
endCount = SDL_GetPerformanceCounter();
observedDeltaTime = (1000.0f * (endCount - startCount)) / performanceFrequency;//gives ms
observedFPS = performanceFrequency / (endCount - startCount);
//if the computer can process the update and draw functions faster than 60 fps...
//cap the frame-rate here to ensure that all computers play roughly around the same fps
float msDifference = targetDeltaTime - observedDeltaTime;
if (msDifference > 0)
{
SDL_Delay((Uint32)msDifference);
//Note: must re-record the times after the delay since the times before the delay maybe
//under 16.666 ms
endCount = SDL_GetPerformanceCounter();
observedDeltaTime = (1000.0f * (endCount - startCount)) / performanceFrequency;//gives ms
observedFPS = performanceFrequency / (endCount - startCount);
}
currentTime += observedDeltaTime;
deltaTime = observedDeltaTime / 1000.0f;
startCount = endCount;
//display fps text in title
std::string title("Beat Em Left");
title += std::string(" | FPS: ") + std::to_string(observedFPS);
SDL_SetWindowTitle(core.getWindow(), title.c_str());
}
SDL_DestroyTexture(grid);
return 0;
}<commit_msg>WIP tile removal button<commit_after>#include <SDL2/SDL.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <Vect2.h>
#include "Systems/RenderSystem.h"
#include "Systems/ComponentManager.h"
#include "Systems/EntitySystem.h"
#include "Components/Sprite.h"
#include "Components/Transform.h"
#include "Components/BoxCollider.h"
#include "Components/SpriteSheet.h"
#include "Components/Animation.h"
#include "Components/SlopeCollider.h"
#include "Systems/ECS.h"
#include "Core.h"
#include "Systems/MovementSystem.h"
#include "Input/KeyboardController.h"
#include "Input/GameController.h"
#include "Utility/TextureLoader.h"
#include "Utility/TextureStore.h"
#include "Utility/ImageStore.h"
#include "Utility/ImageMod.h"
#include "Utility/MapFileLoader.h"
using namespace std;
int main(int argc, char* argv[])
{
Core core;
SDL_Renderer* render = core.getRenderer();
//draw a grid - pre render a static image.
const float tileWidth = 56;
const float tileHeight = 56;
const int level_width = 800;
const int level_height = 600;
const int tiles_per_row = level_width / (int)tileWidth;
const int tiles_per_col = level_height / (int)tileHeight;
const int x_offset = 17 / 2;
const int y_offset = 41 / 2;
SDL_Texture* grid = SDL_CreateTexture(render, SDL_GetWindowPixelFormat(core.getWindow()), SDL_TEXTUREACCESS_TARGET, level_width, level_height);
SDL_SetTextureBlendMode(grid, SDL_BlendMode::SDL_BLENDMODE_BLEND);
SDL_SetRenderTarget(render, grid);
//transparent background
SDL_SetRenderDrawColor(render, 255, 255, 255, 0);
SDL_RenderClear(render);
//black
SDL_SetRenderDrawColor(render, 0, 0, 0, 255);
for (int r = 0;r < tiles_per_col;++r)
{
for (int c = 0;c < tiles_per_row;++c)
{
SDL_Rect gridBox;
gridBox.x = c * (int)tileWidth + x_offset;
gridBox.y = r * (int)tileHeight + y_offset;
gridBox.w = (int)tileWidth;
gridBox.h = (int)tileHeight;
SDL_RenderDrawRect(render,&gridBox);
}
}
SDL_RenderPresent(render);
//set the render target back to the window's screen.
SDL_SetRenderTarget(render, NULL);
//setup texture file paths
string mainPath(SDL_GetBasePath());
mainPath += string("resources\\");
string backgroundPath = mainPath + string("hills.png");
string tilePath = mainPath + string("box.png");
ImageStore store(render);
store.Load("hills.png", backgroundPath);
store.Load("box.png", tilePath);
ECS ecs;
int bgID = ecs.entitySystem.CreateEntity("Background");
auto bgTransform = new Transform();
bgTransform->position = Vect2(0.0f, 0.0f);
auto bgSprite = new Sprite(store.Get("hills.png"));
ecs.transforms.AddComponent(bgID, bgTransform);
ecs.sprites.AddComponent(bgID, bgSprite);
//initialize systems
RenderSystem renderSys(&ecs);
renderSys.Init(SCREEN_WIDTH, SCREEN_HEIGHT);
SDL_Point mousePos{ 0,0 };
//screen to game world coordinates as ints
SDL_Point gameCoords{ 0,0 };
//---------------- Game Loop ------------------//
//observedDeltaTime is measured in milliseconds
float observedDeltaTime = core.getTargetDeltaTime();
float deltaTime = observedDeltaTime / 1000.0f;//converts from milliseconds to seconds
//to avoid unnecessary context switches os might do (which I have no control over.. cache the target delta time)
float targetDeltaTime = core.getTargetDeltaTime();
Uint64 observedFPS = core.getTargetFPS();
float currentTime = 0.0f;
Uint64 performanceFrequency = SDL_GetPerformanceFrequency();
Uint64 startCount = SDL_GetPerformanceCounter();
Uint64 endCount;
bool running = true;
while (running)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
running = false;
if (event.type == SDL_MOUSEBUTTONDOWN)
{
//add a tile
if (event.button.button == SDL_BUTTON_LEFT)
{
printf("left mouse click (%d,%d)\n", mousePos.x, mousePos.y);
printf("game world coords(%d, %d)\n", gameCoords.x, gameCoords.y);
//if (mousePos.x > 0 && mousePos.x + (int)tileWidth < SCREEN_WIDTH)
//{
int tileID = ecs.entitySystem.CreateEntity("Tile");
Vect2 tilePosition;
// tilePosition.x = (float)gameCoords.x;
// tilePosition.y = (float)gameCoords.y;
//clamp tile position to grid.
int r = gameCoords.y / (int)tileHeight;
int c = gameCoords.x / (int)tileWidth;
tilePosition.x = c * tileWidth + x_offset;
tilePosition.y = r * tileHeight + y_offset;
ecs.transforms.AddComponent(tileID, new Transform(tilePosition));
Sprite* sprite = new Sprite(store.Get("box.png"));
sprite->width = (int)tileWidth;
sprite->height = (int)tileHeight;
ecs.sprites.AddComponent(tileID, sprite);
//}
}
//TODO: remove at tile (create a simple data structure that tells us if a tile is occupying a space or not
if (event.button.button == SDL_BUTTON_RIGHT)
{
//check if point overlaps in a rectangle!
SDL_Point pixelCoords;
pixelCoords.y = gameCoords.y / (int)tileHeight;
pixelCoords.x = gameCoords.x / (int)tileWidth;
pixelCoords.y = (pixelCoords.y * (int)tileHeight) + y_offset;
pixelCoords.x = (pixelCoords.x * (int)tileWidth) + x_offset;
//.....
printf("remove tile at: (%d,%d)\n", gameCoords.x, gameCoords.y);
}
}
else if (event.type == SDL_MOUSEMOTION)
{
mousePos.x = event.button.x;
mousePos.y = event.button.y;
gameCoords.x = renderSys.camera.x + mousePos.x;
gameCoords.y = renderSys.camera.y + mousePos.y;
}
}
//pixels per frame
int camSpeed = 2;
if (mousePos.x + 5 > SCREEN_WIDTH)
{
if (renderSys.camera.x + renderSys.camera.w < level_width)
{
renderSys.camera.x += camSpeed;
}
}
if (mousePos.x < 5)
{
if (renderSys.camera.x > 0)
renderSys.camera.x -= camSpeed;
}
if (mousePos.y + 5 > SCREEN_HEIGHT)
{
int level_height = 600;
if (renderSys.camera.y + renderSys.camera.h < level_height)
renderSys.camera.y += camSpeed;
}
if (mousePos.y < 5)
{
if (renderSys.camera.y > 0)
renderSys.camera.y -= camSpeed;
}
renderSys.Update(render);
SDL_RenderCopy(render, grid, &renderSys.camera, NULL);
renderSys.Draw(render);
endCount = SDL_GetPerformanceCounter();
observedDeltaTime = (1000.0f * (endCount - startCount)) / performanceFrequency;//gives ms
observedFPS = performanceFrequency / (endCount - startCount);
//if the computer can process the update and draw functions faster than 60 fps...
//cap the frame-rate here to ensure that all computers play roughly around the same fps
float msDifference = targetDeltaTime - observedDeltaTime;
if (msDifference > 0)
{
SDL_Delay((Uint32)msDifference);
//Note: must re-record the times after the delay since the times before the delay maybe
//under 16.666 ms
endCount = SDL_GetPerformanceCounter();
observedDeltaTime = (1000.0f * (endCount - startCount)) / performanceFrequency;//gives ms
observedFPS = performanceFrequency / (endCount - startCount);
}
currentTime += observedDeltaTime;
deltaTime = observedDeltaTime / 1000.0f;
startCount = endCount;
//display fps text in title
std::string title("Beat Em Left");
title += std::string(" | FPS: ") + std::to_string(observedFPS);
SDL_SetWindowTitle(core.getWindow(), title.c_str());
}
SDL_DestroyTexture(grid);
return 0;
}<|endoftext|> |
<commit_before>#include <Box2D/Box2D.h>
#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/Rand.h"
#include "Attractor.h"
#include "Particle.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class Ex56ForcesApp : public AppNative {
public:
void setup();
void mouseDown( MouseEvent event );
void mouseUp( MouseEvent event );
void mouseMove( MouseEvent event );
void mouseDrag( MouseEvent event );
void update();
void draw();
void shutdown();
b2World *world;
float32 timeStep;
float32 velocityIterations;
int32 positionIterations;
Attractor attractor;
vector<Particle> particles;
Vec2f mouseLocation;
};
void Ex56ForcesApp::setup() {
world = new b2World( b2Vec2( 0.0f, 0.0f ) ); // no gravity in this example!
timeStep = 1.0f / 60.0f;
velocityIterations = 8;
positionIterations = 3;
attractor = Attractor( world, getWindowCenter().x, getWindowCenter().y );
for (int i = 0; i < 100; ++i) {
particles.push_back( Particle(world, Vec2f( Rand::randFloat( getWindowWidth() ), Rand::randFloat( getWindowHeight() ) ), randFloat( 7.0f, 14.0f ) ) );
}
}
void Ex56ForcesApp::mouseDown( MouseEvent event ) {
attractor.clicked( event.getPos() );
}
void Ex56ForcesApp::mouseUp( MouseEvent event ) {
attractor.stopDragging();
}
void Ex56ForcesApp::mouseMove( MouseEvent event ) {
mouseLocation = event.getPos();
}
void Ex56ForcesApp::mouseDrag( MouseEvent event ) {
mouseLocation = event.getPos();
}
void Ex56ForcesApp::update() {
world->Step( timeStep, velocityIterations, positionIterations );
attractor.hover( mouseLocation );
attractor.drag( mouseLocation );
for ( auto& particle : particles ) {
particle.update( world, attractor.attract( particle ) );
}
}
void Ex56ForcesApp::draw() {
gl::clear( Color( 0, 0, 0 ) );
attractor.draw();
for ( auto& particle : particles ) {
particle.draw();
}
}
void Ex56ForcesApp::shutdown() {
for ( auto& particle : particles ) {
particle.killBody( world );
}
attractor.killBody( world );
delete world;
}
CINDER_APP_NATIVE( Ex56ForcesApp, RendererGl )
<commit_msg>Example 5.6 Updated<commit_after>#include <Box2D/Box2D.h>
#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/Rand.h"
#include "Attractor.h"
#include "Particle.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class Ex56ForcesApp : public AppNative {
public:
void setup();
void mouseDown( MouseEvent event );
void mouseUp( MouseEvent event );
void mouseMove( MouseEvent event );
void mouseDrag( MouseEvent event );
void update();
void draw();
void shutdown();
b2World *world;
float32 timeStep;
float32 velocityIterations;
int32 positionIterations;
Attractor attractor;
vector<Particle> particles;
Vec2f mouseLocation;
};
void Ex56ForcesApp::setup() {
world = new b2World( b2Vec2( 0.0f, 0.0f ) ); // no gravity in this example!
timeStep = 1.0f / 60.0f;
velocityIterations = 8;
positionIterations = 3;
attractor = Attractor( world, getWindowCenter().x, getWindowCenter().y );
for (int i = 0; i < 100; ++i) {
particles.push_back( Particle(world, Vec2f( Rand::randFloat( getWindowWidth() ), Rand::randFloat( getWindowHeight() ) ), randFloat( 7.0f, 14.0f ) ) );
}
}
void Ex56ForcesApp::mouseDown( MouseEvent event ) {
attractor.clicked( event.getPos() );
}
void Ex56ForcesApp::mouseUp( MouseEvent event ) {
attractor.stopDragging();
}
void Ex56ForcesApp::mouseMove( MouseEvent event ) {
mouseLocation = event.getPos();
}
void Ex56ForcesApp::mouseDrag( MouseEvent event ) {
mouseLocation = event.getPos();
}
void Ex56ForcesApp::update() {
attractor.hover( mouseLocation );
attractor.drag( mouseLocation );
for ( auto& particle : particles ) {
particle.update( world, attractor.attract( particle ) );
}
world->Step( timeStep, velocityIterations, positionIterations );
world->ClearForces();
}
void Ex56ForcesApp::draw() {
gl::clear( Color( 0, 0, 0 ) );
attractor.draw();
for ( auto& particle : particles ) {
particle.draw();
}
}
void Ex56ForcesApp::shutdown() {
for ( auto& particle : particles ) {
particle.killBody( world );
}
attractor.killBody( world );
delete world;
}
CINDER_APP_NATIVE( Ex56ForcesApp, RendererGl )
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <process/future.hpp>
#include <process/gtest.hpp>
#include <process/owned.hpp>
#include <stout/gtest.hpp>
#include <stout/try.hpp>
#include <mesos/master/detector.hpp>
#include <mesos/mesos.hpp>
#include <mesos/scheduler.hpp>
#include "slave/flags.hpp"
#include "tests/cluster.hpp"
#include "tests/environment.hpp"
#include "tests/mesos.hpp"
using mesos::master::detector::MasterDetector;
using process::Future;
using process::Owned;
using std::string;
using std::vector;
namespace mesos {
namespace internal {
namespace tests {
class PosixRLimitsIsolatorTest : public MesosTest {};
// This test confirms that if a task exceeds configured resource
// limits it is forcibly terminated.
TEST_F(PosixRLimitsIsolatorTest, TaskExceedingLimit)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "posix/rlimits";
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched,
DEFAULT_FRAMEWORK_INFO,
master.get()->pid,
DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(_, _, _))
.Times(1);
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(_, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
ASSERT_NE(0u, offers->size());
// The task attempts to use an infinite amount of CPU time.
TaskInfo task = createTask(
offers.get()[0].slave_id(),
offers.get()[0].resources(),
"while true; do true; done");
ContainerInfo* container = task.mutable_container();
container->set_type(ContainerInfo::MESOS);
// Limit the process to use maximally 1 second of CPU time.
RLimitInfo rlimitInfo;
RLimitInfo::RLimit* cpuLimit = rlimitInfo.add_rlimits();
cpuLimit->set_type(RLimitInfo::RLimit::RLMT_CPU);
cpuLimit->set_soft(1);
cpuLimit->set_hard(1);
container->mutable_rlimit_info()->CopyFrom(rlimitInfo);
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFailed;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFailed));
driver.launchTasks(offers.get()[0].id(), {task});
AWAIT_READY(statusRunning);
EXPECT_EQ(task.task_id(), statusRunning->task_id());
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
AWAIT_READY(statusFailed);
EXPECT_EQ(task.task_id(), statusFailed->task_id());
EXPECT_EQ(TASK_FAILED, statusFailed->state());
driver.stop();
driver.join();
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
<commit_msg>Extended test coverage of posix/rlimits isolator.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <process/future.hpp>
#include <process/gtest.hpp>
#include <process/owned.hpp>
#include <stout/gtest.hpp>
#include <stout/try.hpp>
#include <mesos/master/detector.hpp>
#include <mesos/mesos.hpp>
#include <mesos/scheduler.hpp>
#include "slave/flags.hpp"
#include "tests/cluster.hpp"
#include "tests/environment.hpp"
#include "tests/mesos.hpp"
using mesos::master::detector::MasterDetector;
using process::Future;
using process::Owned;
using std::string;
using std::vector;
namespace mesos {
namespace internal {
namespace tests {
class PosixRLimitsIsolatorTest : public MesosTest {};
// This test checks the behavior of passed invalid limits.
TEST_F(PosixRLimitsIsolatorTest, InvalidLimits)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "posix/rlimits";
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched,
DEFAULT_FRAMEWORK_INFO,
master.get()->pid, DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(_, _, _))
.Times(1);
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(_, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
ASSERT_NE(0u, offers->size());
TaskInfo task = createTask(
offers.get()[0].slave_id(),
offers.get()[0].resources(),
"true");
ContainerInfo* container = task.mutable_container();
container->set_type(ContainerInfo::MESOS);
// Set impossible limit soft > hard.
RLimitInfo rlimitInfo;
RLimitInfo::RLimit* rlimit = rlimitInfo.add_rlimits();
rlimit->set_type(RLimitInfo::RLimit::RLMT_CPU);
rlimit->set_soft(100);
rlimit->set_hard(1);
container->mutable_rlimit_info()->CopyFrom(rlimitInfo);
Future<TaskStatus> taskStatus;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&taskStatus));
driver.launchTasks(offers.get()[0].id(), {task});
AWAIT_READY(taskStatus);
EXPECT_EQ(task.task_id(), taskStatus->task_id());
EXPECT_EQ(TASK_FAILED, taskStatus->state());
EXPECT_EQ(TaskStatus::REASON_EXECUTOR_TERMINATED, taskStatus->reason());
driver.stop();
driver.join();
}
// This test confirms that setting no values for the soft and hard
// limits implies an unlimited resource.
TEST_F(PosixRLimitsIsolatorTest, UnsetLimits) {
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "posix/rlimits";
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched,
DEFAULT_FRAMEWORK_INFO,
master.get()->pid,
DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(_, _, _))
.Times(1);
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(_, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
ASSERT_NE(0u, offers->size());
TaskInfo task = createTask(
offers.get()[0].slave_id(),
offers.get()[0].resources(),
"exit `ulimit -c | grep -q unlimited`");
// Force usage of C locale as we interpret a potentially translated
// string in the task's command.
mesos::Environment::Variable* locale =
task.mutable_command()->mutable_environment()->add_variables();
locale->set_name("LC_ALL");
locale->set_value("C");
ContainerInfo* container = task.mutable_container();
container->set_type(ContainerInfo::MESOS);
// Setting rlimit for core without soft or hard limit signifies
// unlimited range.
RLimitInfo rlimitInfo;
RLimitInfo::RLimit* rlimit = rlimitInfo.add_rlimits();
rlimit->set_type(RLimitInfo::RLimit::RLMT_CORE);
container->mutable_rlimit_info()->CopyFrom(rlimitInfo);
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFinal;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFinal));
driver.launchTasks(offers.get()[0].id(), {task});
AWAIT_READY(statusRunning);
EXPECT_EQ(task.task_id(), statusRunning->task_id());
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
AWAIT_READY(statusFinal);
EXPECT_EQ(task.task_id(), statusFinal->task_id());
EXPECT_EQ(TASK_FINISHED, statusFinal->state());
driver.stop();
driver.join();
}
// This test confirms that setting just one of the soft/hard limits is
// an error.
TEST_F(PosixRLimitsIsolatorTest, BothSoftAndHardLimitSet)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "posix/rlimits";
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched,
DEFAULT_FRAMEWORK_INFO,
master.get()->pid,
DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(_, _, _))
.Times(1);
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(_, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
ASSERT_NE(0u, offers->size());
TaskInfo task = createTask(
offers.get()[0].slave_id(),
offers.get()[0].resources(),
"true");
ContainerInfo* container = task.mutable_container();
container->set_type(ContainerInfo::MESOS);
RLimitInfo rlimitInfo;
RLimitInfo::RLimit* rlimit = rlimitInfo.add_rlimits();
rlimit->set_type(RLimitInfo::RLimit::RLMT_CORE);
rlimit->set_soft(1);
container->mutable_rlimit_info()->CopyFrom(rlimitInfo);
Future<TaskStatus> status;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&status));
driver.launchTasks(offers.get()[0].id(), {task});
AWAIT_READY(status);
EXPECT_EQ(task.task_id(), status->task_id());
EXPECT_EQ(TASK_FAILED, status->state());
EXPECT_EQ(TaskStatus::REASON_EXECUTOR_TERMINATED, status->reason());
driver.stop();
driver.join();
}
// This test confirms that if a task exceeds configured resource
// limits it is forcibly terminated.
TEST_F(PosixRLimitsIsolatorTest, TaskExceedingLimit)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "posix/rlimits";
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched,
DEFAULT_FRAMEWORK_INFO,
master.get()->pid,
DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(_, _, _))
.Times(1);
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(_, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
ASSERT_NE(0u, offers->size());
// The task attempts to use an infinite amount of CPU time.
TaskInfo task = createTask(
offers.get()[0].slave_id(),
offers.get()[0].resources(),
"while true; do true; done");
ContainerInfo* container = task.mutable_container();
container->set_type(ContainerInfo::MESOS);
// Limit the process to use maximally 1 second of CPU time.
RLimitInfo rlimitInfo;
RLimitInfo::RLimit* cpuLimit = rlimitInfo.add_rlimits();
cpuLimit->set_type(RLimitInfo::RLimit::RLMT_CPU);
cpuLimit->set_soft(1);
cpuLimit->set_hard(1);
container->mutable_rlimit_info()->CopyFrom(rlimitInfo);
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFailed;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFailed));
driver.launchTasks(offers.get()[0].id(), {task});
AWAIT_READY(statusRunning);
EXPECT_EQ(task.task_id(), statusRunning->task_id());
EXPECT_EQ(TASK_RUNNING, statusRunning->state());
AWAIT_READY(statusFailed);
EXPECT_EQ(task.task_id(), statusFailed->task_id());
EXPECT_EQ(TASK_FAILED, statusFailed->state());
driver.stop();
driver.join();
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
<|endoftext|> |
<commit_before>
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#ifndef _Stroika_Foundation_Containers_TimedCache_inl_
#define _Stroika_Foundation_Containers_TimedCache_inl_ 1
#include "../Debug/Assertions.h"
namespace Stroika {
namespace Foundation {
namespace Containers {
template <typename KEY, typename RESULT>
TimedCache<KEY,RESULT>::TimedCache (bool accessFreshensDate, Stroika::Foundation::Time::DurationSecondsType timeoutInSeconds):
fMap (),
fAccessFreshensDate (accessFreshensDate),
fTimeout (timeoutInSeconds),
fNextAutoClearAt (Time::GetTickCount () + timeoutInSeconds)
#if qKeepTimedCacheStats
,fCachedCollected_Hits (0)
,fCachedCollected_Misses (0)
#endif
{
Require (fTimeout > 0.0f);
}
template <typename KEY, typename RESULT>
void TimedCache<KEY,RESULT>::SetTimeout (Stroika::Foundation::Time::DurationSecondsType timeoutInSeconds)
{
Require (timeoutInSeconds > 0.0f);
if (fTimeout != timeoutInSeconds) {
ClearIfNeeded_ ();
fTimeout = timeoutInSeconds;
ClearIfNeeded_ ();
}
}
template <typename KEY, typename RESULT>
bool TimedCache<KEY,RESULT>::AccessElement (const KEY& key, RESULT* result)
{
ClearIfNeeded_ ();
map<KEY,MyResult>::iterator i = fMap.find (key);
if (i == fMap.end ()) {
#if qKeepTimedCacheStats
fCachedCollected_Misses++;
#endif
return false;
}
else {
if (fAccessFreshensDate) {
i->second.fLastAccessedAt = Time::GetTickCount ();
}
if (result != NULL) {
*result = i->second.fResult;
}
#if qKeepTimedCacheStats
fCachedCollected_Hits++;
#endif
return true;
}
}
template <typename KEY, typename RESULT>
void TimedCache<KEY,RESULT>::AddElement (const KEY& key, const RESULT& result)
{
ClearIfNeeded_ ();
map<KEY,MyResult>::iterator i = fMap.find (key);
if (i == fMap.end ()) {
fMap.insert (map<KEY,MyResult>::value_type (key, MyResult (result)));
}
else {
i->second = MyResult (result); // overwrite if its already there
}
}
template <typename KEY, typename RESULT>
inline void TimedCache<KEY,RESULT>::DoBookkeeping ()
{
ClearOld_ ();
}
template <typename KEY, typename RESULT>
inline void TimedCache<KEY,RESULT>::ClearIfNeeded_ ()
{
if (fNextAutoClearAt < Time::GetTickCount ()) {
ClearOld_ ();
}
}
template <typename KEY, typename RESULT>
void TimedCache<KEY,RESULT>::ClearOld_ ()
{
Stroika::Foundation::Time::DurationSecondsType now = Time::GetTickCount ();
fNextAutoClearAt = now + fTimeout/2.0f; // somewhat arbitrary how far into the future we do this...
Stroika::Foundation::Time::DurationSecondsType lastAccessThreshold = now - fTimeout;
for (map<KEY,MyResult>::iterator i = fMap.begin (); i != fMap.end (); ) {
if (i->second.fLastAccessedAt < lastAccessThreshold) {
i = fMap.erase (i);
}
else {
++i;
}
}
}
#if qKeepTimedCacheStats
template <typename KEY, typename RESULT>
void TimedCache<KEY,RESULT>::DbgTraceStats (const TCHAR* label) const
{
size_t total = fCachedCollected_Hits + fCachedCollected_Misses;
if (total == 0) {
total = 1; // avoid divide by zero
}
DbgTrace (_T ("%s stats: hits=%d, misses=%d, hit%% %f."), label, fCachedCollected_Hits, fCachedCollected_Misses, float (fCachedCollected_Hits)/(float (total)));
}
#endif
}
}
}
#endif /*_Stroika_Foundation_Containers_TimedCache_inl_*/
<commit_msg>small include fix<commit_after>
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#ifndef _Stroika_Foundation_Containers_TimedCache_inl_
#define _Stroika_Foundation_Containers_TimedCache_inl_ 1
#include "../Debug/Assertions.h"
#include "../Debug/Trace.h"
namespace Stroika {
namespace Foundation {
namespace Containers {
template <typename KEY, typename RESULT>
TimedCache<KEY,RESULT>::TimedCache (bool accessFreshensDate, Stroika::Foundation::Time::DurationSecondsType timeoutInSeconds):
fMap (),
fAccessFreshensDate (accessFreshensDate),
fTimeout (timeoutInSeconds),
fNextAutoClearAt (Time::GetTickCount () + timeoutInSeconds)
#if qKeepTimedCacheStats
,fCachedCollected_Hits (0)
,fCachedCollected_Misses (0)
#endif
{
Require (fTimeout > 0.0f);
}
template <typename KEY, typename RESULT>
void TimedCache<KEY,RESULT>::SetTimeout (Stroika::Foundation::Time::DurationSecondsType timeoutInSeconds)
{
Require (timeoutInSeconds > 0.0f);
if (fTimeout != timeoutInSeconds) {
ClearIfNeeded_ ();
fTimeout = timeoutInSeconds;
ClearIfNeeded_ ();
}
}
template <typename KEY, typename RESULT>
bool TimedCache<KEY,RESULT>::AccessElement (const KEY& key, RESULT* result)
{
ClearIfNeeded_ ();
map<KEY,MyResult>::iterator i = fMap.find (key);
if (i == fMap.end ()) {
#if qKeepTimedCacheStats
fCachedCollected_Misses++;
#endif
return false;
}
else {
if (fAccessFreshensDate) {
i->second.fLastAccessedAt = Time::GetTickCount ();
}
if (result != NULL) {
*result = i->second.fResult;
}
#if qKeepTimedCacheStats
fCachedCollected_Hits++;
#endif
return true;
}
}
template <typename KEY, typename RESULT>
void TimedCache<KEY,RESULT>::AddElement (const KEY& key, const RESULT& result)
{
ClearIfNeeded_ ();
map<KEY,MyResult>::iterator i = fMap.find (key);
if (i == fMap.end ()) {
fMap.insert (map<KEY,MyResult>::value_type (key, MyResult (result)));
}
else {
i->second = MyResult (result); // overwrite if its already there
}
}
template <typename KEY, typename RESULT>
inline void TimedCache<KEY,RESULT>::DoBookkeeping ()
{
ClearOld_ ();
}
template <typename KEY, typename RESULT>
inline void TimedCache<KEY,RESULT>::ClearIfNeeded_ ()
{
if (fNextAutoClearAt < Time::GetTickCount ()) {
ClearOld_ ();
}
}
template <typename KEY, typename RESULT>
void TimedCache<KEY,RESULT>::ClearOld_ ()
{
Stroika::Foundation::Time::DurationSecondsType now = Time::GetTickCount ();
fNextAutoClearAt = now + fTimeout/2.0f; // somewhat arbitrary how far into the future we do this...
Stroika::Foundation::Time::DurationSecondsType lastAccessThreshold = now - fTimeout;
for (map<KEY,MyResult>::iterator i = fMap.begin (); i != fMap.end (); ) {
if (i->second.fLastAccessedAt < lastAccessThreshold) {
i = fMap.erase (i);
}
else {
++i;
}
}
}
#if qKeepTimedCacheStats
template <typename KEY, typename RESULT>
void TimedCache<KEY,RESULT>::DbgTraceStats (const TCHAR* label) const
{
size_t total = fCachedCollected_Hits + fCachedCollected_Misses;
if (total == 0) {
total = 1; // avoid divide by zero
}
DbgTrace (_T ("%s stats: hits=%d, misses=%d, hit%% %f."), label, fCachedCollected_Hits, fCachedCollected_Misses, float (fCachedCollected_Hits)/(float (total)));
}
#endif
}
}
}
#endif /*_Stroika_Foundation_Containers_TimedCache_inl_*/
<|endoftext|> |
<commit_before>#include "erl_nif.h"
static ErlNifResourceType* bulleterl_RESOURCE = NULL;
typedef struct
{
} bulleterl_handle;
// Prototypes
static ERL_NIF_TERM bulleterl_new(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM bulleterl_myfunction(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[]);
static ErlNifFunc nif_funcs[] =
{
{"new", 0, bulleterl_new},
{"myfunction", 1, bulleterl_myfunction}
};
static ERL_NIF_TERM bulleterl_new(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[])
{
bulleterl_handle* handle = enif_alloc_resource(bulleterl_RESOURCE,
sizeof(bulleterl_handle));
ERL_NIF_TERM result = enif_make_resource(env, handle);
enif_release_resource(handle);
return enif_make_tuple2(env, enif_make_atom(env, "ok"), result);
}
static ERL_NIF_TERM bulleterl_myfunction(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[])
{
return enif_make_atom(env, "ok");
}
static void bulleterl_resource_cleanup(ErlNifEnv* env, void* arg)
{
/* Delete any dynamically allocated memory stored in bulleterl_handle */
/* bulleterl_handle* handle = (bulleterl_handle*)arg; */
}
static int on_load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)
{
ErlNifResourceFlags flags = ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER;
ErlNifResourceType* rt = enif_open_resource_type(env, NULL,
"bulleterl_resource",
&bulleterl_resource_cleanup,
flags, NULL);
if (rt == NULL)
return -1;
bulleterl_RESOURCE = rt;
return 0;
}
ERL_NIF_INIT(bulleterl, nif_funcs, &on_load, NULL, NULL, NULL);
<commit_msg>Corrected C++ errors, since C++ seems to be more stringent about types than C.<commit_after>#include "erl_nif.h"
static ErlNifResourceType* bulleterl_RESOURCE = NULL;
typedef struct
{
} bulleterl_handle;
// Prototypes
static ERL_NIF_TERM bulleterl_new(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[]);
static ERL_NIF_TERM bulleterl_myfunction(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[]);
static ErlNifFunc nif_funcs[] =
{
{"new", 0, bulleterl_new},
{"myfunction", 1, bulleterl_myfunction}
};
static ERL_NIF_TERM bulleterl_new(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[])
{
bulleterl_handle* handle = (bulleterl_handle*) enif_alloc_resource(bulleterl_RESOURCE,
sizeof(bulleterl_handle));
ERL_NIF_TERM result = enif_make_resource(env, handle);
enif_release_resource(handle);
return enif_make_tuple2(env, enif_make_atom(env, "ok"), result);
}
static ERL_NIF_TERM bulleterl_myfunction(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[])
{
return enif_make_atom(env, "ok");
}
static void bulleterl_resource_cleanup(ErlNifEnv* env, void* arg)
{
/* Delete any dynamically allocated memory stored in bulleterl_handle */
/* bulleterl_handle* handle = (bulleterl_handle*)arg; */
}
static int on_load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)
{
ErlNifResourceFlags flags = ErlNifResourceFlags(ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER);
ErlNifResourceType* rt = enif_open_resource_type(env, NULL,
"bulleterl_resource",
&bulleterl_resource_cleanup,
flags, NULL);
if (rt == NULL)
return -1;
bulleterl_RESOURCE = rt;
return 0;
}
ERL_NIF_INIT(bulleterl, nif_funcs, &on_load, NULL, NULL, NULL);
<|endoftext|> |
<commit_before>#include "ovpCTestCodecToolkit.h"
using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace OpenViBE::Plugins;
using namespace OpenViBEPlugins;
using namespace OpenViBEPlugins::Samples;
using namespace OpenViBEToolkit;
boolean CTestCodecToolkit::initialize(void)
{
m_oStreamedMatrixDecoder.initialize(*this);
m_oStreamedMatrixEncoder.initialize(*this);
m_oStreamedMatrixEncoder.getInputMatrix().setReferenceTarget(m_oStreamedMatrixDecoder.getOutputMatrix());
m_vDecoders.push_back(&m_oStreamedMatrixDecoder);
m_vEncoders.push_back(&m_oStreamedMatrixEncoder);
m_oChannelLocalisationDecoder.initialize(*this);
m_oChannelLocalisationEncoder.initialize(*this);
m_oChannelLocalisationEncoder.getInputLocalisationMatrix().setReferenceTarget(m_oChannelLocalisationDecoder.getOutputLocalisationMatrix());
m_vDecoders.push_back(&m_oChannelLocalisationDecoder);
m_vEncoders.push_back(&m_oChannelLocalisationEncoder);
m_oFeatureVectorDecoder.initialize(*this);
m_oFeatureVectorEncoder.initialize(*this);
m_oFeatureVectorEncoder.getInputVector().setReferenceTarget(m_oFeatureVectorDecoder.getOutputVector());
m_vDecoders.push_back(&m_oFeatureVectorDecoder);
m_vEncoders.push_back(&m_oFeatureVectorEncoder);
m_oSpectrumDecoder.initialize(*this);
m_oSpectrumEncoder.initialize(*this);
m_oSpectrumEncoder.getInputMatrix().setReferenceTarget(m_oSpectrumDecoder.getOutputMatrix());
m_oSpectrumEncoder.getInputMinMaxFrequencyBands().setReferenceTarget(m_oSpectrumDecoder.getOutputMinMaxFrequencyBands());
m_vDecoders.push_back(&m_oSpectrumDecoder);
m_vEncoders.push_back(&m_oSpectrumEncoder);
m_oSignalDecoder.initialize(*this);
m_oSignalEncoder.initialize(*this);
m_oSignalEncoder.getInputMatrix().setReferenceTarget(m_oSignalDecoder.getOutputMatrix());
m_oSignalEncoder.getInputSamplingRate().setReferenceTarget(m_oSignalDecoder.getOutputSamplingRate());
m_vDecoders.push_back(&m_oSignalDecoder);
m_vEncoders.push_back(&m_oSignalEncoder);
m_oStimDecoder.initialize(*this);
m_oStimEncoder.initialize(*this);
m_oStimEncoder.getInputStimulationSet().setReferenceTarget(m_oStimDecoder.getOutputStimulationSet());
m_vDecoders.push_back(&m_oStimDecoder);
m_vEncoders.push_back(&m_oStimEncoder);
m_oExperimentInformationDecoder.initialize(*this);
m_oExperimentInformationEncoder.initialize(*this);
m_oExperimentInformationEncoder.getInputExperimentIdentifier().setReferenceTarget(m_oExperimentInformationDecoder.getOutputExperimentIdentifier());
m_oExperimentInformationEncoder.getInputExperimentDate().setReferenceTarget(m_oExperimentInformationDecoder.getOutputExperimentDate());
m_oExperimentInformationEncoder.getInputSubjectIdentifier().setReferenceTarget(m_oExperimentInformationDecoder.getOutputSubjectIdentifier());
m_oExperimentInformationEncoder.getInputSubjectName().setReferenceTarget(m_oExperimentInformationDecoder.getOutputSubjectName());
m_oExperimentInformationEncoder.getInputSubjectAge().setReferenceTarget(m_oExperimentInformationDecoder.getOutputSubjectAge());
m_oExperimentInformationEncoder.getInputSubjectGender().setReferenceTarget(m_oExperimentInformationDecoder.getOutputSubjectGender());
m_oExperimentInformationEncoder.getInputLaboratoryIdentifier().setReferenceTarget(m_oExperimentInformationDecoder.getOutputLaboratoryIdentifier());
m_oExperimentInformationEncoder.getInputLaboratoryName().setReferenceTarget(m_oExperimentInformationDecoder.getOutputLaboratoryName());
m_oExperimentInformationEncoder.getInputTechnicianIdentifier().setReferenceTarget(m_oExperimentInformationDecoder.getOutputTechnicianIdentifier());
m_oExperimentInformationEncoder.getInputTechnicianName().setReferenceTarget(m_oExperimentInformationDecoder.getOutputTechnicianName());
m_vDecoders.push_back(&m_oExperimentInformationDecoder);
m_vEncoders.push_back(&m_oExperimentInformationEncoder);
return true;
}
boolean CTestCodecToolkit::uninitialize(void)
{
for(uint32 i = 0; i< m_vDecoders.size(); i++)
{
m_vDecoders[i]->uninitialize();
}
for(uint32 i = 0; i< m_vEncoders.size(); i++)
{
m_vEncoders[i]->uninitialize();
}
return true;
}
boolean CTestCodecToolkit::processInput(uint32 ui32InputIndex)
{
this->getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();
return true;
}
boolean CTestCodecToolkit::process(void)
{
IBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext();
IBox& l_rStaticBoxContext=this->getStaticBoxContext();
for(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++)
{
for(uint32 j=0; j<l_rDynamicBoxContext.getInputChunkCount(i); j++)
{
// we can manipulate decoders and encoders without knowing their types
m_vDecoders[i]->setInputChunk(l_rDynamicBoxContext.getInputChunk(i, j));
m_vEncoders[i]->setOutputChunk(l_rDynamicBoxContext.getOutputChunk(i));
m_vDecoders[i]->decode();
if(m_vDecoders[i]->isHeaderReceived())
{
m_vEncoders[i]->encodeHeader();
l_rDynamicBoxContext.markOutputAsReadyToSend(i, l_rDynamicBoxContext.getInputChunkStartTime(i, j), l_rDynamicBoxContext.getInputChunkEndTime(i, j));
}
if(m_vDecoders[i]->isBufferReceived())
{
//let's check what is inside the buffer
CIdentifier l_oInputType;
l_rStaticBoxContext.getInputType(i, l_oInputType);
if(l_oInputType==OV_TypeId_StreamedMatrix)
{
IMatrix* l_pMatrix = m_oStreamedMatrixDecoder.getOutputMatrix();
this->getLogManager() << LogLevel_Info << "Streamed Matrix buffer received ("<<l_pMatrix->getBufferElementCount()<<" elements in buffer).\n";
}
else if(l_oInputType==OV_TypeId_ChannelLocalisation)
{
IMatrix* l_pMatrix = m_oChannelLocalisationDecoder.getOutputLocalisationMatrix();
this->getLogManager() << LogLevel_Info << "Channel localisation buffer received ("<<l_pMatrix->getBufferElementCount()<<" elements in buffer).\n";
}
else if(l_oInputType==OV_TypeId_FeatureVector)
{
IMatrix* l_pMatrix = m_oFeatureVectorDecoder.getOutputVector();
this->getLogManager() << LogLevel_Info << "Feature Vector buffer received ("<<l_pMatrix->getBufferElementCount()<<" features in vector).\n";
}
else if(l_oInputType==OV_TypeId_Spectrum)
{
IMatrix* l_pMatrix = m_oSpectrumDecoder.getOutputMatrix();
IMatrix* l_pMinMax = m_oSpectrumDecoder.getOutputMinMaxFrequencyBands();
this->getLogManager() << LogLevel_Info << "Spectrum buffer received ("<<l_pMatrix->getBufferElementCount()<<" elements in buffer).\n";
}
else if(l_oInputType==OV_TypeId_Signal)
{
IMatrix* l_pMatrix = m_oSignalDecoder.getOutputMatrix();
this->getLogManager() << LogLevel_Info << "Signal buffer received ("<<l_pMatrix->getBufferElementCount()<<" elements in buffer).\n";
}
else if(l_oInputType==OV_TypeId_Stimulations)
{
IStimulationSet* l_pStimulations = m_oStimDecoder.getOutputStimulationSet();
// as we constantly receive stimulations on the stream, we will check if the incoming set is empty or not
if(l_pStimulations->getStimulationCount() != 0)
this->getLogManager() << LogLevel_Info << "Stimulation Set buffer received ("<<l_pStimulations->getStimulationCount()<<" stims in set).\n";
}
else if(l_oInputType==OV_TypeId_ExperimentationInformation)
{
uint64 l_pXPid = m_oExperimentInformationDecoder.getOutputExperimentIdentifier();
this->getLogManager() << LogLevel_Info << "Experiment information buffer received (xp ID: "<<l_pXPid<<").\n";
}
else
{
this->getLogManager() << LogLevel_Error << "Undefined input type.\n";
return true;
}
m_vEncoders[i]->encodeBuffer();
l_rDynamicBoxContext.markOutputAsReadyToSend(i, l_rDynamicBoxContext.getInputChunkStartTime(i, j), l_rDynamicBoxContext.getInputChunkEndTime(i, j));
}
if(m_vDecoders[i]->isEndReceived())
{
m_vEncoders[i]->encodeEnd();
l_rDynamicBoxContext.markOutputAsReadyToSend(i, l_rDynamicBoxContext.getInputChunkStartTime(i, j), l_rDynamicBoxContext.getInputChunkEndTime(i, j));
}
l_rDynamicBoxContext.markInputAsDeprecated(i, j);
}
}
return true;
}
<commit_msg>openvibeopenvibe-plugins/samples * ovpCTestCodecToolkit.cpp : update to latest toolkit revision.<commit_after>#include "ovpCTestCodecToolkit.h"
using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace OpenViBE::Plugins;
using namespace OpenViBEPlugins;
using namespace OpenViBEPlugins::Samples;
using namespace OpenViBEToolkit;
boolean CTestCodecToolkit::initialize(void)
{
m_oStreamedMatrixDecoder.initialize(*this);
m_oStreamedMatrixEncoder.initialize(*this);
m_oStreamedMatrixEncoder.getInputMatrix().setReferenceTarget(m_oStreamedMatrixDecoder.getOutputMatrix());
m_vDecoders.push_back(&m_oStreamedMatrixDecoder);
m_vEncoders.push_back(&m_oStreamedMatrixEncoder);
m_oChannelLocalisationDecoder.initialize(*this);
m_oChannelLocalisationEncoder.initialize(*this);
m_oChannelLocalisationEncoder.getInputMatrix().setReferenceTarget(m_oChannelLocalisationDecoder.getOutputMatrix());
m_oChannelLocalisationEncoder.getInputDynamic().setReferenceTarget(m_oChannelLocalisationDecoder.getOutputDynamic());
m_vDecoders.push_back(&m_oChannelLocalisationDecoder);
m_vEncoders.push_back(&m_oChannelLocalisationEncoder);
m_oFeatureVectorDecoder.initialize(*this);
m_oFeatureVectorEncoder.initialize(*this);
m_oFeatureVectorEncoder.getInputMatrix().setReferenceTarget(m_oFeatureVectorDecoder.getOutputMatrix());
m_vDecoders.push_back(&m_oFeatureVectorDecoder);
m_vEncoders.push_back(&m_oFeatureVectorEncoder);
m_oSpectrumDecoder.initialize(*this);
m_oSpectrumEncoder.initialize(*this);
m_oSpectrumEncoder.getInputMatrix().setReferenceTarget(m_oSpectrumDecoder.getOutputMatrix());
m_oSpectrumEncoder.getInputMinMaxFrequencyBands().setReferenceTarget(m_oSpectrumDecoder.getOutputMinMaxFrequencyBands());
m_vDecoders.push_back(&m_oSpectrumDecoder);
m_vEncoders.push_back(&m_oSpectrumEncoder);
m_oSignalDecoder.initialize(*this);
m_oSignalEncoder.initialize(*this);
m_oSignalEncoder.getInputMatrix().setReferenceTarget(m_oSignalDecoder.getOutputMatrix());
m_oSignalEncoder.getInputSamplingRate().setReferenceTarget(m_oSignalDecoder.getOutputSamplingRate());
m_vDecoders.push_back(&m_oSignalDecoder);
m_vEncoders.push_back(&m_oSignalEncoder);
m_oStimDecoder.initialize(*this);
m_oStimEncoder.initialize(*this);
m_oStimEncoder.getInputStimulationSet().setReferenceTarget(m_oStimDecoder.getOutputStimulationSet());
m_vDecoders.push_back(&m_oStimDecoder);
m_vEncoders.push_back(&m_oStimEncoder);
m_oExperimentInformationDecoder.initialize(*this);
m_oExperimentInformationEncoder.initialize(*this);
m_oExperimentInformationEncoder.getInputExperimentIdentifier().setReferenceTarget(m_oExperimentInformationDecoder.getOutputExperimentIdentifier());
m_oExperimentInformationEncoder.getInputExperimentDate().setReferenceTarget(m_oExperimentInformationDecoder.getOutputExperimentDate());
m_oExperimentInformationEncoder.getInputSubjectIdentifier().setReferenceTarget(m_oExperimentInformationDecoder.getOutputSubjectIdentifier());
m_oExperimentInformationEncoder.getInputSubjectName().setReferenceTarget(m_oExperimentInformationDecoder.getOutputSubjectName());
m_oExperimentInformationEncoder.getInputSubjectAge().setReferenceTarget(m_oExperimentInformationDecoder.getOutputSubjectAge());
m_oExperimentInformationEncoder.getInputSubjectGender().setReferenceTarget(m_oExperimentInformationDecoder.getOutputSubjectGender());
m_oExperimentInformationEncoder.getInputLaboratoryIdentifier().setReferenceTarget(m_oExperimentInformationDecoder.getOutputLaboratoryIdentifier());
m_oExperimentInformationEncoder.getInputLaboratoryName().setReferenceTarget(m_oExperimentInformationDecoder.getOutputLaboratoryName());
m_oExperimentInformationEncoder.getInputTechnicianIdentifier().setReferenceTarget(m_oExperimentInformationDecoder.getOutputTechnicianIdentifier());
m_oExperimentInformationEncoder.getInputTechnicianName().setReferenceTarget(m_oExperimentInformationDecoder.getOutputTechnicianName());
m_vDecoders.push_back(&m_oExperimentInformationDecoder);
m_vEncoders.push_back(&m_oExperimentInformationEncoder);
return true;
}
boolean CTestCodecToolkit::uninitialize(void)
{
for(uint32 i = 0; i< m_vDecoders.size(); i++)
{
m_vDecoders[i]->uninitialize();
}
for(uint32 i = 0; i< m_vEncoders.size(); i++)
{
m_vEncoders[i]->uninitialize();
}
return true;
}
boolean CTestCodecToolkit::processInput(uint32 ui32InputIndex)
{
this->getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();
return true;
}
boolean CTestCodecToolkit::process(void)
{
IBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext();
IBox& l_rStaticBoxContext=this->getStaticBoxContext();
for(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++)
{
for(uint32 j=0; j<l_rDynamicBoxContext.getInputChunkCount(i); j++)
{
// we can manipulate decoders and encoders without knowing their types
m_vDecoders[i]->setInputChunk(l_rDynamicBoxContext.getInputChunk(i, j));
m_vEncoders[i]->setOutputChunk(l_rDynamicBoxContext.getOutputChunk(i));
m_vDecoders[i]->decode();
if(m_vDecoders[i]->isHeaderReceived())
{
m_vEncoders[i]->encodeHeader();
l_rDynamicBoxContext.markOutputAsReadyToSend(i, l_rDynamicBoxContext.getInputChunkStartTime(i, j), l_rDynamicBoxContext.getInputChunkEndTime(i, j));
}
if(m_vDecoders[i]->isBufferReceived())
{
//let's check what is inside the buffer
CIdentifier l_oInputType;
l_rStaticBoxContext.getInputType(i, l_oInputType);
if(l_oInputType==OV_TypeId_StreamedMatrix)
{
IMatrix* l_pMatrix = m_oStreamedMatrixDecoder.getOutputMatrix();
this->getLogManager() << LogLevel_Info << "Streamed Matrix buffer received ("<<l_pMatrix->getBufferElementCount()<<" elements in buffer).\n";
}
else if(l_oInputType==OV_TypeId_ChannelLocalisation)
{
IMatrix* l_pMatrix = m_oChannelLocalisationDecoder.getOutputMatrix();
this->getLogManager() << LogLevel_Info << "Channel localisation buffer received ("<<l_pMatrix->getBufferElementCount()<<" elements in buffer).\n";
}
else if(l_oInputType==OV_TypeId_FeatureVector)
{
IMatrix* l_pMatrix = m_oFeatureVectorDecoder.getOutputMatrix();
this->getLogManager() << LogLevel_Info << "Feature Vector buffer received ("<<l_pMatrix->getBufferElementCount()<<" features in vector).\n";
}
else if(l_oInputType==OV_TypeId_Spectrum)
{
IMatrix* l_pMatrix = m_oSpectrumDecoder.getOutputMatrix();
IMatrix* l_pMinMax = m_oSpectrumDecoder.getOutputMinMaxFrequencyBands();
this->getLogManager() << LogLevel_Info << "Spectrum buffer received ("<<l_pMatrix->getBufferElementCount()<<" elements in buffer).\n";
}
else if(l_oInputType==OV_TypeId_Signal)
{
IMatrix* l_pMatrix = m_oSignalDecoder.getOutputMatrix();
this->getLogManager() << LogLevel_Info << "Signal buffer received ("<<l_pMatrix->getBufferElementCount()<<" elements in buffer).\n";
}
else if(l_oInputType==OV_TypeId_Stimulations)
{
IStimulationSet* l_pStimulations = m_oStimDecoder.getOutputStimulationSet();
// as we constantly receive stimulations on the stream, we will check if the incoming set is empty or not
if(l_pStimulations->getStimulationCount() != 0)
this->getLogManager() << LogLevel_Info << "Stimulation Set buffer received ("<<l_pStimulations->getStimulationCount()<<" stims in set).\n";
}
else if(l_oInputType==OV_TypeId_ExperimentationInformation)
{
uint64 l_pXPid = m_oExperimentInformationDecoder.getOutputExperimentIdentifier();
this->getLogManager() << LogLevel_Info << "Experiment information buffer received (xp ID: "<<l_pXPid<<").\n";
}
else
{
this->getLogManager() << LogLevel_Error << "Undefined input type.\n";
return true;
}
m_vEncoders[i]->encodeBuffer();
l_rDynamicBoxContext.markOutputAsReadyToSend(i, l_rDynamicBoxContext.getInputChunkStartTime(i, j), l_rDynamicBoxContext.getInputChunkEndTime(i, j));
}
if(m_vDecoders[i]->isEndReceived())
{
m_vEncoders[i]->encodeEnd();
l_rDynamicBoxContext.markOutputAsReadyToSend(i, l_rDynamicBoxContext.getInputChunkStartTime(i, j), l_rDynamicBoxContext.getInputChunkEndTime(i, j));
}
l_rDynamicBoxContext.markInputAsDeprecated(i, j);
}
}
return true;
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkPointCloudScoringFilter.h"
#include <vtkSmartPointer.h>
#include <vtkPoints.h>
#include <vtkKdTree.h>
#include <vtkPolyData.h>
mitk::PointCloudScoringFilter::PointCloudScoringFilter():
m_NumberOfOutpPoints(0)
{
m_OutpSurface = mitk::Surface::New();
this->SetNthOutput(0, m_OutpSurface);
}
mitk::PointCloudScoringFilter::~PointCloudScoringFilter(){}
void mitk::PointCloudScoringFilter::GenerateData()
{
if(SurfaceToSurfaceFilter::GetNumberOfInputs()!=2)
{
MITK_ERROR << "Not enough input arguments for PointCloudScoringFilter" << std::endl;
return;
}
DataObjectPointerArray inputs = SurfaceToSurfaceFilter::GetInputs();
mitk::Surface::Pointer edgeSurface = dynamic_cast<mitk::Surface*>(inputs.at(0).GetPointer());
mitk::Surface::Pointer segmSurface = dynamic_cast<mitk::Surface*>(inputs.at(1).GetPointer());
if(edgeSurface->IsEmpty() || segmSurface->IsEmpty())
{
if(edgeSurface->IsEmpty())
MITK_ERROR << "Cannot convert EdgeSurface into Surfaces" << std::endl;
if(segmSurface->IsEmpty())
MITK_ERROR << "Cannot convert SegmSurface into Surfaces" << std::endl;
}
vtkSmartPointer<vtkPolyData> edgePolyData = edgeSurface->GetVtkPolyData();
vtkSmartPointer<vtkPolyData> segmPolyData = segmSurface->GetVtkPolyData();
// KdTree from here
vtkSmartPointer<vtkPoints> kdPoints = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkKdTree> kdTree = vtkSmartPointer<vtkKdTree>::New();
for(int i=0; i<edgePolyData->GetNumberOfPoints(); i++)
{
kdPoints->InsertNextPoint(edgePolyData->GetPoint(i));
}
kdTree->BuildLocatorFromPoints(kdPoints);
// KdTree until here
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
for(int i=0; i<segmPolyData->GetNumberOfPoints(); i++)
{
points->InsertNextPoint(segmPolyData->GetPoint(i));
}
std::vector< ScorePair > score;
double dist_glob;
double dist;
for(int i=0; i<points->GetNumberOfPoints(); i++)
{
double point[3];
points->GetPoint(i,point);
kdTree->FindClosestPoint(point[0],point[1],point[2],dist);
dist_glob+=dist;
score.push_back(std::make_pair(i,dist));
}
double avg = dist_glob / points->GetNumberOfPoints();
for(unsigned int i=0; i<score.size();++i)
{
if(score.at(i).second > avg)
{
m_FilteredScores.push_back(std::make_pair(score.at(i).first,score.at(i).second));
}
}
m_NumberOfOutpPoints = m_FilteredScores.size();
vtkSmartPointer<vtkPolyData> outpSurface = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkPoints> filteredPoints = vtkSmartPointer<vtkPoints>::New();
for(unsigned int i=0; i<m_FilteredScores.size(); i++)
{
mitk::Point3D point;
point = segmPolyData->GetPoint(m_FilteredScores.at(i).first);
filteredPoints->InsertNextPoint(point[0],point[1],point[2]);
}
outpSurface->SetPoints(filteredPoints);
m_OutpSurface->SetVtkPolyData(outpSurface);
}
void mitk::PointCloudScoringFilter::GenerateOutputInformation()
{
Superclass::GenerateOutputInformation();
}
<commit_msg>added lines between the points for correct visualization<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkPointCloudScoringFilter.h"
#include <vtkSmartPointer.h>
#include <vtkPoints.h>
#include <vtkKdTree.h>
#include <vtkPolyData.h>
#include <vtkPolyLine.h>
#include <vtkCellArray.h>
mitk::PointCloudScoringFilter::PointCloudScoringFilter():
m_NumberOfOutpPoints(0)
{
m_OutpSurface = mitk::Surface::New();
// this->SetNumberOfRequiredInputs(2);
// this->SetNumberOfRequiredOutputs(1);
this->SetNthOutput(0, m_OutpSurface);
}
mitk::PointCloudScoringFilter::~PointCloudScoringFilter(){}
void mitk::PointCloudScoringFilter::GenerateData()
{
if(SurfaceToSurfaceFilter::GetNumberOfInputs()!=2)
{
MITK_ERROR << "Not enough input arguments for PointCloudScoringFilter" << std::endl;
return;
}
DataObjectPointerArray inputs = SurfaceToSurfaceFilter::GetInputs();
mitk::Surface::Pointer edgeSurface = dynamic_cast<mitk::Surface*>(inputs.at(0).GetPointer());
mitk::Surface::Pointer segmSurface = dynamic_cast<mitk::Surface*>(inputs.at(1).GetPointer());
if(edgeSurface->IsEmpty() || segmSurface->IsEmpty())
{
if(edgeSurface->IsEmpty())
MITK_ERROR << "Cannot convert EdgeSurface into Surfaces" << std::endl;
if(segmSurface->IsEmpty())
MITK_ERROR << "Cannot convert SegmSurface into Surfaces" << std::endl;
}
vtkSmartPointer<vtkPolyData> edgePolyData = edgeSurface->GetVtkPolyData();
vtkSmartPointer<vtkPolyData> segmPolyData = segmSurface->GetVtkPolyData();
// KdTree from here
vtkSmartPointer<vtkPoints> kdPoints = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkKdTree> kdTree = vtkSmartPointer<vtkKdTree>::New();
for(int i=0; i<edgePolyData->GetNumberOfPoints(); i++)
{
kdPoints->InsertNextPoint(edgePolyData->GetPoint(i));
}
kdTree->BuildLocatorFromPoints(kdPoints);
// KdTree until here
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
for(int i=0; i<segmPolyData->GetNumberOfPoints(); i++)
{
points->InsertNextPoint(segmPolyData->GetPoint(i));
}
std::vector< ScorePair > score;
double dist_glob;
double dist;
for(int i=0; i<points->GetNumberOfPoints(); i++)
{
double point[3];
points->GetPoint(i,point);
kdTree->FindClosestPoint(point[0],point[1],point[2],dist);
dist_glob+=dist;
score.push_back(std::make_pair(i,dist));
}
double avg = dist_glob / points->GetNumberOfPoints();
for(unsigned int i=0; i<score.size();++i)
{
if(score.at(i).second > avg)
{
m_FilteredScores.push_back(std::make_pair(score.at(i).first,score.at(i).second));
}
}
m_NumberOfOutpPoints = m_FilteredScores.size();
vtkSmartPointer<vtkPolyData> outpSurface = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkPoints> filteredPoints = vtkSmartPointer<vtkPoints>::New();
for(unsigned int i=0; i<m_FilteredScores.size(); i++)
{
mitk::Point3D point;
point = segmPolyData->GetPoint(m_FilteredScores.at(i).first);
filteredPoints->InsertNextPoint(point[0],point[1],point[2]);
}
unsigned int numPoints = filteredPoints->GetNumberOfPoints();
vtkSmartPointer<vtkPolyLine> polyLine = vtkSmartPointer<vtkPolyLine>::New();
polyLine->GetPointIds()->SetNumberOfIds(numPoints);
for(unsigned int i = 0; i < numPoints; i++)
{
polyLine->GetPointIds()->SetId(i,i);
}
vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New();
cells->InsertNextCell(polyLine);
vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
polyData->SetPoints(filteredPoints);
polyData->SetLines(cells);
outpSurface->BuildCells();
outpSurface->BuildLinks();
m_OutpSurface->SetVtkPolyData(polyData);
}
void mitk::PointCloudScoringFilter::GenerateOutputInformation()
{
Superclass::GenerateOutputInformation();
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* common headers */
#include "common.h"
#ifdef HAVE_SDL
/* interface headers */
#include "SDLJoystick.h"
/* implementation headers */
#include "ErrorHandler.h"
#include "bzfSDL.h"
SDLJoystick::SDLJoystick() : joystickID(NULL)
{
if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1) {
std::vector<std::string> args;
args.push_back(SDL_GetError());
printError("Could not initialize SDL Joystick subsystem: %s.\n", &args);
};
}
SDLJoystick::~SDLJoystick()
{
SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
}
void SDLJoystick::initJoystick(const char* joystickName)
{
if (!strcmp(joystickName, "off") || !strcmp(joystickName, "")) {
if (joystickID != NULL) {
SDL_JoystickClose(joystickID);
joystickID = NULL;
}
return;
}
char num = joystickName[0];
int i = (int)num - '0';
if (!isdigit(num) || i >= SDL_NumJoysticks()) {
printError("No supported SDL joysticks were found.");
joystickID = NULL;
return;
}
joystickID = SDL_JoystickOpen(i);
if (joystickID == NULL)
return;
if (SDL_JoystickNumAxes(joystickID) < 2) {
SDL_JoystickClose(joystickID);
printError("Joystick has less then 2 axis:\n");
joystickID = NULL;
return;
}
joystickButtons = SDL_JoystickNumButtons(joystickID);
}
bool SDLJoystick::joystick() const
{
return joystickID != NULL;
}
void SDLJoystick::getJoy(int& x, int& y) const
{
x = y = 0;
if (!joystickID)
return;
SDL_JoystickUpdate();
x = SDL_JoystickGetAxis(joystickID, 0);
y = SDL_JoystickGetAxis(joystickID, 1);
x = x * 1000 / 32768;
y = y * 1000 / 32768;
// ballistic
x = (x * abs(x)) / 1000;
y = (y * abs(y)) / 1000;
}
unsigned long SDLJoystick::getJoyButtons() const
{
unsigned long buttons = 0;
if (!joystickID)
return 0;
SDL_JoystickUpdate();
for (int i = 0; i < joystickButtons; i++)
buttons |= SDL_JoystickGetButton(joystickID, i) << i;
return buttons;
}
void SDLJoystick::getJoyDevices(std::vector<std::string>
&list) const
{
int numJoystick = SDL_NumJoysticks();
int i;
for (i = 0; i < numJoystick; i++) {
char joystickName[256];
sprintf(joystickName, "%d - %s", i, SDL_JoystickName(i));
list.push_back(joystickName);
}
}
#endif
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>deal with extraordinary values sanely (many joysticks or long names)<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* common headers */
#include "common.h"
#ifdef HAVE_SDL
/* interface headers */
#include "SDLJoystick.h"
/* implementation headers */
#include "ErrorHandler.h"
#include "bzfSDL.h"
SDLJoystick::SDLJoystick() : joystickID(NULL)
{
if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1) {
std::vector<std::string> args;
args.push_back(SDL_GetError());
printError("Could not initialize SDL Joystick subsystem: %s.\n", &args);
};
}
SDLJoystick::~SDLJoystick()
{
SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
}
void SDLJoystick::initJoystick(const char* joystickName)
{
if (!strcmp(joystickName, "off") || !strcmp(joystickName, "")) {
if (joystickID != NULL) {
SDL_JoystickClose(joystickID);
joystickID = NULL;
}
return;
}
char num = joystickName[0];
int i = (int)num - '0';
if (!isdigit(num) || i >= SDL_NumJoysticks()) {
printError("No supported SDL joysticks were found.");
joystickID = NULL;
return;
}
joystickID = SDL_JoystickOpen(i);
if (joystickID == NULL)
return;
if (SDL_JoystickNumAxes(joystickID) < 2) {
SDL_JoystickClose(joystickID);
printError("Joystick has less then 2 axis:\n");
joystickID = NULL;
return;
}
joystickButtons = SDL_JoystickNumButtons(joystickID);
}
bool SDLJoystick::joystick() const
{
return joystickID != NULL;
}
void SDLJoystick::getJoy(int& x, int& y) const
{
x = y = 0;
if (!joystickID)
return;
SDL_JoystickUpdate();
x = SDL_JoystickGetAxis(joystickID, 0);
y = SDL_JoystickGetAxis(joystickID, 1);
x = x * 1000 / 32768;
y = y * 1000 / 32768;
// ballistic
x = (x * abs(x)) / 1000;
y = (y * abs(y)) / 1000;
}
unsigned long SDLJoystick::getJoyButtons() const
{
unsigned long buttons = 0;
if (!joystickID)
return 0;
SDL_JoystickUpdate();
for (int i = 0; i < joystickButtons; i++)
buttons |= SDL_JoystickGetButton(joystickID, i) << i;
return buttons;
}
void SDLJoystick::getJoyDevices(std::vector<std::string>
&list) const
{
int numJoystick = SDL_NumJoysticks();
if (numJoystick > 9) //user would have to be insane to have this many anyway
numJoystick = 9;
int i;
for (i = 0; i < numJoystick; i++) {
char joystickName[50]; //only room for so much on the menu
snprintf(joystickName, 50, "%d - %s", i, SDL_JoystickName(i));
list.push_back(joystickName);
}
}
#endif
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>#include "game.h"
#include "camera.h"
#include "util/gui/cutscene.h"
#include "world.h"
#include "util/bitmap.h"
#include "util/stretch-bitmap.h"
#include "util/debug.h"
#include "util/events.h"
#include "util/font.h"
#include "util/init.h"
#include "util/input/input-map.h"
#include "util/input/input-manager.h"
#include "util/input/input-source.h"
#include "util/file-system.h"
#include "util/load_exception.h"
#include "util/token.h"
#include "util/tokenreader.h"
#include <string>
#include <sstream>
using namespace std;
using namespace Platformer;
Game::Game(const std::string & filename){
/* NOTE this is temporary to run tests on the engine
* Eventually it will be replaced with a class that handles the entire game (worlds, etc...)
*/
try {
Global::debug(1,"platformer") << "Loading Platformer: " << filename << endl;
TokenReader tr;
Token * platformToken = tr.readTokenFromFile(filename);
if ( *platformToken != "platformer" ){
throw LoadException(__FILE__, __LINE__, "Not a Platformer");
}
TokenView view = platformToken->view();
while (view.hasMore()){
try{
const Token * tok;
view >> tok;
if ( *tok == "world" ){
worlds.push_back(Util::ReferenceCount<Platformer::World>(new Platformer::World(tok)));
} else if ( *tok == "cutscene" ){
std::string file;
tok->view() >> file;
//Util::ReferenceCount<Gui::CutScene> cutscene(new Gui::CutScene(tok));
Util::ReferenceCount<Gui::CutScene> cutscene(new Gui::CutScene(Filesystem::AbsolutePath(file)));
cutscenes[cutscene->getName()] = cutscene;
} else {
Global::debug(3) << "Unhandled Platformer attribute: " << endl;
if (Global::getDebug() >= 3){
tok->print(" ");
}
}
} catch ( const TokenException & ex ) {
throw LoadException(__FILE__, __LINE__, ex, "Platformer parse error");
} catch ( const LoadException & ex ) {
// delete current;
throw ex;
}
}
} catch (const TokenException & e){
throw LoadException(__FILE__, __LINE__, e, "Error loading platformer file.");
}
// TODO remove test intro cutscene
cutscenes["intro"]->setResolution(worlds[0]->getResolutionX(), worlds[0]->getResolutionY());
}
Game::~Game(){
}
void Game::run(){
// NOTE Testing purposes only
class Logic: public Util::Logic {
public:
Logic(InputMap<Keys> & input, std::vector < Util::ReferenceCount<Platformer::World> > & worlds):
is_done(false),
input(input),
worlds(worlds){
}
bool is_done;
InputMap<Keys> & input;
std::vector < Util::ReferenceCount<Platformer::World> > & worlds;
bool done(){
return is_done;
}
void run(){
// FIXME figure out how many worlds... etc
vector<InputMap<Keys>::InputEvent> out = InputManager::getEvents(input, InputSource());
for (vector<InputMap<Keys>::InputEvent>::iterator it = out.begin(); it != out.end(); it++){
const InputMap<Keys>::InputEvent & event = *it;
if (event.enabled){
if (event.out == Esc){
is_done = true;
}
if (event.out == Up){
worlds[0]->moveCamera(0, 0,-5);
}
if (event.out == Down){
worlds[0]->moveCamera(0, 0,5);
}
if (event.out == Left){
worlds[0]->moveCamera(0, -5,0);
}
if (event.out == Right){
worlds[0]->moveCamera(0, 5,0);
}
if (event.out == K_1){
worlds[0]->moveCamera(1, -5,0);
}
if (event.out == K_2){
worlds[0]->moveCamera(1, 5,0);
}
if (event.out == K_3){
worlds[0]->moveCamera(1, 0, -5);
}
if (event.out == K_4){
worlds[0]->moveCamera(1, 0, 5);
}
}
}
worlds[0]->act();
}
double ticks(double system){
return Global::ticksPerSecond(60) * system;
}
};
class Draw: public Util::Draw {
public:
Draw(std::vector < Util::ReferenceCount<Platformer::World> > & worlds, const Logic & logic):
worlds(worlds),
logic(logic){
}
std::vector < Util::ReferenceCount<Platformer::World> > & worlds;
const Logic & logic;
void draw(const Graphics::Bitmap & buffer){
// FIXME change this later as the actual resolution is in the world configuration
Graphics::StretchedBitmap work(worlds[0]->getResolutionX(), worlds[0]->getResolutionY(), buffer);
work.start();
worlds[0]->draw(work);
ostringstream info;
info << "Camera Info - X: " << worlds[0]->getCamera(0)->getX() << " Y: " << worlds[0]->getCamera(0)->getY();
Font::getDefaultFont().printf( 10, 10, Graphics::makeColor(255,255,255), work, info.str(), 0);
info.str("");
info << "Camera Info - X: " << worlds[0]->getCamera(1)->getX() << " Y: " << worlds[0]->getCamera(1)->getY();
Font::getDefaultFont().printf( 10, 30, Graphics::makeColor(255,255,255), work, info.str(), 0);
work.finish();
buffer.BlitToScreen();
}
};
// set input
input.set(Keyboard::Key_ESC, 0, true, Esc);
input.set(Keyboard::Key_UP, 0, true, Up);
input.set(Keyboard::Key_DOWN, 0, true, Down);
input.set(Keyboard::Key_LEFT, 0, true, Left);
input.set(Keyboard::Key_RIGHT, 0, true, Right);
input.set(Keyboard::Key_1, 0, true, K_1);
input.set(Keyboard::Key_2, 0, true, K_2);
input.set(Keyboard::Key_3, 0, true, K_3);
input.set(Keyboard::Key_4, 0, true, K_4);
// Graphics::Bitmap tmp(640, 480);
cutscenes["intro"]->playAll();
Logic logic(input, worlds);
Draw draw(worlds, logic);
Util::standardLoop(logic, draw);
}
<commit_msg>[platformer] Check if cutscene intro exists.<commit_after>#include "game.h"
#include "camera.h"
#include "util/gui/cutscene.h"
#include "world.h"
#include "util/bitmap.h"
#include "util/stretch-bitmap.h"
#include "util/debug.h"
#include "util/events.h"
#include "util/font.h"
#include "util/init.h"
#include "util/input/input-map.h"
#include "util/input/input-manager.h"
#include "util/input/input-source.h"
#include "util/file-system.h"
#include "util/load_exception.h"
#include "util/token.h"
#include "util/tokenreader.h"
#include <string>
#include <sstream>
using namespace std;
using namespace Platformer;
Game::Game(const std::string & filename){
/* NOTE this is temporary to run tests on the engine
* Eventually it will be replaced with a class that handles the entire game (worlds, etc...)
*/
try {
Global::debug(1,"platformer") << "Loading Platformer: " << filename << endl;
TokenReader tr;
Token * platformToken = tr.readTokenFromFile(filename);
if ( *platformToken != "platformer" ){
throw LoadException(__FILE__, __LINE__, "Not a Platformer");
}
TokenView view = platformToken->view();
while (view.hasMore()){
try{
const Token * tok;
view >> tok;
if ( *tok == "world" ){
worlds.push_back(Util::ReferenceCount<Platformer::World>(new Platformer::World(tok)));
} else if ( *tok == "cutscene" ){
std::string file;
tok->view() >> file;
//Util::ReferenceCount<Gui::CutScene> cutscene(new Gui::CutScene(tok));
Util::ReferenceCount<Gui::CutScene> cutscene(new Gui::CutScene(Filesystem::AbsolutePath(file)));
cutscenes[cutscene->getName()] = cutscene;
} else {
Global::debug(3) << "Unhandled Platformer attribute: " << endl;
if (Global::getDebug() >= 3){
tok->print(" ");
}
}
} catch ( const TokenException & ex ) {
throw LoadException(__FILE__, __LINE__, ex, "Platformer parse error");
} catch ( const LoadException & ex ) {
// delete current;
throw ex;
}
}
} catch (const TokenException & e){
throw LoadException(__FILE__, __LINE__, e, "Error loading platformer file.");
}
// TODO remove test intro cutscene
if (cutscenes["intro"] != NULL){
cutscenes["intro"]->setResolution(worlds[0]->getResolutionX(), worlds[0]->getResolutionY());
}
}
Game::~Game(){
}
void Game::run(){
// NOTE Testing purposes only
class Logic: public Util::Logic {
public:
Logic(InputMap<Keys> & input, std::vector < Util::ReferenceCount<Platformer::World> > & worlds):
is_done(false),
input(input),
worlds(worlds){
}
bool is_done;
InputMap<Keys> & input;
std::vector < Util::ReferenceCount<Platformer::World> > & worlds;
bool done(){
return is_done;
}
void run(){
// FIXME figure out how many worlds... etc
vector<InputMap<Keys>::InputEvent> out = InputManager::getEvents(input, InputSource());
for (vector<InputMap<Keys>::InputEvent>::iterator it = out.begin(); it != out.end(); it++){
const InputMap<Keys>::InputEvent & event = *it;
if (event.enabled){
if (event.out == Esc){
is_done = true;
}
if (event.out == Up){
worlds[0]->moveCamera(0, 0,-5);
}
if (event.out == Down){
worlds[0]->moveCamera(0, 0,5);
}
if (event.out == Left){
worlds[0]->moveCamera(0, -5,0);
}
if (event.out == Right){
worlds[0]->moveCamera(0, 5,0);
}
if (event.out == K_1){
worlds[0]->moveCamera(1, -5,0);
}
if (event.out == K_2){
worlds[0]->moveCamera(1, 5,0);
}
if (event.out == K_3){
worlds[0]->moveCamera(1, 0, -5);
}
if (event.out == K_4){
worlds[0]->moveCamera(1, 0, 5);
}
}
}
worlds[0]->act();
}
double ticks(double system){
return Global::ticksPerSecond(60) * system;
}
};
class Draw: public Util::Draw {
public:
Draw(std::vector < Util::ReferenceCount<Platformer::World> > & worlds, const Logic & logic):
worlds(worlds),
logic(logic){
}
std::vector < Util::ReferenceCount<Platformer::World> > & worlds;
const Logic & logic;
void draw(const Graphics::Bitmap & buffer){
// FIXME change this later as the actual resolution is in the world configuration
Graphics::StretchedBitmap work(worlds[0]->getResolutionX(), worlds[0]->getResolutionY(), buffer);
work.start();
worlds[0]->draw(work);
ostringstream info;
info << "Camera Info - X: " << worlds[0]->getCamera(0)->getX() << " Y: " << worlds[0]->getCamera(0)->getY();
Font::getDefaultFont().printf( 10, 10, Graphics::makeColor(255,255,255), work, info.str(), 0);
info.str("");
info << "Camera Info - X: " << worlds[0]->getCamera(1)->getX() << " Y: " << worlds[0]->getCamera(1)->getY();
Font::getDefaultFont().printf( 10, 30, Graphics::makeColor(255,255,255), work, info.str(), 0);
work.finish();
buffer.BlitToScreen();
}
};
// set input
input.set(Keyboard::Key_ESC, 0, true, Esc);
input.set(Keyboard::Key_UP, 0, true, Up);
input.set(Keyboard::Key_DOWN, 0, true, Down);
input.set(Keyboard::Key_LEFT, 0, true, Left);
input.set(Keyboard::Key_RIGHT, 0, true, Right);
input.set(Keyboard::Key_1, 0, true, K_1);
input.set(Keyboard::Key_2, 0, true, K_2);
input.set(Keyboard::Key_3, 0, true, K_3);
input.set(Keyboard::Key_4, 0, true, K_4);
// Graphics::Bitmap tmp(640, 480);
if (cutscenes["intro"] != NULL){
cutscenes["intro"]->playAll();
}
Logic logic(input, worlds);
Draw draw(worlds, logic);
Util::standardLoop(logic, draw);
}
<|endoftext|> |
<commit_before>#include "../stdafx.h"
#include "SLCImageProcess.h"
#include <vector>
namespace slcimage
{
//====================================================================================================================
//--------------------------------------------------------------------------------------------------------------------
void DuplicateImage(const ATL::CImage& srcImage, ATL::CImage& dstImage)
{
assert(!srcImage.IsNull());
if (srcImage == dstImage) return;
if (!dstImage.IsNull()) dstImage.Destroy();
int srcBitsCount = srcImage.GetBPP();
if (srcBitsCount == 32) dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), srcBitsCount, CImage::createAlphaChannel);
else dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), srcBitsCount, 0);
if (srcImage.IsIndexed()) {
// 8-bit: 0x100000000 = 256, in the same way, 4-bit: 0x10000 = 16, 2-bit: 0x100 = 4, 1-bit: 0x10 = 2
int nColors = srcImage.GetMaxColorTableEntries();
if (nColors > 0) {
std::vector<RGBQUAD> rgbColors(nColors);
srcImage.GetColorTable(0, nColors, rgbColors.data());
dstImage.SetColorTable(0, nColors, rgbColors.data());
}
}
srcImage.BitBlt(dstImage.GetDC(), 0, 0, SRCCOPY);
dstImage.ReleaseDC(); // Remember to dstImage.ReleaseDC() after dstImage.GetDC()
};// End of DuplicateImage(const CImage& srcImage, CImage& destImage)
//========================================================================================================================
//========================================================================================================================
//------------------------------------------------------------------------------------------------------------------------
void StretchImageByWidth(const ATL::CImage& srcImage, int widthInPixel, ATL::CImage& dstImage)
{
assert(!srcImage.IsNull() && srcImage != dstImage && widthInPixel > 0);
int srcBitsCount = srcImage.GetBPP();
double imageAspectRatio = static_cast<double>( srcImage.GetHeight() ) / srcImage.GetWidth() ;
// Get valid dstImageWidth and dstImageHeight
int dstImageWidth = widthInPixel;
double tmpDstImageHeight = imageAspectRatio * dstImageWidth;
int dstImageHeight = tmpDstImageHeight > 1.0 ? static_cast<int>(tmpDstImageHeight) : 1;
if (!dstImage.IsNull()) dstImage.Destroy();
if (srcBitsCount == 32) dstImage.Create(dstImageWidth, dstImageHeight, srcBitsCount, CImage::createAlphaChannel);
else dstImage.Create(dstImageWidth, dstImageHeight, srcBitsCount, 0);
// For 8bit CImage, we need to copy the ColorTable after image creation
if (srcImage.IsIndexed()) {
// 8-bit: 0x100000000 = 256, in the same way, 4-bit: 0x10000 = 16, 2-bit: 0x100 = 4, 1-bit: 0x10 = 2
int nColors = srcImage.GetMaxColorTableEntries();
if (nColors > 0) {
std::vector<RGBQUAD> rgbColors(nColors);
srcImage.GetColorTable(0, nColors, rgbColors.data());
dstImage.SetColorTable(0, nColors, rgbColors.data());
}
}
HDC dstHDC = dstImage.GetDC();
SetStretchBltMode(dstHDC, COLORONCOLOR);
srcImage.StretchBlt(dstHDC, 0, 0, dstImageWidth, dstImageHeight, SRCCOPY);
dstImage.ReleaseDC(); // Remember to dstImage.ReleaseDC() after dstImage.GetDC()
//========== Below is for DownSample Algorithms Testing ===============================================
//---------- include #include <wincodec.h> before using IWICBitmapScaler ------------------------
//IWICImagingFactory *imagingFactory;
//CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&imagingFactory));
//IWICBitmap* srcIWICBitmap;
//imagingFactory->CreateBitmapFromHBITMAP(srcImage, 0, WICBitmapUseAlpha, &srcIWICBitmap);
//IWICBitmapScaler* bitmapScaler;
//imagingFactory->CreateBitmapScaler(&bitmapScaler);
//bitmapScaler->Initialize(srcIWICBitmap, dstImageWidth, dstImageHeight, WICBitmapInterpolationModeCubic);
//WICRect rect = { 0, 0, dstImageWidth, 1 };
//int stride = std::abs(dstImage.GetPitch());
//BYTE* bufferEntry = static_cast<BYTE*>(dstImage.GetBits());
//for (int i = 0; i < dstImageHeight; ++i)
//{
// bitmapScaler->CopyPixels(&rect, stride, stride, bufferEntry);
// bufferEntry -= stride;
// rect.Y += 1;
//}
//bitmapScaler->Release();
//imagingFactory->Release();
}// End of GetSmallerImageByWidth(const ATL::CImage& srcImage, int widthInPixel, ATL::CImage& dstImage)
//====================================================================================================================
//--------------------------------------------------------------------------------------------------------------------
/// <summary>Converting 1Bit/4Bit image to 8Bit/24Bit, help low bit image loading for LibreImage</summary>
void Convert8BitBelowToAbove(const ATL::CImage& srcImage, int dstBitPerPixel, ATL::CImage& dstImage)
{
assert(!srcImage.IsNull() && srcImage != dstImage && srcImage.GetBPP() <= 8 && srcImage.GetBPP() < dstBitPerPixel);
assert(dstBitPerPixel == 1 || dstBitPerPixel == 4 || dstBitPerPixel == 8 // GrayScaled
|| dstBitPerPixel == 24 || dstBitPerPixel == 32); // Colored
if (!dstImage.IsNull()) dstImage.Destroy();
dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), dstBitPerPixel, 0);
// For 8bit CImage, we need to copy the ColorTable after image creation
if (dstImage.IsIndexed()) {
// 8-bit: 0x100000000 = 256, in the same way, 4-bit: 0x10000 = 16, 2-bit: 0x100 = 4, 1-bit: 0x10 = 2
int nColors = srcImage.GetMaxColorTableEntries();
if (nColors > 0) {
std::vector<RGBQUAD> rgbColors(nColors);
srcImage.GetColorTable(0, nColors, rgbColors.data());
dstImage.SetColorTable(0, nColors, rgbColors.data());
}
}
srcImage.BitBlt(dstImage.GetDC(), 0, 0, SRCCOPY);
dstImage.ReleaseDC(); // Remember to dstImage.ReleaseDC() after dstImage.GetDC()
}
void Convert8bitTo32Bit(const ATL::CImage& srcImage, ATL::CImage& dstImage)
{
assert(!srcImage.IsNull() && srcImage != dstImage && srcImage.GetBPP() == 8);
if (!dstImage.IsNull()) dstImage.Destroy();
dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), 32, CImage::createAlphaChannel);
// CImage::BitBlt won't work with alpha channel, we have to set pixel one by one
for (int row = 0; row < dstImage.GetHeight(); row++)
{
for (int col = 0; col < dstImage.GetWidth(); col++)
{
BYTE* pixelEntry = static_cast<BYTE*>(dstImage.GetPixelAddress(col, row));
const BYTE intensity = static_cast<const BYTE*>(srcImage.GetPixelAddress(col, row))[0];
pixelEntry[0] = intensity;
pixelEntry[1] = intensity;
pixelEntry[2] = intensity;
pixelEntry[3] = 0xFF;
}
}
}
} // End of namespace slcimage
<commit_msg>Fix use CImage srcImage.StretchBlt HALFTONE for 8bit image<commit_after>#include "../stdafx.h"
#include "SLCImageProcess.h"
#include <vector>
#include <wincodec.h> // for COM: IWICImagingFactory / IWICBitmapScaler
#include <VersionHelpers.h>
namespace slcimage
{
//====================================================================================================================
//--------------------------------------------------------------------------------------------------------------------
void DuplicateImage(const ATL::CImage& srcImage, ATL::CImage& dstImage)
{
assert(!srcImage.IsNull());
if (srcImage == dstImage) return;
if (!dstImage.IsNull()) dstImage.Destroy();
int srcBitsCount = srcImage.GetBPP();
if (srcBitsCount == 32) dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), srcBitsCount, CImage::createAlphaChannel);
else dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), srcBitsCount, 0);
if (srcImage.IsIndexed()) {
// 8-bit: 0x100000000 = 256, in the same way, 4-bit: 0x10000 = 16, 2-bit: 0x100 = 4, 1-bit: 0x10 = 2
int nColors = srcImage.GetMaxColorTableEntries();
if (nColors > 0) {
std::vector<RGBQUAD> rgbColors(nColors);
srcImage.GetColorTable(0, nColors, rgbColors.data());
dstImage.SetColorTable(0, nColors, rgbColors.data());
}
}
srcImage.BitBlt(dstImage.GetDC(), 0, 0, SRCCOPY);
dstImage.ReleaseDC(); // Remember to dstImage.ReleaseDC() after dstImage.GetDC()
};// End of DuplicateImage(const CImage& srcImage, CImage& destImage)
//========================================================================================================================
//========================================================================================================================
//------------------------------------------------------------------------------------------------------------------------
void StretchImageByWidth(const ATL::CImage& srcImage, int widthInPixel, ATL::CImage& dstImage)
{
assert(!srcImage.IsNull() && srcImage != dstImage && widthInPixel > 0);
int srcBitsCount = srcImage.GetBPP();
double imageAspectRatio = static_cast<double>( srcImage.GetHeight() ) / srcImage.GetWidth() ;
// Get valid dstImageWidth and dstImageHeight
int dstImageWidth = widthInPixel;
double tmpDstImageHeight = imageAspectRatio * dstImageWidth;
int dstImageHeight = tmpDstImageHeight > 1.0 ? static_cast<int>(tmpDstImageHeight) : 1;
if (!dstImage.IsNull()) dstImage.Destroy();
if (srcBitsCount == 32) dstImage.Create(dstImageWidth, dstImageHeight, srcBitsCount, CImage::createAlphaChannel);
else dstImage.Create(dstImageWidth, dstImageHeight, srcBitsCount, 0);
// For 8bit CImage, we need to copy the ColorTable after image creation
// IWICBitmapScaler::CopyPixels will always fail on 8bit image and BPP smaller than 8, can only use StretchBlt
if (srcImage.IsIndexed()) {
// 8-bit: 0x100000000 = 256, in the same way, 4-bit: 0x10000 = 16, 2-bit: 0x100 = 4, 1-bit: 0x10 = 2
int nColors = srcImage.GetMaxColorTableEntries();
if (nColors > 0) {
std::vector<RGBQUAD> rgbColors(nColors);
srcImage.GetColorTable(0, nColors, rgbColors.data());
dstImage.SetColorTable(0, nColors, rgbColors.data());
}
HDC dstHDC = dstImage.GetDC();
SetBrushOrgEx(dstHDC, 0, 0, nullptr);
SetStretchBltMode(dstHDC, HALFTONE);
srcImage.StretchBlt(dstHDC, 0, 0, dstImageWidth, dstImageHeight, SRCCOPY);
dstImage.ReleaseDC();
}
else
{
// Down-Sampling using Bicubic algorithm
IWICImagingFactory *imagingFactory;
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
assert(hr == S_OK);
hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&imagingFactory));
assert(hr == S_OK);
if (hr != S_OK) return;
IWICBitmap* srcIWICBitmap;
hr = imagingFactory->CreateBitmapFromHBITMAP(srcImage, 0, WICBitmapUseAlpha, &srcIWICBitmap);
IWICBitmapScaler* bitmapScaler;
hr = imagingFactory->CreateBitmapScaler(&bitmapScaler);
if (IsWindows10OrGreater())
hr = bitmapScaler->Initialize(srcIWICBitmap, dstImageWidth, dstImageHeight, WICBitmapInterpolationModeHighQualityCubic);
else
hr = bitmapScaler->Initialize(srcIWICBitmap, dstImageWidth, dstImageHeight, WICBitmapInterpolationModeCubic);
WICRect rect = { 0, 0, dstImageWidth, 1 };
int stride = std::abs(dstImage.GetPitch());
BYTE* bufferEntry = static_cast<BYTE*>(dstImage.GetBits());
for (int i = 0; i < dstImageHeight; ++i) {
hr = bitmapScaler->CopyPixels(&rect, stride, stride, bufferEntry);
bufferEntry -= stride;
rect.Y += 1;
}
bitmapScaler->Release();
imagingFactory->Release();
CoUninitialize();
}
}// End of GetSmallerImageByWidth(const ATL::CImage& srcImage, int widthInPixel, ATL::CImage& dstImage)
//====================================================================================================================
//--------------------------------------------------------------------------------------------------------------------
/// <summary>Converting 1Bit/4Bit image to 8Bit/24Bit, help low bit image loading for LibreImage</summary>
void Convert8BitBelowToAbove(const ATL::CImage& srcImage, int dstBitPerPixel, ATL::CImage& dstImage)
{
assert(!srcImage.IsNull() && srcImage != dstImage && srcImage.GetBPP() <= 8 && srcImage.GetBPP() < dstBitPerPixel);
assert(dstBitPerPixel == 1 || dstBitPerPixel == 4 || dstBitPerPixel == 8 // GrayScaled
|| dstBitPerPixel == 24 || dstBitPerPixel == 32); // Colored
if (!dstImage.IsNull()) dstImage.Destroy();
dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), dstBitPerPixel, 0);
// For 8bit CImage, we need to copy the ColorTable after image creation
if (dstImage.IsIndexed()) {
// 8-bit: 0x100000000 = 256, in the same way, 4-bit: 0x10000 = 16, 2-bit: 0x100 = 4, 1-bit: 0x10 = 2
int nColors = srcImage.GetMaxColorTableEntries();
if (nColors > 0) {
std::vector<RGBQUAD> rgbColors(nColors);
srcImage.GetColorTable(0, nColors, rgbColors.data());
dstImage.SetColorTable(0, nColors, rgbColors.data());
}
}
srcImage.BitBlt(dstImage.GetDC(), 0, 0, SRCCOPY);
dstImage.ReleaseDC(); // Remember to dstImage.ReleaseDC() after dstImage.GetDC()
}
void Convert8bitTo32Bit(const ATL::CImage& srcImage, ATL::CImage& dstImage)
{
assert(!srcImage.IsNull() && srcImage != dstImage && srcImage.GetBPP() == 8);
if (!dstImage.IsNull()) dstImage.Destroy();
dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), 32, CImage::createAlphaChannel);
// CImage::BitBlt won't work with alpha channel, we have to set pixel one by one
for (int row = 0; row < dstImage.GetHeight(); row++)
{
for (int col = 0; col < dstImage.GetWidth(); col++)
{
BYTE* pixelEntry = static_cast<BYTE*>(dstImage.GetPixelAddress(col, row));
const BYTE intensity = static_cast<const BYTE*>(srcImage.GetPixelAddress(col, row))[0];
pixelEntry[0] = intensity;
pixelEntry[1] = intensity;
pixelEntry[2] = intensity;
pixelEntry[3] = 0xFF;
}
}
}
} // End of namespace slcimage
<|endoftext|> |
<commit_before><commit_msg>ServiceWorker: Add null check in ServiceWorkerContextWrapper::DeleteAndStartOver<commit_after><|endoftext|> |
<commit_before>// Copyright 2016 Benjamin Glatzel
//
// 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.
// Precompiled header file
#include "stdafx_vulkan.h"
#include "stdafx.h"
namespace Intrinsic
{
namespace Renderer
{
namespace Vulkan
{
namespace RenderPass
{
namespace
{
Resources::ImageRef _shadowBufferImageRef;
_INTR_ARRAY(Resources::FramebufferRef) _framebufferRefs;
Resources::RenderPassRef _renderPassRef;
// <-
_INTR_INLINE void
calculateFrustumForSplit(uint32_t p_SplitIdx,
Core::Resources::FrustumRef p_FrustumRef,
Components::CameraRef p_CameraRef)
{
_INTR_PROFILE_CPU("Render Pass", "Calc. Shadow Map Matrices");
// Make this configurable
const bool lastSplit = p_SplitIdx == _INTR_PSSM_SPLIT_COUNT - 1u;
const float maxShadowDistance = 3000.0f;
const float splitDistance = 5.0f;
// TODO: Replace this with an actual scene AABB
Math::AABB worldBounds = {glm::vec3(-5000.0f, -5000.0f, -5000.0f),
glm::vec3(5000.0f, 5000.0f, 5000.0f)};
const glm::vec3 worldBoundsHalfExtent = Math::calcAABBHalfExtent(worldBounds);
const float worldBoundsHalfExtentLength = glm::length(worldBoundsHalfExtent);
const glm::vec3 worldBoundsCenter = Math::calcAABBCenter(worldBounds);
const glm::vec3 eye =
worldBoundsHalfExtentLength *
(Core::Resources::PostEffectManager::_descMainLightOrientation(
Core::Resources::PostEffectManager::_blendTargetRef) *
glm::vec3(0.0f, 0.0f, 1.0f));
const glm::vec3 center = glm::vec3(0.0f, 0.0f, 0.0f);
glm::mat4& shadowViewMatrix =
Core::Resources::FrustumManager::_descViewMatrix(p_FrustumRef);
shadowViewMatrix = glm::lookAt(eye, center, glm::vec3(0.0f, 1.0f, 0.0f));
const float nearPlane =
glm::max(glm::pow(splitDistance * p_SplitIdx, 2.0f), 0.1f);
const float farPlane = !lastSplit
? glm::pow(splitDistance * (p_SplitIdx + 1u), 2.0f)
: maxShadowDistance;
const glm::mat4 inverseProj =
glm::inverse(Components::CameraManager::computeCustomProjMatrix(
p_CameraRef, nearPlane, farPlane));
Math::FrustumCorners viewSpaceCorners;
Math::extractFrustumsCorners(inverseProj, viewSpaceCorners);
glm::vec3 fpMin = glm::vec3(FLT_MAX, FLT_MAX, FLT_MAX);
glm::vec3 fpMax = glm::vec3(-FLT_MAX, -FLT_MAX, -FLT_MAX);
for (uint32_t cornerIdx = 0; cornerIdx < 8u; ++cornerIdx)
{
const glm::vec3& fp = viewSpaceCorners.c[cornerIdx];
fpMin = Math::calcVecMin(fpMin, fp);
fpMax = Math::calcVecMax(fpMax, fp);
}
const glm::vec3 boundingSphereCenter = (fpMin + fpMax) * 0.5f;
const glm::mat4 viewToShadowView =
shadowViewMatrix *
Components::CameraManager::_inverseViewMatrix(p_CameraRef);
const glm::vec3 boundingSphereCenterShadowSpace =
glm::vec3(viewToShadowView * glm::vec4(boundingSphereCenter, 1.0f));
const float boundingSphereRadius = glm::length(fpMax - fpMin) * 0.5f;
fpMin = boundingSphereCenterShadowSpace - boundingSphereRadius;
fpMax = boundingSphereCenterShadowSpace + boundingSphereRadius;
// Snap to texel increments
{
const glm::vec2 worldUnitsPerTexel =
glm::vec2(fpMax - fpMin) / glm::vec2(Shadow::_shadowMapSize);
fpMin.x /= worldUnitsPerTexel.x;
fpMin.y /= worldUnitsPerTexel.y;
fpMin.x = floor(fpMin.x);
fpMin.y = floor(fpMin.y);
fpMin.x *= worldUnitsPerTexel.x;
fpMin.y *= worldUnitsPerTexel.y;
fpMax.x /= worldUnitsPerTexel.x;
fpMax.y /= worldUnitsPerTexel.y;
fpMax.x = floor(fpMax.x);
fpMax.y = floor(fpMax.y);
fpMax.x *= worldUnitsPerTexel.x;
fpMax.y *= worldUnitsPerTexel.y;
}
const float orthoLeft = fpMin.x;
const float orthoRight = fpMax.x;
const float orthoBottom = fpMax.y;
const float orthoTop = fpMin.y;
float orthoNear = FLT_MAX;
float orthoFar = -FLT_MAX;
// Calc. near/fear
{
glm::vec3 aabbCorners[8];
Math::calcAABBCorners(worldBounds, aabbCorners);
for (uint32_t i = 0u; i < 8; ++i)
{
aabbCorners[i] =
glm::vec3(shadowViewMatrix * glm::vec4(aabbCorners[i], 1.0));
orthoNear = glm::min(orthoNear, -aabbCorners[i].z);
orthoFar = glm::max(orthoFar, -aabbCorners[i].z);
}
}
Core::Resources::FrustumManager::_descProjectionType(p_FrustumRef) =
Core::Resources::ProjectionType::kOrthographic;
Core::Resources::FrustumManager::_descNearFarPlaneDistances(p_FrustumRef) =
glm::vec2(orthoNear, orthoFar);
Core::Resources::FrustumManager::_descProjectionMatrix(p_FrustumRef) =
glm::ortho(orthoLeft, orthoRight, orthoBottom, orthoTop, orthoNear,
orthoFar);
}
}
// <-
// Static members
glm::uvec2 Shadow::_shadowMapSize = glm::uvec2(1024u, 1024u);
// <-
void Shadow::init()
{
using namespace Resources;
RenderPassRefArray renderPassesToCreate;
ImageRefArray imagesToCreate;
// Render passes
{
_renderPassRef = RenderPassManager::createRenderPass(_N(Shadow));
RenderPassManager::resetToDefault(_renderPassRef);
AttachmentDescription shadowBufferAttachment = {
(uint8_t)RenderSystem::_depthStencilFormatToUse,
AttachmentFlags::kClearOnLoad | AttachmentFlags::kClearStencilOnLoad};
RenderPassManager::_descAttachments(_renderPassRef)
.push_back(shadowBufferAttachment);
}
renderPassesToCreate.push_back(_renderPassRef);
RenderPassManager::createResources(renderPassesToCreate);
glm::uvec3 dim = glm::uvec3(_shadowMapSize, 1u);
// Create images
_shadowBufferImageRef = ImageManager::createImage(_N(ShadowBuffer));
{
ImageManager::resetToDefault(_shadowBufferImageRef);
ImageManager::addResourceFlags(
_shadowBufferImageRef,
Dod::Resources::ResourceFlags::kResourceVolatile);
ImageManager::_descDimensions(_shadowBufferImageRef) = dim;
ImageManager::_descImageFormat(_shadowBufferImageRef) =
RenderSystem::_depthStencilFormatToUse;
ImageManager::_descImageType(_shadowBufferImageRef) = ImageType::kTexture;
ImageManager::_descArrayLayerCount(_shadowBufferImageRef) =
_INTR_MAX_SHADOW_MAP_COUNT;
}
imagesToCreate.push_back(_shadowBufferImageRef);
// Create framebuffers
for (uint32_t shadowMapIdx = 0u; shadowMapIdx < _INTR_MAX_SHADOW_MAP_COUNT;
++shadowMapIdx)
{
FramebufferRef frameBufferRef =
FramebufferManager::createFramebuffer(_N(RenderPassShadow));
{
FramebufferManager::resetToDefault(frameBufferRef);
FramebufferManager::addResourceFlags(
frameBufferRef, Dod::Resources::ResourceFlags::kResourceVolatile);
FramebufferManager::_descAttachedImages(frameBufferRef)
.push_back(AttachmentInfo(_shadowBufferImageRef, shadowMapIdx));
FramebufferManager::_descDimensions(frameBufferRef) = glm::uvec2(dim);
FramebufferManager::_descRenderPass(frameBufferRef) = _renderPassRef;
}
_framebufferRefs.push_back(frameBufferRef);
}
ImageManager::createResources(imagesToCreate);
FramebufferManager::createResources(_framebufferRefs);
}
// <-
void Shadow::onReinitRendering() {}
// <-
void Shadow::destroy() {}
// <-
void Shadow::prepareFrustums(Components::CameraRef p_CameraRef,
_INTR_ARRAY(Core::Resources::FrustumRef) &
p_ShadowFrustums)
{
_INTR_PROFILE_CPU("Render Pass", "Prepare Shadow Frustums");
for (uint32_t i = 0u; i < p_ShadowFrustums.size(); ++i)
{
Core::Resources::FrustumManager::destroyFrustum(p_ShadowFrustums[i]);
}
p_ShadowFrustums.clear();
for (uint32_t shadowMapIdx = 0u; shadowMapIdx < _INTR_PSSM_SPLIT_COUNT;
++shadowMapIdx)
{
Core::Resources::FrustumRef frustumRef =
Core::Resources::FrustumManager::createFrustum(_N(ShadowFrustum));
calculateFrustumForSplit(shadowMapIdx, frustumRef, p_CameraRef);
p_ShadowFrustums.push_back(frustumRef);
}
}
// <-
void Shadow::render(float p_DeltaT, Components::CameraRef p_CameraRef)
{
using namespace Resources;
_INTR_PROFILE_CPU("Render Pass", "Render Shadows");
_INTR_PROFILE_GPU("Render Shadows");
_INTR_PROFILE_COUNTER_SET("Dispatched Draw Calls (Shadows)",
DrawCallDispatcher::_dispatchedDrawCallCount);
const _INTR_ARRAY(Core::Resources::FrustumRef)& shadowFrustums =
RenderProcess::Default::_shadowFrustums[p_CameraRef];
for (uint32_t shadowMapIdx = 0u; shadowMapIdx < shadowFrustums.size();
++shadowMapIdx)
{
_INTR_PROFILE_CPU("Render Pass", "Render Shadow Map");
_INTR_PROFILE_GPU("Render Shadow Map");
Core::Resources::FrustumRef frustumRef = shadowFrustums[shadowMapIdx];
ImageManager::insertImageMemoryBarrierSubResource(
_shadowBufferImageRef, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, 0u, shadowMapIdx);
const uint32_t frustumIdx = shadowMapIdx + 1u;
static DrawCallRefArray visibleDrawCalls;
visibleDrawCalls.clear();
RenderProcess::Default::getVisibleDrawCalls(
p_CameraRef, frustumIdx, MaterialManager::getMaterialPassId(_N(Shadow)))
.copy(visibleDrawCalls);
RenderProcess::Default::getVisibleDrawCalls(
p_CameraRef, frustumIdx,
MaterialManager::getMaterialPassId(_N(ShadowFoliage)))
.copy(visibleDrawCalls);
DrawCallManager::sortDrawCallsFrontToBack(visibleDrawCalls);
// Update per mesh uniform data
{
Components::MeshManager::updatePerInstanceData(p_CameraRef, frustumIdx);
Core::Components::MeshManager::updateUniformData(visibleDrawCalls);
}
VkClearValue clearValues[1] = {};
{
clearValues[0].depthStencil.depth = 1.0f;
clearValues[0].depthStencil.stencil = 0u;
}
RenderSystem::beginRenderPass(
_renderPassRef, _framebufferRefs[shadowMapIdx],
VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS, 1u, clearValues);
{
DrawCallDispatcher::queueDrawCalls(visibleDrawCalls, _renderPassRef,
_framebufferRefs[shadowMapIdx]);
_INTR_PROFILE_COUNTER_ADD("Dispatched Draw Calls (Shadows)",
DrawCallDispatcher::_dispatchedDrawCallCount);
}
RenderSystem::endRenderPass(_renderPassRef);
ImageManager::insertImageMemoryBarrierSubResource(
_shadowBufferImageRef, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, 0u, shadowMapIdx);
}
}
}
}
}
}
<commit_msg>Use 1.5k shadow maps by default<commit_after>// Copyright 2016 Benjamin Glatzel
//
// 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.
// Precompiled header file
#include "stdafx_vulkan.h"
#include "stdafx.h"
namespace Intrinsic
{
namespace Renderer
{
namespace Vulkan
{
namespace RenderPass
{
namespace
{
Resources::ImageRef _shadowBufferImageRef;
_INTR_ARRAY(Resources::FramebufferRef) _framebufferRefs;
Resources::RenderPassRef _renderPassRef;
// <-
_INTR_INLINE void
calculateFrustumForSplit(uint32_t p_SplitIdx,
Core::Resources::FrustumRef p_FrustumRef,
Components::CameraRef p_CameraRef)
{
_INTR_PROFILE_CPU("Render Pass", "Calc. Shadow Map Matrices");
// Make this configurable
const bool lastSplit = p_SplitIdx == _INTR_PSSM_SPLIT_COUNT - 1u;
const float maxShadowDistance = 3000.0f;
const float splitDistance = 5.0f;
// TODO: Replace this with an actual scene AABB
Math::AABB worldBounds = {glm::vec3(-5000.0f, -5000.0f, -5000.0f),
glm::vec3(5000.0f, 5000.0f, 5000.0f)};
const glm::vec3 worldBoundsHalfExtent = Math::calcAABBHalfExtent(worldBounds);
const float worldBoundsHalfExtentLength = glm::length(worldBoundsHalfExtent);
const glm::vec3 worldBoundsCenter = Math::calcAABBCenter(worldBounds);
const glm::vec3 eye =
worldBoundsHalfExtentLength *
(Core::Resources::PostEffectManager::_descMainLightOrientation(
Core::Resources::PostEffectManager::_blendTargetRef) *
glm::vec3(0.0f, 0.0f, 1.0f));
const glm::vec3 center = glm::vec3(0.0f, 0.0f, 0.0f);
glm::mat4& shadowViewMatrix =
Core::Resources::FrustumManager::_descViewMatrix(p_FrustumRef);
shadowViewMatrix = glm::lookAt(eye, center, glm::vec3(0.0f, 1.0f, 0.0f));
const float nearPlane =
glm::max(glm::pow(splitDistance * p_SplitIdx, 2.0f), 0.1f);
const float farPlane = !lastSplit
? glm::pow(splitDistance * (p_SplitIdx + 1u), 2.0f)
: maxShadowDistance;
const glm::mat4 inverseProj =
glm::inverse(Components::CameraManager::computeCustomProjMatrix(
p_CameraRef, nearPlane, farPlane));
Math::FrustumCorners viewSpaceCorners;
Math::extractFrustumsCorners(inverseProj, viewSpaceCorners);
glm::vec3 fpMin = glm::vec3(FLT_MAX, FLT_MAX, FLT_MAX);
glm::vec3 fpMax = glm::vec3(-FLT_MAX, -FLT_MAX, -FLT_MAX);
for (uint32_t cornerIdx = 0; cornerIdx < 8u; ++cornerIdx)
{
const glm::vec3& fp = viewSpaceCorners.c[cornerIdx];
fpMin = Math::calcVecMin(fpMin, fp);
fpMax = Math::calcVecMax(fpMax, fp);
}
const glm::vec3 boundingSphereCenter = (fpMin + fpMax) * 0.5f;
const glm::mat4 viewToShadowView =
shadowViewMatrix *
Components::CameraManager::_inverseViewMatrix(p_CameraRef);
const glm::vec3 boundingSphereCenterShadowSpace =
glm::vec3(viewToShadowView * glm::vec4(boundingSphereCenter, 1.0f));
const float boundingSphereRadius = glm::length(fpMax - fpMin) * 0.5f;
fpMin = boundingSphereCenterShadowSpace - boundingSphereRadius;
fpMax = boundingSphereCenterShadowSpace + boundingSphereRadius;
// Snap to texel increments
{
const glm::vec2 worldUnitsPerTexel =
glm::vec2(fpMax - fpMin) / glm::vec2(Shadow::_shadowMapSize);
fpMin.x /= worldUnitsPerTexel.x;
fpMin.y /= worldUnitsPerTexel.y;
fpMin.x = floor(fpMin.x);
fpMin.y = floor(fpMin.y);
fpMin.x *= worldUnitsPerTexel.x;
fpMin.y *= worldUnitsPerTexel.y;
fpMax.x /= worldUnitsPerTexel.x;
fpMax.y /= worldUnitsPerTexel.y;
fpMax.x = floor(fpMax.x);
fpMax.y = floor(fpMax.y);
fpMax.x *= worldUnitsPerTexel.x;
fpMax.y *= worldUnitsPerTexel.y;
}
const float orthoLeft = fpMin.x;
const float orthoRight = fpMax.x;
const float orthoBottom = fpMax.y;
const float orthoTop = fpMin.y;
float orthoNear = FLT_MAX;
float orthoFar = -FLT_MAX;
// Calc. near/fear
{
glm::vec3 aabbCorners[8];
Math::calcAABBCorners(worldBounds, aabbCorners);
for (uint32_t i = 0u; i < 8; ++i)
{
aabbCorners[i] =
glm::vec3(shadowViewMatrix * glm::vec4(aabbCorners[i], 1.0));
orthoNear = glm::min(orthoNear, -aabbCorners[i].z);
orthoFar = glm::max(orthoFar, -aabbCorners[i].z);
}
}
Core::Resources::FrustumManager::_descProjectionType(p_FrustumRef) =
Core::Resources::ProjectionType::kOrthographic;
Core::Resources::FrustumManager::_descNearFarPlaneDistances(p_FrustumRef) =
glm::vec2(orthoNear, orthoFar);
Core::Resources::FrustumManager::_descProjectionMatrix(p_FrustumRef) =
glm::ortho(orthoLeft, orthoRight, orthoBottom, orthoTop, orthoNear,
orthoFar);
}
}
// <-
// Static members
glm::uvec2 Shadow::_shadowMapSize = glm::uvec2(1536u, 1536u);
// <-
void Shadow::init()
{
using namespace Resources;
RenderPassRefArray renderPassesToCreate;
ImageRefArray imagesToCreate;
// Render passes
{
_renderPassRef = RenderPassManager::createRenderPass(_N(Shadow));
RenderPassManager::resetToDefault(_renderPassRef);
AttachmentDescription shadowBufferAttachment = {
(uint8_t)RenderSystem::_depthStencilFormatToUse,
AttachmentFlags::kClearOnLoad | AttachmentFlags::kClearStencilOnLoad};
RenderPassManager::_descAttachments(_renderPassRef)
.push_back(shadowBufferAttachment);
}
renderPassesToCreate.push_back(_renderPassRef);
RenderPassManager::createResources(renderPassesToCreate);
glm::uvec3 dim = glm::uvec3(_shadowMapSize, 1u);
// Create images
_shadowBufferImageRef = ImageManager::createImage(_N(ShadowBuffer));
{
ImageManager::resetToDefault(_shadowBufferImageRef);
ImageManager::addResourceFlags(
_shadowBufferImageRef,
Dod::Resources::ResourceFlags::kResourceVolatile);
ImageManager::_descDimensions(_shadowBufferImageRef) = dim;
ImageManager::_descImageFormat(_shadowBufferImageRef) =
RenderSystem::_depthStencilFormatToUse;
ImageManager::_descImageType(_shadowBufferImageRef) = ImageType::kTexture;
ImageManager::_descArrayLayerCount(_shadowBufferImageRef) =
_INTR_MAX_SHADOW_MAP_COUNT;
}
imagesToCreate.push_back(_shadowBufferImageRef);
// Create framebuffers
for (uint32_t shadowMapIdx = 0u; shadowMapIdx < _INTR_MAX_SHADOW_MAP_COUNT;
++shadowMapIdx)
{
FramebufferRef frameBufferRef =
FramebufferManager::createFramebuffer(_N(RenderPassShadow));
{
FramebufferManager::resetToDefault(frameBufferRef);
FramebufferManager::addResourceFlags(
frameBufferRef, Dod::Resources::ResourceFlags::kResourceVolatile);
FramebufferManager::_descAttachedImages(frameBufferRef)
.push_back(AttachmentInfo(_shadowBufferImageRef, shadowMapIdx));
FramebufferManager::_descDimensions(frameBufferRef) = glm::uvec2(dim);
FramebufferManager::_descRenderPass(frameBufferRef) = _renderPassRef;
}
_framebufferRefs.push_back(frameBufferRef);
}
ImageManager::createResources(imagesToCreate);
FramebufferManager::createResources(_framebufferRefs);
}
// <-
void Shadow::onReinitRendering() {}
// <-
void Shadow::destroy() {}
// <-
void Shadow::prepareFrustums(Components::CameraRef p_CameraRef,
_INTR_ARRAY(Core::Resources::FrustumRef) &
p_ShadowFrustums)
{
_INTR_PROFILE_CPU("Render Pass", "Prepare Shadow Frustums");
for (uint32_t i = 0u; i < p_ShadowFrustums.size(); ++i)
{
Core::Resources::FrustumManager::destroyFrustum(p_ShadowFrustums[i]);
}
p_ShadowFrustums.clear();
for (uint32_t shadowMapIdx = 0u; shadowMapIdx < _INTR_PSSM_SPLIT_COUNT;
++shadowMapIdx)
{
Core::Resources::FrustumRef frustumRef =
Core::Resources::FrustumManager::createFrustum(_N(ShadowFrustum));
calculateFrustumForSplit(shadowMapIdx, frustumRef, p_CameraRef);
p_ShadowFrustums.push_back(frustumRef);
}
}
// <-
void Shadow::render(float p_DeltaT, Components::CameraRef p_CameraRef)
{
using namespace Resources;
_INTR_PROFILE_CPU("Render Pass", "Render Shadows");
_INTR_PROFILE_GPU("Render Shadows");
_INTR_PROFILE_COUNTER_SET("Dispatched Draw Calls (Shadows)",
DrawCallDispatcher::_dispatchedDrawCallCount);
const _INTR_ARRAY(Core::Resources::FrustumRef)& shadowFrustums =
RenderProcess::Default::_shadowFrustums[p_CameraRef];
for (uint32_t shadowMapIdx = 0u; shadowMapIdx < shadowFrustums.size();
++shadowMapIdx)
{
_INTR_PROFILE_CPU("Render Pass", "Render Shadow Map");
_INTR_PROFILE_GPU("Render Shadow Map");
Core::Resources::FrustumRef frustumRef = shadowFrustums[shadowMapIdx];
ImageManager::insertImageMemoryBarrierSubResource(
_shadowBufferImageRef, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, 0u, shadowMapIdx);
const uint32_t frustumIdx = shadowMapIdx + 1u;
static DrawCallRefArray visibleDrawCalls;
visibleDrawCalls.clear();
RenderProcess::Default::getVisibleDrawCalls(
p_CameraRef, frustumIdx, MaterialManager::getMaterialPassId(_N(Shadow)))
.copy(visibleDrawCalls);
RenderProcess::Default::getVisibleDrawCalls(
p_CameraRef, frustumIdx,
MaterialManager::getMaterialPassId(_N(ShadowFoliage)))
.copy(visibleDrawCalls);
DrawCallManager::sortDrawCallsFrontToBack(visibleDrawCalls);
// Update per mesh uniform data
{
Components::MeshManager::updatePerInstanceData(p_CameraRef, frustumIdx);
Core::Components::MeshManager::updateUniformData(visibleDrawCalls);
}
VkClearValue clearValues[1] = {};
{
clearValues[0].depthStencil.depth = 1.0f;
clearValues[0].depthStencil.stencil = 0u;
}
RenderSystem::beginRenderPass(
_renderPassRef, _framebufferRefs[shadowMapIdx],
VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS, 1u, clearValues);
{
DrawCallDispatcher::queueDrawCalls(visibleDrawCalls, _renderPassRef,
_framebufferRefs[shadowMapIdx]);
_INTR_PROFILE_COUNTER_ADD("Dispatched Draw Calls (Shadows)",
DrawCallDispatcher::_dispatchedDrawCallCount);
}
RenderSystem::endRenderPass(_renderPassRef);
ImageManager::insertImageMemoryBarrierSubResource(
_shadowBufferImageRef, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, 0u, shadowMapIdx);
}
}
}
}
}
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE path_element_tests
// boost.test
#include <boost/test/included/unit_test.hpp>
// boost.filesystem
#include <boost/filesystem.hpp>
// mapnik
#include <mapnik/map.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/feature_type_style.hpp>
#include <mapnik/svg/output/svg_renderer.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/expression.hpp>
#include <mapnik/color_factory.hpp>
// stl
#include <fstream>
#include <iterator>
namespace fs = boost::filesystem;
using namespace mapnik;
void prepare_map(Map& m)
{
const std::string mapnik_dir("/usr/local/lib/mapnik/");
std::cout << " looking for 'shape.input' plugin in... " << mapnik_dir << "input/" << "\n";
datasource_cache::instance().register_datasources(mapnik_dir + "input/");
// create styles
// Provinces (polygon)
feature_type_style provpoly_style;
rule provpoly_rule_on;
provpoly_rule_on.set_filter(parse_expression("[NAME_EN] = 'Ontario'"));
provpoly_rule_on.append(polygon_symbolizer(color(250, 190, 183)));
provpoly_style.add_rule(provpoly_rule_on);
rule provpoly_rule_qc;
provpoly_rule_qc.set_filter(parse_expression("[NOM_FR] = 'Québec'"));
provpoly_rule_qc.append(polygon_symbolizer(color(217, 235, 203)));
provpoly_style.add_rule(provpoly_rule_qc);
m.insert_style("provinces",provpoly_style);
// Provinces (polyline)
feature_type_style provlines_style;
stroke provlines_stk (color(0,0,0),1.0);
provlines_stk.add_dash(8, 4);
provlines_stk.add_dash(2, 2);
provlines_stk.add_dash(2, 2);
rule provlines_rule;
provlines_rule.append(line_symbolizer(provlines_stk));
provlines_style.add_rule(provlines_rule);
m.insert_style("provlines",provlines_style);
// Drainage
feature_type_style qcdrain_style;
rule qcdrain_rule;
qcdrain_rule.set_filter(parse_expression("[HYC] = 8"));
qcdrain_rule.append(polygon_symbolizer(color(153, 204, 255)));
qcdrain_style.add_rule(qcdrain_rule);
m.insert_style("drainage",qcdrain_style);
// Roads 3 and 4 (The "grey" roads)
feature_type_style roads34_style;
rule roads34_rule;
roads34_rule.set_filter(parse_expression("[CLASS] = 3 or [CLASS] = 4"));
stroke roads34_rule_stk(color(171,158,137),2.0);
roads34_rule_stk.set_line_cap(ROUND_CAP);
roads34_rule_stk.set_line_join(ROUND_JOIN);
roads34_rule.append(line_symbolizer(roads34_rule_stk));
roads34_style.add_rule(roads34_rule);
m.insert_style("smallroads",roads34_style);
// Roads 2 (The thin yellow ones)
feature_type_style roads2_style_1;
rule roads2_rule_1;
roads2_rule_1.set_filter(parse_expression("[CLASS] = 2"));
stroke roads2_rule_stk_1(color(171,158,137),4.0);
roads2_rule_stk_1.set_line_cap(ROUND_CAP);
roads2_rule_stk_1.set_line_join(ROUND_JOIN);
roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1));
roads2_style_1.add_rule(roads2_rule_1);
m.insert_style("road-border", roads2_style_1);
feature_type_style roads2_style_2;
rule roads2_rule_2;
roads2_rule_2.set_filter(parse_expression("[CLASS] = 2"));
stroke roads2_rule_stk_2(color(255,250,115),2.0);
roads2_rule_stk_2.set_line_cap(ROUND_CAP);
roads2_rule_stk_2.set_line_join(ROUND_JOIN);
roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2));
roads2_style_2.add_rule(roads2_rule_2);
m.insert_style("road-fill", roads2_style_2);
// Roads 1 (The big orange ones, the highways)
feature_type_style roads1_style_1;
rule roads1_rule_1;
roads1_rule_1.set_filter(parse_expression("[CLASS] = 1"));
stroke roads1_rule_stk_1(color(188,149,28),7.0);
roads1_rule_stk_1.set_line_cap(ROUND_CAP);
roads1_rule_stk_1.set_line_join(ROUND_JOIN);
roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1));
roads1_style_1.add_rule(roads1_rule_1);
m.insert_style("highway-border", roads1_style_1);
feature_type_style roads1_style_2;
rule roads1_rule_2;
roads1_rule_2.set_filter(parse_expression("[CLASS] = 1"));
stroke roads1_rule_stk_2(color(242,191,36),5.0);
roads1_rule_stk_2.set_line_cap(ROUND_CAP);
roads1_rule_stk_2.set_line_join(ROUND_JOIN);
roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2));
roads1_style_2.add_rule(roads1_rule_2);
m.insert_style("highway-fill", roads1_style_2);
// layers
// Provincial polygons
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/boundaries";
layer lyr("Provinces");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("provinces");
m.addLayer(lyr);
}
// Drainage
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/qcdrainage";
layer lyr("Quebec Hydrography");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("drainage");
m.addLayer(lyr);
}
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/ontdrainage";
layer lyr("Ontario Hydrography");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("drainage");
m.addLayer(lyr);
}
// Provincial boundaries
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/boundaries_l";
layer lyr("Provincial borders");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("provlines");
m.addLayer(lyr);
}
// Roads
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/roads";
layer lyr("Roads");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("smallroads");
lyr.add_style("road-border");
lyr.add_style("road-fill");
lyr.add_style("highway-border");
lyr.add_style("highway-fill");
m.addLayer(lyr);
}
}
void render_to_file(Map const& m, const std::string output_filename)
{
std::ofstream output_stream(output_filename.c_str());
if(output_stream)
{
typedef svg_renderer<std::ostream_iterator<char> > svg_ren;
std::ostream_iterator<char> output_stream_iterator(output_stream);
svg_ren renderer(m, output_stream_iterator);
renderer.apply();
output_stream.close();
fs::path output_filename_path =
fs::system_complete(fs::path(".")) / fs::path(output_filename);
BOOST_CHECK_MESSAGE(fs::exists(output_filename_path),
"File '"+output_filename_path.string()+"' was created.");
}
else
{
BOOST_FAIL("Could not create create/open file '"+output_filename+"'.");
}
}
BOOST_AUTO_TEST_CASE(path_element_test_case_1)
{
Map m(800,600);
m.set_background(parse_color("steelblue"));
prepare_map(m);
//m.zoom_to_box(box2d<double>(1405120.04127408, -247003.813399447,
//1706357.31328276, -25098.593149577));
m.zoom_all();
render_to_file(m, "path_element_test_case_1.svg");
}
<commit_msg>catch another addLayer -> add_layer case<commit_after>#define BOOST_TEST_MODULE path_element_tests
// boost.test
#include <boost/test/included/unit_test.hpp>
// boost.filesystem
#include <boost/filesystem.hpp>
// mapnik
#include <mapnik/map.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/feature_type_style.hpp>
#include <mapnik/svg/output/svg_renderer.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/expression.hpp>
#include <mapnik/color_factory.hpp>
// stl
#include <fstream>
#include <iterator>
namespace fs = boost::filesystem;
using namespace mapnik;
void prepare_map(Map& m)
{
const std::string mapnik_dir("/usr/local/lib/mapnik/");
std::cout << " looking for 'shape.input' plugin in... " << mapnik_dir << "input/" << "\n";
datasource_cache::instance().register_datasources(mapnik_dir + "input/");
// create styles
// Provinces (polygon)
feature_type_style provpoly_style;
rule provpoly_rule_on;
provpoly_rule_on.set_filter(parse_expression("[NAME_EN] = 'Ontario'"));
provpoly_rule_on.append(polygon_symbolizer(color(250, 190, 183)));
provpoly_style.add_rule(provpoly_rule_on);
rule provpoly_rule_qc;
provpoly_rule_qc.set_filter(parse_expression("[NOM_FR] = 'Québec'"));
provpoly_rule_qc.append(polygon_symbolizer(color(217, 235, 203)));
provpoly_style.add_rule(provpoly_rule_qc);
m.insert_style("provinces",provpoly_style);
// Provinces (polyline)
feature_type_style provlines_style;
stroke provlines_stk (color(0,0,0),1.0);
provlines_stk.add_dash(8, 4);
provlines_stk.add_dash(2, 2);
provlines_stk.add_dash(2, 2);
rule provlines_rule;
provlines_rule.append(line_symbolizer(provlines_stk));
provlines_style.add_rule(provlines_rule);
m.insert_style("provlines",provlines_style);
// Drainage
feature_type_style qcdrain_style;
rule qcdrain_rule;
qcdrain_rule.set_filter(parse_expression("[HYC] = 8"));
qcdrain_rule.append(polygon_symbolizer(color(153, 204, 255)));
qcdrain_style.add_rule(qcdrain_rule);
m.insert_style("drainage",qcdrain_style);
// Roads 3 and 4 (The "grey" roads)
feature_type_style roads34_style;
rule roads34_rule;
roads34_rule.set_filter(parse_expression("[CLASS] = 3 or [CLASS] = 4"));
stroke roads34_rule_stk(color(171,158,137),2.0);
roads34_rule_stk.set_line_cap(ROUND_CAP);
roads34_rule_stk.set_line_join(ROUND_JOIN);
roads34_rule.append(line_symbolizer(roads34_rule_stk));
roads34_style.add_rule(roads34_rule);
m.insert_style("smallroads",roads34_style);
// Roads 2 (The thin yellow ones)
feature_type_style roads2_style_1;
rule roads2_rule_1;
roads2_rule_1.set_filter(parse_expression("[CLASS] = 2"));
stroke roads2_rule_stk_1(color(171,158,137),4.0);
roads2_rule_stk_1.set_line_cap(ROUND_CAP);
roads2_rule_stk_1.set_line_join(ROUND_JOIN);
roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1));
roads2_style_1.add_rule(roads2_rule_1);
m.insert_style("road-border", roads2_style_1);
feature_type_style roads2_style_2;
rule roads2_rule_2;
roads2_rule_2.set_filter(parse_expression("[CLASS] = 2"));
stroke roads2_rule_stk_2(color(255,250,115),2.0);
roads2_rule_stk_2.set_line_cap(ROUND_CAP);
roads2_rule_stk_2.set_line_join(ROUND_JOIN);
roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2));
roads2_style_2.add_rule(roads2_rule_2);
m.insert_style("road-fill", roads2_style_2);
// Roads 1 (The big orange ones, the highways)
feature_type_style roads1_style_1;
rule roads1_rule_1;
roads1_rule_1.set_filter(parse_expression("[CLASS] = 1"));
stroke roads1_rule_stk_1(color(188,149,28),7.0);
roads1_rule_stk_1.set_line_cap(ROUND_CAP);
roads1_rule_stk_1.set_line_join(ROUND_JOIN);
roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1));
roads1_style_1.add_rule(roads1_rule_1);
m.insert_style("highway-border", roads1_style_1);
feature_type_style roads1_style_2;
rule roads1_rule_2;
roads1_rule_2.set_filter(parse_expression("[CLASS] = 1"));
stroke roads1_rule_stk_2(color(242,191,36),5.0);
roads1_rule_stk_2.set_line_cap(ROUND_CAP);
roads1_rule_stk_2.set_line_join(ROUND_JOIN);
roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2));
roads1_style_2.add_rule(roads1_rule_2);
m.insert_style("highway-fill", roads1_style_2);
// layers
// Provincial polygons
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/boundaries";
layer lyr("Provinces");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("provinces");
m.add_layer(lyr);
}
// Drainage
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/qcdrainage";
layer lyr("Quebec Hydrography");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("drainage");
m.add_layer(lyr);
}
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/ontdrainage";
layer lyr("Ontario Hydrography");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("drainage");
m.add_layer(lyr);
}
// Provincial boundaries
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/boundaries_l";
layer lyr("Provincial borders");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("provlines");
m.add_layer(lyr);
}
// Roads
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/roads";
layer lyr("Roads");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("smallroads");
lyr.add_style("road-border");
lyr.add_style("road-fill");
lyr.add_style("highway-border");
lyr.add_style("highway-fill");
m.add_layer(lyr);
}
}
void render_to_file(Map const& m, const std::string output_filename)
{
std::ofstream output_stream(output_filename.c_str());
if(output_stream)
{
typedef svg_renderer<std::ostream_iterator<char> > svg_ren;
std::ostream_iterator<char> output_stream_iterator(output_stream);
svg_ren renderer(m, output_stream_iterator);
renderer.apply();
output_stream.close();
fs::path output_filename_path =
fs::system_complete(fs::path(".")) / fs::path(output_filename);
BOOST_CHECK_MESSAGE(fs::exists(output_filename_path),
"File '"+output_filename_path.string()+"' was created.");
}
else
{
BOOST_FAIL("Could not create create/open file '"+output_filename+"'.");
}
}
BOOST_AUTO_TEST_CASE(path_element_test_case_1)
{
Map m(800,600);
m.set_background(parse_color("steelblue"));
prepare_map(m);
//m.zoom_to_box(box2d<double>(1405120.04127408, -247003.813399447,
//1706357.31328276, -25098.593149577));
m.zoom_all();
render_to_file(m, "path_element_test_case_1.svg");
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkAutoSelectingDICOMReaderService.h"
#include <mitkDICOMFileReaderSelector.h>
namespace mitk {
AutoSelectingDICOMReaderService::AutoSelectingDICOMReaderService()
: BaseDICOMReaderService("MITK DICOM Reader v2 (autoselect)")
{
this->RegisterService();
}
DICOMFileReader::Pointer AutoSelectingDICOMReaderService::GetReader(const mitk::StringList& relevantFiles) const
{
mitk::DICOMFileReaderSelector::Pointer selector = mitk::DICOMFileReaderSelector::New();
selector->LoadBuiltIn3DConfigs();
selector->LoadBuiltIn3DnTConfigs();
selector->SetInputFiles(relevantFiles);
mitk::DICOMFileReader::Pointer reader = selector->GetFirstReaderWithMinimumNumberOfOutputImages();
if(reader.IsNotNull())
{
//reset tag cache to ensure that additional tags of interest
//will be regarded by the reader if set later on.
reader->SetTagCache(nullptr);
}
return reader;
};
AutoSelectingDICOMReaderService* AutoSelectingDICOMReaderService::Clone() const
{
return new AutoSelectingDICOMReaderService(*this);
}
}
<commit_msg>Increase autoselect dicom reader ranking to make it default<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkAutoSelectingDICOMReaderService.h"
#include <mitkDICOMFileReaderSelector.h>
namespace mitk {
AutoSelectingDICOMReaderService::AutoSelectingDICOMReaderService()
: BaseDICOMReaderService("MITK DICOM Reader v2 (autoselect)")
{
this->SetRanking(5);
this->RegisterService();
}
DICOMFileReader::Pointer AutoSelectingDICOMReaderService::GetReader(const mitk::StringList& relevantFiles) const
{
mitk::DICOMFileReaderSelector::Pointer selector = mitk::DICOMFileReaderSelector::New();
selector->LoadBuiltIn3DConfigs();
selector->LoadBuiltIn3DnTConfigs();
selector->SetInputFiles(relevantFiles);
mitk::DICOMFileReader::Pointer reader = selector->GetFirstReaderWithMinimumNumberOfOutputImages();
if(reader.IsNotNull())
{
//reset tag cache to ensure that additional tags of interest
//will be regarded by the reader if set later on.
reader->SetTagCache(nullptr);
}
return reader;
};
AutoSelectingDICOMReaderService* AutoSelectingDICOMReaderService::Clone() const
{
return new AutoSelectingDICOMReaderService(*this);
}
}
<|endoftext|> |
<commit_before><commit_msg>fix typo<commit_after><|endoftext|> |
<commit_before>#include "addressbookdialog.h"
#include "ui_addressbookdialog.h"
#include "addresstablemodel.h"
#include "editaddressdialog.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QDebug>
AddressBookDialog::AddressBookDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddressBookDialog),
model(0)
{
ui->setupUi(this);
switch(mode)
{
case ForSending:
connect(ui->receiveTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_buttonBox_accepted()));
connect(ui->sendTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_buttonBox_accepted()));
break;
case ForEditing:
connect(ui->receiveTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_editButton_clicked()));
connect(ui->sendTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_editButton_clicked()));
break;
}
}
AddressBookDialog::~AddressBookDialog()
{
delete ui;
}
void AddressBookDialog::setModel(AddressTableModel *model)
{
this->model = model;
// Refresh list from core
model->updateList();
// Receive filter
QSortFilterProxyModel *receive_model = new QSortFilterProxyModel(this);
receive_model->setSourceModel(model);
receive_model->setDynamicSortFilter(true);
receive_model->setFilterRole(AddressTableModel::TypeRole);
receive_model->setFilterFixedString(AddressTableModel::Receive);
ui->receiveTableView->setModel(receive_model);
// Send filter
QSortFilterProxyModel *send_model = new QSortFilterProxyModel(this);
send_model->setSourceModel(model);
send_model->setDynamicSortFilter(true);
send_model->setFilterRole(AddressTableModel::TypeRole);
send_model->setFilterFixedString(AddressTableModel::Send);
ui->sendTableView->setModel(send_model);
// Set column widths
ui->receiveTableView->horizontalHeader()->resizeSection(
AddressTableModel::Address, 320);
ui->receiveTableView->horizontalHeader()->setResizeMode(
AddressTableModel::Label, QHeaderView::Stretch);
ui->sendTableView->horizontalHeader()->resizeSection(
AddressTableModel::Address, 320);
ui->sendTableView->horizontalHeader()->setResizeMode(
AddressTableModel::Label, QHeaderView::Stretch);
}
void AddressBookDialog::setTab(int tab)
{
ui->tabWidget->setCurrentIndex(tab);
on_tabWidget_currentChanged(tab);
}
QTableView *AddressBookDialog::getCurrentTable()
{
switch(ui->tabWidget->currentIndex())
{
case SendingTab:
return ui->sendTableView;
case ReceivingTab:
return ui->receiveTableView;
default:
return 0;
}
}
void AddressBookDialog::on_copyToClipboard_clicked()
{
// Copy currently selected address to clipboard
// (or nothing, if nothing selected)
QTableView *table = getCurrentTable();
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QVariant address = index.data();
QApplication::clipboard()->setText(address.toString());
}
}
void AddressBookDialog::on_editButton_clicked()
{
QModelIndexList indexes = getCurrentTable()->selectionModel()->selectedRows();
if(indexes.isEmpty())
{
return;
}
// Map selected index to source address book model
QAbstractProxyModel *proxy_model = static_cast<QAbstractProxyModel*>(getCurrentTable()->model());
QModelIndex selected = proxy_model->mapToSource(indexes.at(0));
// Double click also triggers edit button
EditAddressDialog dlg(
ui->tabWidget->currentIndex() == SendingTab ?
EditAddressDialog::EditSendingAddress :
EditAddressDialog::EditReceivingAddress);
dlg.setModel(model);
dlg.loadRow(selected.row());
if(dlg.exec())
{
dlg.saveCurrentRow();
}
}
void AddressBookDialog::on_newAddressButton_clicked()
{
EditAddressDialog dlg(
ui->tabWidget->currentIndex() == SendingTab ?
EditAddressDialog::NewSendingAddress :
EditAddressDialog::NewReceivingAddress);
dlg.setModel(model);
if(dlg.exec())
{
dlg.saveCurrentRow();
}
}
void AddressBookDialog::on_tabWidget_currentChanged(int index)
{
// Enable/disable buttons based on selected tab
switch(index)
{
case SendingTab:
ui->deleteButton->setEnabled(true);
break;
case ReceivingTab:
ui->deleteButton->setEnabled(false);
break;
}
}
void AddressBookDialog::on_deleteButton_clicked()
{
QTableView *table = getCurrentTable();
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void AddressBookDialog::on_buttonBox_accepted()
{
QTableView *table = getCurrentTable();
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if(!returnValue.isEmpty())
{
accept();
}
else
{
reject();
}
}
<commit_msg>fix sorting in address table dialog<commit_after>#include "addressbookdialog.h"
#include "ui_addressbookdialog.h"
#include "addresstablemodel.h"
#include "editaddressdialog.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QDebug>
AddressBookDialog::AddressBookDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddressBookDialog),
model(0)
{
ui->setupUi(this);
switch(mode)
{
case ForSending:
connect(ui->receiveTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_buttonBox_accepted()));
connect(ui->sendTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_buttonBox_accepted()));
break;
case ForEditing:
connect(ui->receiveTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_editButton_clicked()));
connect(ui->sendTableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_editButton_clicked()));
break;
}
}
AddressBookDialog::~AddressBookDialog()
{
delete ui;
}
void AddressBookDialog::setModel(AddressTableModel *model)
{
this->model = model;
// Refresh list from core
model->updateList();
// Receive filter
QSortFilterProxyModel *receive_model = new QSortFilterProxyModel(this);
receive_model->setSourceModel(model);
receive_model->setDynamicSortFilter(true);
receive_model->setFilterRole(AddressTableModel::TypeRole);
receive_model->setFilterFixedString(AddressTableModel::Receive);
ui->receiveTableView->setModel(receive_model);
ui->receiveTableView->sortByColumn(0, Qt::AscendingOrder);
// Send filter
QSortFilterProxyModel *send_model = new QSortFilterProxyModel(this);
send_model->setSourceModel(model);
send_model->setDynamicSortFilter(true);
send_model->setFilterRole(AddressTableModel::TypeRole);
send_model->setFilterFixedString(AddressTableModel::Send);
ui->sendTableView->setModel(send_model);
ui->sendTableView->sortByColumn(0, Qt::AscendingOrder);
// Set column widths
ui->receiveTableView->horizontalHeader()->resizeSection(
AddressTableModel::Address, 320);
ui->receiveTableView->horizontalHeader()->setResizeMode(
AddressTableModel::Label, QHeaderView::Stretch);
ui->sendTableView->horizontalHeader()->resizeSection(
AddressTableModel::Address, 320);
ui->sendTableView->horizontalHeader()->setResizeMode(
AddressTableModel::Label, QHeaderView::Stretch);
}
void AddressBookDialog::setTab(int tab)
{
ui->tabWidget->setCurrentIndex(tab);
on_tabWidget_currentChanged(tab);
}
QTableView *AddressBookDialog::getCurrentTable()
{
switch(ui->tabWidget->currentIndex())
{
case SendingTab:
return ui->sendTableView;
case ReceivingTab:
return ui->receiveTableView;
default:
return 0;
}
}
void AddressBookDialog::on_copyToClipboard_clicked()
{
// Copy currently selected address to clipboard
// (or nothing, if nothing selected)
QTableView *table = getCurrentTable();
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QVariant address = index.data();
QApplication::clipboard()->setText(address.toString());
}
}
void AddressBookDialog::on_editButton_clicked()
{
QModelIndexList indexes = getCurrentTable()->selectionModel()->selectedRows();
if(indexes.isEmpty())
{
return;
}
// Map selected index to source address book model
QAbstractProxyModel *proxy_model = static_cast<QAbstractProxyModel*>(getCurrentTable()->model());
QModelIndex selected = proxy_model->mapToSource(indexes.at(0));
// Double click also triggers edit button
EditAddressDialog dlg(
ui->tabWidget->currentIndex() == SendingTab ?
EditAddressDialog::EditSendingAddress :
EditAddressDialog::EditReceivingAddress);
dlg.setModel(model);
dlg.loadRow(selected.row());
if(dlg.exec())
{
dlg.saveCurrentRow();
}
}
void AddressBookDialog::on_newAddressButton_clicked()
{
EditAddressDialog dlg(
ui->tabWidget->currentIndex() == SendingTab ?
EditAddressDialog::NewSendingAddress :
EditAddressDialog::NewReceivingAddress);
dlg.setModel(model);
if(dlg.exec())
{
dlg.saveCurrentRow();
}
}
void AddressBookDialog::on_tabWidget_currentChanged(int index)
{
// Enable/disable buttons based on selected tab
switch(index)
{
case SendingTab:
ui->deleteButton->setEnabled(true);
break;
case ReceivingTab:
ui->deleteButton->setEnabled(false);
break;
}
}
void AddressBookDialog::on_deleteButton_clicked()
{
QTableView *table = getCurrentTable();
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void AddressBookDialog::on_buttonBox_accepted()
{
QTableView *table = getCurrentTable();
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes)
{
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if(!returnValue.isEmpty())
{
accept();
}
else
{
reject();
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <cstdint>
#include <array>
namespace Utility
{
namespace MemoryManager
{
class AllocationHeaderBuilder
{
private:
AllocationHeaderBuilder();
virtual ~AllocationHeaderBuilder();
public:
/**
Sets the byte to zero
*/
// TODORT move to .cpp file
static void SetByteAsZero(void* p_pointerToByte) { *(uint8_t*)p_pointerToByte = 0; }
/**
Sets the byte to a specific value;
*/
// TODORT move to .cpp file
static void SetByte(void* p_pointerToByte, const uint8_t& value) { *(uint8_t*)p_pointerToByte = value; }
// TODORT move to .cpp file
static void BuildCustomByteBasedOnFlags(void* p_pointerToByte, const bool& f0, const bool& f1, const bool& f2, const bool& f3,
const bool& f4, const bool& f5, const bool& f6, const bool& f7)
{
uint8_t flagValue = 0;
if(f0)
{
flagValue |= 1;
}
if(f1)
{
flagValue |= 2;
}
if(f2)
{
flagValue |= 4;
}
if(f3)
{
flagValue |= 8;
}
if(f4)
{
flagValue |= 16;
}
if(f5)
{
flagValue |= 32;
}
if(f6)
{
flagValue |= 64;
}
if(f7)
{
flagValue |= 128;
}
*(uint8_t*)p_pointerToByte = flagValue;
}
// TODORT move to .cpp file
static void MarkByteBasedOnFlags(void* p_pointerToByte, const std::array<bool, 8>& flags)
{
uint8_t flagValue = 0;
if(flags[0])
{
flagValue |= 1;
}
if(flags[1])
{
flagValue |= 2;
}
if(flags[2])
{
flagValue |= 4;
}
if(flags[3])
{
flagValue |= 8;
}
if(flags[4])
{
flagValue |= 16;
}
if(flags[5])
{
flagValue |= 32;
}
if(flags[6])
{
flagValue |= 64;
}
if(flags[7])
{
flagValue |= 128;
}
*(uint8_t*)p_pointerToByte = flagValue;
}
// TODORT move to .cpp file
static void MarkByteAsOccupied(void* p_pointerToByte)
{
/*
XXXX XXXX
| 0000 0001
*/
*(uint8_t*)p_pointerToByte |= 1;
}
// TODORT move to .cpp file
static void MarkByteAsFree(void* p_pointerToByte)
{
/*
XXXX XXXX
& 1111 1110
*/
*(uint8_t*)p_pointerToByte &= 254;
}
// TODORT move to .cpp file
static std::array<bool, 8>& FetchAllFlagsFromByte(const void const* p_pointerToByte)
{
const uint8_t& value = *(uint8_t*)p_pointerToByte;
std::array<bool, 8> returnValue; // All false at the beginning
if((value & 1) == 1)
{
returnValue[0] = true;
}
if((value & 2) == 2)
{
returnValue[1] = true;
}
if((value & 4) == 4)
{
returnValue[2] = true;
}
if((value & 8) == 8)
{
returnValue[3] = true;
}
if((value & 16) == 16)
{
returnValue[4] = true;
}
if((value & 32) == 32)
{
returnValue[5] = true;
}
if((value & 64) == 64)
{
returnValue[6] = true;
}
if((value & 128) == 128)
{
returnValue[7] = true;
}
return returnValue;
}
};
}
}<commit_msg>Fixed warning by moving const keyword<commit_after>#pragma once
#include <cstdint>
#include <array>
namespace Utility
{
namespace MemoryManager
{
class AllocationHeaderBuilder
{
private:
AllocationHeaderBuilder();
virtual ~AllocationHeaderBuilder();
public:
/**
Sets the byte to zero
*/
// TODORT move to .cpp file
static void SetByteAsZero(void* p_pointerToByte) { *(uint8_t*)p_pointerToByte = 0; }
/**
Sets the byte to a specific value;
*/
// TODORT move to .cpp file
static void SetByte(void* p_pointerToByte, const uint8_t& value) { *(uint8_t*)p_pointerToByte = value; }
// TODORT move to .cpp file
static void BuildCustomByteBasedOnFlags(void* p_pointerToByte, const bool& f0, const bool& f1, const bool& f2, const bool& f3,
const bool& f4, const bool& f5, const bool& f6, const bool& f7)
{
uint8_t flagValue = 0;
if(f0)
{
flagValue |= 1;
}
if(f1)
{
flagValue |= 2;
}
if(f2)
{
flagValue |= 4;
}
if(f3)
{
flagValue |= 8;
}
if(f4)
{
flagValue |= 16;
}
if(f5)
{
flagValue |= 32;
}
if(f6)
{
flagValue |= 64;
}
if(f7)
{
flagValue |= 128;
}
*(uint8_t*)p_pointerToByte = flagValue;
}
// TODORT move to .cpp file
static void MarkByteBasedOnFlags(void* p_pointerToByte, const std::array<bool, 8>& flags)
{
uint8_t flagValue = 0;
if(flags[0])
{
flagValue |= 1;
}
if(flags[1])
{
flagValue |= 2;
}
if(flags[2])
{
flagValue |= 4;
}
if(flags[3])
{
flagValue |= 8;
}
if(flags[4])
{
flagValue |= 16;
}
if(flags[5])
{
flagValue |= 32;
}
if(flags[6])
{
flagValue |= 64;
}
if(flags[7])
{
flagValue |= 128;
}
*(uint8_t*)p_pointerToByte = flagValue;
}
// TODORT move to .cpp file
static void MarkByteAsOccupied(void* p_pointerToByte)
{
/*
XXXX XXXX
| 0000 0001
*/
*(uint8_t*)p_pointerToByte |= 1;
}
// TODORT move to .cpp file
static void MarkByteAsFree(void* p_pointerToByte)
{
/*
XXXX XXXX
& 1111 1110
*/
*(uint8_t*)p_pointerToByte &= 254;
}
// TODORT move to .cpp file
static std::array<bool, 8>& FetchAllFlagsFromByte(const void* const p_pointerToByte)
{
const uint8_t& value = *(uint8_t*)p_pointerToByte;
std::array<bool, 8> returnValue; // All false at the beginning
if((value & 1) == 1)
{
returnValue[0] = true;
}
if((value & 2) == 2)
{
returnValue[1] = true;
}
if((value & 4) == 4)
{
returnValue[2] = true;
}
if((value & 8) == 8)
{
returnValue[3] = true;
}
if((value & 16) == 16)
{
returnValue[4] = true;
}
if((value & 32) == 32)
{
returnValue[5] = true;
}
if((value & 64) == 64)
{
returnValue[6] = true;
}
if((value & 128) == 128)
{
returnValue[7] = true;
}
return returnValue;
}
};
}
}<|endoftext|> |
<commit_before>/*ckwg +5
* Copyright 2011-2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "utils.h"
#ifdef HAVE_PTHREAD_NAMING
#define NAME_THREAD_USING_PTHREAD
#ifdef HAVE_PTHREAD_SET_NAME_NP
#ifdef NDEBUG
// The mechanism only make sense in debugging mode.
#undef NAME_THREAD_USING_PTHREAD
#endif
#endif
#endif
#ifdef HAVE_SETPROCTITLE
#define NAME_THREAD_USING_SETPROCTITLE
#endif
#ifdef __linux__
#define NAME_THREAD_USING_PRCTL
#endif
#if defined(_WIN32) || defined(_WIN64)
#ifndef NDEBUG
#define NAME_THREAD_USING_WIN32
#endif
#endif
#ifdef NAME_THREAD_USING_PTHREAD
#include <pthread.h>
#ifdef HAVE_PTHREAD_SET_NAME_NP
#include <pthread_np.h>
#endif
#endif
#ifdef NAME_THREAD_USING_PRCTL
#include <sys/prctl.h>
#endif
#if defined(_WIN32) || defined(_WIN64)
#include <boost/scoped_array.hpp>
#include <windows.h>
#else
#include <cstdlib>
#endif
/**
* \file utils.cxx
*
* \brief Implementation of pipeline utilities.
*/
namespace vistk
{
#ifdef NAME_THREAD_USING_PTHREAD
static bool name_thread_pthread(thread_name_t const& name);
#endif
#ifdef NAME_THREAD_USING_SETPROCTITLE
static bool name_thread_setproctitle(thread_name_t const& name);
#endif
#ifdef NAME_THREAD_USING_PRCTL
static bool name_thread_prctl(thread_name_t const& name);
#endif
#ifdef NAME_THREAD_USING_WIN32
static bool name_thread_win32(thread_name_t const& name);
#endif
bool
name_thread(thread_name_t const& name)
{
bool ret = false;
#ifdef NAME_THREAD_USING_PTHREAD
if (!ret)
{
ret = name_thread_pthread(name);
}
#endif
#ifdef NAME_THREAD_USING_SETPROCTITLE
if (!ret)
{
ret = name_thread_setproctitle(name);
}
#endif
#ifdef NAME_THREAD_USING_PRCTL
if (!ret)
{
ret = name_thread_prctl(name);
}
#endif
#ifdef NAME_THREAD_USING_WIN32
if (!ret)
{
ret = name_thread_win32(name);
}
#endif
return ret;
}
envvar_value_t
get_envvar(envvar_name_t const& name)
{
envvar_value_t value;
#if defined(_WIN32) || defined(_WIN64)
char const* const name_cstr = name.c_str();
DWORD sz = GetEnvironmentVariable(name_cstr, NULL, 0);
if (sz)
{
typedef boost::scoped_array<char> raw_envvar_value_t;
raw_envvar_value_t const envvalue(new char[sz]);
sz = GetEnvironmentVariable(name_cstr, envvalue.get(), sz);
value = envvalue.get();
}
if (!sz)
{
/// \todo Log error that the environment reading failed.
}
#else
char const* const envvalue = getenv(name.c_str());
if (envvalue)
{
value = envvalue;
}
#endif
return value;
}
#ifdef NAME_THREAD_USING_PTHREAD
bool
name_thread_pthread(thread_name_t const& name)
{
int ret;
#ifdef HAVE_PTHREAD_SETNAME_NP
#ifdef PTHREAD_SETNAME_NP_TAKES_ID
pthread_t const tid = pthread_self();
ret = pthread_setname_np(tid, name.c_str());
#else
ret = pthread_setname_np(name.c_str());
#endif
#elif defined(HAVE_PTHREAD_SET_NAME_NP)
// The documentation states that it only makes sense in debugging; respect it.
#ifndef NDEBUG
pthread_t const tid = pthread_self();
ret = pthread_set_name_np(tid, name.c_str());
#else
// Fail if not debugging.
ret = 1;
#endif
#endif
return (ret == 0);
}
#endif
#ifdef NAME_THREAD_USING_SETPROCTITLE
bool
name_thread_setproctitle(thread_name_t const& name)
{
setproctitle("%s", name.c_str());
}
#endif
#ifdef NAME_THREAD_USING_PRCTL
bool
name_thread_prctl(thread_name_t const& name)
{
int const ret = prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name.c_str()), 0, 0, 0);
return (ret == 0);
}
#endif
#ifdef NAME_THREAD_USING_WIN32
// The mechanism only make sense in debugging mode.
#ifndef NDEBUG
static void SetThreadName(DWORD dwThreadID, LPCSTR threadName);
#endif
bool
name_thread_win32(thread_name_t const& name)
{
bool ret;
#ifndef NDEBUG
static DWORD const current_thread = -1;
set_thread_name(current_thread, name.c_str());
ret = true;
#else
ret = false;
#endif
return ret;
}
// Code obtained from http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1 = caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
void
SetThreadName(DWORD dwThreadID, LPCSTR threadName)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
static DWORD const MS_VC_EXCEPTION = 0x406D1388;
RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}
#endif
}
<commit_msg>Clean up some style with the Windows support<commit_after>/*ckwg +5
* Copyright 2011-2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "utils.h"
#ifdef HAVE_PTHREAD_NAMING
#define NAME_THREAD_USING_PTHREAD
#ifdef HAVE_PTHREAD_SET_NAME_NP
#ifdef NDEBUG
// The mechanism only make sense in debugging mode.
#undef NAME_THREAD_USING_PTHREAD
#endif
#endif
#endif
#ifdef HAVE_SETPROCTITLE
#define NAME_THREAD_USING_SETPROCTITLE
#endif
#ifdef __linux__
#define NAME_THREAD_USING_PRCTL
#endif
#if defined(_WIN32) || defined(_WIN64)
#ifndef NDEBUG
#define NAME_THREAD_USING_WIN32
#endif
#endif
#ifdef NAME_THREAD_USING_PTHREAD
#include <pthread.h>
#ifdef HAVE_PTHREAD_SET_NAME_NP
#include <pthread_np.h>
#endif
#endif
#ifdef NAME_THREAD_USING_PRCTL
#include <sys/prctl.h>
#endif
#if defined(_WIN32) || defined(_WIN64)
#include <boost/scoped_array.hpp>
#include <windows.h>
#else
#include <cstdlib>
#endif
/**
* \file utils.cxx
*
* \brief Implementation of pipeline utilities.
*/
namespace vistk
{
#ifdef NAME_THREAD_USING_PTHREAD
static bool name_thread_pthread(thread_name_t const& name);
#endif
#ifdef NAME_THREAD_USING_SETPROCTITLE
static bool name_thread_setproctitle(thread_name_t const& name);
#endif
#ifdef NAME_THREAD_USING_PRCTL
static bool name_thread_prctl(thread_name_t const& name);
#endif
#ifdef NAME_THREAD_USING_WIN32
static bool name_thread_win32(thread_name_t const& name);
#endif
bool
name_thread(thread_name_t const& name)
{
bool ret = false;
#ifdef NAME_THREAD_USING_PTHREAD
if (!ret)
{
ret = name_thread_pthread(name);
}
#endif
#ifdef NAME_THREAD_USING_SETPROCTITLE
if (!ret)
{
ret = name_thread_setproctitle(name);
}
#endif
#ifdef NAME_THREAD_USING_PRCTL
if (!ret)
{
ret = name_thread_prctl(name);
}
#endif
#ifdef NAME_THREAD_USING_WIN32
if (!ret)
{
ret = name_thread_win32(name);
}
#endif
return ret;
}
envvar_value_t
get_envvar(envvar_name_t const& name)
{
envvar_value_t value;
#if defined(_WIN32) || defined(_WIN64)
char const* const name_cstr = name.c_str();
DWORD sz = GetEnvironmentVariable(name_cstr, NULL, 0);
if (sz)
{
typedef boost::scoped_array<char> raw_envvar_value_t;
raw_envvar_value_t const envvalue(new char[sz]);
sz = GetEnvironmentVariable(name_cstr, envvalue.get(), sz);
value = envvalue.get();
}
if (!sz)
{
/// \todo Log error that the environment reading failed.
}
#else
char const* const envvalue = getenv(name.c_str());
if (envvalue)
{
value = envvalue;
}
#endif
return value;
}
#ifdef NAME_THREAD_USING_PTHREAD
bool
name_thread_pthread(thread_name_t const& name)
{
int ret;
#ifdef HAVE_PTHREAD_SETNAME_NP
#ifdef PTHREAD_SETNAME_NP_TAKES_ID
pthread_t const tid = pthread_self();
ret = pthread_setname_np(tid, name.c_str());
#else
ret = pthread_setname_np(name.c_str());
#endif
#elif defined(HAVE_PTHREAD_SET_NAME_NP)
// The documentation states that it only makes sense in debugging; respect it.
#ifndef NDEBUG
pthread_t const tid = pthread_self();
ret = pthread_set_name_np(tid, name.c_str());
#else
// Fail if not debugging.
ret = 1;
#endif
#endif
return (ret == 0);
}
#endif
#ifdef NAME_THREAD_USING_SETPROCTITLE
bool
name_thread_setproctitle(thread_name_t const& name)
{
setproctitle("%s", name.c_str());
}
#endif
#ifdef NAME_THREAD_USING_PRCTL
bool
name_thread_prctl(thread_name_t const& name)
{
int const ret = prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name.c_str()), 0, 0, 0);
return (ret == 0);
}
#endif
#ifdef NAME_THREAD_USING_WIN32
// The mechanism only make sense in debugging mode.
#ifndef NDEBUG
static void set_thread_name(DWORD thread_id, LPCSTR name);
#endif
bool
name_thread_win32(thread_name_t const& name)
{
bool ret;
#ifndef NDEBUG
static DWORD const current_thread = -1;
set_thread_name(current_thread, name.c_str());
ret = true;
#else
ret = false;
#endif
return ret;
}
// Code obtained from http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1 = caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
void
set_thread_name(DWORD thread_id, LPCSTR name)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = name;
info.dwThreadID = thread_id;
info.dwFlags = 0;
__try
{
static DWORD const MS_VC_EXCEPTION = 0x406D1388;
RaiseException(MS_VC_EXCEPTION,
0,
sizeof(info) / sizeof(ULONG_PTR),
reinterpret_cast<ULONG_PTR*>&info);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}
#endif
}
<|endoftext|> |
<commit_before>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2017, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef CRC32CheckSum_INCLUDE_ONCE
#define CRC32CheckSum_INCLUDE_ONCE
#include <vlCore/VirtualFile.hpp>
namespace vl
{
/**
* Computes the a CRC32 checksum of a given buffer or VirtualFile
*/
class CRC32CheckSum
{
// Lower this if you need to limit the amount of data allocated to the stack, for example to 16K.
static const int CHUNK_SIZE = 128*1024;
public:
//! Constructor.
CRC32CheckSum() { crc32_init(); }
unsigned int compute(const void* buf, int length)
{
const unsigned char* buffer = (const unsigned char*)buf;
unsigned int mCRC32 = 0xffffffff;
while(length--)
mCRC32 = (mCRC32 >> 8) ^ crc32_table[(mCRC32 & 0xFF) ^ *buffer++];
return mCRC32 ^ 0xffffffff;
}
unsigned int compute(VirtualFile* stream)
{
std::vector<unsigned char> buffer;
buffer.resize(CHUNK_SIZE);
unsigned char *ptr = &buffer.front();
startCRC32();
for( int length = (int)stream->read(ptr, CHUNK_SIZE); length; length = (int)stream->read(ptr, CHUNK_SIZE) )
continueCRC32(ptr,length);
return finalizeCRC32();
}
void startCRC32() { mCRC32 = 0xffffffff; }
unsigned int finalizeCRC32() { return mCRC32 ^ 0xffffffff; }
void continueCRC32(unsigned char* ptr, int length)
{
while(length--)
mCRC32 = (mCRC32 >> 8) ^ crc32_table[(mCRC32 & 0xFF) ^ *ptr++];
}
protected:
void crc32_init()
{
mCRC32 = 0;
unsigned int ulPolynomial = 0x04c11db7;
for(int i = 0; i <= 0xFF; i++)
{
crc32_table[i]=reflect(i, 8) << 24;
for (int j = 0; j < 8; j++)
crc32_table[i] = (crc32_table[i] << 1) ^ (crc32_table[i] & (1 << 31) ? ulPolynomial : 0);
crc32_table[i] = reflect(crc32_table[i], 32);
}
}
unsigned int reflect(unsigned int val, char ch)
{
unsigned int refl = 0;
for(int i = 1; i < (ch + 1); i++)
{
if(val & 1)
refl |= 1 << (ch - i);
val >>= 1;
}
return refl;
}
protected:
unsigned int mCRC32;
unsigned int crc32_table[256];
};
}
#endif
<commit_msg>Fixed CRC32CheckSum::mCRC32 initialization<commit_after>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2017, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef CRC32CheckSum_INCLUDE_ONCE
#define CRC32CheckSum_INCLUDE_ONCE
#include <vlCore/VirtualFile.hpp>
namespace vl
{
/**
* Computes the a CRC32 checksum of a given buffer or VirtualFile
*/
class CRC32CheckSum
{
// Lower this if you need to limit the amount of data allocated to the stack, for example to 16K.
static const int CHUNK_SIZE = 128*1024;
public:
//! Constructor.
CRC32CheckSum() { crc32_init(); }
unsigned int compute(const void* buf, int length)
{
const unsigned char* buffer = (const unsigned char*)buf;
mCRC32 = 0xffffffff;
while(length--)
mCRC32 = (mCRC32 >> 8) ^ crc32_table[(mCRC32 & 0xFF) ^ *buffer++];
return mCRC32 ^ 0xffffffff;
}
unsigned int compute(VirtualFile* stream)
{
std::vector<unsigned char> buffer;
buffer.resize(CHUNK_SIZE);
unsigned char *ptr = &buffer.front();
startCRC32();
for( int length = (int)stream->read(ptr, CHUNK_SIZE); length; length = (int)stream->read(ptr, CHUNK_SIZE) )
continueCRC32(ptr,length);
return finalizeCRC32();
}
void startCRC32() { mCRC32 = 0xffffffff; }
unsigned int finalizeCRC32() { return mCRC32 ^ 0xffffffff; }
void continueCRC32(unsigned char* ptr, int length)
{
while(length--)
mCRC32 = (mCRC32 >> 8) ^ crc32_table[(mCRC32 & 0xFF) ^ *ptr++];
}
protected:
void crc32_init()
{
mCRC32 = 0;
unsigned int ulPolynomial = 0x04c11db7;
for(int i = 0; i <= 0xFF; i++)
{
crc32_table[i]=reflect(i, 8) << 24;
for (int j = 0; j < 8; j++)
crc32_table[i] = (crc32_table[i] << 1) ^ (crc32_table[i] & (1 << 31) ? ulPolynomial : 0);
crc32_table[i] = reflect(crc32_table[i], 32);
}
}
unsigned int reflect(unsigned int val, char ch)
{
unsigned int refl = 0;
for(int i = 1; i < (ch + 1); i++)
{
if(val & 1)
refl |= 1 << (ch - i);
val >>= 1;
}
return refl;
}
protected:
unsigned int mCRC32;
unsigned int crc32_table[256];
};
}
#endif
<|endoftext|> |
<commit_before>#include "widgets/notebookpage.hpp"
#include "colorscheme.hpp"
#include "widgets/chatwidget.hpp"
#include "widgets/notebook.hpp"
#include "widgets/notebooktab.hpp"
#include <QDebug>
#include <QHBoxLayout>
#include <QMimeData>
#include <QObject>
#include <QPainter>
#include <QVBoxLayout>
#include <QWidget>
#include <boost/foreach.hpp>
#include <algorithm>
namespace chatterino {
namespace widgets {
bool NotebookPage::isDraggingSplit = false;
ChatWidget *NotebookPage::draggingSplit = nullptr;
std::pair<int, int> NotebookPage::dropPosition = std::pair<int, int>(-1, -1);
NotebookPage::NotebookPage(ChannelManager &_channelManager, Notebook *parent, NotebookTab *_tab)
: BaseWidget(parent->colorScheme, parent)
, channelManager(_channelManager)
, completionManager(parent->completionManager)
, tab(_tab)
, dropPreview(this)
{
this->tab->page = this;
this->setLayout(&this->ui.parentLayout);
this->setHidden(true);
this->setAcceptDrops(true);
this->ui.parentLayout.addSpacing(2);
this->ui.parentLayout.addLayout(&this->ui.hbox);
this->ui.parentLayout.setMargin(0);
this->ui.hbox.setSpacing(1);
this->ui.hbox.setMargin(0);
}
std::pair<int, int> NotebookPage::removeFromLayout(ChatWidget *widget)
{
// remove reference to chat widget from chatWidgets vector
auto it = std::find(std::begin(this->chatWidgets), std::end(this->chatWidgets), widget);
if (it != std::end(this->chatWidgets)) {
this->chatWidgets.erase(it);
}
// remove from box and return location
for (int i = 0; i < this->ui.hbox.count(); ++i) {
auto vbox = static_cast<QVBoxLayout *>(this->ui.hbox.itemAt(i));
for (int j = 0; j < vbox->count(); ++j) {
if (vbox->itemAt(j)->widget() != widget) {
continue;
}
widget->setParent(nullptr);
bool isLastItem = vbox->count() == 0;
if (isLastItem) {
this->ui.hbox.removeItem(vbox);
delete vbox;
}
return std::pair<int, int>(i, isLastItem ? -1 : j);
}
}
return std::pair<int, int>(-1, -1);
}
void NotebookPage::addToLayout(ChatWidget *widget,
std::pair<int, int> position = std::pair<int, int>(-1, -1))
{
this->chatWidgets.push_back(widget);
widget->giveFocus();
// add vbox at the end
if (position.first < 0 || position.first >= this->ui.hbox.count()) {
auto vbox = new QVBoxLayout();
vbox->addWidget(widget);
this->ui.hbox.addLayout(vbox, 1);
return;
}
// insert vbox
if (position.second == -1) {
auto vbox = new QVBoxLayout();
vbox->addWidget(widget);
this->ui.hbox.insertLayout(position.first, vbox, 1);
return;
}
// add to existing vbox
auto vbox = static_cast<QVBoxLayout *>(this->ui.hbox.itemAt(position.first));
vbox->insertWidget(std::max(0, std::min(vbox->count(), position.second)), widget);
}
const std::vector<ChatWidget *> &NotebookPage::getChatWidgets() const
{
return this->chatWidgets;
}
NotebookTab *NotebookPage::getTab() const
{
return this->tab;
}
void NotebookPage::addChat(bool openChannelNameDialog)
{
ChatWidget *w = this->createChatWidget();
if (openChannelNameDialog) {
bool ret = w->showChangeChannelPopup("Open channel", true);
if (!ret) {
delete w;
return;
}
}
this->addToLayout(w, std::pair<int, int>(-1, -1));
}
void NotebookPage::enterEvent(QEvent *)
{
if (this->ui.hbox.count() == 0) {
this->setCursor(QCursor(Qt::PointingHandCursor));
} else {
this->setCursor(QCursor(Qt::ArrowCursor));
}
}
void NotebookPage::leaveEvent(QEvent *)
{
}
void NotebookPage::mouseReleaseEvent(QMouseEvent *event)
{
if (this->ui.hbox.count() == 0 && event->button() == Qt::LeftButton) {
// "Add Chat" was clicked
this->addChat(true);
this->setCursor(QCursor(Qt::ArrowCursor));
}
}
void NotebookPage::dragEnterEvent(QDragEnterEvent *event)
{
if (!event->mimeData()->hasFormat("chatterino/split"))
return;
if (isDraggingSplit) {
return;
}
this->dropRegions.clear();
if (this->ui.hbox.count() == 0) {
this->dropRegions.push_back(DropRegion(rect(), std::pair<int, int>(-1, -1)));
} else {
for (int i = 0; i < this->ui.hbox.count() + 1; ++i) {
this->dropRegions.push_back(
DropRegion(QRect(((i * 4 - 1) * width() / this->ui.hbox.count()) / 4, 0,
width() / this->ui.hbox.count() / 2 + 1, height() + 1),
std::pair<int, int>(i, -1)));
}
for (int i = 0; i < this->ui.hbox.count(); ++i) {
auto vbox = static_cast<QVBoxLayout *>(this->ui.hbox.itemAt(i));
for (int j = 0; j < vbox->count() + 1; ++j) {
this->dropRegions.push_back(DropRegion(
QRect(i * width() / this->ui.hbox.count(),
((j * 2 - 1) * height() / vbox->count()) / 2,
width() / this->ui.hbox.count() + 1, height() / vbox->count() + 1),
std::pair<int, int>(i, j)));
}
}
}
setPreviewRect(event->pos());
event->acceptProposedAction();
}
void NotebookPage::dragMoveEvent(QDragMoveEvent *event)
{
setPreviewRect(event->pos());
}
void NotebookPage::setPreviewRect(QPoint mousePos)
{
for (DropRegion region : this->dropRegions) {
if (region.rect.contains(mousePos)) {
this->dropPreview.setBounds(region.rect);
if (!this->dropPreview.isVisible()) {
this->dropPreview.show();
this->dropPreview.raise();
}
dropPosition = region.position;
return;
}
}
this->dropPreview.hide();
}
void NotebookPage::dragLeaveEvent(QDragLeaveEvent *event)
{
this->dropPreview.hide();
}
void NotebookPage::dropEvent(QDropEvent *event)
{
if (isDraggingSplit) {
event->acceptProposedAction();
NotebookPage::draggingSplit->setParent(this);
addToLayout(NotebookPage::draggingSplit, dropPosition);
}
this->dropPreview.hide();
}
void NotebookPage::paintEvent(QPaintEvent *)
{
QPainter painter(this);
if (this->ui.hbox.count() == 0) {
painter.fillRect(rect(), this->colorScheme.ChatBackground);
painter.fillRect(0, 0, width(), 2, this->colorScheme.TabSelectedBackground);
painter.setPen(this->colorScheme.Text);
painter.drawText(rect(), "Add Chat", QTextOption(Qt::AlignCenter));
} else {
//painter.fillRect(rect(), this->colorScheme.TabSelectedBackground);
painter.fillRect(rect(), QColor(127, 127, 127));
painter.fillRect(0, 0, width(), 2, this->colorScheme.TabSelectedBackground);
}
}
static std::pair<int, int> getWidgetPositionInLayout(QLayout *layout, const ChatWidget *chatWidget)
{
for (int i = 0; i < layout->count(); ++i) {
printf("xD\n");
}
return std::make_pair(-1, -1);
}
std::pair<int, int> NotebookPage::getChatPosition(const ChatWidget *chatWidget)
{
auto layout = this->ui.hbox.layout();
if (layout == nullptr) {
return std::make_pair(-1, -1);
}
return getWidgetPositionInLayout(layout, chatWidget);
}
ChatWidget *NotebookPage::createChatWidget()
{
return new ChatWidget(this->channelManager, this);
}
void NotebookPage::load(const boost::property_tree::ptree &tree)
{
try {
int column = 0;
for (const auto &v : tree.get_child("columns.")) {
int row = 0;
for (const auto &innerV : v.second.get_child("")) {
auto widget = this->createChatWidget();
widget->load(innerV.second);
addToLayout(widget, std::pair<int, int>(column, row));
++row;
}
++column;
}
} catch (boost::property_tree::ptree_error &) {
// can't read tabs
}
}
static void saveFromLayout(QLayout *layout, boost::property_tree::ptree &tree)
{
for (int i = 0; i < layout->count(); ++i) {
auto item = layout->itemAt(i);
auto innerLayout = item->layout();
if (innerLayout != nullptr) {
boost::property_tree::ptree innerLayoutTree;
saveFromLayout(innerLayout, innerLayoutTree);
if (innerLayoutTree.size() > 0) {
tree.push_back(std::make_pair("", innerLayoutTree));
}
continue;
}
auto widget = item->widget();
if (widget == nullptr) {
// This layoutitem does not manage a widget for some reason
continue;
}
ChatWidget *chatWidget = qobject_cast<ChatWidget *>(widget);
if (chatWidget != nullptr) {
boost::property_tree::ptree chat = chatWidget->save();
tree.push_back(std::make_pair("", chat));
continue;
}
}
}
boost::property_tree::ptree NotebookPage::save()
{
boost::property_tree::ptree tree;
auto layout = this->ui.hbox.layout();
saveFromLayout(layout, tree);
/*
for (const auto &chat : this->chatWidgets) {
boost::property_tree::ptree child = chat->save();
// Set child position
child.put("position", "5,3");
tree.push_back(std::make_pair("", child));
}
*/
return tree;
}
} // namespace widgets
} // namespace chatterino
<commit_msg>fixed split drag n drop<commit_after>#include "widgets/notebookpage.hpp"
#include "colorscheme.hpp"
#include "widgets/chatwidget.hpp"
#include "widgets/notebook.hpp"
#include "widgets/notebooktab.hpp"
#include <QDebug>
#include <QHBoxLayout>
#include <QMimeData>
#include <QObject>
#include <QPainter>
#include <QVBoxLayout>
#include <QWidget>
#include <boost/foreach.hpp>
#include <algorithm>
namespace chatterino {
namespace widgets {
bool NotebookPage::isDraggingSplit = false;
ChatWidget *NotebookPage::draggingSplit = nullptr;
std::pair<int, int> NotebookPage::dropPosition = std::pair<int, int>(-1, -1);
NotebookPage::NotebookPage(ChannelManager &_channelManager, Notebook *parent, NotebookTab *_tab)
: BaseWidget(parent->colorScheme, parent)
, channelManager(_channelManager)
, completionManager(parent->completionManager)
, tab(_tab)
, dropPreview(this)
{
this->tab->page = this;
this->setLayout(&this->ui.parentLayout);
this->setHidden(true);
this->setAcceptDrops(true);
this->ui.parentLayout.addSpacing(2);
this->ui.parentLayout.addLayout(&this->ui.hbox);
this->ui.parentLayout.setMargin(0);
this->ui.hbox.setSpacing(1);
this->ui.hbox.setMargin(0);
}
std::pair<int, int> NotebookPage::removeFromLayout(ChatWidget *widget)
{
// remove reference to chat widget from chatWidgets vector
auto it = std::find(std::begin(this->chatWidgets), std::end(this->chatWidgets), widget);
if (it != std::end(this->chatWidgets)) {
this->chatWidgets.erase(it);
}
// remove from box and return location
for (int i = 0; i < this->ui.hbox.count(); ++i) {
auto vbox = static_cast<QVBoxLayout *>(this->ui.hbox.itemAt(i));
for (int j = 0; j < vbox->count(); ++j) {
if (vbox->itemAt(j)->widget() != widget) {
continue;
}
widget->setParent(nullptr);
bool isLastItem = vbox->count() == 0;
if (isLastItem) {
this->ui.hbox.removeItem(vbox);
delete vbox;
}
return std::pair<int, int>(i, isLastItem ? -1 : j);
}
}
return std::pair<int, int>(-1, -1);
}
void NotebookPage::addToLayout(ChatWidget *widget,
std::pair<int, int> position = std::pair<int, int>(-1, -1))
{
this->chatWidgets.push_back(widget);
widget->giveFocus();
// add vbox at the end
if (position.first < 0 || position.first >= this->ui.hbox.count()) {
auto vbox = new QVBoxLayout();
vbox->addWidget(widget);
this->ui.hbox.addLayout(vbox, 1);
return;
}
// insert vbox
if (position.second == -1) {
auto vbox = new QVBoxLayout();
vbox->addWidget(widget);
this->ui.hbox.insertLayout(position.first, vbox, 1);
return;
}
// add to existing vbox
auto vbox = static_cast<QVBoxLayout *>(this->ui.hbox.itemAt(position.first));
vbox->insertWidget(std::max(0, std::min(vbox->count(), position.second)), widget);
}
const std::vector<ChatWidget *> &NotebookPage::getChatWidgets() const
{
return this->chatWidgets;
}
NotebookTab *NotebookPage::getTab() const
{
return this->tab;
}
void NotebookPage::addChat(bool openChannelNameDialog)
{
ChatWidget *w = this->createChatWidget();
if (openChannelNameDialog) {
bool ret = w->showChangeChannelPopup("Open channel", true);
if (!ret) {
delete w;
return;
}
}
this->addToLayout(w, std::pair<int, int>(-1, -1));
}
void NotebookPage::enterEvent(QEvent *)
{
if (this->ui.hbox.count() == 0) {
this->setCursor(QCursor(Qt::PointingHandCursor));
} else {
this->setCursor(QCursor(Qt::ArrowCursor));
}
}
void NotebookPage::leaveEvent(QEvent *)
{
}
void NotebookPage::mouseReleaseEvent(QMouseEvent *event)
{
if (this->ui.hbox.count() == 0 && event->button() == Qt::LeftButton) {
// "Add Chat" was clicked
this->addChat(true);
this->setCursor(QCursor(Qt::ArrowCursor));
}
}
void NotebookPage::dragEnterEvent(QDragEnterEvent *event)
{
if (!event->mimeData()->hasFormat("chatterino/split"))
return;
if (!isDraggingSplit) {
return;
}
this->dropRegions.clear();
if (this->ui.hbox.count() == 0) {
this->dropRegions.push_back(DropRegion(rect(), std::pair<int, int>(-1, -1)));
} else {
for (int i = 0; i < this->ui.hbox.count() + 1; ++i) {
this->dropRegions.push_back(
DropRegion(QRect(((i * 4 - 1) * width() / this->ui.hbox.count()) / 4, 0,
width() / this->ui.hbox.count() / 2 + 1, height() + 1),
std::pair<int, int>(i, -1)));
}
for (int i = 0; i < this->ui.hbox.count(); ++i) {
auto vbox = static_cast<QVBoxLayout *>(this->ui.hbox.itemAt(i));
for (int j = 0; j < vbox->count() + 1; ++j) {
this->dropRegions.push_back(DropRegion(
QRect(i * width() / this->ui.hbox.count(),
((j * 2 - 1) * height() / vbox->count()) / 2,
width() / this->ui.hbox.count() + 1, height() / vbox->count() + 1),
std::pair<int, int>(i, j)));
}
}
}
setPreviewRect(event->pos());
event->acceptProposedAction();
}
void NotebookPage::dragMoveEvent(QDragMoveEvent *event)
{
setPreviewRect(event->pos());
}
void NotebookPage::setPreviewRect(QPoint mousePos)
{
for (DropRegion region : this->dropRegions) {
if (region.rect.contains(mousePos)) {
this->dropPreview.setBounds(region.rect);
if (!this->dropPreview.isVisible()) {
this->dropPreview.show();
this->dropPreview.raise();
}
dropPosition = region.position;
return;
}
}
this->dropPreview.hide();
}
void NotebookPage::dragLeaveEvent(QDragLeaveEvent *event)
{
this->dropPreview.hide();
}
void NotebookPage::dropEvent(QDropEvent *event)
{
if (isDraggingSplit) {
event->acceptProposedAction();
NotebookPage::draggingSplit->setParent(this);
addToLayout(NotebookPage::draggingSplit, dropPosition);
}
this->dropPreview.hide();
}
void NotebookPage::paintEvent(QPaintEvent *)
{
QPainter painter(this);
if (this->ui.hbox.count() == 0) {
painter.fillRect(rect(), this->colorScheme.ChatBackground);
painter.fillRect(0, 0, width(), 2, this->colorScheme.TabSelectedBackground);
painter.setPen(this->colorScheme.Text);
painter.drawText(rect(), "Add Chat", QTextOption(Qt::AlignCenter));
} else {
//painter.fillRect(rect(), this->colorScheme.TabSelectedBackground);
painter.fillRect(rect(), QColor(127, 127, 127));
painter.fillRect(0, 0, width(), 2, this->colorScheme.TabSelectedBackground);
}
}
static std::pair<int, int> getWidgetPositionInLayout(QLayout *layout, const ChatWidget *chatWidget)
{
for (int i = 0; i < layout->count(); ++i) {
printf("xD\n");
}
return std::make_pair(-1, -1);
}
std::pair<int, int> NotebookPage::getChatPosition(const ChatWidget *chatWidget)
{
auto layout = this->ui.hbox.layout();
if (layout == nullptr) {
return std::make_pair(-1, -1);
}
return getWidgetPositionInLayout(layout, chatWidget);
}
ChatWidget *NotebookPage::createChatWidget()
{
return new ChatWidget(this->channelManager, this);
}
void NotebookPage::load(const boost::property_tree::ptree &tree)
{
try {
int column = 0;
for (const auto &v : tree.get_child("columns.")) {
int row = 0;
for (const auto &innerV : v.second.get_child("")) {
auto widget = this->createChatWidget();
widget->load(innerV.second);
addToLayout(widget, std::pair<int, int>(column, row));
++row;
}
++column;
}
} catch (boost::property_tree::ptree_error &) {
// can't read tabs
}
}
static void saveFromLayout(QLayout *layout, boost::property_tree::ptree &tree)
{
for (int i = 0; i < layout->count(); ++i) {
auto item = layout->itemAt(i);
auto innerLayout = item->layout();
if (innerLayout != nullptr) {
boost::property_tree::ptree innerLayoutTree;
saveFromLayout(innerLayout, innerLayoutTree);
if (innerLayoutTree.size() > 0) {
tree.push_back(std::make_pair("", innerLayoutTree));
}
continue;
}
auto widget = item->widget();
if (widget == nullptr) {
// This layoutitem does not manage a widget for some reason
continue;
}
ChatWidget *chatWidget = qobject_cast<ChatWidget *>(widget);
if (chatWidget != nullptr) {
boost::property_tree::ptree chat = chatWidget->save();
tree.push_back(std::make_pair("", chat));
continue;
}
}
}
boost::property_tree::ptree NotebookPage::save()
{
boost::property_tree::ptree tree;
auto layout = this->ui.hbox.layout();
saveFromLayout(layout, tree);
/*
for (const auto &chat : this->chatWidgets) {
boost::property_tree::ptree child = chat->save();
// Set child position
child.put("position", "5,3");
tree.push_back(std::make_pair("", child));
}
*/
return tree;
}
} // namespace widgets
} // namespace chatterino
<|endoftext|> |
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2015 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/gpu/trace_dump.h"
#include <gflags/gflags.h>
#include "third_party/stb/stb_image_write.h"
#include "xenia/base/logging.h"
#include "xenia/base/profiling.h"
#include "xenia/base/string.h"
#include "xenia/base/threading.h"
#include "xenia/gpu/command_processor.h"
#include "xenia/gpu/graphics_system.h"
#include "xenia/memory.h"
#include "xenia/ui/file_picker.h"
#include "xenia/ui/window.h"
#include "xenia/xbox.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#undef _CRT_SECURE_NO_WARNINGS
#undef _CRT_NONSTDC_NO_DEPRECATE
#include "third_party/stb/stb_image_write.h"
DEFINE_string(target_trace_file, "", "Specifies the trace file to load.");
DEFINE_string(trace_dump_path, "", "Output path for dumped files.");
namespace xe {
namespace gpu {
using namespace xe::gpu::xenos;
TraceDump::TraceDump() = default;
TraceDump::~TraceDump() = default;
int TraceDump::Main(const std::vector<std::wstring>& args) {
// Grab path from the flag or unnamed argument.
std::wstring path;
std::wstring output_path;
if (!FLAGS_target_trace_file.empty()) {
// Passed as a named argument.
// TODO(benvanik): find something better than gflags that supports
// unicode.
path = xe::to_wstring(FLAGS_target_trace_file);
} else if (args.size() >= 2) {
// Passed as an unnamed argument.
path = args[1];
if (args.size() >= 3) {
output_path = args[2];
}
} else {
// Open a file chooser and ask the user.
auto file_picker = xe::ui::FilePicker::Create();
file_picker->set_mode(ui::FilePicker::Mode::kOpen);
file_picker->set_type(ui::FilePicker::Type::kFile);
file_picker->set_multi_selection(false);
file_picker->set_title(L"Select Trace File");
file_picker->set_extensions({
{L"Supported Files", L"*.xenia_gpu_trace"},
{L"All Files (*.*)", L"*.*"},
});
if (file_picker->Show()) {
auto selected_files = file_picker->selected_files();
if (!selected_files.empty()) {
path = selected_files[0];
}
}
}
if (path.empty()) {
xe::FatalError("No trace file specified");
return 1;
}
// Normalize the path and make absolute.
auto abs_path = xe::to_absolute_path(path);
XELOGI("Loading trace file %ls...", abs_path.c_str());
if (!Setup()) {
xe::FatalError("Unable to setup trace dump tool");
return 1;
}
if (!Load(std::move(abs_path))) {
xe::FatalError("Unable to load trace file; not found?");
return 1;
}
// Root file name for outputs.
if (output_path.empty()) {
base_output_path_ =
xe::fix_path_separators(xe::to_wstring(FLAGS_trace_dump_path));
base_output_path_ =
xe::join_paths(base_output_path_,
xe::find_name_from_path(xe::fix_path_separators(path)));
} else {
base_output_path_ = xe::fix_path_separators(output_path);
}
// Ensure output path exists.
xe::filesystem::CreateParentFolder(base_output_path_);
return Run();
}
bool TraceDump::Setup() {
// Main display window.
loop_ = ui::Loop::Create();
window_ = xe::ui::Window::Create(loop_.get(), L"xenia-gpu-trace-dump");
loop_->PostSynchronous([&]() {
xe::threading::set_name("Win32 Loop");
if (!window_->Initialize()) {
xe::FatalError("Failed to initialize main window");
return;
}
});
window_->on_closed.AddListener([&](xe::ui::UIEvent* e) {
loop_->Quit();
XELOGI("User-initiated death!");
exit(1);
});
loop_->on_quit.AddListener([&](xe::ui::UIEvent* e) { window_.reset(); });
window_->Resize(1920, 1200);
// Create the emulator but don't initialize so we can setup the window.
emulator_ = std::make_unique<Emulator>(L"");
X_STATUS result =
emulator_->Setup(window_.get(), nullptr,
[this]() { return CreateGraphicsSystem(); }, nullptr);
if (XFAILED(result)) {
XELOGE("Failed to setup emulator: %.8X", result);
return false;
}
memory_ = emulator_->memory();
graphics_system_ = emulator_->graphics_system();
window_->on_key_char.AddListener([&](xe::ui::KeyEvent* e) {
if (e->key_code() == 0x74 /* VK_F5 */) {
graphics_system_->ClearCaches();
e->set_handled(true);
}
});
player_ = std::make_unique<TracePlayer>(loop_.get(), graphics_system_);
window_->on_painting.AddListener([&](xe::ui::UIEvent* e) {
// Update titlebar status.
auto file_name = xe::find_name_from_path(trace_file_path_);
std::wstring title = std::wstring(L"Xenia GPU Trace Dump: ") + file_name;
if (player_->is_playing_trace()) {
int percent =
static_cast<int>(player_->playback_percent() / 10000.0 * 100.0);
title += xe::format_string(L" (%d%%)", percent);
}
window_->set_title(title);
// Continuous paint.
window_->Invalidate();
});
window_->Invalidate();
return true;
}
bool TraceDump::Load(std::wstring trace_file_path) {
trace_file_path_ = std::move(trace_file_path);
if (!player_->Open(trace_file_path_)) {
XELOGE("Could not load trace file");
return false;
}
return true;
}
int TraceDump::Run() {
loop_->Post([&]() {
player_->SeekFrame(0);
player_->SeekCommand(
static_cast<int>(player_->current_frame()->commands.size() - 1));
});
player_->WaitOnPlayback();
loop_->PostSynchronous([&]() {
// Breathe.
});
loop_->PostSynchronous([&]() {
// Breathe.
});
xe::threading::Fence capture_fence;
int result = 0;
loop_->PostDelayed(
[&]() {
// Capture.
auto raw_image = graphics_system_->Capture();
if (!raw_image) {
// Failed to capture anything.
result = -1;
capture_fence.Signal();
return;
}
// Save framebuffer png.
std::string png_path = xe::to_string(base_output_path_ + L".png");
stbi_write_png(png_path.c_str(), static_cast<int>(raw_image->width),
static_cast<int>(raw_image->height), 4,
raw_image->data.data(),
static_cast<int>(raw_image->stride));
result = 0;
capture_fence.Signal();
},
50);
capture_fence.Wait();
// Wait until we are exited.
loop_->Quit();
loop_->AwaitQuit();
Profiler::Shutdown();
window_.reset();
loop_.reset();
player_.reset();
emulator_.reset();
return result;
}
} // namespace gpu
} // namespace xe
<commit_msg>[GPU] Don't bother redrawing the trace dump window<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2015 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/gpu/trace_dump.h"
#include <gflags/gflags.h>
#include "third_party/stb/stb_image_write.h"
#include "xenia/base/logging.h"
#include "xenia/base/profiling.h"
#include "xenia/base/string.h"
#include "xenia/base/threading.h"
#include "xenia/gpu/command_processor.h"
#include "xenia/gpu/graphics_system.h"
#include "xenia/memory.h"
#include "xenia/ui/file_picker.h"
#include "xenia/ui/window.h"
#include "xenia/xbox.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#undef _CRT_SECURE_NO_WARNINGS
#undef _CRT_NONSTDC_NO_DEPRECATE
#include "third_party/stb/stb_image_write.h"
DEFINE_string(target_trace_file, "", "Specifies the trace file to load.");
DEFINE_string(trace_dump_path, "", "Output path for dumped files.");
namespace xe {
namespace gpu {
using namespace xe::gpu::xenos;
TraceDump::TraceDump() = default;
TraceDump::~TraceDump() = default;
int TraceDump::Main(const std::vector<std::wstring>& args) {
// Grab path from the flag or unnamed argument.
std::wstring path;
std::wstring output_path;
if (!FLAGS_target_trace_file.empty()) {
// Passed as a named argument.
// TODO(benvanik): find something better than gflags that supports
// unicode.
path = xe::to_wstring(FLAGS_target_trace_file);
} else if (args.size() >= 2) {
// Passed as an unnamed argument.
path = args[1];
if (args.size() >= 3) {
output_path = args[2];
}
} else {
// Open a file chooser and ask the user.
auto file_picker = xe::ui::FilePicker::Create();
file_picker->set_mode(ui::FilePicker::Mode::kOpen);
file_picker->set_type(ui::FilePicker::Type::kFile);
file_picker->set_multi_selection(false);
file_picker->set_title(L"Select Trace File");
file_picker->set_extensions({
{L"Supported Files", L"*.xenia_gpu_trace"},
{L"All Files (*.*)", L"*.*"},
});
if (file_picker->Show()) {
auto selected_files = file_picker->selected_files();
if (!selected_files.empty()) {
path = selected_files[0];
}
}
}
if (path.empty()) {
xe::FatalError("No trace file specified");
return 1;
}
// Normalize the path and make absolute.
auto abs_path = xe::to_absolute_path(path);
XELOGI("Loading trace file %ls...", abs_path.c_str());
if (!Setup()) {
xe::FatalError("Unable to setup trace dump tool");
return 1;
}
if (!Load(std::move(abs_path))) {
xe::FatalError("Unable to load trace file; not found?");
return 1;
}
// Root file name for outputs.
if (output_path.empty()) {
base_output_path_ =
xe::fix_path_separators(xe::to_wstring(FLAGS_trace_dump_path));
base_output_path_ =
xe::join_paths(base_output_path_,
xe::find_name_from_path(xe::fix_path_separators(path)));
} else {
base_output_path_ = xe::fix_path_separators(output_path);
}
// Ensure output path exists.
xe::filesystem::CreateParentFolder(base_output_path_);
return Run();
}
bool TraceDump::Setup() {
// Main display window.
loop_ = ui::Loop::Create();
window_ = xe::ui::Window::Create(loop_.get(), L"xenia-gpu-trace-dump");
loop_->PostSynchronous([&]() {
xe::threading::set_name("Win32 Loop");
if (!window_->Initialize()) {
xe::FatalError("Failed to initialize main window");
return;
}
});
window_->on_closed.AddListener([&](xe::ui::UIEvent* e) {
loop_->Quit();
XELOGI("User-initiated death!");
exit(1);
});
loop_->on_quit.AddListener([&](xe::ui::UIEvent* e) { window_.reset(); });
window_->Resize(1280, 720);
// Create the emulator but don't initialize so we can setup the window.
emulator_ = std::make_unique<Emulator>(L"");
X_STATUS result =
emulator_->Setup(window_.get(), nullptr,
[this]() { return CreateGraphicsSystem(); }, nullptr);
if (XFAILED(result)) {
XELOGE("Failed to setup emulator: %.8X", result);
return false;
}
memory_ = emulator_->memory();
graphics_system_ = emulator_->graphics_system();
window_->on_key_char.AddListener([&](xe::ui::KeyEvent* e) {
if (e->key_code() == 0x74 /* VK_F5 */) {
graphics_system_->ClearCaches();
e->set_handled(true);
}
});
player_ = std::make_unique<TracePlayer>(loop_.get(), graphics_system_);
return true;
}
bool TraceDump::Load(std::wstring trace_file_path) {
trace_file_path_ = std::move(trace_file_path);
if (!player_->Open(trace_file_path_)) {
XELOGE("Could not load trace file");
return false;
}
return true;
}
int TraceDump::Run() {
loop_->Post([&]() {
player_->SeekFrame(0);
player_->SeekCommand(
static_cast<int>(player_->current_frame()->commands.size() - 1));
});
player_->WaitOnPlayback();
loop_->PostSynchronous([&]() {
// Breathe.
});
loop_->PostSynchronous([&]() {
// Breathe.
});
int result = 0;
auto capture_event = xe::threading::Event::CreateManualResetEvent(false);
loop_->PostDelayed(
[&]() {
// Capture.
auto raw_image = graphics_system_->Capture();
if (!raw_image) {
// Failed to capture anything.
result = -1;
capture_event->Set();
return;
}
// Save framebuffer png.
std::string png_path = xe::to_string(base_output_path_ + L".png");
stbi_write_png(png_path.c_str(), static_cast<int>(raw_image->width),
static_cast<int>(raw_image->height), 4,
raw_image->data.data(),
static_cast<int>(raw_image->stride));
result = 0;
capture_event->Set();
},
50);
while (xe::threading::Wait(capture_event.get(), false,
std::chrono::milliseconds(1)) ==
xe::threading::WaitResult::kTimeout) {
// Update titlebar status.
auto file_name = xe::find_name_from_path(trace_file_path_);
std::wstring title = std::wstring(L"Xenia GPU Trace Dump: ") + file_name;
if (player_->is_playing_trace()) {
int percent =
static_cast<int>(player_->playback_percent() / 10000.0 * 100.0);
title += xe::format_string(L" (%d%%)", percent);
}
window_->set_title(title);
}
// Profiler must exit before the window is closed.
Profiler::Shutdown();
// Wait until we are exited.
loop_->Quit();
loop_->AwaitQuit();
window_.reset();
loop_.reset();
player_.reset();
emulator_.reset();
return result;
}
} // namespace gpu
} // namespace xe
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
#include <set>
#include <string>
#include <mesos/zookeeper/contender.hpp>
#include <mesos/zookeeper/detector.hpp>
#include <mesos/zookeeper/group.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/id.hpp>
#include <stout/check.hpp>
#include <stout/lambda.hpp>
#include <stout/option.hpp>
#include <stout/some.hpp>
using namespace process;
using std::set;
using std::string;
namespace zookeeper {
class LeaderContenderProcess : public Process<LeaderContenderProcess>
{
public:
LeaderContenderProcess(
Group* group,
const string& data,
const Option<string>& label);
virtual ~LeaderContenderProcess();
// LeaderContender implementation.
Future<Future<Nothing> > contend();
Future<bool> withdraw();
protected:
virtual void finalize();
private:
// Invoked when we have joined the group (or failed to do so).
void joined();
// Invoked when the group membership is cancelled.
void cancelled(const Future<bool>& result);
// Helper for cancelling the Group membership.
void cancel();
Group* group;
const string data;
const Option<string> label;
// The contender's state transitions from contending -> watching ->
// withdrawing or contending -> withdrawing. Each state is
// identified by the corresponding Option<Promise> being assigned.
// Note that these Option<Promise>s are never reset to None once it
// is assigned.
// Holds the promise for the future for contend().
Option<Promise<Future<Nothing> >*> contending;
// Holds the promise for the inner future enclosed by contend()'s
// result which is satisfied when the contender's candidacy is
// lost.
Option<Promise<Nothing>*> watching;
// Holds the promise for the future for withdraw().
Option<Promise<bool>*> withdrawing;
// Stores the result for joined().
Future<Group::Membership> candidacy;
};
LeaderContenderProcess::LeaderContenderProcess(
Group* _group,
const string& _data,
const Option<string>& _label)
: ProcessBase(ID::generate("leader-contender")),
group(_group),
data(_data),
label(_label) {}
LeaderContenderProcess::~LeaderContenderProcess()
{
if (contending.isSome()) {
contending.get()->discard();
delete contending.get();
contending = None();
}
if (watching.isSome()) {
watching.get()->discard();
delete watching.get();
watching = None();
}
if (withdrawing.isSome()) {
withdrawing.get()->discard();
delete withdrawing.get();
withdrawing = None();
}
}
void LeaderContenderProcess::finalize()
{
// We do not wait for the result here because the Group keeps
// retrying (even after the contender is destroyed) until it
// succeeds so the old membership is eventually going to be
// cancelled.
// There is a tricky situation where the contender terminates after
// it has contended but before it is notified of the obtained
// membership. In this case the membership is not cancelled during
// contender destruction. The client thus should use withdraw() to
// wait for the membership to be first obtained and then cancelled.
cancel();
}
Future<Future<Nothing> > LeaderContenderProcess::contend()
{
if (contending.isSome()) {
return Failure("Cannot contend more than once");
}
LOG(INFO) << "Joining the ZK group";
candidacy = group->join(data, label);
candidacy
.onAny(defer(self(), &Self::joined));
// Okay, we wait and see what unfolds.
contending = new Promise<Future<Nothing> >();
return contending.get()->future();
}
Future<bool> LeaderContenderProcess::withdraw()
{
if (contending.isNone()) {
// Nothing to withdraw because the contender has not contended.
return false;
}
if (withdrawing.isSome()) {
// Repeated calls to withdraw get the same result.
return withdrawing.get();
}
withdrawing = new Promise<bool>();
CHECK(!candidacy.isDiscarded());
if (candidacy.isPending()) {
// If we have not obtained the candidacy yet, we withdraw after
// it is obtained.
LOG(INFO) << "Withdraw requested before the candidacy is obtained; will "
<< "withdraw after it happens";
candidacy.onAny(defer(self(), &Self::cancel));
} else if (candidacy.isReady()) {
cancel();
} else {
// We have failed to obtain the candidacy so we do not need to
// cancel it.
return false;
}
return withdrawing.get()->future();
}
void LeaderContenderProcess::cancel()
{
if (!candidacy.isReady()) {
// Nothing to cancel.
if (withdrawing.isSome()) {
withdrawing.get()->set(false);
}
return;
}
LOG(INFO) << "Now cancelling the membership: " << candidacy.get().id();
group->cancel(candidacy.get())
.onAny(defer(self(), &Self::cancelled, lambda::_1));
}
void LeaderContenderProcess::cancelled(const Future<bool>& result)
{
CHECK(candidacy.isReady());
LOG(INFO) << "Membership cancelled: " << candidacy.get().id();
// Can be called as a result of either withdraw() or server side
// expiration.
CHECK(withdrawing.isSome() || watching.isSome());
CHECK(!result.isDiscarded());
if (result.isFailed()) {
if (withdrawing.isSome()) {
withdrawing.get()->fail(result.failure());
}
if (watching.isSome()) {
watching.get()->fail(result.failure());
}
} else {
if (withdrawing.isSome()) {
withdrawing.get()->set(result);
}
if (watching.isSome()) {
watching.get()->set(Nothing());
}
}
}
void LeaderContenderProcess::joined()
{
CHECK(!candidacy.isDiscarded());
// Cannot be watching because the candidacy is not obtained yet.
CHECK_NONE(watching);
CHECK_SOME(contending);
if (candidacy.isFailed()) {
// The promise 'withdrawing' will be set to false in cancel().
contending.get()->fail(candidacy.failure());
return;
}
if (withdrawing.isSome()) {
LOG(INFO) << "Joined group after the contender started withdrawing";
// The promise 'withdrawing' will be set to 'false' in subsequent
// 'cancel()' call.
return;
}
LOG(INFO) << "New candidate (id='" << candidacy.get().id()
<< "') has entered the contest for leadership";
// Transition to 'watching' state.
watching = new Promise<Nothing>();
// Notify the client.
if (contending.get()->set(watching.get()->future())) {
// Continue to watch that our membership is not removed (if the
// client still cares about it).
candidacy.get().cancelled()
.onAny(defer(self(), &Self::cancelled, lambda::_1));
}
}
LeaderContender::LeaderContender(
Group* group,
const string& data,
const Option<string>& label)
{
process = new LeaderContenderProcess(group, data, label);
spawn(process);
}
LeaderContender::~LeaderContender()
{
terminate(process);
process::wait(process);
delete process;
}
Future<Future<Nothing> > LeaderContender::contend()
{
return dispatch(process, &LeaderContenderProcess::contend);
}
Future<bool> LeaderContender::withdraw()
{
return dispatch(process, &LeaderContenderProcess::withdraw);
}
} // namespace zookeeper {
<commit_msg>Replaced CHECK with CHECK_READY.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
#include <string>
#include <mesos/zookeeper/contender.hpp>
#include <mesos/zookeeper/detector.hpp>
#include <mesos/zookeeper/group.hpp>
#include <process/check.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/id.hpp>
#include <stout/lambda.hpp>
#include <stout/option.hpp>
using namespace process;
using std::string;
namespace zookeeper {
class LeaderContenderProcess : public Process<LeaderContenderProcess>
{
public:
LeaderContenderProcess(
Group* group,
const string& data,
const Option<string>& label);
virtual ~LeaderContenderProcess();
// LeaderContender implementation.
Future<Future<Nothing> > contend();
Future<bool> withdraw();
protected:
virtual void finalize();
private:
// Invoked when we have joined the group (or failed to do so).
void joined();
// Invoked when the group membership is cancelled.
void cancelled(const Future<bool>& result);
// Helper for cancelling the Group membership.
void cancel();
Group* group;
const string data;
const Option<string> label;
// The contender's state transitions from contending -> watching ->
// withdrawing or contending -> withdrawing. Each state is
// identified by the corresponding Option<Promise> being assigned.
// Note that these Option<Promise>s are never reset to None once it
// is assigned.
// Holds the promise for the future for contend().
Option<Promise<Future<Nothing> >*> contending;
// Holds the promise for the inner future enclosed by contend()'s
// result which is satisfied when the contender's candidacy is
// lost.
Option<Promise<Nothing>*> watching;
// Holds the promise for the future for withdraw().
Option<Promise<bool>*> withdrawing;
// Stores the result for joined().
Future<Group::Membership> candidacy;
};
LeaderContenderProcess::LeaderContenderProcess(
Group* _group,
const string& _data,
const Option<string>& _label)
: ProcessBase(ID::generate("leader-contender")),
group(_group),
data(_data),
label(_label) {}
LeaderContenderProcess::~LeaderContenderProcess()
{
if (contending.isSome()) {
contending.get()->discard();
delete contending.get();
contending = None();
}
if (watching.isSome()) {
watching.get()->discard();
delete watching.get();
watching = None();
}
if (withdrawing.isSome()) {
withdrawing.get()->discard();
delete withdrawing.get();
withdrawing = None();
}
}
void LeaderContenderProcess::finalize()
{
// We do not wait for the result here because the Group keeps
// retrying (even after the contender is destroyed) until it
// succeeds so the old membership is eventually going to be
// cancelled.
// There is a tricky situation where the contender terminates after
// it has contended but before it is notified of the obtained
// membership. In this case the membership is not cancelled during
// contender destruction. The client thus should use withdraw() to
// wait for the membership to be first obtained and then cancelled.
cancel();
}
Future<Future<Nothing> > LeaderContenderProcess::contend()
{
if (contending.isSome()) {
return Failure("Cannot contend more than once");
}
LOG(INFO) << "Joining the ZK group";
candidacy = group->join(data, label);
candidacy
.onAny(defer(self(), &Self::joined));
// Okay, we wait and see what unfolds.
contending = new Promise<Future<Nothing> >();
return contending.get()->future();
}
Future<bool> LeaderContenderProcess::withdraw()
{
if (contending.isNone()) {
// Nothing to withdraw because the contender has not contended.
return false;
}
if (withdrawing.isSome()) {
// Repeated calls to withdraw get the same result.
return withdrawing.get();
}
withdrawing = new Promise<bool>();
CHECK(!candidacy.isDiscarded());
if (candidacy.isPending()) {
// If we have not obtained the candidacy yet, we withdraw after
// it is obtained.
LOG(INFO) << "Withdraw requested before the candidacy is obtained; will "
<< "withdraw after it happens";
candidacy.onAny(defer(self(), &Self::cancel));
} else if (candidacy.isReady()) {
cancel();
} else {
// We have failed to obtain the candidacy so we do not need to
// cancel it.
return false;
}
return withdrawing.get()->future();
}
void LeaderContenderProcess::cancel()
{
if (!candidacy.isReady()) {
// Nothing to cancel.
if (withdrawing.isSome()) {
withdrawing.get()->set(false);
}
return;
}
LOG(INFO) << "Now cancelling the membership: " << candidacy.get().id();
group->cancel(candidacy.get())
.onAny(defer(self(), &Self::cancelled, lambda::_1));
}
void LeaderContenderProcess::cancelled(const Future<bool>& result)
{
CHECK_READY(candidacy);
LOG(INFO) << "Membership cancelled: " << candidacy.get().id();
// Can be called as a result of either withdraw() or server side
// expiration.
CHECK(withdrawing.isSome() || watching.isSome());
CHECK(!result.isDiscarded());
if (result.isFailed()) {
if (withdrawing.isSome()) {
withdrawing.get()->fail(result.failure());
}
if (watching.isSome()) {
watching.get()->fail(result.failure());
}
} else {
if (withdrawing.isSome()) {
withdrawing.get()->set(result);
}
if (watching.isSome()) {
watching.get()->set(Nothing());
}
}
}
void LeaderContenderProcess::joined()
{
CHECK(!candidacy.isDiscarded());
// Cannot be watching because the candidacy is not obtained yet.
CHECK_NONE(watching);
CHECK_SOME(contending);
if (candidacy.isFailed()) {
// The promise 'withdrawing' will be set to false in cancel().
contending.get()->fail(candidacy.failure());
return;
}
if (withdrawing.isSome()) {
LOG(INFO) << "Joined group after the contender started withdrawing";
// The promise 'withdrawing' will be set to 'false' in subsequent
// 'cancel()' call.
return;
}
LOG(INFO) << "New candidate (id='" << candidacy.get().id()
<< "') has entered the contest for leadership";
// Transition to 'watching' state.
watching = new Promise<Nothing>();
// Notify the client.
if (contending.get()->set(watching.get()->future())) {
// Continue to watch that our membership is not removed (if the
// client still cares about it).
candidacy.get().cancelled()
.onAny(defer(self(), &Self::cancelled, lambda::_1));
}
}
LeaderContender::LeaderContender(
Group* group,
const string& data,
const Option<string>& label)
{
process = new LeaderContenderProcess(group, data, label);
spawn(process);
}
LeaderContender::~LeaderContender()
{
terminate(process);
process::wait(process);
delete process;
}
Future<Future<Nothing> > LeaderContender::contend()
{
return dispatch(process, &LeaderContenderProcess::contend);
}
Future<bool> LeaderContender::withdraw()
{
return dispatch(process, &LeaderContenderProcess::withdraw);
}
} // namespace zookeeper {
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "Sleep.h"
#include "ThreadPool.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
class ThreadPool::MyRunnable_ : public IRunnable {
public:
MyRunnable_ (ThreadPool& threadPool)
: fThreadPool_ (threadPool)
, fCurTask_ ()
, fNextTask_ ()
, fCurTaskUpdateCritSection_ ()
{
}
public:
ThreadPool::TaskType GetCurrentTask () const
{
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
// THIS CODE IS TOO SUBTLE - BUT BECAUSE OF HOW THIS IS CALLED - fNextTask_ will NEVER be in the middle of being updated during this code - so this test is OK
// Caller is never in the middle of doing a WaitForNextTask - and because we have this lock - we aren't updateing fCurTask_ or fNextTask_ either
Assert (fCurTask_.IsNull () or fNextTask_.IsNull ()); // one or both must be null
return fCurTask_.IsNull ()? fNextTask_ : fCurTask_;
}
public:
virtual void Run () override
{
// For NOW - allow ThreadAbort to just kill this thread. In the future - we may want to implement some sort of restartability
// Keep grabbing new tasks, and running them
while (true) {
{
fThreadPool_.WaitForNextTask_ (&fNextTask_); // This will block INDEFINITELY until ThreadAbort throws out or we have a new task to run
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
Assert (not fNextTask_.IsNull ());
Assert (fCurTask_.IsNull ());
fCurTask_ = fNextTask_;
fNextTask_.clear ();
Assert (not fCurTask_.IsNull ());
Assert (fNextTask_.IsNull ());
}
try {
fCurTask_->Run ();
fCurTask_.clear ();
}
catch (const ThreadAbortException&) {
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
fCurTask_.clear ();
throw; // cancel this thread
}
catch (...) {
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
fCurTask_.clear ();
// other exceptions WARNING WITH DEBUG MESSAGE - but otehrwise - EAT/IGNORE
}
}
}
private:
ThreadPool& fThreadPool_;
mutable CriticalSection fCurTaskUpdateCritSection_;
ThreadPool::TaskType fCurTask_;
ThreadPool::TaskType fNextTask_;
public:
DECLARE_USE_BLOCK_ALLOCATION(MyRunnable_);
};
/*
********************************************************************************
********************************* Execution::ThreadPool ************************
********************************************************************************
*/
ThreadPool::ThreadPool (unsigned int nThreads)
: fCriticalSection_ ()
, fAborted_ (false)
, fThreads_ ()
, fTasks_ ()
, fTasksAdded_ ()
{
SetPoolSize (nThreads);
}
unsigned int ThreadPool::GetPoolSize () const
{
AutoCriticalSection critSection (fCriticalSection_);
return fThreads_.size ();
}
void ThreadPool::SetPoolSize (unsigned int poolSize)
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::SetPoolSize"));
Require (not fAborted_);
AutoCriticalSection critSection (fCriticalSection_);
fThreads_.reserve (poolSize);
while (poolSize > fThreads_.size ()) {
fThreads_.push_back (mkThread_ ());
}
if (poolSize < fThreads_.size ()) {
AssertNotImplemented ();
// MUST STOP THREADS and WAIT FOR THEM TO BE DONE (OR STORE THEM SOMEPLACE ELSE - NO - I THINK MUST ABORTANDWAIT(). Unsure.
// For now - just assert!!!
// TODO:
// (1) HOIRRIBLE - NOW
fThreads_.resize (poolSize); // remove some off the end. OK if they are running?
}
}
void ThreadPool::AddTask (const TaskType& task)
{
//Debug::TraceContextBumper ctx (TSTR ("ThreadPool::AddTask"));
Require (not fAborted_);
{
AutoCriticalSection critSection (fCriticalSection_);
fTasks_.push_back (task);
}
// Notify any waiting threads to wakeup and claim the next task
fTasksAdded_.Set ();
}
void ThreadPool::AbortTask (const TaskType& task, Time::DurationSecondsType timeout)
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::AbortTask"));
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
for (list<TaskType>::iterator i = fTasks_.begin (); i != fTasks_.end (); ++i) {
if (*i == task) {
fTasks_.erase (i);
return;
}
}
}
// If we got here - its NOT in the task Q, so maybe its already running.
//
//
// TODO:
// We walk the list of existing threads and ask each one if its (indirected - running task) is the given one and abort that task.
// But that requires we can RESTART an ABORTED thread (or that we remove it from the list - maybe thats better). THat COULD be OK
// actually since it involves on API changes and makes sense. The only slight issue is a peformace one but probably for soemthing
// quite rare.
//
// Anyhow SB OK for now to just not allow aborting a task which has already started....
Thread thread2Kill;
{
AutoCriticalSection critSection (fCriticalSection_);
for (vector<Thread>::iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> ct = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (task == ct) {
thread2Kill = *i;
*i = mkThread_ ();
break;
}
}
}
if (not thread2Kill.GetStatus () != Thread::eNull) {
thread2Kill.AbortAndWaitForDone (timeout);
}
}
bool ThreadPool::IsPresent (const TaskType& task) const
{
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
for (list<TaskType>::const_iterator i = fTasks_.begin (); i != fTasks_.end (); ++i) {
if (*i == task) {
return true;
}
}
}
return IsRunning (task);
}
bool ThreadPool::IsRunning (const TaskType& task) const
{
Require (not task.IsNull ());
{
AutoCriticalSection critSection (fCriticalSection_);
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> rTask = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (task == rTask) {
return true;
}
}
}
return false;
}
void ThreadPool::WaitForTask (const TaskType& task, Time::DurationSecondsType timeout) const
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::WaitForTask"));
// Inefficient / VERY SLOPPY impl
Time::DurationSecondsType endAt = timeout + Time::GetTickCount ();
while (true) {
if (not IsPresent (task)) {
return;
}
Time::DurationSecondsType remaining = timeout - Time::GetTickCount ();
if (remaining <= 0.0) {
DoThrow (WaitTimedOutException ());
}
Execution::Sleep (min (remaining, 1.0));
}
}
vector<ThreadPool::TaskType> ThreadPool::GetTasks () const
{
vector<ThreadPool::TaskType> result;
{
AutoCriticalSection critSection (fCriticalSection_);
result.reserve (fTasks_.size () + fThreads_.size ());
result.insert (result.begin (), fTasks_.begin (), fTasks_.end ()); // copy pending tasks
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> task = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (not task.IsNull ()) {
result.push_back (task);
}
}
}
return result;
}
vector<ThreadPool::TaskType> ThreadPool::GetRunningTasks () const
{
vector<ThreadPool::TaskType> result;
{
AutoCriticalSection critSection (fCriticalSection_);
result.reserve (fThreads_.size ());
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> task = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (not task.IsNull ()) {
result.push_back (task);
}
}
}
return result;
}
size_t ThreadPool::GetTasksCount () const
{
size_t count = 0;
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
count += fTasks_.size ();
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> task = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (not task.IsNull ()) {
count++;
}
}
}
return count;
}
void ThreadPool::WaitForDone (Time::DurationSecondsType timeout) const
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::WaitForDone"));
Require (fAborted_);
{
Time::DurationSecondsType endAt = timeout + Time::GetTickCount ();
AutoCriticalSection critSection (fCriticalSection_);
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
i->WaitForDone (endAt - Time::GetTickCount ());
}
}
}
void ThreadPool::Abort ()
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::Abort"));
fAborted_ = true;
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
fTasks_.clear ();
for (vector<Thread>::iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
i->Abort ();
}
}
}
void ThreadPool::AbortAndWaitForDone (Time::DurationSecondsType timeout)
{
Abort ();
WaitForDone (timeout);
}
// THIS is called NOT from 'this' - but from the context of an OWNED thread of the pool
void ThreadPool::WaitForNextTask_ (TaskType* result)
{
RequireNotNull (result);
if (fAborted_) {
Execution::DoThrow (ThreadAbortException ());
}
while (true) {
{
AutoCriticalSection critSection (fCriticalSection_);
if (not fTasks_.empty ()) {
*result = fTasks_.front ();
fTasks_.pop_front ();
DbgTrace ("ThreadPool::WaitForNextTask_ () is starting a new task");
return;
}
}
// Prevent spinwaiting... This event is SET when any new item arrives
//DbgTrace ("ThreadPool::WaitForNextTask_ () - about to wait for added tasks");
fTasksAdded_.Wait ();
//DbgTrace ("ThreadPool::WaitForNextTask_ () - completed wait for added tasks");
}
}
Thread ThreadPool::mkThread_ ()
{
Thread t = Thread (SharedPtr<IRunnable> (new ThreadPool::MyRunnable_ (*this))); // ADD MY THREADOBJ
t.SetThreadName (L"Thread Pool");
t.Start ();
return t;
}
<commit_msg>comments<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#include "../StroikaPreComp.h"
#include "Sleep.h"
#include "ThreadPool.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Execution;
class ThreadPool::MyRunnable_ : public IRunnable {
public:
MyRunnable_ (ThreadPool& threadPool)
: fThreadPool_ (threadPool)
, fCurTask_ ()
, fNextTask_ ()
, fCurTaskUpdateCritSection_ ()
{
}
public:
ThreadPool::TaskType GetCurrentTask () const
{
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
// THIS CODE IS TOO SUBTLE - BUT BECAUSE OF HOW THIS IS CALLED - fNextTask_ will NEVER be in the middle of being updated during this code - so this test is OK
// Caller is never in the middle of doing a WaitForNextTask - and because we have this lock - we aren't updateing fCurTask_ or fNextTask_ either
Assert (fCurTask_.IsNull () or fNextTask_.IsNull ()); // one or both must be null
return fCurTask_.IsNull ()? fNextTask_ : fCurTask_;
}
public:
virtual void Run () override
{
// For NOW - allow ThreadAbort to just kill this thread. In the future - we may want to implement some sort of restartability
// Keep grabbing new tasks, and running them
while (true) {
{
fThreadPool_.WaitForNextTask_ (&fNextTask_); // This will block INDEFINITELY until ThreadAbort throws out or we have a new task to run
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
Assert (not fNextTask_.IsNull ());
Assert (fCurTask_.IsNull ());
fCurTask_ = fNextTask_;
fNextTask_.clear ();
Assert (not fCurTask_.IsNull ());
Assert (fNextTask_.IsNull ());
}
try {
fCurTask_->Run ();
fCurTask_.clear ();
}
catch (const ThreadAbortException&) {
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
fCurTask_.clear ();
throw; // cancel this thread
}
catch (...) {
AutoCriticalSection critSect (fCurTaskUpdateCritSection_);
fCurTask_.clear ();
// other exceptions WARNING WITH DEBUG MESSAGE - but otehrwise - EAT/IGNORE
}
}
}
private:
ThreadPool& fThreadPool_;
mutable CriticalSection fCurTaskUpdateCritSection_;
ThreadPool::TaskType fCurTask_;
ThreadPool::TaskType fNextTask_;
public:
DECLARE_USE_BLOCK_ALLOCATION(MyRunnable_);
};
/*
********************************************************************************
****************************** Execution::ThreadPool ***************************
********************************************************************************
*/
ThreadPool::ThreadPool (unsigned int nThreads)
: fCriticalSection_ ()
, fAborted_ (false)
, fThreads_ ()
, fTasks_ ()
, fTasksAdded_ ()
{
SetPoolSize (nThreads);
}
unsigned int ThreadPool::GetPoolSize () const
{
AutoCriticalSection critSection (fCriticalSection_);
return fThreads_.size ();
}
void ThreadPool::SetPoolSize (unsigned int poolSize)
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::SetPoolSize"));
Require (not fAborted_);
AutoCriticalSection critSection (fCriticalSection_);
fThreads_.reserve (poolSize);
while (poolSize > fThreads_.size ()) {
fThreads_.push_back (mkThread_ ());
}
if (poolSize < fThreads_.size ()) {
AssertNotImplemented ();
// MUST STOP THREADS and WAIT FOR THEM TO BE DONE (OR STORE THEM SOMEPLACE ELSE - NO - I THINK MUST ABORTANDWAIT(). Unsure.
// For now - just assert!!!
// TODO:
// (1) HOIRRIBLE - NOW
fThreads_.resize (poolSize); // remove some off the end. OK if they are running?
}
}
void ThreadPool::AddTask (const TaskType& task)
{
//Debug::TraceContextBumper ctx (TSTR ("ThreadPool::AddTask"));
Require (not fAborted_);
{
AutoCriticalSection critSection (fCriticalSection_);
fTasks_.push_back (task);
}
// Notify any waiting threads to wakeup and claim the next task
fTasksAdded_.Set ();
}
void ThreadPool::AbortTask (const TaskType& task, Time::DurationSecondsType timeout)
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::AbortTask"));
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
for (list<TaskType>::iterator i = fTasks_.begin (); i != fTasks_.end (); ++i) {
if (*i == task) {
fTasks_.erase (i);
return;
}
}
}
// If we got here - its NOT in the task Q, so maybe its already running.
//
//
// TODO:
// We walk the list of existing threads and ask each one if its (indirected - running task) is the given one and abort that task.
// But that requires we can RESTART an ABORTED thread (or that we remove it from the list - maybe thats better). THat COULD be OK
// actually since it involves on API changes and makes sense. The only slight issue is a peformace one but probably for soemthing
// quite rare.
//
// Anyhow SB OK for now to just not allow aborting a task which has already started....
Thread thread2Kill;
{
AutoCriticalSection critSection (fCriticalSection_);
for (vector<Thread>::iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> ct = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (task == ct) {
thread2Kill = *i;
*i = mkThread_ ();
break;
}
}
}
if (not thread2Kill.GetStatus () != Thread::eNull) {
thread2Kill.AbortAndWaitForDone (timeout);
}
}
bool ThreadPool::IsPresent (const TaskType& task) const
{
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
for (list<TaskType>::const_iterator i = fTasks_.begin (); i != fTasks_.end (); ++i) {
if (*i == task) {
return true;
}
}
}
return IsRunning (task);
}
bool ThreadPool::IsRunning (const TaskType& task) const
{
Require (not task.IsNull ());
{
AutoCriticalSection critSection (fCriticalSection_);
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> rTask = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (task == rTask) {
return true;
}
}
}
return false;
}
void ThreadPool::WaitForTask (const TaskType& task, Time::DurationSecondsType timeout) const
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::WaitForTask"));
// Inefficient / VERY SLOPPY impl
Time::DurationSecondsType endAt = timeout + Time::GetTickCount ();
while (true) {
if (not IsPresent (task)) {
return;
}
Time::DurationSecondsType remaining = timeout - Time::GetTickCount ();
if (remaining <= 0.0) {
DoThrow (WaitTimedOutException ());
}
Execution::Sleep (min (remaining, 1.0));
}
}
vector<ThreadPool::TaskType> ThreadPool::GetTasks () const
{
vector<ThreadPool::TaskType> result;
{
AutoCriticalSection critSection (fCriticalSection_);
result.reserve (fTasks_.size () + fThreads_.size ());
result.insert (result.begin (), fTasks_.begin (), fTasks_.end ()); // copy pending tasks
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> task = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (not task.IsNull ()) {
result.push_back (task);
}
}
}
return result;
}
vector<ThreadPool::TaskType> ThreadPool::GetRunningTasks () const
{
vector<ThreadPool::TaskType> result;
{
AutoCriticalSection critSection (fCriticalSection_);
result.reserve (fThreads_.size ());
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> task = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (not task.IsNull ()) {
result.push_back (task);
}
}
}
return result;
}
size_t ThreadPool::GetTasksCount () const
{
size_t count = 0;
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
count += fTasks_.size ();
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
SharedPtr<IRunnable> tr = i->GetRunnable ();
Assert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);
SharedPtr<IRunnable> task = dynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();
if (not task.IsNull ()) {
count++;
}
}
}
return count;
}
void ThreadPool::WaitForDone (Time::DurationSecondsType timeout) const
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::WaitForDone"));
Require (fAborted_);
{
Time::DurationSecondsType endAt = timeout + Time::GetTickCount ();
AutoCriticalSection critSection (fCriticalSection_);
for (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
i->WaitForDone (endAt - Time::GetTickCount ());
}
}
}
void ThreadPool::Abort ()
{
Debug::TraceContextBumper ctx (TSTR ("ThreadPool::Abort"));
fAborted_ = true;
{
// First see if its in the Q
AutoCriticalSection critSection (fCriticalSection_);
fTasks_.clear ();
for (vector<Thread>::iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {
i->Abort ();
}
}
}
void ThreadPool::AbortAndWaitForDone (Time::DurationSecondsType timeout)
{
Abort ();
WaitForDone (timeout);
}
// THIS is called NOT from 'this' - but from the context of an OWNED thread of the pool
void ThreadPool::WaitForNextTask_ (TaskType* result)
{
RequireNotNull (result);
if (fAborted_) {
Execution::DoThrow (ThreadAbortException ());
}
while (true) {
{
AutoCriticalSection critSection (fCriticalSection_);
if (not fTasks_.empty ()) {
*result = fTasks_.front ();
fTasks_.pop_front ();
DbgTrace ("ThreadPool::WaitForNextTask_ () is starting a new task");
return;
}
}
// Prevent spinwaiting... This event is SET when any new item arrives
//DbgTrace ("ThreadPool::WaitForNextTask_ () - about to wait for added tasks");
fTasksAdded_.Wait ();
//DbgTrace ("ThreadPool::WaitForNextTask_ () - completed wait for added tasks");
}
}
Thread ThreadPool::mkThread_ ()
{
Thread t = Thread (SharedPtr<IRunnable> (new ThreadPool::MyRunnable_ (*this))); // ADD MY THREADOBJ
t.SetThreadName (L"Thread Pool");
t.Start ();
return t;
}
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "SurgSim/DataStructures/TriangleMesh.h"
#include "SurgSim/DataStructures/TriangleMeshBase.h"
#include "SurgSim/Math/Vector.h"
using SurgSim::DataStructures::TriangleMesh;
using SurgSim::Math::Vector3d;
namespace SurgSim
{
namespace DataStructures
{
TEST(MeshTest, NormalTest)
{
typedef SurgSim::DataStructures::TriangleMeshBase<void, void, void> TriangleMeshBase;
typedef SurgSim::DataStructures::MeshElement<2, void> EdgeElement;
typedef SurgSim::DataStructures::MeshElement<3, void> TriangleElement;
std::shared_ptr<TriangleMeshBase> mesh = std::make_shared<TriangleMeshBase>();
// Add vertex
TriangleMeshBase::VertexType v0(Vector3d(-1.0, -1.0, -1.0));
TriangleMeshBase::VertexType v1(Vector3d( 1.0, -1.0, -1.0));
TriangleMeshBase::VertexType v2(Vector3d(-1.0, 1.0, -1.0));
mesh->addVertex(v0);
mesh->addVertex(v1);
mesh->addVertex(v2);
// Add edges
std::array<unsigned int, 2> edgePoints01;
std::array<unsigned int, 2> edgePoints02;
std::array<unsigned int, 2> edgePoints12;
EdgeElement element01(edgePoints01);
EdgeElement element02(edgePoints02);
EdgeElement element12(edgePoints12);
TriangleMeshBase::EdgeType e01(element01);
TriangleMeshBase::EdgeType e02(element02);
TriangleMeshBase::EdgeType e12(element12);
mesh->addEdge(e01);
mesh->addEdge(e02);
mesh->addEdge(e12);
// Add triangle
std::array<unsigned int, 3> trianglePoints = {0, 1, 2};
TriangleElement triangleElement(trianglePoints);
TriangleMeshBase::TriangleType t(triangleElement);
mesh->addTriangle(t);
std::shared_ptr<TriangleMesh> collisionMesh = std::make_shared<TriangleMesh>(mesh);
Vector3d expectedZNormal(0.0, 0.0, 1.0);
EXPECT_EQ(expectedZNormal, collisionMesh->getNormal(0));
// Update new vertex location of v2 to v3
Vector3d v3(-1.0, -1.0, 1.0);
SurgSim::DataStructures::Vertex<SurgSim::DataStructures::EmptyData>& v2p = collisionMesh->getVertex(2);
v2p = v3;
// Recompute normals for CollisionMesh
collisionMesh->calculateNormals();
Vector3d expectedXNormal(0.0, -1.0, 0.0);
EXPECT_EQ(expectedXNormal, collisionMesh->getNormal(0));
}
};
};<commit_msg>Fix UnitTest failing of DataStructure::TriangleMesh<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "SurgSim/DataStructures/TriangleMesh.h"
#include "SurgSim/DataStructures/TriangleMeshBase.h"
#include "SurgSim/Math/Vector.h"
using SurgSim::DataStructures::TriangleMesh;
using SurgSim::Math::Vector3d;
namespace SurgSim
{
namespace DataStructures
{
TEST(TriangleMeshTest, NormalTest)
{
typedef SurgSim::DataStructures::TriangleMeshBase<void, void, void> TriangleMeshBase;
typedef SurgSim::DataStructures::MeshElement<2, void> EdgeElement;
typedef SurgSim::DataStructures::MeshElement<3, void> TriangleElement;
std::shared_ptr<TriangleMeshBase> mesh = std::make_shared<TriangleMeshBase>();
// Add vertex
TriangleMeshBase::VertexType v0(Vector3d(-1.0, -1.0, -1.0));
TriangleMeshBase::VertexType v1(Vector3d( 1.0, -1.0, -1.0));
TriangleMeshBase::VertexType v2(Vector3d(-1.0, 1.0, -1.0));
mesh->addVertex(v0);
mesh->addVertex(v1);
mesh->addVertex(v2);
// Add edges
std::array<unsigned int, 2> edgePoints01;
std::array<unsigned int, 2> edgePoints02;
std::array<unsigned int, 2> edgePoints12;
EdgeElement element01(edgePoints01);
EdgeElement element02(edgePoints02);
EdgeElement element12(edgePoints12);
TriangleMeshBase::EdgeType e01(element01);
TriangleMeshBase::EdgeType e02(element02);
TriangleMeshBase::EdgeType e12(element12);
mesh->addEdge(e01);
mesh->addEdge(e02);
mesh->addEdge(e12);
// Add triangle
std::array<unsigned int, 3> trianglePoints = {0, 1, 2};
TriangleElement triangleElement(trianglePoints);
TriangleMeshBase::TriangleType t(triangleElement);
mesh->addTriangle(t);
std::shared_ptr<TriangleMesh> collisionMesh = std::make_shared<TriangleMesh>(mesh);
Vector3d expectedZNormal(0.0, 0.0, 1.0);
EXPECT_EQ(expectedZNormal, collisionMesh->getNormal(0));
// Update new vertex location of v2 to v3
Vector3d v3(-1.0, -1.0, 1.0);
SurgSim::DataStructures::Vertex<SurgSim::DataStructures::EmptyData>& v2p = collisionMesh->getVertex(2);
v2p = v3;
// Recompute normals for CollisionMesh
collisionMesh->calculateNormals();
Vector3d expectedXNormal(0.0, -1.0, 0.0);
EXPECT_EQ(expectedXNormal, collisionMesh->getNormal(0));
}
};
};<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkMacro.h"
#include "otbImage.h"
#include <iostream>
#include <fstream>
#include "otbSVMModel.h"
#include "otbSVMKernels.h"
#include "svm.h"
int otbSVMComposedKernelFunctorTest( int itkNotUsed(argc), char* argv[] )
{
typedef unsigned char InputPixelType;
typedef unsigned char LabelPixelType;
typedef otb::SVMModel< InputPixelType, LabelPixelType > ModelType;
ModelType::Pointer svmModel = ModelType::New();
otb::CustomKernelFunctor customFunctor;
otb::SAMKernelFunctor SAMFunctor;
ComposedKernelFunctor composedKernelFunctor;
composedKernelFunctor.AddKernelFunctorModelToKernelList(&customFunctor);
composedKernelFunctor.AddKernelFunctorModelToKernelList(&SAMFunctor);
composedKernelFunctor.AddPonderationToPonderationList(1.5);
composedKernelFunctor.AddPonderationToPonderationList(2.0);
composedKernelFunctor.SetName("compositionFilter");
struct svm_model *model;
model = new svm_model;
model->param.svm_type = 0;
model->param.kernel_type = 6;
model->nr_class = 2;
model->l = 5;
model->sv_coef = new double*[model->nr_class-1];
for(int i=0; i<model->nr_class-1; i++)
model->sv_coef[i] = new double[model->l];
model->SV = new svm_node*[model->l];
for(int n = 0; n<model->l; ++n)
{
model->SV[n]= new svm_node;
model->SV[n]->index = -1;
model->SV[n]->value = 0.;
}
model->sv_coef[0][0] = 0.125641;
model->sv_coef[0][1] = 1;
model->sv_coef[0][2] = 0;
model->sv_coef[0][3] = -1;
model->sv_coef[0][4] = -0.54994;
model->rho = new double[1];
model->probA = new double[1];
model->probB = new double[1];
model->rho[0] = 22.3117;
model->probA[0] = -0.541009;
model->probB[0] = -0.687381;
model->param.const_coef = 2.;
model->param.lin_coef = 5.;
model->param.gamma = 1.5;
model->param.degree = 2;
model->label = new int[2];
model->label[0] = 1;
model->label[1] = -1;
model->nSV = new int[2];
model->nSV[0] = 3;
model->nSV[1] = 2;
model->param.kernel_composed = &composedKernelFunctor;
svmModel->SetModel(model);
struct svm_node *x = new svm_node[3];
struct svm_node *y = new svm_node[3];
struct svm_node **SVx = new svm_node*[1];
struct svm_node **SVy = new svm_node*[1];
SVx[0] = new svm_node[1];
SVy[0] = new svm_node[1];
SVx[0] = &x[0];
SVy[0] = &y[0];
x[0].index = 1;
x[0].value = 10;
x[1].index = -1;
x[1].value = 10000;
y[0].index = 1;
y[0].value = 5;
y[1].index = -1;
y[1].value = 10000;
double resAdd =0.;
double resMul =0.;
double res1 = 0.;
double res2 = 0.;
std::ofstream file;
file.open(argv[1]);
file<<"Inputs Values: 10, 5, Inputs Ponderation: 1.5, 2"<<std::endl;
file<<std::endl;
file<<"Functor Results:"<<std::endl;
res1 = customFunctor(SVx[0], SVy[0], model->param);
file<<"Custom Functor only: "<<res1<<std::endl;
//std::cout<<"customFunctor : "<<res1<<std::endl;
res2 = SAMFunctor(SVx[0], SVy[0], model->param);
file<<"SAM Functor only: "<<res2<<std::endl;
//std::cout<<"SAMFunctor : "<<res2<<std::endl;
file<<"Composed Functor: "<<std::endl;
resAdd = (*(svmModel->GetModel()->param.kernel_composed))(SVx[0], SVy[0], svmModel->GetModel()->param);
//std::cout<<"composed : "<<resAdd<<std::endl;
svmModel->GetModel()->param.kernel_composed->SetMultiplyKernelFunctor(true);
resMul = (*(svmModel->GetModel()->param.kernel_composed))(SVx[0], SVy[0], svmModel->GetModel()->param);
//std::cout<<"composed : "<<resAdd<<std::endl;
file<<"Addition: "<<resAdd<<", "<<"Multiplication: "<<resMul<<std::endl;
file.close();
//svmModel->GetModel()->param.kernel_composed->print_parameters();
svmModel->SaveModel(argv[2]);
ModelType::Pointer svmModelBis = ModelType::New();
svmModelBis->LoadModel(argv[2]);
//svmModelBis->GetModel()->param.kernel_composed->print_parameters();
svmModelBis->SaveModel(argv[3]);
// Free all memory
for(int i=0; i<model->nr_class-1; i++)
delete [] model->sv_coef[i];
delete model->sv_coef;
for(int n = 0; n<model->l; ++n)
delete model->SV[n];
delete [] model->SV;
delete [] model->rho;
delete [] model->probA;
delete [] model->probB;
delete [] model->label;
delete [] model->nSV;
delete [] x;
delete [] y;
delete [] SVx[0];
delete [] SVy[0];
delete [] SVx;
delete [] sVy;
delete model;
return EXIT_SUCCESS;
}
<commit_msg>COMP: small error<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkMacro.h"
#include "otbImage.h"
#include <iostream>
#include <fstream>
#include "otbSVMModel.h"
#include "otbSVMKernels.h"
#include "svm.h"
int otbSVMComposedKernelFunctorTest( int itkNotUsed(argc), char* argv[] )
{
typedef unsigned char InputPixelType;
typedef unsigned char LabelPixelType;
typedef otb::SVMModel< InputPixelType, LabelPixelType > ModelType;
ModelType::Pointer svmModel = ModelType::New();
otb::CustomKernelFunctor customFunctor;
otb::SAMKernelFunctor SAMFunctor;
ComposedKernelFunctor composedKernelFunctor;
composedKernelFunctor.AddKernelFunctorModelToKernelList(&customFunctor);
composedKernelFunctor.AddKernelFunctorModelToKernelList(&SAMFunctor);
composedKernelFunctor.AddPonderationToPonderationList(1.5);
composedKernelFunctor.AddPonderationToPonderationList(2.0);
composedKernelFunctor.SetName("compositionFilter");
struct svm_model *model;
model = new svm_model;
model->param.svm_type = 0;
model->param.kernel_type = 6;
model->nr_class = 2;
model->l = 5;
model->sv_coef = new double*[model->nr_class-1];
for(int i=0; i<model->nr_class-1; i++)
model->sv_coef[i] = new double[model->l];
model->SV = new svm_node*[model->l];
for(int n = 0; n<model->l; ++n)
{
model->SV[n]= new svm_node;
model->SV[n]->index = -1;
model->SV[n]->value = 0.;
}
model->sv_coef[0][0] = 0.125641;
model->sv_coef[0][1] = 1;
model->sv_coef[0][2] = 0;
model->sv_coef[0][3] = -1;
model->sv_coef[0][4] = -0.54994;
model->rho = new double[1];
model->probA = new double[1];
model->probB = new double[1];
model->rho[0] = 22.3117;
model->probA[0] = -0.541009;
model->probB[0] = -0.687381;
model->param.const_coef = 2.;
model->param.lin_coef = 5.;
model->param.gamma = 1.5;
model->param.degree = 2;
model->label = new int[2];
model->label[0] = 1;
model->label[1] = -1;
model->nSV = new int[2];
model->nSV[0] = 3;
model->nSV[1] = 2;
model->param.kernel_composed = &composedKernelFunctor;
svmModel->SetModel(model);
struct svm_node *x = new svm_node[3];
struct svm_node *y = new svm_node[3];
struct svm_node **SVx = new svm_node*[1];
struct svm_node **SVy = new svm_node*[1];
SVx[0] = new svm_node[1];
SVy[0] = new svm_node[1];
SVx[0] = &x[0];
SVy[0] = &y[0];
x[0].index = 1;
x[0].value = 10;
x[1].index = -1;
x[1].value = 10000;
y[0].index = 1;
y[0].value = 5;
y[1].index = -1;
y[1].value = 10000;
double resAdd =0.;
double resMul =0.;
double res1 = 0.;
double res2 = 0.;
std::ofstream file;
file.open(argv[1]);
file<<"Inputs Values: 10, 5, Inputs Ponderation: 1.5, 2"<<std::endl;
file<<std::endl;
file<<"Functor Results:"<<std::endl;
res1 = customFunctor(SVx[0], SVy[0], model->param);
file<<"Custom Functor only: "<<res1<<std::endl;
//std::cout<<"customFunctor : "<<res1<<std::endl;
res2 = SAMFunctor(SVx[0], SVy[0], model->param);
file<<"SAM Functor only: "<<res2<<std::endl;
//std::cout<<"SAMFunctor : "<<res2<<std::endl;
file<<"Composed Functor: "<<std::endl;
resAdd = (*(svmModel->GetModel()->param.kernel_composed))(SVx[0], SVy[0], svmModel->GetModel()->param);
//std::cout<<"composed : "<<resAdd<<std::endl;
svmModel->GetModel()->param.kernel_composed->SetMultiplyKernelFunctor(true);
resMul = (*(svmModel->GetModel()->param.kernel_composed))(SVx[0], SVy[0], svmModel->GetModel()->param);
//std::cout<<"composed : "<<resAdd<<std::endl;
file<<"Addition: "<<resAdd<<", "<<"Multiplication: "<<resMul<<std::endl;
file.close();
//svmModel->GetModel()->param.kernel_composed->print_parameters();
svmModel->SaveModel(argv[2]);
ModelType::Pointer svmModelBis = ModelType::New();
svmModelBis->LoadModel(argv[2]);
//svmModelBis->GetModel()->param.kernel_composed->print_parameters();
svmModelBis->SaveModel(argv[3]);
// Free all memory
for(int i=0; i<model->nr_class-1; i++)
delete [] model->sv_coef[i];
delete model->sv_coef;
for(int n = 0; n<model->l; ++n)
delete model->SV[n];
delete [] model->SV;
delete [] model->rho;
delete [] model->probA;
delete [] model->probB;
delete [] model->label;
delete [] model->nSV;
delete [] x;
delete [] y;
delete [] SVx[0];
delete [] SVy[0];
delete [] SVx;
delete [] SVy;
delete model;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud.h>
void center_cloud_cb(const sensor_msgs::PointCloud::ConstPtr& inMsg)
{
if (inMsg->points.size()>0)
{
ros::Time now = ros::Time(0);
sensor_msgs::PointCloud cloud_in;
cloud_in.header.stamp = inMsg->header.stamp;
cloud_in.header.frame_id = inMsg->header.frame_id;
cloud_in.points=inMsg->points;
//center_cloud.points.resize(sifted_centroid_list.size());
//one_centroid=sifted_centroid_list[0];
std::cout<<"centroids are:"<<std::endl;
std::cout<<inMsg->points[0].x<<std::endl;
tf::StampedTransform transform;
tf::TransformListener listener;
//ros::Time now = ros::Time::now();
ros::Duration(2).sleep();
listener.waitForTransform("/base_link","/velodyne",now,ros::Duration(0.0));
listener.lookupTransform("/base_link","/velodyne",now,transform);
sensor_msgs::PointCloud gobal;
//cloud_in=*inMsg;
try {
//listener.transformPointCloud("/base_link",cloud_in, gobal);
listener.transformPointCloud("/base_link",now,cloud_in, "/velodyne",gobal);
std::cout<<"New centroids are:"<<std::endl;
std::cout<<gobal.points[0].x<<std::endl;
} catch (tf2::ExtrapolationException &ex){
//std::cout<<ex.msg<<std::endl;
//continue;
}
}
}
int main(int argc, char** argv){
ros::init(argc, argv, "tf_listener");
ros::NodeHandle node;
ros::Subscriber input=node.subscribe("center_cloud",10, center_cloud_cb);
tf::StampedTransform transform;
tf::TransformListener listener;
//listener.lookupTransform("/velodyne","/bask_link",ros::Time(0),transform);
//std::cout << transform.stamp << std::endl;
//ros::Rate rate(10.0);
ros::spin();
return 0;
};
<commit_msg>Removing remnant<commit_after><|endoftext|> |
<commit_before>/*
* 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.
*
* Modified by Cloudius Systems.
* Copyright 2015 Cloudius Systems.
*/
#include "streaming/stream_request.hh"
namespace streaming {
void stream_request::serialize(bytes::iterator& out) const {
serialize_string(out, keyspace);
serialize_int32(out, uint32_t(ranges.size()));
// for (auto& x : ranges) {
// FIXME: query::range<token>
// }
serialize_int32(out, uint32_t(column_families.size()));
for (auto& x : column_families) {
serialize_string(out, x);
}
serialize_int64(out, repaired_at);
}
stream_request stream_request::deserialize(bytes_view& v) {
auto keyspace_ = read_simple_short_string(v);
auto num = read_simple<int32_t>(v);
std::vector<query::range<token>> ranges_;
for (int32_t i = 0; i < num; i++) {
// FIXME: query::range<token>
ranges_.push_back(query::range<token>::make_open_ended_both_sides());
}
num = read_simple<int32_t>(v);
std::vector<sstring> column_families_;
for (int32_t i = 0; i < num; i++) {
auto s = read_simple_short_string(v);
column_families_.push_back(std::move(s));
}
auto repaired_at_ = read_simple<int64_t>(v);
return stream_request(std::move(keyspace_), std::move(ranges_), std::move(column_families_), repaired_at_);
}
size_t stream_request::serialized_size() const {
size_t size = serialize_string_size(keyspace);
size += serialize_int32_size;
// for (auto& x : ranges) {
// FIXME: query::range<token>
// }
size += serialize_int32_size;
for (auto& x : column_families) {
size += serialize_string_size(x);
}
size += serialize_int64_size;
return size;
}
std::ostream& operator<<(std::ostream& os, const stream_request& sr) {
os << "[ ks = " << sr.keyspace << " cf = ";
for (auto& cf : sr.column_families) {
os << cf << " ";
}
return os << "]";
}
} // namespace streaming;
<commit_msg>streaming: Serialize query::range<token> in stream_request<commit_after>/*
* 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.
*
* Modified by Cloudius Systems.
* Copyright 2015 Cloudius Systems.
*/
#include "streaming/stream_request.hh"
#include "query-request.hh"
namespace streaming {
void stream_request::serialize(bytes::iterator& out) const {
serialize_string(out, keyspace);
serialize_int32(out, uint32_t(ranges.size()));
for (auto& x : ranges) {
x.serialize(out);
}
serialize_int32(out, uint32_t(column_families.size()));
for (auto& x : column_families) {
serialize_string(out, x);
}
serialize_int64(out, repaired_at);
}
stream_request stream_request::deserialize(bytes_view& v) {
auto keyspace_ = read_simple_short_string(v);
auto num = read_simple<int32_t>(v);
std::vector<query::range<token>> ranges_;
for (int32_t i = 0; i < num; i++) {
ranges_.push_back(query::range<token>::deserialize(v));
}
num = read_simple<int32_t>(v);
std::vector<sstring> column_families_;
for (int32_t i = 0; i < num; i++) {
auto s = read_simple_short_string(v);
column_families_.push_back(std::move(s));
}
auto repaired_at_ = read_simple<int64_t>(v);
return stream_request(std::move(keyspace_), std::move(ranges_), std::move(column_families_), repaired_at_);
}
size_t stream_request::serialized_size() const {
size_t size = serialize_string_size(keyspace);
size += serialize_int32_size;
for (auto& x : ranges) {
size += x.serialized_size();
}
size += serialize_int32_size;
for (auto& x : column_families) {
size += serialize_string_size(x);
}
size += serialize_int64_size;
return size;
}
std::ostream& operator<<(std::ostream& os, const stream_request& sr) {
os << "[ ks = " << sr.keyspace << " cf = ";
for (auto& cf : sr.column_families) {
os << cf << " ";
}
return os << "]";
}
} // namespace streaming;
<|endoftext|> |
<commit_before>/*=========================================================================
*
* 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 <string.h>
#include "itkVersion.h"
#include "itkTransformFactoryBase.h"
int itkTransformFactoryBaseTest (int, char*[])
{
// Call register default transforms
itk::TransformFactoryBase::RegisterDefaultTransforms();
// create the list of default transforms
std::list<std::string> defaultTransforms;
defaultTransforms.push_back("AffineTransform_double_2_2");
defaultTransforms.push_back("AffineTransform_double_3_3");
defaultTransforms.push_back("AffineTransform_double_4_4");
defaultTransforms.push_back("AffineTransform_double_5_5");
defaultTransforms.push_back("AffineTransform_double_6_6");
defaultTransforms.push_back("AffineTransform_double_7_7");
defaultTransforms.push_back("AffineTransform_double_8_8");
defaultTransforms.push_back("AffineTransform_double_9_9");
defaultTransforms.push_back("IdentityTransform_double_2_2");
defaultTransforms.push_back("IdentityTransform_double_3_3");
defaultTransforms.push_back("IdentityTransform_double_4_4");
defaultTransforms.push_back("IdentityTransform_double_5_5");
defaultTransforms.push_back("IdentityTransform_double_6_6");
defaultTransforms.push_back("IdentityTransform_double_7_7");
defaultTransforms.push_back("IdentityTransform_double_8_8");
defaultTransforms.push_back("IdentityTransform_double_9_9");
defaultTransforms.push_back("BSplineTransform_double_2_2");
defaultTransforms.push_back("BSplineTransform_double_3_3");
#ifdef ITKV3_COMPATIBILITY
defaultTransforms.push_back("BSplineDeformableTransform_double_2_2");
defaultTransforms.push_back("BSplineDeformableTransform_double_3_3");
#endif
defaultTransforms.push_back("CenteredAffineTransform_double_2_2");
defaultTransforms.push_back("CenteredAffineTransform_double_3_3");
defaultTransforms.push_back("CenteredEuler3DTransform_double_3_3");
defaultTransforms.push_back("CenteredRigid2DTransform_double_2_2");
defaultTransforms.push_back("CenteredSimilarity2DTransform_double_2_2");
defaultTransforms.push_back("Euler2DTransform_double_2_2");
defaultTransforms.push_back("Euler3DTransform_double_3_3");
defaultTransforms.push_back("FixedCenterOfRotationAffineTransform_double_3_3");
defaultTransforms.push_back("QuaternionRigidTransform_double_3_3");
defaultTransforms.push_back("Rigid2DTransform_double_2_2");
defaultTransforms.push_back("Rigid3DPerspectiveTransform_double_3_2");
defaultTransforms.push_back("Rigid3DTransform_double_3_3");
defaultTransforms.push_back("ScalableAffineTransform_double_3_3");
defaultTransforms.push_back("ScaleLogarithmicTransform_double_3_3");
defaultTransforms.push_back("ScaleVersor3DTransform_double_3_3");
defaultTransforms.push_back("ScaleSkewVersor3DTransform_double_3_3");
defaultTransforms.push_back("ScaleTransform_double_2_2");
defaultTransforms.push_back("ScaleTransform_double_3_3");
defaultTransforms.push_back("ScaleTransform_double_4_4");
defaultTransforms.push_back("TranslationTransform_double_3_3");
defaultTransforms.push_back("VersorRigid3DTransform_double_3_3");
defaultTransforms.push_back("VersorTransform_double_3_3");
defaultTransforms.push_back("Similarity2DTransform_double_2_2");
defaultTransforms.push_back("AffineTransform_float_2_2");
defaultTransforms.push_back("AffineTransform_float_3_3");
defaultTransforms.push_back("AffineTransform_float_4_4");
defaultTransforms.push_back("AffineTransform_float_5_5");
defaultTransforms.push_back("AffineTransform_float_6_6");
defaultTransforms.push_back("AffineTransform_float_7_7");
defaultTransforms.push_back("AffineTransform_float_8_8");
defaultTransforms.push_back("AffineTransform_float_9_9");
defaultTransforms.push_back("IdentityTransform_float_2_2");
defaultTransforms.push_back("IdentityTransform_float_3_3");
defaultTransforms.push_back("IdentityTransform_float_4_4");
defaultTransforms.push_back("IdentityTransform_float_5_5");
defaultTransforms.push_back("IdentityTransform_float_6_6");
defaultTransforms.push_back("IdentityTransform_float_7_7");
defaultTransforms.push_back("IdentityTransform_float_8_8");
defaultTransforms.push_back("IdentityTransform_float_9_9");
defaultTransforms.push_back("BSplineTransform_float_2_2");
defaultTransforms.push_back("BSplineTransform_float_3_3");
#ifdef ITKV3_COMPATIBILITY
defaultTransforms.push_back("BSplineDeformableTransform_float_2_2");
defaultTransforms.push_back("BSplineDeformableTransform_float_3_3");
#endif
defaultTransforms.push_back("CenteredAffineTransform_float_2_2");
defaultTransforms.push_back("CenteredAffineTransform_float_3_3");
defaultTransforms.push_back("CenteredEuler3DTransform_float_3_3");
defaultTransforms.push_back("CenteredRigid2DTransform_float_2_2");
defaultTransforms.push_back("CenteredSimilarity2DTransform_float_2_2");
defaultTransforms.push_back("Euler2DTransform_float_2_2");
defaultTransforms.push_back("Euler3DTransform_float_3_3");
defaultTransforms.push_back("FixedCenterOfRotationAffineTransform_float_3_3");
defaultTransforms.push_back("QuaternionRigidTransform_float_3_3");
defaultTransforms.push_back("Rigid2DTransform_float_2_2");
defaultTransforms.push_back("Rigid3DPerspectiveTransform_float_3_2");
defaultTransforms.push_back("Rigid3DTransform_float_3_3");
defaultTransforms.push_back("ScalableAffineTransform_float_3_3");
defaultTransforms.push_back("ScaleLogarithmicTransform_float_3_3");
defaultTransforms.push_back("ScaleVersor3DTransform_float_3_3");
defaultTransforms.push_back("ScaleSkewVersor3DTransform_float_3_3");
defaultTransforms.push_back("ScaleTransform_float_2_2");
defaultTransforms.push_back("ScaleTransform_float_3_3");
defaultTransforms.push_back("ScaleTransform_float_4_4");
defaultTransforms.push_back("TranslationTransform_float_3_3");
defaultTransforms.push_back("VersorRigid3DTransform_float_3_3");
defaultTransforms.push_back("VersorTransform_float_3_3");
defaultTransforms.push_back("Similarity2DTransform_float_2_2");
// check to make sure that all default transforms have been registered
defaultTransforms.sort();
// Print out the names of all the registered transforms
std::list<std::string> names = itk::TransformFactoryBase::GetFactory()->GetClassOverrideWithNames();
names.sort();
std::list<std::string>::iterator namesIt;
std::list<std::string>::iterator defaultsIt;
for (namesIt = names.begin(), defaultsIt = defaultTransforms.begin();
namesIt != names.end(), defaultsIt != defaultTransforms.end();
namesIt++, defaultsIt++)
{
if (strcmp((*namesIt).c_str(), (*defaultsIt).c_str()) != 0)
{
std::cout << "[FAILED] " << *defaultsIt << " not registered properly with defaults" << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "[SUCCESS] " << *defaultsIt << " registered properly" << std::endl;
}
}
// test other methods
itk::TransformFactoryBase::Pointer base = itk::TransformFactoryBase::New();
const char* itkVersion = base->GetITKSourceVersion();
const char* description = base->GetDescription();
const char* type = base->GetNameOfClass();
if (strcmp(itkVersion, ITK_SOURCE_VERSION) != 0)
{
std::cout << "[FAILED] Did not report version correctly" << std::endl;
}
else
{
std::cout << "[SUCCESS] Reported version correctly as " << itkVersion << std::endl;
}
if (strcmp(description, "Transform FactoryBase") != 0)
{
std::cout << "[FAILED] Did not report description correctly" << std::endl;
}
else
{
std::cout << "[SUCCESS] Reported description correctly as " << description << std::endl;
}
if (strcmp(type, "TransformFactoryBase") != 0)
{
std::cout << "[FAILED] Did not report type correctly" << std::endl;
}
else
{
std::cout << "[SUCCESS] Reported type correctly as " << type << std::endl;
}
// return successfully
return EXIT_SUCCESS;
}
<commit_msg>COMP: Fix TransformFactoryBase test by adding new Composite XFRMS<commit_after>/*=========================================================================
*
* 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 <string.h>
#include "itkVersion.h"
#include "itkTransformFactoryBase.h"
int itkTransformFactoryBaseTest (int, char*[])
{
// Call register default transforms
itk::TransformFactoryBase::RegisterDefaultTransforms();
// create the list of default transforms
std::list<std::string> defaultTransforms;
defaultTransforms.push_back("AffineTransform_double_2_2");
defaultTransforms.push_back("AffineTransform_double_3_3");
defaultTransforms.push_back("AffineTransform_double_4_4");
defaultTransforms.push_back("AffineTransform_double_5_5");
defaultTransforms.push_back("AffineTransform_double_6_6");
defaultTransforms.push_back("AffineTransform_double_7_7");
defaultTransforms.push_back("AffineTransform_double_8_8");
defaultTransforms.push_back("AffineTransform_double_9_9");
defaultTransforms.push_back("IdentityTransform_double_2_2");
defaultTransforms.push_back("IdentityTransform_double_3_3");
defaultTransforms.push_back("IdentityTransform_double_4_4");
defaultTransforms.push_back("IdentityTransform_double_5_5");
defaultTransforms.push_back("IdentityTransform_double_6_6");
defaultTransforms.push_back("IdentityTransform_double_7_7");
defaultTransforms.push_back("IdentityTransform_double_8_8");
defaultTransforms.push_back("IdentityTransform_double_9_9");
defaultTransforms.push_back("BSplineTransform_double_2_2");
defaultTransforms.push_back("BSplineTransform_double_3_3");
#ifdef ITKV3_COMPATIBILITY
defaultTransforms.push_back("BSplineDeformableTransform_double_2_2");
defaultTransforms.push_back("BSplineDeformableTransform_double_3_3");
#endif
defaultTransforms.push_back("CenteredAffineTransform_double_2_2");
defaultTransforms.push_back("CenteredAffineTransform_double_3_3");
defaultTransforms.push_back("CenteredEuler3DTransform_double_3_3");
defaultTransforms.push_back("CenteredRigid2DTransform_double_2_2");
defaultTransforms.push_back("CenteredSimilarity2DTransform_double_2_2");
defaultTransforms.push_back("Euler2DTransform_double_2_2");
defaultTransforms.push_back("Euler3DTransform_double_3_3");
defaultTransforms.push_back("FixedCenterOfRotationAffineTransform_double_3_3");
defaultTransforms.push_back("QuaternionRigidTransform_double_3_3");
defaultTransforms.push_back("Rigid2DTransform_double_2_2");
defaultTransforms.push_back("Rigid3DPerspectiveTransform_double_3_2");
defaultTransforms.push_back("Rigid3DTransform_double_3_3");
defaultTransforms.push_back("ScalableAffineTransform_double_3_3");
defaultTransforms.push_back("ScaleLogarithmicTransform_double_3_3");
defaultTransforms.push_back("ScaleVersor3DTransform_double_3_3");
defaultTransforms.push_back("ScaleSkewVersor3DTransform_double_3_3");
defaultTransforms.push_back("ScaleTransform_double_2_2");
defaultTransforms.push_back("ScaleTransform_double_3_3");
defaultTransforms.push_back("ScaleTransform_double_4_4");
defaultTransforms.push_back("TranslationTransform_double_3_3");
defaultTransforms.push_back("VersorRigid3DTransform_double_3_3");
defaultTransforms.push_back("VersorTransform_double_3_3");
defaultTransforms.push_back("Similarity2DTransform_double_2_2");
defaultTransforms.push_back("AffineTransform_float_2_2");
defaultTransforms.push_back("AffineTransform_float_3_3");
defaultTransforms.push_back("AffineTransform_float_4_4");
defaultTransforms.push_back("AffineTransform_float_5_5");
defaultTransforms.push_back("AffineTransform_float_6_6");
defaultTransforms.push_back("AffineTransform_float_7_7");
defaultTransforms.push_back("AffineTransform_float_8_8");
defaultTransforms.push_back("AffineTransform_float_9_9");
defaultTransforms.push_back("IdentityTransform_float_2_2");
defaultTransforms.push_back("IdentityTransform_float_3_3");
defaultTransforms.push_back("IdentityTransform_float_4_4");
defaultTransforms.push_back("IdentityTransform_float_5_5");
defaultTransforms.push_back("IdentityTransform_float_6_6");
defaultTransforms.push_back("IdentityTransform_float_7_7");
defaultTransforms.push_back("IdentityTransform_float_8_8");
defaultTransforms.push_back("IdentityTransform_float_9_9");
defaultTransforms.push_back("BSplineTransform_float_2_2");
defaultTransforms.push_back("BSplineTransform_float_3_3");
#ifdef ITKV3_COMPATIBILITY
defaultTransforms.push_back("BSplineDeformableTransform_float_2_2");
defaultTransforms.push_back("BSplineDeformableTransform_float_3_3");
#endif
defaultTransforms.push_back("CenteredAffineTransform_float_2_2");
defaultTransforms.push_back("CenteredAffineTransform_float_3_3");
defaultTransforms.push_back("CenteredEuler3DTransform_float_3_3");
defaultTransforms.push_back("CenteredRigid2DTransform_float_2_2");
defaultTransforms.push_back("CenteredSimilarity2DTransform_float_2_2");
defaultTransforms.push_back("Euler2DTransform_float_2_2");
defaultTransforms.push_back("Euler3DTransform_float_3_3");
defaultTransforms.push_back("FixedCenterOfRotationAffineTransform_float_3_3");
defaultTransforms.push_back("QuaternionRigidTransform_float_3_3");
defaultTransforms.push_back("Rigid2DTransform_float_2_2");
defaultTransforms.push_back("Rigid3DPerspectiveTransform_float_3_2");
defaultTransforms.push_back("Rigid3DTransform_float_3_3");
defaultTransforms.push_back("ScalableAffineTransform_float_3_3");
defaultTransforms.push_back("ScaleLogarithmicTransform_float_3_3");
defaultTransforms.push_back("ScaleVersor3DTransform_float_3_3");
defaultTransforms.push_back("ScaleSkewVersor3DTransform_float_3_3");
defaultTransforms.push_back("ScaleTransform_float_2_2");
defaultTransforms.push_back("ScaleTransform_float_3_3");
defaultTransforms.push_back("ScaleTransform_float_4_4");
defaultTransforms.push_back("TranslationTransform_float_3_3");
defaultTransforms.push_back("VersorRigid3DTransform_float_3_3");
defaultTransforms.push_back("VersorTransform_float_3_3");
defaultTransforms.push_back("Similarity2DTransform_float_2_2");
// add composites
defaultTransforms.push_back("CompositeTransform_double_2_2");
defaultTransforms.push_back("CompositeTransform_double_3_3");
defaultTransforms.push_back("CompositeTransform_double_4_4");
defaultTransforms.push_back("CompositeTransform_double_5_5");
defaultTransforms.push_back("CompositeTransform_double_6_6");
defaultTransforms.push_back("CompositeTransform_double_7_7");
defaultTransforms.push_back("CompositeTransform_double_8_8");
defaultTransforms.push_back("CompositeTransform_double_9_9");
defaultTransforms.push_back("CompositeTransform_float_2_2");
defaultTransforms.push_back("CompositeTransform_float_3_3");
defaultTransforms.push_back("CompositeTransform_float_4_4");
defaultTransforms.push_back("CompositeTransform_float_5_5");
defaultTransforms.push_back("CompositeTransform_float_6_6");
defaultTransforms.push_back("CompositeTransform_float_7_7");
defaultTransforms.push_back("CompositeTransform_float_8_8");
defaultTransforms.push_back("CompositeTransform_float_9_9");
// check to make sure that all default transforms have been registered
defaultTransforms.sort();
// Print out the names of all the registered transforms
std::list<std::string> names = itk::TransformFactoryBase::GetFactory()->GetClassOverrideWithNames();
names.sort();
std::list<std::string>::iterator namesIt;
std::list<std::string>::iterator defaultsIt;
for (namesIt = names.begin(), defaultsIt = defaultTransforms.begin();
namesIt != names.end(), defaultsIt != defaultTransforms.end();
namesIt++, defaultsIt++)
{
if (strcmp((*namesIt).c_str(), (*defaultsIt).c_str()) != 0)
{
std::cout << "[FAILED] " << *defaultsIt << " not registered properly with defaults" << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "[SUCCESS] " << *defaultsIt << " registered properly" << std::endl;
}
}
// test other methods
itk::TransformFactoryBase::Pointer base = itk::TransformFactoryBase::New();
const char* itkVersion = base->GetITKSourceVersion();
const char* description = base->GetDescription();
const char* type = base->GetNameOfClass();
if (strcmp(itkVersion, ITK_SOURCE_VERSION) != 0)
{
std::cout << "[FAILED] Did not report version correctly" << std::endl;
}
else
{
std::cout << "[SUCCESS] Reported version correctly as " << itkVersion << std::endl;
}
if (strcmp(description, "Transform FactoryBase") != 0)
{
std::cout << "[FAILED] Did not report description correctly" << std::endl;
}
else
{
std::cout << "[SUCCESS] Reported description correctly as " << description << std::endl;
}
if (strcmp(type, "TransformFactoryBase") != 0)
{
std::cout << "[FAILED] Did not report type correctly" << std::endl;
}
else
{
std::cout << "[SUCCESS] Reported type correctly as " << type << std::endl;
}
// return successfully
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/**********************************
* create an event and perform *
* flow analysis 'on the fly' *
* *
* authors: Raimond Snellings *
* ([email protected]) *
* Ante Bilandzic *
* ([email protected]) *
*********************************/
#include "Riostream.h"
#include "TMath.h"
#include "TF1.h"
#include "TRandom3.h"
#include "AliFlowEventSimpleMakerOnTheFly.h"
#include "AliFlowEventSimple.h"
#include "AliFlowTrackSimple.h"
ClassImp(AliFlowEventSimpleMakerOnTheFly)
//========================================================================
AliFlowEventSimpleMakerOnTheFly::AliFlowEventSimpleMakerOnTheFly(UInt_t iseed):
fMultiplicityOfRP(0),
fMultiplicitySpreadOfRP(0.),
fV1RP(0.),
fV1SpreadRP(0.),
fV2RP(0.),
fV2SpreadRP(0.),
fPtSpectra(NULL),
fPhiDistribution(NULL),
fMyTRandom3(NULL),
fCount(0),
fNoOfLoops(1)
{
// constructor
fMyTRandom3 = new TRandom3(iseed);
}
//========================================================================
AliFlowEventSimpleMakerOnTheFly::~AliFlowEventSimpleMakerOnTheFly()
{
// destructor
if (fPtSpectra) delete fPtSpectra;
if (fPhiDistribution) delete fPhiDistribution;
if (fMyTRandom3) delete fMyTRandom3;
}
//========================================================================
AliFlowEventSimple* AliFlowEventSimpleMakerOnTheFly::CreateEventOnTheFly()
{
// method to create event on the fly
AliFlowEventSimple* pEvent = new AliFlowEventSimple(fMultiplicityOfRP);
//reaction plane
Double_t fMCReactionPlaneAngle = fMyTRandom3->Uniform(0.,TMath::TwoPi());
// pt:
Double_t dPtMin = 0.; // to be improved
Double_t dPtMax = 10.; // to be improved
fPtSpectra = new TF1("fPtSpectra","[0]*x*TMath::Exp(-x*x)",dPtMin,dPtMax);
fPtSpectra->SetParName(0,"Multiplicity of RPs");
// sampling the multiplicity:
Int_t fNewMultiplicityOfRP = fMyTRandom3->Gaus(fMultiplicityOfRP,fMultiplicitySpreadOfRP);
fPtSpectra->SetParameter(0,fNewMultiplicityOfRP);
// phi:
Double_t dPhiMin = 0.; // to be improved
Double_t dPhiMax = TMath::TwoPi(); // to be improved
fPhiDistribution = new TF1("fPhiDistribution","1+2.*[0]*TMath::Cos(x)+2.*[1]*TMath::Cos(2*x)",dPhiMin,dPhiMax);
// sampling the V1:
fPhiDistribution->SetParName(0,"directed flow");
Double_t fNewV1RP=0.;
if(fV1RP>0.0) {fNewV1RP = fMyTRandom3->Gaus(fV1RP,fV1SpreadRP);}
fPhiDistribution->SetParameter(0,fNewV1RP);
// sampling the V2:
fPhiDistribution->SetParName(1,"elliptic flow");
Double_t fNewV2RP = fMyTRandom3->Gaus(fV2RP,fV2SpreadRP);
fPhiDistribution->SetParameter(1,fNewV2RP);
// eta:
Double_t dEtaMin = -1.; // to be improved
Double_t dEtaMax = 1.; // to be improved
Int_t iGoodTracks = 0;
Int_t iSelParticlesRP = 0;
Int_t iSelParticlesPOI = 0;
Double_t fTmpPt =0;
Double_t fTmpEta =0;
Double_t fTmpPhi =0;
for(Int_t i=0;i<fNewMultiplicityOfRP;i++) {
fTmpPt = fPtSpectra->GetRandom();
fTmpEta = fMyTRandom3->Uniform(dEtaMin,dEtaMax);
fTmpPhi = fPhiDistribution->GetRandom()+fMCReactionPlaneAngle;
for(Int_t d=0;d<fNoOfLoops;d++) {
AliFlowTrackSimple* pTrack = new AliFlowTrackSimple();
pTrack->SetPt(fTmpPt);
pTrack->SetEta(fTmpEta);
pTrack->SetPhi(fTmpPhi);
pTrack->SetForRPSelection(kTRUE);
iSelParticlesRP++;
pTrack->SetForPOISelection(kTRUE);
iSelParticlesPOI++;
pEvent->TrackCollection()->Add(pTrack);
iGoodTracks++;
}
}
pEvent->SetEventNSelTracksRP(iSelParticlesRP);
pEvent->SetNumberOfTracks(iGoodTracks);//tracks used either for RP or for POI selection
pEvent->SetMCReactionPlaneAngle(fMCReactionPlaneAngle);
if (!fMCReactionPlaneAngle == 0) cout<<" MC Reaction Plane Angle = "<< fMCReactionPlaneAngle << endl;
else cout<<" MC Reaction Plane Angle = unknown "<< endl;
cout<<" iGoodTracks = "<< iGoodTracks << endl;
cout<<" # of RP selected tracks = "<<iSelParticlesRP<<endl;
cout<<" # of POI selected tracks = "<<iSelParticlesPOI<<endl;
cout << "# " << ++fCount << " events processed" << endl;
delete fPhiDistribution;
delete fPtSpectra;
return pEvent;
} // end of CreateEventOnTheFly()
<commit_msg>fix random distribution<commit_after>/*************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/**********************************
* create an event and perform *
* flow analysis 'on the fly' *
* *
* authors: Raimond Snellings *
* ([email protected]) *
* Ante Bilandzic *
* ([email protected]) *
*********************************/
#include "Riostream.h"
#include "TMath.h"
#include "TF1.h"
#include "TRandom3.h"
#include "AliFlowEventSimpleMakerOnTheFly.h"
#include "AliFlowEventSimple.h"
#include "AliFlowTrackSimple.h"
ClassImp(AliFlowEventSimpleMakerOnTheFly)
//========================================================================
AliFlowEventSimpleMakerOnTheFly::AliFlowEventSimpleMakerOnTheFly(UInt_t iseed):
fMultiplicityOfRP(0),
fMultiplicitySpreadOfRP(0.),
fV1RP(0.),
fV1SpreadRP(0.),
fV2RP(0.),
fV2SpreadRP(0.),
fPtSpectra(NULL),
fPhiDistribution(NULL),
fMyTRandom3(NULL),
fCount(0),
fNoOfLoops(1)
{
// constructor
fMyTRandom3 = new TRandom3(iseed);
}
//========================================================================
AliFlowEventSimpleMakerOnTheFly::~AliFlowEventSimpleMakerOnTheFly()
{
// destructor
if (fPtSpectra) delete fPtSpectra;
if (fPhiDistribution) delete fPhiDistribution;
if (fMyTRandom3) delete fMyTRandom3;
}
//========================================================================
AliFlowEventSimple* AliFlowEventSimpleMakerOnTheFly::CreateEventOnTheFly()
{
// method to create event on the fly
AliFlowEventSimple* pEvent = new AliFlowEventSimple(fMultiplicityOfRP);
// pt:
Double_t dPtMin = 0.; // to be improved
Double_t dPtMax = 10.; // to be improved
fPtSpectra = new TF1("fPtSpectra","[0]*x*TMath::Exp(-x*x)",dPtMin,dPtMax);
fPtSpectra->SetParName(0,"Multiplicity of RPs");
// sampling the multiplicity:
Int_t fNewMultiplicityOfRP = fMyTRandom3->Gaus(fMultiplicityOfRP,fMultiplicitySpreadOfRP);
fPtSpectra->SetParameter(0,fNewMultiplicityOfRP);
// phi:
Double_t dPhiMin = 0.; // to be improved
Double_t dPhiMax = TMath::TwoPi(); // to be improved
fPhiDistribution = new TF1("fPhiDistribution","1+2.*[0]*TMath::Cos(x-[2])+2.*[1]*TMath::Cos(2*(x-[2]))",dPhiMin,dPhiMax);
// samling the reaction plane
Double_t fMCReactionPlaneAngle = fMyTRandom3->Uniform(0.,TMath::TwoPi());
fPhiDistribution->SetParName(2,"Reaction Plane");
fPhiDistribution->SetParameter(2,fMCReactionPlaneAngle);
// sampling the V1:
fPhiDistribution->SetParName(0,"directed flow");
Double_t fNewV1RP=fV1RP;
if(fV1SpreadRP>0.0) {fNewV1RP = fMyTRandom3->Gaus(fV1RP,fV1SpreadRP);}
fPhiDistribution->SetParameter(0,fNewV1RP);
// sampling the V2:
fPhiDistribution->SetParName(1,"elliptic flow");
Double_t fNewV2RP = fV2RP;
if(fV2SpreadRP>0.0) fNewV2RP = fMyTRandom3->Gaus(fV2RP,fV2SpreadRP);
fPhiDistribution->SetParameter(1,fNewV2RP);
// eta:
Double_t dEtaMin = -1.; // to be improved
Double_t dEtaMax = 1.; // to be improved
Int_t iGoodTracks = 0;
Int_t iSelParticlesRP = 0;
Int_t iSelParticlesPOI = 0;
Double_t fTmpPt =0;
Double_t fTmpEta =0;
Double_t fTmpPhi =0;
for(Int_t i=0;i<fNewMultiplicityOfRP;i++) {
fTmpPt = fPtSpectra->GetRandom();
fTmpEta = fMyTRandom3->Uniform(dEtaMin,dEtaMax);
fTmpPhi = fPhiDistribution->GetRandom();
for(Int_t d=0;d<fNoOfLoops;d++) {
AliFlowTrackSimple* pTrack = new AliFlowTrackSimple();
pTrack->SetPt(fTmpPt);
pTrack->SetEta(fTmpEta);
pTrack->SetPhi(fTmpPhi);
pTrack->SetForRPSelection(kTRUE);
iSelParticlesRP++;
pTrack->SetForPOISelection(kTRUE);
iSelParticlesPOI++;
pEvent->TrackCollection()->Add(pTrack);
iGoodTracks++;
}
}
pEvent->SetEventNSelTracksRP(iSelParticlesRP);
pEvent->SetNumberOfTracks(iGoodTracks);//tracks used either for RP or for POI selection
pEvent->SetMCReactionPlaneAngle(fMCReactionPlaneAngle);
if (!fMCReactionPlaneAngle == 0) cout<<" MC Reaction Plane Angle = "<< fMCReactionPlaneAngle << endl;
else cout<<" MC Reaction Plane Angle = unknown "<< endl;
cout<<" iGoodTracks = "<< iGoodTracks << endl;
cout<<" # of RP selected tracks = "<<iSelParticlesRP<<endl;
cout<<" # of POI selected tracks = "<<iSelParticlesPOI<<endl;
cout << "# " << ++fCount << " events processed" << endl;
delete fPhiDistribution;
delete fPtSpectra;
return pEvent;
} // end of CreateEventOnTheFly()
<|endoftext|> |
<commit_before>{
{
mode: "dorian",
progression: "1,2,1,5,5,2,2,4,5,2",
origin: "white stripes - little apple blossom"
},
{
mode: "dorian",
progression: "1,7,4,4",
origin: "depeche mode - never let me down"
},
{
mode: "minor",
progression: "1,7,4,6",
origin: "cure - the figurehead"
},
{
mode: "minor",
progression: "1,3,6,4",
origin: "??"
},
{
mode: "minor",
progression: "1,4,6,4",
origin: "??"
},
{
mode: "harmonic_minor",
progression: "1,4,6,57",
origin: "amy whinehouse - back to black"
},
{
mode: "minor",
progression: "1,3,7,1,7,5,1,1",
origin: "dolly parton - jolene"
},
{
mode: "dorian",
progression: "1,5,1,5,1,5,3,4,7,7",
origin: "beatles - and I love her"
},
{
mode: "major",
progression: "1,3,5,5",
origin: "queen of the stone age - go with the flow"
}
{
mode: "major",
progression: "5,5,1,4,5,1,4,bIII"
}
}
<commit_msg>more progression<commit_after>{
{
mode: "dorian",
progression: "1,2,1,5,5,2,2,4,5,2",
origin: "white stripes - little apple blossom"
},
{
mode: "dorian",
progression: "1,7,4,4",
origin: "depeche mode - never let me down"
},
{
mode: "minor",
progression: "1,7,4,6",
origin: "cure - the figurehead"
},
{
mode: "minor",
progression: "1,3,6,4",
origin: "??"
},
{
mode: "minor",
progression: "1,4,6,4",
origin: "??"
},
{
mode: "harmonic_minor",
progression: "1,4,6,57",
origin: "amy whinehouse - back to black"
},
{
mode: "minor",
progression: "1,3,7,1,7,5,1,1",
origin: "dolly parton - jolene"
},
{
mode: "dorian",
progression: "1,5,1,5,1,5,3,4,7,7",
origin: "beatles - and I love her"
},
{
mode: "major",
progression: "1,3,5,5",
origin: "queen of the stone age - go with the flow"
}
{
mode: "major",
progression: "5,5,1,4,5,1,4,bIII".
origin: "kinks - lola"
}
{
mode: "minor",
progression: "1, 7m, 3m, 3m",
origin: "rob - maniac (altered)"
}
}
<|endoftext|> |
<commit_before>/*
* File: deletions.cpp
* Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
*/
#include "common/sedna.h"
#include "tr/updates/updates.h"
#include "tr/executor/base/xptr_sequence.h"
#include "tr/mo/micro.h"
#include "tr/auth/auc.h"
#ifdef SE_ENABLE_TRIGGERS
#include "tr/triggers/triggers.h"
#endif
void delete_undeep(PPOpIn arg)
{
// Creating the first sequence (different validity tests+ indirection deref)
tuple t(arg.ts);
xptr_sequence argseq;
arg.op->next(t);
while (!t.is_eos())
{
if (t.cells[0].is_node())
{
xptr node=t.cells[0].get_node();
CHECKP(node);
if (is_node_persistent(node)&& !is_node_document(node))
{
//xptr indir=((n_dsc*)XADDR(node))->indir;
argseq.add(node);
}
#ifndef IGNORE_UPDATE_ERRORS
else
{
throw USER_EXCEPTION(SE2010);
}
#endif
}
#ifndef IGNORE_UPDATE_ERRORS
else
{
throw USER_EXCEPTION(SE2011);
}
#endif
arg.op->next(t);
}
//Sort in document order
if (argseq.size()<=0) return;
argseq.sort();
// INDIR
xptr_sequence::iterator it=argseq.begin();
xptr node;
while (it!=argseq.end())
{
node=*it;
CHECKP(node);
xptr indir=((n_dsc*)XADDR(node))->indir;
argseq.set(indir,it);
it++;
}
// Checking authorization
if (is_auth_check_needed(DELETE_STATEMENT))
auth_for_update(&argseq, DELETE_STATEMENT, false);
// cycle on sequence
#ifdef SE_ENABLE_FTSEARCH
clear_ft_sequences();
#endif
#ifdef SE_ENABLE_TRIGGERS
apply_per_statement_triggers(&argseq, false, NULL, false, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT);
#endif
it=argseq.end();
do
{
--it;
xptr node=removeIndirection(*it);
CHECKP(node);
{
t_item type=GETTYPE((GETBLOCKBYNODE(node))->snode);
switch(type)
{
case attribute: case text: case comment: case pr_ins:
{
delete_node(node);
break;
}
case element:
{
xptr indir=*it;
//1.INSERT
xptr parent=removeIndirection(((n_dsc*)XADDR(node))->pdsc);
copy_content(parent,node,node);
//2.DELETE
CHECKP(indir);
delete_node(*((xptr*)XADDR(indir)));
}
}
}
if (it==argseq.begin()) break;
}
while (true);
#ifdef SE_ENABLE_FTSEARCH
execute_modifications();
#endif
#ifdef SE_ENABLE_TRIGGERS
apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_DELETE_EVENT);
#endif
}
void delete_deep(PPOpIn arg)
{
// Creating the first sequence (different validity tests+ indirection deref)
/*xptr blk(0,(void*)0x33fd0000);
CHECKP(blk)
{shft hh_size=HHSIZE(blk);
for (int i=0; i<hh_size; i++)
{
hh_slot* tmp = (hh_slot*)HH_ADDR(blk, i);
if (tmp->hole_shft+ tmp->hole_size==SSB(blk) )
{
throw SYSTEM_EXCEPTION("[pstr_deallocate()] string can not be adjacent with with SS tail and with some hole on the right simultaneously");
}
}
}*/
tuple t(arg.ts);
xptr_sequence argseq;
arg.op->next(t);
while (!t.is_eos())
{
if (t.cells[0].is_node())
{
xptr node=t.cells[0].get_node();
// node.print();
CHECKP(node);
if (is_node_persistent(node) ) argseq.add(node);
#ifndef IGNORE_UPDATE_ERRORS
else
{
throw USER_EXCEPTION(SE2012);
}
#endif
}
#ifndef IGNORE_UPDATE_ERRORS
else
{
throw USER_EXCEPTION(SE2011);
}
#endif
arg.op->next(t);
}
// Checking authorization
if (is_auth_check_needed(DELETE_STATEMENT))
auth_for_update(&argseq, DELETE_STATEMENT, true);
//Sort in document order
if (argseq.size()<=0) return;
//!!! debug
/*
xptr_sequence::iterator my_it;
for (my_it = argseq.begin(); my_it != argseq.end(); my_it++)
{
xptr p = argseq.get(my_it);
p.print();
}
*/
#ifdef SE_ENABLE_FTSEARCH
clear_ft_sequences();
#endif
#ifdef SE_ENABLE_TRIGGERS
apply_per_statement_triggers(&argseq, true, NULL, false, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT);
#endif
argseq.sort();
// cycle on sequence
xptr_sequence::iterator it=argseq.begin();
bool mark=false;
xptr tmp_node, parent;
do
{
xptr node=*it;
do
{
if (it+1==argseq.end()) {mark=true; break;}
++it;
}
while (nid_ancestor(node,*it));
/*#ifdef SE_ENABLE_TRIGGERS
tmp_node = copy_to_temp(node);
schema_node* scm_node=GETSCHEMENODEX(node);
parent=removeIndirection(((n_dsc*)XADDR(node))->pdsc);
if (apply_per_node_triggers(XNULL, node, XNULL, NULL, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT) != XNULL)
{
delete_node(node);
apply_per_node_triggers(XNULL, tmp_node, parent, scm_node, TRIGGER_AFTER, TRIGGER_DELETE_EVENT);
}
#else
delete_node(node);
#endif*/
delete_node(node);
if (mark) break;
}
while (true);
#ifdef SE_ENABLE_FTSEARCH
execute_modifications();
#endif
#ifdef SE_ENABLE_TRIGGERS
apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_DELETE_EVENT);
#endif
}<commit_msg>delete fix<commit_after>/*
* File: deletions.cpp
* Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
*/
#include "common/sedna.h"
#include "tr/updates/updates.h"
#include "tr/executor/base/xptr_sequence.h"
#include "tr/mo/micro.h"
#include "tr/auth/auc.h"
#ifdef SE_ENABLE_TRIGGERS
#include "tr/triggers/triggers.h"
#endif
void delete_undeep(PPOpIn arg)
{
// Creating the first sequence (different validity tests+ indirection deref)
tuple t(arg.ts);
xptr_sequence argseq;
arg.op->next(t);
while (!t.is_eos())
{
if (t.cells[0].is_node())
{
xptr node=t.cells[0].get_node();
CHECKP(node);
if (is_node_persistent(node)&& !is_node_document(node))
{
//xptr indir=((n_dsc*)XADDR(node))->indir;
argseq.add(node);
}
#ifndef IGNORE_UPDATE_ERRORS
else
{
throw USER_EXCEPTION(SE2010);
}
#endif
}
#ifndef IGNORE_UPDATE_ERRORS
else
{
throw USER_EXCEPTION(SE2011);
}
#endif
arg.op->next(t);
}
//Sort in document order
if (argseq.size()<=0) return;
argseq.sort();
// INDIR
xptr_sequence::iterator it=argseq.begin();
xptr node;
while (it!=argseq.end())
{
node=*it;
CHECKP(node);
xptr indir=((n_dsc*)XADDR(node))->indir;
argseq.set(indir,it);
it++;
}
// Checking authorization
if (is_auth_check_needed(DELETE_STATEMENT))
auth_for_update(&argseq, DELETE_STATEMENT, false);
// cycle on sequence
#ifdef SE_ENABLE_FTSEARCH
clear_ft_sequences();
#endif
#ifdef SE_ENABLE_TRIGGERS
apply_per_statement_triggers(&argseq, false, NULL, false, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT);
#endif
it=argseq.end();
do
{
--it;
xptr node=removeIndirection(*it);
CHECKP(node);
{
t_item type=GETTYPE((GETBLOCKBYNODE(node))->snode);
switch(type)
{
case attribute: case text: case comment: case pr_ins:
{
delete_node(node);
break;
}
case element:
{
xptr indir=*it;
//1.INSERT
xptr parent=removeIndirection(((n_dsc*)XADDR(node))->pdsc);
copy_content(parent,node,node);
//2.DELETE
CHECKP(indir);
delete_node(*((xptr*)XADDR(indir)));
}
}
}
if (it==argseq.begin()) break;
}
while (true);
#ifdef SE_ENABLE_FTSEARCH
execute_modifications();
#endif
#ifdef SE_ENABLE_TRIGGERS
apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_DELETE_EVENT);
#endif
}
void delete_deep(PPOpIn arg)
{
// Creating the first sequence (different validity tests+ indirection deref)
/*xptr blk(0,(void*)0x33fd0000);
CHECKP(blk)
{shft hh_size=HHSIZE(blk);
for (int i=0; i<hh_size; i++)
{
hh_slot* tmp = (hh_slot*)HH_ADDR(blk, i);
if (tmp->hole_shft+ tmp->hole_size==SSB(blk) )
{
throw SYSTEM_EXCEPTION("[pstr_deallocate()] string can not be adjacent with with SS tail and with some hole on the right simultaneously");
}
}
}*/
tuple t(arg.ts);
xptr_sequence argseq;
arg.op->next(t);
while (!t.is_eos())
{
if (t.cells[0].is_node())
{
xptr node=t.cells[0].get_node();
// node.print();
CHECKP(node);
if (is_node_persistent(node) ) argseq.add(node);
#ifndef IGNORE_UPDATE_ERRORS
else
{
throw USER_EXCEPTION(SE2012);
}
#endif
}
#ifndef IGNORE_UPDATE_ERRORS
else
{
throw USER_EXCEPTION(SE2011);
}
#endif
arg.op->next(t);
}
// Checking authorization
if (is_auth_check_needed(DELETE_STATEMENT))
auth_for_update(&argseq, DELETE_STATEMENT, true);
//Sort in document order
if (argseq.size()<=0) return;
//!!! debug
/*
xptr_sequence::iterator my_it;
for (my_it = argseq.begin(); my_it != argseq.end(); my_it++)
{
xptr p = argseq.get(my_it);
p.print();
}
*/
#ifdef SE_ENABLE_FTSEARCH
clear_ft_sequences();
#endif
#ifdef SE_ENABLE_TRIGGERS
apply_per_statement_triggers(&argseq, true, NULL, false, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT);
#endif
argseq.sort();
// cycle on sequence
xptr_sequence::iterator it=argseq.begin();
bool mark=false;
xptr tmp_node, parent;
do
{
xptr node=*it;
do
{
if (it+1==argseq.end()) {mark=true; break;}
++it;
}
while ((node == *it) || nid_ancestor(node,*it));
/*#ifdef SE_ENABLE_TRIGGERS
tmp_node = copy_to_temp(node);
schema_node* scm_node=GETSCHEMENODEX(node);
parent=removeIndirection(((n_dsc*)XADDR(node))->pdsc);
if (apply_per_node_triggers(XNULL, node, XNULL, NULL, TRIGGER_BEFORE, TRIGGER_DELETE_EVENT) != XNULL)
{
delete_node(node);
apply_per_node_triggers(XNULL, tmp_node, parent, scm_node, TRIGGER_AFTER, TRIGGER_DELETE_EVENT);
}
#else
delete_node(node);
#endif*/
delete_node(node);
if (mark) break;
}
while (true);
#ifdef SE_ENABLE_FTSEARCH
execute_modifications();
#endif
#ifdef SE_ENABLE_TRIGGERS
apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_DELETE_EVENT);
#endif
}
<|endoftext|> |
<commit_before>#include <kdebug.h>
#include "certificatewizardimpl.h"
/*
* Constructs a CertificateWizardImpl which is a child of 'parent', with the
* name 'name' and widget flags set to 'f'
*
* The wizard will by default be modeless, unless you set 'modal' to
* TRUE to construct a modal wizard.
*/
CertificateWizardImpl::CertificateWizardImpl( QWidget* parent, const char* name, bool modal, WFlags fl )
: CertificateWizard( parent, name, modal, fl )
{
}
/*
* Destroys the object and frees any allocated resources
*/
CertificateWizardImpl::~CertificateWizardImpl()
{
// no need to delete child widgets, Qt does it all for us
}
/*
* protected slot
*/
void CertificateWizardImpl::slotCreatePSE()
{
kdWarning() << "CertificateWizardImpl::slotCreatePSE() not yet implemented!" << endl;
}
#include "certificatewizardimpl.moc"
<commit_msg>CVS_SILENT yet another diff massage<commit_after>#include "certificatewizardimpl.h"
#include <kdebug.h>
/*
* Constructs a CertificateWizardImpl which is a child of 'parent', with the
* name 'name' and widget flags set to 'f'
*
* The wizard will by default be modeless, unless you set 'modal' to
* TRUE to construct a modal wizard.
*/
CertificateWizardImpl::CertificateWizardImpl( QWidget* parent, const char* name, bool modal, WFlags fl )
: CertificateWizard( parent, name, modal, fl )
{
}
/*
* Destroys the object and frees any allocated resources
*/
CertificateWizardImpl::~CertificateWizardImpl()
{
// no need to delete child widgets, Qt does it all for us
}
/*
* protected slot
*/
void CertificateWizardImpl::slotCreatePSE()
{
kdWarning() << "CertificateWizardImpl::slotCreatePSE() not yet implemented!" << endl;
}
#include "certificatewizardimpl.moc"
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013 Google 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 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 "config.h"
#include "bindings/core/v8/CustomElementConstructorBuilder.h"
#include "bindings/core/v8/CustomElementBinding.h"
#include "bindings/core/v8/DOMWrapperWorld.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8Document.h"
#include "bindings/core/v8/V8HTMLElement.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "bindings/core/v8/V8PerContextData.h"
#include "bindings/core/v8/V8SVGElement.h"
#include "core/HTMLNames.h"
#include "core/SVGNames.h"
#include "core/dom/Document.h"
#include "core/dom/ElementRegistrationOptions.h"
#include "core/dom/custom/CustomElementDefinition.h"
#include "core/dom/custom/CustomElementDescriptor.h"
#include "core/dom/custom/CustomElementException.h"
#include "core/dom/custom/CustomElementProcessingStack.h"
#include "wtf/Assertions.h"
namespace blink {
static void constructCustomElement(const v8::FunctionCallbackInfo<v8::Value>&);
CustomElementConstructorBuilder::CustomElementConstructorBuilder(ScriptState* scriptState, const ElementRegistrationOptions& options)
: m_scriptState(scriptState)
, m_options(options)
{
ASSERT(m_scriptState->context() == m_scriptState->isolate()->GetCurrentContext());
}
bool CustomElementConstructorBuilder::isFeatureAllowed() const
{
return m_scriptState->world().isMainWorld();
}
bool CustomElementConstructorBuilder::validateOptions(const AtomicString& type, QualifiedName& tagName, ExceptionState& exceptionState)
{
ASSERT(m_prototype.IsEmpty());
v8::TryCatch tryCatch;
if (!m_scriptState->perContextData()) {
// FIXME: This should generate an InvalidContext exception at a later point.
CustomElementException::throwException(CustomElementException::ContextDestroyedCheckingPrototype, type, exceptionState);
tryCatch.ReThrow();
return false;
}
if (m_options.hasPrototype()) {
ASSERT(m_options.prototype().isObject());
m_prototype = m_options.prototype().v8Value().As<v8::Object>();
} else {
m_prototype = v8::Object::New(m_scriptState->isolate());
v8::Local<v8::Object> basePrototype = m_scriptState->perContextData()->prototypeForType(&V8HTMLElement::wrapperTypeInfo);
if (!basePrototype.IsEmpty())
m_prototype->SetPrototype(basePrototype);
}
AtomicString namespaceURI = HTMLNames::xhtmlNamespaceURI;
if (hasValidPrototypeChainFor(&V8SVGElement::wrapperTypeInfo))
namespaceURI = SVGNames::svgNamespaceURI;
ASSERT(!tryCatch.HasCaught());
AtomicString localName;
if (m_options.hasExtends()) {
localName = AtomicString(m_options.extends().lower());
if (!Document::isValidName(localName)) {
CustomElementException::throwException(CustomElementException::ExtendsIsInvalidName, type, exceptionState);
tryCatch.ReThrow();
return false;
}
if (CustomElement::isValidName(localName)) {
CustomElementException::throwException(CustomElementException::ExtendsIsCustomElementName, type, exceptionState);
tryCatch.ReThrow();
return false;
}
} else {
if (namespaceURI == SVGNames::svgNamespaceURI) {
CustomElementException::throwException(CustomElementException::ExtendsIsInvalidName, type, exceptionState);
tryCatch.ReThrow();
return false;
}
localName = type;
}
ASSERT(!tryCatch.HasCaught());
tagName = QualifiedName(nullAtom, localName, namespaceURI);
return true;
}
PassRefPtrWillBeRawPtr<CustomElementLifecycleCallbacks> CustomElementConstructorBuilder::createCallbacks()
{
ASSERT(!m_prototype.IsEmpty());
v8::TryCatch exceptionCatcher;
exceptionCatcher.SetVerbose(true);
v8::Isolate* isolate = m_scriptState->isolate();
v8::Handle<v8::Function> created = retrieveCallback(isolate, "createdCallback");
v8::Handle<v8::Function> attached = retrieveCallback(isolate, "attachedCallback");
v8::Handle<v8::Function> detached = retrieveCallback(isolate, "detachedCallback");
v8::Handle<v8::Function> attributeChanged = retrieveCallback(isolate, "attributeChangedCallback");
m_callbacks = V8CustomElementLifecycleCallbacks::create(m_scriptState.get(), m_prototype, created, attached, detached, attributeChanged);
return m_callbacks.get();
}
v8::Handle<v8::Function> CustomElementConstructorBuilder::retrieveCallback(v8::Isolate* isolate, const char* name)
{
v8::Handle<v8::Value> value = m_prototype->Get(v8String(isolate, name));
if (value.IsEmpty() || !value->IsFunction())
return v8::Handle<v8::Function>();
return value.As<v8::Function>();
}
bool CustomElementConstructorBuilder::createConstructor(Document* document, CustomElementDefinition* definition, ExceptionState& exceptionState)
{
ASSERT(!m_prototype.IsEmpty());
ASSERT(m_constructor.IsEmpty());
ASSERT(document);
v8::Isolate* isolate = m_scriptState->isolate();
if (!prototypeIsValid(definition->descriptor().type(), exceptionState))
return false;
v8::Local<v8::FunctionTemplate> constructorTemplate = v8::FunctionTemplate::New(isolate);
constructorTemplate->SetCallHandler(constructCustomElement);
m_constructor = constructorTemplate->GetFunction();
if (m_constructor.IsEmpty()) {
CustomElementException::throwException(CustomElementException::ContextDestroyedRegisteringDefinition, definition->descriptor().type(), exceptionState);
return false;
}
const CustomElementDescriptor& descriptor = definition->descriptor();
v8::Handle<v8::String> v8TagName = v8String(isolate, descriptor.localName());
v8::Handle<v8::Value> v8Type;
if (descriptor.isTypeExtension())
v8Type = v8String(isolate, descriptor.type());
else
v8Type = v8::Null(isolate);
m_constructor->SetName(v8Type->IsNull() ? v8TagName : v8Type.As<v8::String>());
V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementDocument(isolate), toV8(document, m_scriptState->context()->Global(), isolate));
V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementNamespaceURI(isolate), v8String(isolate, descriptor.namespaceURI()));
V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementTagName(isolate), v8TagName);
V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementType(isolate), v8Type);
v8::Handle<v8::String> prototypeKey = v8String(isolate, "prototype");
ASSERT(m_constructor->HasOwnProperty(prototypeKey));
// This sets the property *value*; calling Set is safe because
// "prototype" is a non-configurable data property so there can be
// no side effects.
m_constructor->Set(prototypeKey, m_prototype);
// This *configures* the property. ForceSet of a function's
// "prototype" does not affect the value, but can reconfigure the
// property.
m_constructor->ForceSet(prototypeKey, m_prototype, v8::PropertyAttribute(v8::ReadOnly | v8::DontEnum | v8::DontDelete));
V8HiddenValue::setHiddenValue(isolate, m_prototype, V8HiddenValue::customElementIsInterfacePrototypeObject(isolate), v8::True(isolate));
m_prototype->ForceSet(v8String(isolate, "constructor"), m_constructor, v8::DontEnum);
return true;
}
bool CustomElementConstructorBuilder::prototypeIsValid(const AtomicString& type, ExceptionState& exceptionState) const
{
if (m_prototype->InternalFieldCount() || !V8HiddenValue::getHiddenValue(m_scriptState->isolate(), m_prototype, V8HiddenValue::customElementIsInterfacePrototypeObject(m_scriptState->isolate())).IsEmpty()) {
CustomElementException::throwException(CustomElementException::PrototypeInUse, type, exceptionState);
return false;
}
if (m_prototype->GetPropertyAttributes(v8String(m_scriptState->isolate(), "constructor")) & v8::DontDelete) {
CustomElementException::throwException(CustomElementException::ConstructorPropertyNotConfigurable, type, exceptionState);
return false;
}
return true;
}
bool CustomElementConstructorBuilder::didRegisterDefinition(CustomElementDefinition* definition) const
{
ASSERT(!m_constructor.IsEmpty());
return m_callbacks->setBinding(definition, CustomElementBinding::create(m_scriptState->isolate(), m_prototype));
}
ScriptValue CustomElementConstructorBuilder::bindingsReturnValue() const
{
return ScriptValue(m_scriptState.get(), m_constructor);
}
bool CustomElementConstructorBuilder::hasValidPrototypeChainFor(const WrapperTypeInfo* type) const
{
v8::Handle<v8::Object> elementPrototype = m_scriptState->perContextData()->prototypeForType(type);
if (elementPrototype.IsEmpty())
return false;
v8::Handle<v8::Value> chain = m_prototype;
while (!chain.IsEmpty() && chain->IsObject()) {
if (chain == elementPrototype)
return true;
chain = chain.As<v8::Object>()->GetPrototype();
}
return false;
}
static void constructCustomElement(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
if (!info.IsConstructCall()) {
V8ThrowException::throwTypeError(isolate, "DOM object constructor cannot be called as a function.");
return;
}
if (info.Length() > 0) {
V8ThrowException::throwTypeError(isolate, "This constructor should be called without arguments.");
return;
}
Document* document = V8Document::toImpl(V8HiddenValue::getHiddenValue(info.GetIsolate(), info.Callee(), V8HiddenValue::customElementDocument(isolate)).As<v8::Object>());
TOSTRING_VOID(V8StringResource<>, namespaceURI, V8HiddenValue::getHiddenValue(isolate, info.Callee(), V8HiddenValue::customElementNamespaceURI(isolate)));
TOSTRING_VOID(V8StringResource<>, tagName, V8HiddenValue::getHiddenValue(isolate, info.Callee(), V8HiddenValue::customElementTagName(isolate)));
v8::Handle<v8::Value> maybeType = V8HiddenValue::getHiddenValue(info.GetIsolate(), info.Callee(), V8HiddenValue::customElementType(isolate));
TOSTRING_VOID(V8StringResource<>, type, maybeType);
ExceptionState exceptionState(ExceptionState::ConstructionContext, "CustomElement", info.Holder(), info.GetIsolate());
CustomElementProcessingStack::CallbackDeliveryScope deliveryScope;
RefPtrWillBeRawPtr<Element> element = document->createElementNS(namespaceURI, tagName, maybeType->IsNull() ? nullAtom : type, exceptionState);
if (exceptionState.throwIfNeeded())
return;
v8SetReturnValueFast(info, element.release(), document);
}
} // namespace blink
<commit_msg>bindings: Use Maybe version of GetPropertyAttributes<commit_after>/*
* Copyright (C) 2013 Google 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 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 "config.h"
#include "bindings/core/v8/CustomElementConstructorBuilder.h"
#include "bindings/core/v8/CustomElementBinding.h"
#include "bindings/core/v8/DOMWrapperWorld.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8Document.h"
#include "bindings/core/v8/V8HTMLElement.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "bindings/core/v8/V8PerContextData.h"
#include "bindings/core/v8/V8SVGElement.h"
#include "core/HTMLNames.h"
#include "core/SVGNames.h"
#include "core/dom/Document.h"
#include "core/dom/ElementRegistrationOptions.h"
#include "core/dom/custom/CustomElementDefinition.h"
#include "core/dom/custom/CustomElementDescriptor.h"
#include "core/dom/custom/CustomElementException.h"
#include "core/dom/custom/CustomElementProcessingStack.h"
#include "wtf/Assertions.h"
namespace blink {
static void constructCustomElement(const v8::FunctionCallbackInfo<v8::Value>&);
CustomElementConstructorBuilder::CustomElementConstructorBuilder(ScriptState* scriptState, const ElementRegistrationOptions& options)
: m_scriptState(scriptState)
, m_options(options)
{
ASSERT(m_scriptState->context() == m_scriptState->isolate()->GetCurrentContext());
}
bool CustomElementConstructorBuilder::isFeatureAllowed() const
{
return m_scriptState->world().isMainWorld();
}
bool CustomElementConstructorBuilder::validateOptions(const AtomicString& type, QualifiedName& tagName, ExceptionState& exceptionState)
{
ASSERT(m_prototype.IsEmpty());
v8::TryCatch tryCatch;
if (!m_scriptState->perContextData()) {
// FIXME: This should generate an InvalidContext exception at a later point.
CustomElementException::throwException(CustomElementException::ContextDestroyedCheckingPrototype, type, exceptionState);
tryCatch.ReThrow();
return false;
}
if (m_options.hasPrototype()) {
ASSERT(m_options.prototype().isObject());
m_prototype = m_options.prototype().v8Value().As<v8::Object>();
} else {
m_prototype = v8::Object::New(m_scriptState->isolate());
v8::Local<v8::Object> basePrototype = m_scriptState->perContextData()->prototypeForType(&V8HTMLElement::wrapperTypeInfo);
if (!basePrototype.IsEmpty())
m_prototype->SetPrototype(basePrototype);
}
AtomicString namespaceURI = HTMLNames::xhtmlNamespaceURI;
if (hasValidPrototypeChainFor(&V8SVGElement::wrapperTypeInfo))
namespaceURI = SVGNames::svgNamespaceURI;
ASSERT(!tryCatch.HasCaught());
AtomicString localName;
if (m_options.hasExtends()) {
localName = AtomicString(m_options.extends().lower());
if (!Document::isValidName(localName)) {
CustomElementException::throwException(CustomElementException::ExtendsIsInvalidName, type, exceptionState);
tryCatch.ReThrow();
return false;
}
if (CustomElement::isValidName(localName)) {
CustomElementException::throwException(CustomElementException::ExtendsIsCustomElementName, type, exceptionState);
tryCatch.ReThrow();
return false;
}
} else {
if (namespaceURI == SVGNames::svgNamespaceURI) {
CustomElementException::throwException(CustomElementException::ExtendsIsInvalidName, type, exceptionState);
tryCatch.ReThrow();
return false;
}
localName = type;
}
ASSERT(!tryCatch.HasCaught());
tagName = QualifiedName(nullAtom, localName, namespaceURI);
return true;
}
PassRefPtrWillBeRawPtr<CustomElementLifecycleCallbacks> CustomElementConstructorBuilder::createCallbacks()
{
ASSERT(!m_prototype.IsEmpty());
v8::TryCatch exceptionCatcher;
exceptionCatcher.SetVerbose(true);
v8::Isolate* isolate = m_scriptState->isolate();
v8::Handle<v8::Function> created = retrieveCallback(isolate, "createdCallback");
v8::Handle<v8::Function> attached = retrieveCallback(isolate, "attachedCallback");
v8::Handle<v8::Function> detached = retrieveCallback(isolate, "detachedCallback");
v8::Handle<v8::Function> attributeChanged = retrieveCallback(isolate, "attributeChangedCallback");
m_callbacks = V8CustomElementLifecycleCallbacks::create(m_scriptState.get(), m_prototype, created, attached, detached, attributeChanged);
return m_callbacks.get();
}
v8::Handle<v8::Function> CustomElementConstructorBuilder::retrieveCallback(v8::Isolate* isolate, const char* name)
{
v8::Handle<v8::Value> value = m_prototype->Get(v8String(isolate, name));
if (value.IsEmpty() || !value->IsFunction())
return v8::Handle<v8::Function>();
return value.As<v8::Function>();
}
bool CustomElementConstructorBuilder::createConstructor(Document* document, CustomElementDefinition* definition, ExceptionState& exceptionState)
{
ASSERT(!m_prototype.IsEmpty());
ASSERT(m_constructor.IsEmpty());
ASSERT(document);
v8::Isolate* isolate = m_scriptState->isolate();
if (!prototypeIsValid(definition->descriptor().type(), exceptionState))
return false;
v8::Local<v8::FunctionTemplate> constructorTemplate = v8::FunctionTemplate::New(isolate);
constructorTemplate->SetCallHandler(constructCustomElement);
m_constructor = constructorTemplate->GetFunction();
if (m_constructor.IsEmpty()) {
CustomElementException::throwException(CustomElementException::ContextDestroyedRegisteringDefinition, definition->descriptor().type(), exceptionState);
return false;
}
const CustomElementDescriptor& descriptor = definition->descriptor();
v8::Handle<v8::String> v8TagName = v8String(isolate, descriptor.localName());
v8::Handle<v8::Value> v8Type;
if (descriptor.isTypeExtension())
v8Type = v8String(isolate, descriptor.type());
else
v8Type = v8::Null(isolate);
m_constructor->SetName(v8Type->IsNull() ? v8TagName : v8Type.As<v8::String>());
V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementDocument(isolate), toV8(document, m_scriptState->context()->Global(), isolate));
V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementNamespaceURI(isolate), v8String(isolate, descriptor.namespaceURI()));
V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementTagName(isolate), v8TagName);
V8HiddenValue::setHiddenValue(isolate, m_constructor, V8HiddenValue::customElementType(isolate), v8Type);
v8::Handle<v8::String> prototypeKey = v8String(isolate, "prototype");
ASSERT(m_constructor->HasOwnProperty(prototypeKey));
// This sets the property *value*; calling Set is safe because
// "prototype" is a non-configurable data property so there can be
// no side effects.
m_constructor->Set(prototypeKey, m_prototype);
// This *configures* the property. ForceSet of a function's
// "prototype" does not affect the value, but can reconfigure the
// property.
m_constructor->ForceSet(prototypeKey, m_prototype, v8::PropertyAttribute(v8::ReadOnly | v8::DontEnum | v8::DontDelete));
V8HiddenValue::setHiddenValue(isolate, m_prototype, V8HiddenValue::customElementIsInterfacePrototypeObject(isolate), v8::True(isolate));
m_prototype->ForceSet(v8String(isolate, "constructor"), m_constructor, v8::DontEnum);
return true;
}
bool CustomElementConstructorBuilder::prototypeIsValid(const AtomicString& type, ExceptionState& exceptionState) const
{
if (m_prototype->InternalFieldCount() || !V8HiddenValue::getHiddenValue(m_scriptState->isolate(), m_prototype, V8HiddenValue::customElementIsInterfacePrototypeObject(m_scriptState->isolate())).IsEmpty()) {
CustomElementException::throwException(CustomElementException::PrototypeInUse, type, exceptionState);
return false;
}
v8::PropertyAttribute propertyAttribute;
if (!getValueFromMaybe(m_prototype->GetPropertyAttributes(m_scriptState->isolate()->GetCurrentContext(), v8String(m_scriptState->isolate(), "constructor")), propertyAttribute) || (propertyAttribute & v8::DontDelete)) {
CustomElementException::throwException(CustomElementException::ConstructorPropertyNotConfigurable, type, exceptionState);
return false;
}
return true;
}
bool CustomElementConstructorBuilder::didRegisterDefinition(CustomElementDefinition* definition) const
{
ASSERT(!m_constructor.IsEmpty());
return m_callbacks->setBinding(definition, CustomElementBinding::create(m_scriptState->isolate(), m_prototype));
}
ScriptValue CustomElementConstructorBuilder::bindingsReturnValue() const
{
return ScriptValue(m_scriptState.get(), m_constructor);
}
bool CustomElementConstructorBuilder::hasValidPrototypeChainFor(const WrapperTypeInfo* type) const
{
v8::Handle<v8::Object> elementPrototype = m_scriptState->perContextData()->prototypeForType(type);
if (elementPrototype.IsEmpty())
return false;
v8::Handle<v8::Value> chain = m_prototype;
while (!chain.IsEmpty() && chain->IsObject()) {
if (chain == elementPrototype)
return true;
chain = chain.As<v8::Object>()->GetPrototype();
}
return false;
}
static void constructCustomElement(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Isolate* isolate = info.GetIsolate();
if (!info.IsConstructCall()) {
V8ThrowException::throwTypeError(isolate, "DOM object constructor cannot be called as a function.");
return;
}
if (info.Length() > 0) {
V8ThrowException::throwTypeError(isolate, "This constructor should be called without arguments.");
return;
}
Document* document = V8Document::toImpl(V8HiddenValue::getHiddenValue(info.GetIsolate(), info.Callee(), V8HiddenValue::customElementDocument(isolate)).As<v8::Object>());
TOSTRING_VOID(V8StringResource<>, namespaceURI, V8HiddenValue::getHiddenValue(isolate, info.Callee(), V8HiddenValue::customElementNamespaceURI(isolate)));
TOSTRING_VOID(V8StringResource<>, tagName, V8HiddenValue::getHiddenValue(isolate, info.Callee(), V8HiddenValue::customElementTagName(isolate)));
v8::Handle<v8::Value> maybeType = V8HiddenValue::getHiddenValue(info.GetIsolate(), info.Callee(), V8HiddenValue::customElementType(isolate));
TOSTRING_VOID(V8StringResource<>, type, maybeType);
ExceptionState exceptionState(ExceptionState::ConstructionContext, "CustomElement", info.Holder(), info.GetIsolate());
CustomElementProcessingStack::CallbackDeliveryScope deliveryScope;
RefPtrWillBeRawPtr<Element> element = document->createElementNS(namespaceURI, tagName, maybeType->IsNull() ? nullAtom : type, exceptionState);
if (exceptionState.throwIfNeeded())
return;
v8SetReturnValueFast(info, element.release(), document);
}
} // namespace blink
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/include/usr/ipmi/ipmiif.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2012,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __IPMI_IPMIIF_H
#define __IPMI_IPMIIF_H
#include <sys/msg.h>
#include <errl/errlentry.H>
#include <map>
namespace IPMI
{
// Message types which travel on the IPMI message queues
enum msg_type
{
// Sent when the interface goes idle *and* we had write which
// was told the interface was busy. We won't get notified of
// the general idle state.
MSG_STATE_IDLE,
// Ready to read a response
MSG_STATE_RESP,
// Ready to read an event/sms
MSG_STATE_EVNT,
// A message which needs to be sent
MSG_STATE_SEND,
MSG_STATE_SHUTDOWN,
MSG_STATE_SHUTDOWN_SEL,
MSG_STATE_GRACEFUL_SHUTDOWN,
// initiate a reboot request
MSG_STATE_INITIATE_POWER_CYCLE,
// Used to check range. Leave as last.
MSG_LAST_TYPE = MSG_STATE_INITIATE_POWER_CYCLE,
};
/**
* @brief Returns whether IPMI message type is related to
* system shutdown/reboot or not
*
* @param[in] i_msgType IPMI message type in question
*
* @return bool True or false value indicating whether requested IPMI
* message type is related to system shutdown/reboot or not
*/
inline bool validShutdownRebootMsgType(const msg_type i_msgType)
{
return ( (i_msgType == MSG_STATE_SHUTDOWN)
|| (i_msgType == MSG_STATE_SHUTDOWN_SEL)
|| (i_msgType == MSG_STATE_GRACEFUL_SHUTDOWN)
|| (i_msgType == MSG_STATE_INITIATE_POWER_CYCLE));
}
// chassis power off request types
enum power_request_type
{
CHASSIS_POWER_OFF = 0x00,
CHASSIS_POWER_SOFT_RESET = 0x01,
CHASSIS_POWER_CYCLE = 0x02,
CHASSIS_POWER_RESET = 0x03,
};
// Used in the factory for creating the proper subclass.
enum message_type
{
TYPE_SYNC = 0,
TYPE_ASYNC = 1,
TYPE_EVENT = 2,
};
// IPMI network functions
enum network_function
{
// These are the command network functions, the response
// network functions are the function + 1. So to determine
// the proper network function which issued the command
// associated with a response, subtract 1.
// Note: these are also shifted left to make room for the LUN.
NETFUN_CHASSIS = (0x00 << 2),
NETFUN_BRIDGE = (0x02 << 2),
NETFUN_SENSOR = (0x04 << 2),
NETFUN_APP = (0x06 << 2),
NETFUN_FIRMWARE = (0x08 << 2),
NETFUN_STORAGE = (0x0a << 2),
NETFUN_TRANPORT = (0x0c << 2),
NETFUN_GRPEXT = (0x2c << 2),
NETFUN_AMI = (0x32 << 2),
NETFUN_IBM = (0x3a << 2),
// Overload the OEM netfun for a "none" netfun. We use this as a
// default for objects which will have their netfun filled in
NETFUN_NONE = (0x30 << 2),
};
// SMS_ATN OEM Event constants
enum oem_event
{
OEM_VALID_NETFUN = 0x3a,
OEM_VALID_SEL_ID = 0x5555,
OEM_VALID_RECORD_TYPE = 0xC0,
};
// IPMI Completion Codes
enum completion_code
{
CC_OK = 0x00,
CC_CMDSPC1 = 0x80, // command specific completion code
CC_CMDSPC2 = 0x81, // command specific completion code
CC_BUSY = 0xc0,
CC_INVALID = 0xc1,
CC_CMDLUN = 0xc2,
CC_TIMEOUT = 0xc3,
CC_NOSPACE = 0xc4,
CC_BADRESV = 0xc5,
CC_TRUNC = 0xc6,
CC_BADLEN = 0xc7,
CC_TOOLONG = 0xc8,
CC_OORANGE = 0xc9,
CC_LONGREPLY = 0xca,
CC_BADSENSOR = 0xcb,
CC_REQINVAL = 0xcc,
CC_CMDSENSOR = 0xcd,
CC_CANTREPLY = 0xce,
CC_DUPREQ = 0xcf,
CC_SDRUPDATE = 0xd0,
CC_FMWUPDATE = 0xd1,
CC_BMCINIT = 0xd2,
CC_BADDEST = 0xd3,
CC_NOPERM = 0xd4,
CC_BADSTATE = 0xd5,
CC_ILLPARAM = 0xd6,
CC_UNKBAD = 0xff
};
// per IPMI Spec, section 32.2 OEM SEL Event Records
struct oemSEL {
enum Constants
{
MANUF_LENGTH = 3,
CMD_LENGTH = 5,
LENGTH = 16,
};
// ID used for SEL Record access. The Record ID values 0000h and FFFFh
// have special meaning in the Event Access commands and must not be
// used as Record ID values for stored SEL Event Records.
uint16_t iv_record;
// [7:0] - Record Type
// 02h = system event record
// C0h-DFh = OEM timestamped, bytes 8-16 OEM defined
// E0h-FFh = OEM non-timestamped, bytes 4-16 OEM defined
uint8_t iv_record_type;
// Time when event was logged. LS byte first.
uint32_t iv_timestamp;
// 3 bytes for the manuf id
uint8_t iv_manufacturer[MANUF_LENGTH];
// Presently 0x3A for IBM
uint8_t iv_netfun;
// Current command and arguments
uint8_t iv_cmd[CMD_LENGTH];
// @brief Populate a selRecord from the wire representation of an event
// @param[in] i_raw_event_data, pointer to the raw data
void populateFromEvent(uint8_t const* i_raw_event_data);
// ctor
oemSEL():
iv_record(0),
iv_record_type(0),
iv_timestamp(0),
iv_netfun(0)
{
memset(iv_manufacturer, 0, MANUF_LENGTH);
memset(iv_cmd, 0, CMD_LENGTH);
};
// @Brief Create a selRecord from the wire representation of an event
// @param[in] i_event_data, pointer to the event data
oemSEL( uint8_t const* i_event_data )
{ populateFromEvent( i_event_data ); }
};
//
// Network function, command pairs.
//
typedef std::pair<network_function, uint8_t> command_t;
// Application messages
inline const command_t get_device_id(void)
{ return std::make_pair(NETFUN_APP, 0x01); }
inline const command_t set_acpi_power_state(void)
{ return std::make_pair(NETFUN_APP, 0x06); }
inline const command_t set_watchdog(void)
{ return std::make_pair(NETFUN_APP, 0x24); }
inline const command_t reset_watchdog(void)
{ return std::make_pair(NETFUN_APP, 0x22); }
inline const command_t read_event(void)
{ return std::make_pair(NETFUN_APP, 0x35); }
inline const command_t get_capabilities(void)
{ return std::make_pair(NETFUN_APP, 0x36); }
// Chassis messages
inline const command_t chassis_power_off(void)
{ return std::make_pair(NETFUN_CHASSIS, 0x02); }
// Storage messages
inline const command_t set_sel_time(void)
{ return std::make_pair(NETFUN_STORAGE, 0x49); }
inline const command_t write_fru_data(void)
{ return std::make_pair(NETFUN_STORAGE, 0x12); }
inline const command_t get_sel_info(void)
{ return std::make_pair(NETFUN_STORAGE, 0x40); }
inline const command_t reserve_sel(void)
{ return std::make_pair(NETFUN_STORAGE, 0x42); }
inline const command_t add_sel(void)
{ return std::make_pair(NETFUN_STORAGE, 0x44); }
//AMI-specific storage messages
inline const command_t partial_add_esel(void)
{ return std::make_pair(NETFUN_AMI, 0xf0); }
// event messages
inline const command_t platform_event(void)
{ return std::make_pair(NETFUN_SENSOR, 0x02); }
// Sensor messages
inline const command_t set_sensor_reading(void)
{ return std::make_pair(NETFUN_SENSOR, 0x30); }
inline const command_t get_sensor_reading(void)
{ return std::make_pair(NETFUN_SENSOR, 0x2D); }
inline const command_t get_sensor_type(void)
{ return std::make_pair(NETFUN_SENSOR, 0x2F); }
// OEM Messages
inline const command_t power_off(void)
{ return std::make_pair(NETFUN_IBM, 0x04); }
inline const command_t pnor_request(void)
{ return std::make_pair(NETFUN_IBM, 0x07); }
inline const command_t pnor_response(void)
{ return std::make_pair(NETFUN_IBM, 0x08); }
// $TODO RTC:123256 - need to add code to get dcmi capabilities
// This is a dcmi message used to request the
// user defined power limit from the BMC.
inline const command_t get_power_limit(void)
{ return std::make_pair(NETFUN_GRPEXT, 0x03); }
// Some helper messages
// Used to create an empty message for reception
inline const command_t no_command(void)
{ return std::make_pair(NETFUN_NONE, 0x00); }
// This is a message used only for testing. The ipmid responder
// will drop this message so we can test timeouts.
inline const command_t test_drop(void)
{ return std::make_pair(NETFUN_APP, 0x3e); }
/**
* Send message asynchronously
* @param[in] i_cmd, the network function and command
* @param[in] i_len, the length of the buffer
* @param[in] i_data, the buffer - must be new'd
* @param[in] i_type, the message type EVENT/ASYNC- defaults to ASYNC
* @example uint8_t* data = new uint8_t[length];
* @warning do *not* delete data, the resource provider will do that.
*
* @return errlHndl_t, NULL on success
*/
errlHndl_t send(const command_t& i_cmd,
const size_t i_len,
uint8_t* i_data,
message_type i_type = TYPE_ASYNC);
/**
* Send message synchronously
* @param[in] i_cmd, the command and network function
* @param[out] o_completion_code, the completion code
* @param[in,out] io_len, the length of the buffer
* @param[in] i_data, the buffer - must be new'd
* @example uint8_t* data = new uint8_t[length];
* @example delete[] data;
*
* @return errlHndl_t, NULL on success
*/
errlHndl_t sendrecv(const command_t& i_cmd,
completion_code& o_completion_code,
size_t& io_len, uint8_t*& io_data);
/**
* Synchronously send an event
* @param[in] i_sensor_type, the sensor type
* @param[in] i_sensor_num, the sensor number
* @param[in] i_assertion, bool true is assert, false is deassert.
* @param[in] i_type, event type
* @param[out] o_completion_code, completion code
* @param[in] i_len, number of data bytes (1-3)
* @param[in] i_data, data bytes
*
* @return errlHndl_t, NULL on success
*/
errlHndl_t send_event(const uint8_t i_sensor_type,
const uint8_t i_sensor_number,
const bool i_assertion,
const uint8_t i_type,
completion_code& o_completion_code,
const size_t i_len,
uint8_t* i_data);
/**
* Get the max buffer size
* @param void
*
* @return the maximum space allowed for data, per message
* (max message for the transport - the header size)
*/
size_t max_buffer(void);
/**
* @brief Initiate a graceful reboot sequence via the IPMI resource
* provider
*/
void initiateReboot();
/**
* @brief Initiate a power off sequence via the IPMI resource provider
*/
void initiatePowerOff();
/**
* Structure to return BMC/IPMI information in
*/
struct BmcInfo_t
{
uint64_t bulkTransferLpcBaseAddr; //< Base address of the bulk transfer
// LPC bus. Relative to the IO space on the LPC
uint32_t bulkTransferSize; //< Size of bulk transfer device address
// space on the LPC bus
uint8_t chipVersion; //< ML2 chip version
uint8_t smsAttnInterrupt; //< SMS attention interrupt number
uint8_t bmcToHostInterrupt; //< BMC to Host response interrupt
char bmcVendor[32]; //< BMC vendor string. AMI, Aten or OpenBmc
};
/**
* Retrieve some information about the BMC and the connection
* we have to it.
*
* @return Structure of BMC data
*/
BmcInfo_t getBmcInfo(void);
}; // end namespace IPMI
#endif
<commit_msg>Remove NETFUN_AMI from ipmiif.H<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/include/usr/ipmi/ipmiif.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2012,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __IPMI_IPMIIF_H
#define __IPMI_IPMIIF_H
#include <sys/msg.h>
#include <errl/errlentry.H>
#include <map>
namespace IPMI
{
// Message types which travel on the IPMI message queues
enum msg_type
{
// Sent when the interface goes idle *and* we had write which
// was told the interface was busy. We won't get notified of
// the general idle state.
MSG_STATE_IDLE,
// Ready to read a response
MSG_STATE_RESP,
// Ready to read an event/sms
MSG_STATE_EVNT,
// A message which needs to be sent
MSG_STATE_SEND,
MSG_STATE_SHUTDOWN,
MSG_STATE_SHUTDOWN_SEL,
MSG_STATE_GRACEFUL_SHUTDOWN,
// initiate a reboot request
MSG_STATE_INITIATE_POWER_CYCLE,
// Used to check range. Leave as last.
MSG_LAST_TYPE = MSG_STATE_INITIATE_POWER_CYCLE,
};
/**
* @brief Returns whether IPMI message type is related to
* system shutdown/reboot or not
*
* @param[in] i_msgType IPMI message type in question
*
* @return bool True or false value indicating whether requested IPMI
* message type is related to system shutdown/reboot or not
*/
inline bool validShutdownRebootMsgType(const msg_type i_msgType)
{
return ( (i_msgType == MSG_STATE_SHUTDOWN)
|| (i_msgType == MSG_STATE_SHUTDOWN_SEL)
|| (i_msgType == MSG_STATE_GRACEFUL_SHUTDOWN)
|| (i_msgType == MSG_STATE_INITIATE_POWER_CYCLE));
}
// chassis power off request types
enum power_request_type
{
CHASSIS_POWER_OFF = 0x00,
CHASSIS_POWER_SOFT_RESET = 0x01,
CHASSIS_POWER_CYCLE = 0x02,
CHASSIS_POWER_RESET = 0x03,
};
// Used in the factory for creating the proper subclass.
enum message_type
{
TYPE_SYNC = 0,
TYPE_ASYNC = 1,
TYPE_EVENT = 2,
};
// IPMI network functions
enum network_function
{
// These are the command network functions, the response
// network functions are the function + 1. So to determine
// the proper network function which issued the command
// associated with a response, subtract 1.
// Note: these are also shifted left to make room for the LUN.
NETFUN_CHASSIS = (0x00 << 2),
NETFUN_BRIDGE = (0x02 << 2),
NETFUN_SENSOR = (0x04 << 2),
NETFUN_APP = (0x06 << 2),
NETFUN_FIRMWARE = (0x08 << 2),
NETFUN_STORAGE = (0x0a << 2),
NETFUN_TRANPORT = (0x0c << 2),
NETFUN_GRPEXT = (0x2c << 2),
NETFUN_IBM = (0x3a << 2),
// Overload the OEM netfun for a "none" netfun. We use this as a
// default for objects which will have their netfun filled in
NETFUN_NONE = (0x30 << 2),
};
// SMS_ATN OEM Event constants
enum oem_event
{
OEM_VALID_NETFUN = 0x3a,
OEM_VALID_SEL_ID = 0x5555,
OEM_VALID_RECORD_TYPE = 0xC0,
};
// IPMI Completion Codes
enum completion_code
{
CC_OK = 0x00,
CC_CMDSPC1 = 0x80, // command specific completion code
CC_CMDSPC2 = 0x81, // command specific completion code
CC_BUSY = 0xc0,
CC_INVALID = 0xc1,
CC_CMDLUN = 0xc2,
CC_TIMEOUT = 0xc3,
CC_NOSPACE = 0xc4,
CC_BADRESV = 0xc5,
CC_TRUNC = 0xc6,
CC_BADLEN = 0xc7,
CC_TOOLONG = 0xc8,
CC_OORANGE = 0xc9,
CC_LONGREPLY = 0xca,
CC_BADSENSOR = 0xcb,
CC_REQINVAL = 0xcc,
CC_CMDSENSOR = 0xcd,
CC_CANTREPLY = 0xce,
CC_DUPREQ = 0xcf,
CC_SDRUPDATE = 0xd0,
CC_FMWUPDATE = 0xd1,
CC_BMCINIT = 0xd2,
CC_BADDEST = 0xd3,
CC_NOPERM = 0xd4,
CC_BADSTATE = 0xd5,
CC_ILLPARAM = 0xd6,
CC_UNKBAD = 0xff
};
// per IPMI Spec, section 32.2 OEM SEL Event Records
struct oemSEL {
enum Constants
{
MANUF_LENGTH = 3,
CMD_LENGTH = 5,
LENGTH = 16,
};
// ID used for SEL Record access. The Record ID values 0000h and FFFFh
// have special meaning in the Event Access commands and must not be
// used as Record ID values for stored SEL Event Records.
uint16_t iv_record;
// [7:0] - Record Type
// 02h = system event record
// C0h-DFh = OEM timestamped, bytes 8-16 OEM defined
// E0h-FFh = OEM non-timestamped, bytes 4-16 OEM defined
uint8_t iv_record_type;
// Time when event was logged. LS byte first.
uint32_t iv_timestamp;
// 3 bytes for the manuf id
uint8_t iv_manufacturer[MANUF_LENGTH];
// Presently 0x3A for IBM
uint8_t iv_netfun;
// Current command and arguments
uint8_t iv_cmd[CMD_LENGTH];
// @brief Populate a selRecord from the wire representation of an event
// @param[in] i_raw_event_data, pointer to the raw data
void populateFromEvent(uint8_t const* i_raw_event_data);
// ctor
oemSEL():
iv_record(0),
iv_record_type(0),
iv_timestamp(0),
iv_netfun(0)
{
memset(iv_manufacturer, 0, MANUF_LENGTH);
memset(iv_cmd, 0, CMD_LENGTH);
};
// @Brief Create a selRecord from the wire representation of an event
// @param[in] i_event_data, pointer to the event data
oemSEL( uint8_t const* i_event_data )
{ populateFromEvent( i_event_data ); }
};
//
// Network function, command pairs.
//
typedef std::pair<network_function, uint8_t> command_t;
// Application messages
inline const command_t get_device_id(void)
{ return std::make_pair(NETFUN_APP, 0x01); }
inline const command_t set_acpi_power_state(void)
{ return std::make_pair(NETFUN_APP, 0x06); }
inline const command_t set_watchdog(void)
{ return std::make_pair(NETFUN_APP, 0x24); }
inline const command_t reset_watchdog(void)
{ return std::make_pair(NETFUN_APP, 0x22); }
inline const command_t read_event(void)
{ return std::make_pair(NETFUN_APP, 0x35); }
inline const command_t get_capabilities(void)
{ return std::make_pair(NETFUN_APP, 0x36); }
// Chassis messages
inline const command_t chassis_power_off(void)
{ return std::make_pair(NETFUN_CHASSIS, 0x02); }
// Storage messages
inline const command_t set_sel_time(void)
{ return std::make_pair(NETFUN_STORAGE, 0x49); }
inline const command_t write_fru_data(void)
{ return std::make_pair(NETFUN_STORAGE, 0x12); }
inline const command_t get_sel_info(void)
{ return std::make_pair(NETFUN_STORAGE, 0x40); }
inline const command_t reserve_sel(void)
{ return std::make_pair(NETFUN_STORAGE, 0x42); }
inline const command_t add_sel(void)
{ return std::make_pair(NETFUN_STORAGE, 0x44); }
inline const command_t partial_add_esel(void)
{ return std::make_pair(NETFUN_IBM, 0xf0); }
// event messages
inline const command_t platform_event(void)
{ return std::make_pair(NETFUN_SENSOR, 0x02); }
// Sensor messages
inline const command_t set_sensor_reading(void)
{ return std::make_pair(NETFUN_SENSOR, 0x30); }
inline const command_t get_sensor_reading(void)
{ return std::make_pair(NETFUN_SENSOR, 0x2D); }
inline const command_t get_sensor_type(void)
{ return std::make_pair(NETFUN_SENSOR, 0x2F); }
// OEM Messages
inline const command_t power_off(void)
{ return std::make_pair(NETFUN_IBM, 0x04); }
inline const command_t pnor_request(void)
{ return std::make_pair(NETFUN_IBM, 0x07); }
inline const command_t pnor_response(void)
{ return std::make_pair(NETFUN_IBM, 0x08); }
// $TODO RTC:123256 - need to add code to get dcmi capabilities
// This is a dcmi message used to request the
// user defined power limit from the BMC.
inline const command_t get_power_limit(void)
{ return std::make_pair(NETFUN_GRPEXT, 0x03); }
// Some helper messages
// Used to create an empty message for reception
inline const command_t no_command(void)
{ return std::make_pair(NETFUN_NONE, 0x00); }
// This is a message used only for testing. The ipmid responder
// will drop this message so we can test timeouts.
inline const command_t test_drop(void)
{ return std::make_pair(NETFUN_APP, 0x3e); }
/**
* Send message asynchronously
* @param[in] i_cmd, the network function and command
* @param[in] i_len, the length of the buffer
* @param[in] i_data, the buffer - must be new'd
* @param[in] i_type, the message type EVENT/ASYNC- defaults to ASYNC
* @example uint8_t* data = new uint8_t[length];
* @warning do *not* delete data, the resource provider will do that.
*
* @return errlHndl_t, NULL on success
*/
errlHndl_t send(const command_t& i_cmd,
const size_t i_len,
uint8_t* i_data,
message_type i_type = TYPE_ASYNC);
/**
* Send message synchronously
* @param[in] i_cmd, the command and network function
* @param[out] o_completion_code, the completion code
* @param[in,out] io_len, the length of the buffer
* @param[in] i_data, the buffer - must be new'd
* @example uint8_t* data = new uint8_t[length];
* @example delete[] data;
*
* @return errlHndl_t, NULL on success
*/
errlHndl_t sendrecv(const command_t& i_cmd,
completion_code& o_completion_code,
size_t& io_len, uint8_t*& io_data);
/**
* Synchronously send an event
* @param[in] i_sensor_type, the sensor type
* @param[in] i_sensor_num, the sensor number
* @param[in] i_assertion, bool true is assert, false is deassert.
* @param[in] i_type, event type
* @param[out] o_completion_code, completion code
* @param[in] i_len, number of data bytes (1-3)
* @param[in] i_data, data bytes
*
* @return errlHndl_t, NULL on success
*/
errlHndl_t send_event(const uint8_t i_sensor_type,
const uint8_t i_sensor_number,
const bool i_assertion,
const uint8_t i_type,
completion_code& o_completion_code,
const size_t i_len,
uint8_t* i_data);
/**
* Get the max buffer size
* @param void
*
* @return the maximum space allowed for data, per message
* (max message for the transport - the header size)
*/
size_t max_buffer(void);
/**
* @brief Initiate a graceful reboot sequence via the IPMI resource
* provider
*/
void initiateReboot();
/**
* @brief Initiate a power off sequence via the IPMI resource provider
*/
void initiatePowerOff();
/**
* Structure to return BMC/IPMI information in
*/
struct BmcInfo_t
{
uint64_t bulkTransferLpcBaseAddr; //< Base address of the bulk transfer
// LPC bus. Relative to the IO space on the LPC
uint32_t bulkTransferSize; //< Size of bulk transfer device address
// space on the LPC bus
uint8_t chipVersion; //< ML2 chip version
uint8_t smsAttnInterrupt; //< SMS attention interrupt number
uint8_t bmcToHostInterrupt; //< BMC to Host response interrupt
char bmcVendor[32]; //< BMC vendor string. AMI, Aten or OpenBmc
};
/**
* Retrieve some information about the BMC and the connection
* we have to it.
*
* @return Structure of BMC data
*/
BmcInfo_t getBmcInfo(void);
}; // end namespace IPMI
#endif
<|endoftext|> |
<commit_before>/****************************************************************************
ui_features.hpp - Support file for writing LV2 plugins in C++
Copyright (C) 2013 Michael Fisher <[email protected]>
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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA
****************************************************************************/
#ifndef LVTK_UI_FEATURES_HPP
#define LVTK_UI_FEATURES_HPP
#include <lv2/lv2plug.in/ns/extensions/ui/ui.h>
namespace lvtk {
/** The PortSubscribe Mixin.
@ingroup guimixins
@see The internal struct I for details.
*/
template<bool Required = false>
struct PortSubscribe
{
template<class Derived>
struct I : Extension<Required>
{
I() { memset (&m_pmap, 0, sizeof (LV2UI_Port_Map)); }
/** @internal */
static void
map_feature_handlers (FeatureHandlerMap& hmap)
{
hmap[LV2_UI__portSubscribe] = &I<Derived>::handle_feature;
}
/** @internal */
static void
handle_feature (void* instance, FeatureData* data)
{
Derived* d = reinterpret_cast<Derived*>(instance);
I<Derived>* mixin = static_cast<I<Derived>*>(d);
LV2UI_Port_Subscribe* ps (reinterpret_cast<LV2UI_Port_Subscribe*> (data));
memcpy (&mixin->m_subscribe, ps, sizeof (LV2UI_Port_Subscribe));
mixin->m_ok = (ps->handle != NULL &&
ps->subscribe != NULL &&
ps->unsubscribe != NULL);
}
bool
check_ok()
{
if (! Required)
this->m_ok = true;
if (LVTK_DEBUG)
{
std::clog << " [PortSubscribe] Validation "
<< (this->m_ok ? "succeeded" : "failed")
<< "." << std::endl;
}
return this->m_ok;
}
protected:
bool
subscribe (uint32_t port, uint32_t protocol, const Feature* const* features)
{
if (portsubscribe_is_valid())
return (0 == m_subscribe.subscribe (m_subscribe.handle, port, protocol, features));
return false;
}
bool
unsubscribe (uint32_t port, uint32_t protocol, const Feature* const* features)
{
if (portsubscribe_is_valid())
return (0 == m_subscribe.unsubscribe (m_subscribe.handle, port, protocol, features));
return false;
}
private:
LV2UI_Port_Subscribe m_subscribe;
/** @internal */
bool portsubscribe_is_valid() const
{
return (m_subscribe.handle != NULL &&
m_subscribe.subscribe != NULL &&
m_subscribe.unsubscribe != NULL);
}
};
};
/** The PortMap Mixin.
@ingroup guimixins
@see The internal struct I for details.
*/
template<bool Required = false>
struct PortMap
{
template<class Derived>
struct I : Extension<Required>
{
I() { memset (&m_pmap, 0, sizeof (LV2UI_Port_Map)); }
/** @internal */
static void
map_feature_handlers (FeatureHandlerMap& hmap)
{
hmap[LV2_UI__portIndex] = &I<Derived>::handle_feature;
//hmap[LV2_UI__portMap] = &I<Derived>::handle_feature;
}
/** @internal */
static void
handle_feature (void* instance, FeatureData* data)
{
Derived* d = reinterpret_cast<Derived*>(instance);
I<Derived>* mixin = static_cast<I<Derived>*>(d);
LV2UI_Port_Map* pm (reinterpret_cast<LV2UI_Port_Map*> (data));
mixin->m_pmap.handle = pm->handle;
mixin->m_pmap.port_index = pm->port_index;
mixin->m_ok = (pm->handle != NULL && pm->port_index != NULL);
}
bool
check_ok()
{
if (! Required)
this->m_ok = true;
if (LVTK_DEBUG)
{
std::clog << " [PortMap] Validation "
<< (this->m_ok ? "succeeded" : "failed")
<< "." << std::endl;
}
return this->m_ok;
}
protected:
uint32_t
port_index (const char* symbol)
{
if (portmap_is_valid())
return m_pmap.port_index (m_pmap.handle, symbol);
return LV2UI_INVALID_PORT_INDEX;
}
private:
LV2UI_Port_Map m_pmap;
/** @internal */
bool portmap_is_valid() const
{
return (m_pmap.handle != NULL &&
m_pmap.port_index != NULL);
}
};
};
/** The Touch Mixin.
@ingroup guimixins
@see The internal struct I for details.
*/
template<bool Required = false>
struct Touch
{
template<class Derived>
struct I : Extension<Required>
{
I() { memset (&m_touch, 0, sizeof (LV2UI_Touch)); }
/** @internal */
static void
map_feature_handlers (FeatureHandlerMap& hmap)
{
hmap[LV2_UI__touch] = &I<Derived>::handle_feature;
}
/** @internal */
static void
handle_feature (void* instance, void* data)
{
Derived* d = reinterpret_cast<Derived*>(instance);
I<Derived>* mixin = static_cast<I<Derived>*>(d);
LV2UI_Touch* t (reinterpret_cast<LV2UI_Touch*> (data));
mixin->m_touch.handle = t->handle;
mixin->m_touch.touch = t->touch;
mixin->m_ok = (mixin->m_touch.handle != NULL &&
mixin->m_touch.touch != NULL);
}
bool
check_ok()
{
if (! Required)
this->m_ok = true;
if (LVTK_DEBUG)
{
std::clog << " [Touch] Validation "
<< (this->m_ok ? "succeeded" : "failed")
<< "." << std::endl;
}
return this->m_ok;
}
protected:
void
touch (uint32_t port, bool grabbed)
{
if (touch_is_valid())
m_touch.touch (m_touch.handle, port, grabbed);
}
private:
LV2UI_Touch m_touch;
/** @internal */
bool touch_is_valid() const
{
return m_touch.handle != NULL &&
m_touch.touch != NULL;
}
};
};
/** The Parent Mixin.
@ingroup guimixins
@see The internal struct I for details.
*/
template<bool Required = false>
struct Parent
{
template<class Derived>
struct I : Extension<Required>
{
I() : p_parent (NULL) { }
/** @internal */
static void
map_feature_handlers(FeatureHandlerMap& hmap)
{
hmap[LV2_UI__parent] = &I<Derived>::handle_feature;
}
/** @internal */
static void
handle_feature(void* instance, void* data)
{
Derived* d = reinterpret_cast<Derived*>(instance);
I<Derived>* mixin = static_cast<I<Derived>*>(d);
mixin->p_parent = reinterpret_cast<LV2UI_Widget*> (data);
mixin->m_ok = mixin->p_parent != NULL;
}
bool
check_ok()
{
if (! Required)
this->m_ok = true;
if (LVTK_DEBUG)
{
std::clog << " [Parent] Validation "
<< (this->m_ok ? "succeeded" : "failed")
<< "." << std::endl;
}
return this->m_ok;
}
protected:
/** Get the parent widget if any
@return The parent LV2_Widget or NULL if not provided
*/
LV2UI_Widget*
get_parent()
{
return p_parent;
}
private:
LV2UI_Widget* p_parent;
};
};
/** The UIResize Mixin.
@ingroup guimixins
@see The internal struct I for details.
*/
template<bool Required = true>
struct UIResize
{
template<class Derived>
struct I : Extension<Required>
{
I()
{
m_resize.handle = NULL;
m_resize.ui_resize = NULL;
}
/** @internal */
static void
map_feature_handlers(FeatureHandlerMap& hmap)
{
hmap[LV2_UI__resize] = &I<Derived>::handle_feature;
}
/** @internal */
static void
handle_feature(void* instance, void* data)
{
Derived* d = reinterpret_cast<Derived*>(instance);
I<Derived>* mixin = static_cast<I<Derived>*>(d);
LV2UI_Resize* rz (reinterpret_cast<LV2UI_Resize*> (data));
mixin->m_resize.handle = rz->handle;
mixin->m_resize.ui_resize = rz->ui_resize;
mixin->m_ok = true;
}
bool
check_ok()
{
if (! Required) {
this->m_ok = true;
} else {
this->m_ok = rsz_is_valid();
}
if (LVTK_DEBUG)
{
std::clog << " [UIResize] Validation "
<< (this->m_ok ? "succeeded" : "failed")
<< "." << std::endl;
}
return this->m_ok;
}
protected:
/** */
bool
ui_resize(int width, int height)
{
if (rsz_is_valid())
return (0 == m_resize.ui_resize (m_resize.handle, width, height));
return false;
}
private:
LV2UI_Resize m_resize;
bool rsz_is_valid() const { return m_resize.ui_resize != NULL && m_resize.handle != NULL; }
};
};
}
#endif /* LVTK_UI_FEATURES_HPP */
<commit_msg>Fixed a typo in PortSubscribe mixin<commit_after>/****************************************************************************
ui_features.hpp - Support file for writing LV2 plugins in C++
Copyright (C) 2013 Michael Fisher <[email protected]>
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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA
****************************************************************************/
#ifndef LVTK_UI_FEATURES_HPP
#define LVTK_UI_FEATURES_HPP
#include <lv2/lv2plug.in/ns/extensions/ui/ui.h>
namespace lvtk {
/** The PortSubscribe Mixin.
@ingroup guimixins
@see The internal struct I for details.
*/
template<bool Required = false>
struct PortSubscribe
{
template<class Derived>
struct I : Extension<Required>
{
I() { memset (&m_subscribe, 0, sizeof (LV2UI_Port_Subscribe)); }
/** @internal */
static void
map_feature_handlers (FeatureHandlerMap& hmap)
{
hmap[LV2_UI__portSubscribe] = &I<Derived>::handle_feature;
}
/** @internal */
static void
handle_feature (void* instance, FeatureData* data)
{
Derived* d = reinterpret_cast<Derived*>(instance);
I<Derived>* mixin = static_cast<I<Derived>*>(d);
LV2UI_Port_Subscribe* ps (reinterpret_cast<LV2UI_Port_Subscribe*> (data));
memcpy (&mixin->m_subscribe, ps, sizeof (LV2UI_Port_Subscribe));
mixin->m_ok = (ps->handle != NULL &&
ps->subscribe != NULL &&
ps->unsubscribe != NULL);
}
bool
check_ok()
{
if (! Required)
this->m_ok = true;
if (LVTK_DEBUG)
{
std::clog << " [PortSubscribe] Validation "
<< (this->m_ok ? "succeeded" : "failed")
<< "." << std::endl;
}
return this->m_ok;
}
protected:
bool
subscribe (uint32_t port, uint32_t protocol, const Feature* const* features)
{
if (portsubscribe_is_valid())
return (0 == m_subscribe.subscribe (m_subscribe.handle, port, protocol, features));
return false;
}
bool
unsubscribe (uint32_t port, uint32_t protocol, const Feature* const* features)
{
if (portsubscribe_is_valid())
return (0 == m_subscribe.unsubscribe (m_subscribe.handle, port, protocol, features));
return false;
}
private:
LV2UI_Port_Subscribe m_subscribe;
/** @internal */
bool portsubscribe_is_valid() const
{
return (m_subscribe.handle != NULL &&
m_subscribe.subscribe != NULL &&
m_subscribe.unsubscribe != NULL);
}
};
};
/** The PortMap Mixin.
@ingroup guimixins
@see The internal struct I for details.
*/
template<bool Required = false>
struct PortMap
{
template<class Derived>
struct I : Extension<Required>
{
I() { memset (&m_pmap, 0, sizeof (LV2UI_Port_Map)); }
/** @internal */
static void
map_feature_handlers (FeatureHandlerMap& hmap)
{
hmap[LV2_UI__portIndex] = &I<Derived>::handle_feature;
//hmap[LV2_UI__portMap] = &I<Derived>::handle_feature;
}
/** @internal */
static void
handle_feature (void* instance, FeatureData* data)
{
Derived* d = reinterpret_cast<Derived*>(instance);
I<Derived>* mixin = static_cast<I<Derived>*>(d);
LV2UI_Port_Map* pm (reinterpret_cast<LV2UI_Port_Map*> (data));
mixin->m_pmap.handle = pm->handle;
mixin->m_pmap.port_index = pm->port_index;
mixin->m_ok = (pm->handle != NULL && pm->port_index != NULL);
}
bool
check_ok()
{
if (! Required)
this->m_ok = true;
if (LVTK_DEBUG)
{
std::clog << " [PortMap] Validation "
<< (this->m_ok ? "succeeded" : "failed")
<< "." << std::endl;
}
return this->m_ok;
}
protected:
uint32_t
port_index (const char* symbol)
{
if (portmap_is_valid())
return m_pmap.port_index (m_pmap.handle, symbol);
return LV2UI_INVALID_PORT_INDEX;
}
private:
LV2UI_Port_Map m_pmap;
/** @internal */
bool portmap_is_valid() const
{
return (m_pmap.handle != NULL &&
m_pmap.port_index != NULL);
}
};
};
/** The Touch Mixin.
@ingroup guimixins
@see The internal struct I for details.
*/
template<bool Required = false>
struct Touch
{
template<class Derived>
struct I : Extension<Required>
{
I() { memset (&m_touch, 0, sizeof (LV2UI_Touch)); }
/** @internal */
static void
map_feature_handlers (FeatureHandlerMap& hmap)
{
hmap[LV2_UI__touch] = &I<Derived>::handle_feature;
}
/** @internal */
static void
handle_feature (void* instance, void* data)
{
Derived* d = reinterpret_cast<Derived*>(instance);
I<Derived>* mixin = static_cast<I<Derived>*>(d);
LV2UI_Touch* t (reinterpret_cast<LV2UI_Touch*> (data));
mixin->m_touch.handle = t->handle;
mixin->m_touch.touch = t->touch;
mixin->m_ok = (mixin->m_touch.handle != NULL &&
mixin->m_touch.touch != NULL);
}
bool
check_ok()
{
if (! Required)
this->m_ok = true;
if (LVTK_DEBUG)
{
std::clog << " [Touch] Validation "
<< (this->m_ok ? "succeeded" : "failed")
<< "." << std::endl;
}
return this->m_ok;
}
protected:
void
touch (uint32_t port, bool grabbed)
{
if (touch_is_valid())
m_touch.touch (m_touch.handle, port, grabbed);
}
private:
LV2UI_Touch m_touch;
/** @internal */
bool touch_is_valid() const
{
return m_touch.handle != NULL &&
m_touch.touch != NULL;
}
};
};
/** The Parent Mixin.
@ingroup guimixins
@see The internal struct I for details.
*/
template<bool Required = false>
struct Parent
{
template<class Derived>
struct I : Extension<Required>
{
I() : p_parent (NULL) { }
/** @internal */
static void
map_feature_handlers(FeatureHandlerMap& hmap)
{
hmap[LV2_UI__parent] = &I<Derived>::handle_feature;
}
/** @internal */
static void
handle_feature(void* instance, void* data)
{
Derived* d = reinterpret_cast<Derived*>(instance);
I<Derived>* mixin = static_cast<I<Derived>*>(d);
mixin->p_parent = reinterpret_cast<LV2UI_Widget*> (data);
mixin->m_ok = mixin->p_parent != NULL;
}
bool
check_ok()
{
if (! Required)
this->m_ok = true;
if (LVTK_DEBUG)
{
std::clog << " [Parent] Validation "
<< (this->m_ok ? "succeeded" : "failed")
<< "." << std::endl;
}
return this->m_ok;
}
protected:
/** Get the parent widget if any
@return The parent LV2_Widget or NULL if not provided
*/
LV2UI_Widget*
get_parent()
{
return p_parent;
}
private:
LV2UI_Widget* p_parent;
};
};
/** The UIResize Mixin.
@ingroup guimixins
@see The internal struct I for details.
*/
template<bool Required = true>
struct UIResize
{
template<class Derived>
struct I : Extension<Required>
{
I()
{
m_resize.handle = NULL;
m_resize.ui_resize = NULL;
}
/** @internal */
static void
map_feature_handlers(FeatureHandlerMap& hmap)
{
hmap[LV2_UI__resize] = &I<Derived>::handle_feature;
}
/** @internal */
static void
handle_feature(void* instance, void* data)
{
Derived* d = reinterpret_cast<Derived*>(instance);
I<Derived>* mixin = static_cast<I<Derived>*>(d);
LV2UI_Resize* rz (reinterpret_cast<LV2UI_Resize*> (data));
mixin->m_resize.handle = rz->handle;
mixin->m_resize.ui_resize = rz->ui_resize;
mixin->m_ok = true;
}
bool
check_ok()
{
if (! Required) {
this->m_ok = true;
} else {
this->m_ok = rsz_is_valid();
}
if (LVTK_DEBUG)
{
std::clog << " [UIResize] Validation "
<< (this->m_ok ? "succeeded" : "failed")
<< "." << std::endl;
}
return this->m_ok;
}
protected:
/** */
bool
ui_resize(int width, int height)
{
if (rsz_is_valid())
return (0 == m_resize.ui_resize (m_resize.handle, width, height));
return false;
}
private:
LV2UI_Resize m_resize;
bool rsz_is_valid() const { return m_resize.ui_resize != NULL && m_resize.handle != NULL; }
};
};
}
#endif /* LVTK_UI_FEATURES_HPP */
<|endoftext|> |
<commit_before>/*
MusicXML Library
Copyright (C) Grame 2006-2013
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France
[email protected]
*/
#include <vector>
#include "libmusicxml.h"
#include "musicxmlfactory.h"
#include "versions.h"
using namespace std;
namespace MusicXML2
{
EXP float musicxmllibVersion() { return versions::libVersion(); }
EXP const char* musicxmllibVersionStr() { return versions::libVersionStr(); }
EXP float musicxml2guidoVersion() { return versions::xml2guidoVersion(); }
EXP const char* musicxml2guidoVersionStr() { return versions::xml2guidoVersionStr(); }
//EXP int musicxml2antescofoVersion() { return versions::xml2antescofoVersion(); }
//EXP const char* musicxml2antescofoVersionStr() { return versions::xml2antescofoVersionStr(); }
//------------------------------------------------------------------------
EXP TFactory factoryOpen () { return new musicxmlfactory(); }
EXP void factoryClose (TFactory f) { delete f; }
EXP void factoryPrint (TFactory f, ostream& out) { f->print(out); }
//------------------------------------------------------------------------
static TElement __retainElt (Sxmlelement elt) { elt->addReference(); return (TElement)elt; }
static TAttribute __retainAttr (Sxmlattribute attr) { attr->addReference(); return (TAttribute)attr; }
static Sxmlelement __releaseElt (TElement elt) { Sxmlelement xml(elt); elt->removeReference(); return xml; }
static Sxmlattribute __releaseAttr (TAttribute attr) { Sxmlattribute xml(attr); attr->removeReference(); return xml; }
//------------------------------------------------------------------------
// high level operations
//------------------------------------------------------------------------
EXP void factoryHeader (TFactory f, const char* wn, const char* wt, const char* mn, const char* mt)
{ f->header(wn, wt, mn, mt); }
EXP void factoryCreator (TFactory f, const char* c, const char* type)
{ f->creator(c, type); }
EXP void factoryRights (TFactory f, const char* c, const char* type)
{ f->rights(c, type); }
EXP void factoryEncoding (TFactory f, const char* soft)
{ f->encoding(soft); }
EXP void factoryAddGroup (TFactory f, int number, const char* name, const char* abbrev, bool groupbarline, TElement* parts)
{
vector<Sxmlelement> list;
while (*parts) {
list.push_back(__releaseElt(*parts));
parts++;
}
f->addgroup (number, name, abbrev, groupbarline, list);
}
EXP void factoryAddPart (TFactory f, TElement part)
{ f->addpart (__releaseElt(part)); }
EXP TElement factoryScorepart (TFactory f, const char* id, const char* name, const char* abbrev)
{ return __retainElt (f->scorepart (id, name, abbrev)); }
EXP TElement factoryPart (TFactory f, const char* id)
{ return __retainElt (f->part (id)); }
EXP TElement factoryMeasure (TFactory f, int number)
{ return __retainElt (f->newmeasure (number)); }
EXP TElement factoryMeasureWithAttributes (TFactory f, int number, const char* time, const char* clef, int line, int key, int division)
{ return __retainElt (f->newmeasure (number, time, clef, line, key, division)); }
EXP TElement factoryNote (TFactory f, const char* step, float alter, int octave, int duration, const char* type)
{ return __retainElt (f->newnote (step, alter, octave, duration, type)); }
EXP TElement factoryRest (TFactory f, int duration, const char* type)
{ return __retainElt (f->newrest (duration, type)); }
EXP TElement factoryDynamic (TFactory f, int type, const char* placement)
{ return __retainElt (f->newdynamics (type, placement)); }
EXP TElement factoryBarline (TFactory f, const char* location, const char* barstyle, const char *repeat)
{ return __retainElt (f->newbarline (location, barstyle, repeat)); }
EXP void factoryTuplet (TFactory f, int actual, int normal, TElement * notes)
{
vector<Sxmlelement> list;
while (*notes) {
list.push_back(*notes);
notes++;
}
f->maketuplet (actual, normal, list);
}
EXP void factoryTie (TFactory f, TElement from, TElement to)
{ f->tie (from, to); }
EXP void factoryNotation (TFactory f, TElement elt, TElement notation)
{ f->addnotation (elt, __releaseElt(notation)); }
EXP void factoryArticulation (TFactory f, TElement elt, TElement articulation)
{ f->addarticulation (elt, __releaseElt(articulation)); }
EXP void factoryChord (TFactory f, TElement * notes)
{
vector<Sxmlelement> list;
while (*notes) {
list.push_back(*notes);
notes++;
}
f->makechord (list);
}
//------------------------------------------------------------------------
EXP void factoryAddElement (TFactory f, TElement elt, TElement subelt)
{ f->add (elt, __releaseElt(subelt)); }
EXP void factoryAddAttribute (TFactory f, TElement elt, TAttribute attr)
{ f->add (elt, __releaseAttr(attr)); }
EXP void factoryAddElements (TFactory f, TElement elt, TElement* subelts)
{
vector<Sxmlelement> list;
while (*subelts) {
list.push_back(*subelts);
subelts++;
}
f->add (elt, list);
}
//------------------------------------------------------------------------
// elements creation
//------------------------------------------------------------------------
template <typename T> TElement __factoryElement (TFactory f, int type, T value)
{ return __retainElt (f->element (type, value)); }
EXP TElement factoryElement (TFactory f, int type)
{ return __factoryElement (f, type, (char*)0); }
EXP TElement factoryStrElement (TFactory f, int type, const char * value)
{ return __factoryElement (f, type, value); }
EXP TElement factoryIntElement (TFactory f, int type, int value)
{ return __factoryElement (f, type, value); }
EXP TElement factoryFloatElement (TFactory f, int type, float value)
{ return __factoryElement (f, type, value); }
//------------------------------------------------------------------------
// attributes creation
//------------------------------------------------------------------------
template <typename T> TAttribute __factoryAttribute (TFactory f, const char * name, T value)
{ return __retainAttr (f->attribute (name, value)); }
EXP TAttribute factoryStrAttribute (TFactory f, const char * name, const char* value)
{ return __factoryAttribute (f, name, value); }
EXP TAttribute factoryIntAttribute (TFactory f, const char * name, int value)
{ return __factoryAttribute (f, name, value); }
EXP TAttribute factoryFloatAttribute (TFactory f, const char * name, float value)
{ return __factoryAttribute (f, name, value); }
//------------------------------------------------------------------------
EXP void factoryFreeElement (TFactory f, TElement elt) { elt->removeReference(); }
EXP void factoryFreeAttribute (TFactory f, TAttribute attr) { attr->removeReference(); }
}
<commit_msg>back to previous version and layout<commit_after>/*
MusicXML Library
Copyright (C) Grame 2006-2013
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France
[email protected]
*/
#include <vector>
#include "libmusicxml.h"
#include "musicxmlfactory.h"
#include "versions.h"
using namespace std;
namespace MusicXML2
{
EXP float musicxmllibVersion() { return versions::libVersion(); }
EXP const char* musicxmllibVersionStr() { return versions::libVersionStr(); }
EXP float musicxml2guidoVersion() { return versions::xml2guidoVersion(); }
EXP const char* musicxml2guidoVersionStr() { return versions::xml2guidoVersionStr(); }
//EXP int musicxml2antescofoVersion() { return versions::xml2antescofoVersion(); }
//EXP const char* musicxml2antescofoVersionStr() { return versions::xml2antescofoVersionStr(); }
//------------------------------------------------------------------------
EXP TFactory factoryOpen () { return new musicxmlfactory(); }
EXP void factoryClose (TFactory f) { delete f; }
EXP void factoryPrint (TFactory f, ostream& out) { f->print(out); }
//------------------------------------------------------------------------
static TElement __retainElt (Sxmlelement elt) { elt->addReference(); return (TElement)elt; }
static TAttribute __retainAttr (Sxmlattribute attr) { attr->addReference(); return (TAttribute)attr; }
static Sxmlelement __releaseElt (TElement elt) { Sxmlelement xml(elt); elt->removeReference(); return xml; }
static Sxmlattribute __releaseAttr (TAttribute attr) { Sxmlattribute xml(attr); attr->removeReference(); return xml; }
//------------------------------------------------------------------------
// high level operations
//------------------------------------------------------------------------
EXP void factoryHeader (TFactory f, const char* wn, const char* wt, const char* mn, const char* mt)
{ f->header(wn, wt, mn, mt); }
EXP void factoryCreator (TFactory f, const char* c, const char* type)
{ f->creator(c, type); }
EXP void factoryRights (TFactory f, const char* c, const char* type)
{ f->rights(c, type); }
EXP void factoryEncoding (TFactory f, const char* soft)
{ f->encoding(soft); }
EXP void factoryAddGroup (TFactory f, int number, const char* name, const char* abbrev, bool groupbarline, TElement* parts)
{
vector<Sxmlelement> list;
while (*parts) {
list.push_back(__releaseElt(*parts));
parts++;
}
f->addgroup (number, name, abbrev, groupbarline, list);
}
EXP void factoryAddPart (TFactory f, TElement part)
{ f->addpart (__releaseElt(part)); }
EXP TElement factoryScorepart (TFactory f, const char* id, const char* name, const char* abbrev)
{ return __retainElt (f->scorepart (id, name, abbrev)); }
EXP TElement factoryPart (TFactory f, const char* id)
{ return __retainElt (f->part (id)); }
EXP TElement factoryMeasure (TFactory f, int number)
{ return __retainElt (f->newmeasure (number)); }
EXP TElement factoryMeasureWithAttributes (TFactory f, int number, const char* time, const char* clef, int line, int key, int division)
{ return __retainElt (f->newmeasure (number, time, clef, line, key, division)); }
EXP TElement factoryNote (TFactory f, const char* step, float alter, int octave, int duration, const char* type)
{ return __retainElt (f->newnote (step, alter, octave, duration, type)); }
EXP TElement factoryRest (TFactory f, int duration, const char* type)
{ return __retainElt (f->newrest (duration, type)); }
EXP TElement factoryDynamic (TFactory f, int type, const char* placement)
{ return __retainElt (f->newdynamics (type, placement)); }
EXP TElement factoryBarline (TFactory f, const char* location, const char* barstyle, const char *repeat)
{ return __retainElt (f->newbarline (location, barstyle, repeat)); }
EXP void factoryTuplet (TFactory f, int actual, int normal, TElement * notes)
{
vector<Sxmlelement> list;
while (*notes) {
list.push_back(*notes);
notes++;
}
f->maketuplet (actual, normal, list);
}
EXP void factoryTie (TFactory f, TElement from, TElement to)
{ f->tie (from, to); }
EXP void factoryNotation (TFactory f, TElement elt, TElement notation)
{ f->addnotation (elt, __releaseElt(notation)); }
EXP void factoryArticulation (TFactory f, TElement elt, TElement articulation)
{ f->addarticulation (elt, __releaseElt(articulation)); }
EXP void factoryChord (TFactory f, TElement * notes)
{
vector<Sxmlelement> list;
while (*notes) {
list.push_back(*notes);
notes++;
}
f->makechord (list);
}
//------------------------------------------------------------------------
EXP void factoryAddElement (TFactory f, TElement elt, TElement subelt)
{ f->add (elt, __releaseElt(subelt)); }
EXP void factoryAddAttribute (TFactory f, TElement elt, TAttribute attr)
{ f->add (elt, __releaseAttr(attr)); }
EXP void factoryAddElements (TFactory f, TElement elt, TElement* subelts)
{
vector<Sxmlelement> list;
while (*subelts) {
list.push_back(*subelts);
subelts++;
}
f->add (elt, list);
}
//------------------------------------------------------------------------
// elements creation
//------------------------------------------------------------------------
template <typename T> TElement __factoryElement (TFactory f, int type, T value)
{ return __retainElt (f->element (type, value)); }
EXP TElement factoryElement (TFactory f, int type)
{ return __factoryElement (f, type, (char*)0); }
EXP TElement factoryStrElement (TFactory f, int type, const char * value)
{ return __factoryElement (f, type, value); }
EXP TElement factoryIntElement (TFactory f, int type, int value)
{ return __factoryElement (f, type, value); }
EXP TElement factoryFloatElement (TFactory f, int type, float value)
{ return __factoryElement (f, type, value); }
//------------------------------------------------------------------------
// attributes creation
//------------------------------------------------------------------------
template <typename T> TAttribute __factoryAttribute (TFactory f, const char * name, T value)
{ return __retainAttr (f->attribute (name, value)); }
EXP TAttribute factoryStrAttribute (TFactory f, const char * name, const char* value)
{ return __factoryAttribute (f, name, value); }
EXP TAttribute factoryIntAttribute (TFactory f, const char * name, int value)
{ return __factoryAttribute (f, name, value); }
EXP TAttribute factoryFloatAttribute (TFactory f, const char * name, float value)
{ return __factoryAttribute (f, name, value); }
//------------------------------------------------------------------------
EXP void factoryFreeElement (TFactory f, TElement elt) { elt->removeReference(); }
EXP void factoryFreeAttribute (TFactory f, TAttribute attr) { attr->removeReference(); }
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkExceptionObject.h"
#include "itkFixedArray.h"
#include "otbLandsatTMIndices.h"
#include <vector>
#include <algorithm>
int otbLandsatTMKernelSpectralRules(int argc, char * argv[])
{
typedef double PrecisionType;
typedef itk::FixedArray< PrecisionType, 8 > InputPixelType;
double TM1 = (::atof(argv[1]));
double TM2 = (::atof(argv[2]));
double TM3 = (::atof(argv[3]));
double TM4 = (::atof(argv[4]));
double TM5 = (::atof(argv[5]));
double TM61 = (::atof(argv[6]));
double TM62 = (::atof(argv[7]));
double TM7 = (::atof(argv[8]));
InputPixelType pixel;
pixel[0] = TM1;
pixel[1] = TM2;
pixel[2] = TM3;
pixel[3] = TM4;
pixel[4] = TM5;
pixel[5] = TM61;
pixel[6] = TM62;
pixel[7] = TM7;
std::vector< PrecisionType > v123;
v123.push_back(TM1);
v123.push_back(TM2);
v123.push_back(TM3);
PrecisionType max123 = *(max_element ( v123.begin(), v123.end() ));
PrecisionType min123 = *(min_element ( v123.begin(), v123.end() ));
PrecisionType TV1 = 0.7;
PrecisionType TV2 = 0.5;
typedef otb::Functor::LandsatTM::ThickCloudsSpectralRule<InputPixelType> R1FunctorType;
R1FunctorType r1Funct = R1FunctorType();
bool result = r1Funct(pixel);
bool goodResult = (min123 >= (TV1 * max123))
and (max123 <= TV1 * TM4)
and (TM5 <= TV1 * TM4)
and (TM5 >= TV1 * max123)
and (TM7 <= TV1 * TM4);
std::cout << "Rule 1 " << goodResult << " " << result << std::endl;
if( result!=goodResult ) return EXIT_FAILURE;
typedef otb::Functor::LandsatTM::ThinCloudsSpectralRule<InputPixelType> R2FunctorType;
R2FunctorType r2Funct = R2FunctorType();
result = r2Funct(pixel);
goodResult = (min123 >= (TV1 * max123))
and (TM4 >= max123)
and !((TM1<=TM2 and TM2<=TM3 and TM3<=TM4) and TM3 >= TV1*TM4)
and (TM4 >= TV1*TM5) and (TM5 >= TV1*TM4)
and (TM5 >= TV1*max123) and (TM5 >= TV1*TM7);
std::cout << "Rule 2 " << goodResult << " " << result << std::endl;
if( result!=goodResult ) return EXIT_FAILURE;
typedef otb::Functor::LandsatTM::SnowOrIceSpectralRule<InputPixelType> R3FunctorType;
R3FunctorType r3Funct = R3FunctorType();
result = r3Funct(pixel);
goodResult = (min123 >= (TV1 * max123))
and (TM4 >= TV1 * max123)
and (TM5 <= TV2 * TM4)
and (TM5 <= TV1* min123)
and (TM7 <= TV2 * TM4)
and (TM7 <= TV1*min123);
std::cout << "Rule 3 " << goodResult << " " << result << std::endl;
if( result!=goodResult ) return EXIT_FAILURE;
typedef otb::Functor::LandsatTM::WaterOrShadowSpectralRule<InputPixelType> R4FunctorType;
R4FunctorType r4Funct = R4FunctorType();
result = r4Funct(pixel);
goodResult = (TM1 >= TM2) and (TM2 >= TM3) and (TM3 >= TM4) and (TM4 >= TM5) and (TM4 >= TM7);
std::cout << "Rule 4 " << goodResult << " " << result << std::endl;
if( result!=goodResult ) return EXIT_FAILURE;
typedef otb::Functor::LandsatTM::PitbogOrGreenhouseSpectralRule<InputPixelType> R5FunctorType;
R5FunctorType r5Funct = R5FunctorType();
result = r5Funct(pixel);
goodResult = (TM3 >= TV1 * TM1)
and (TM1 >= TV1 * TM3)
and (max123 <= TV1 * TM4)
and (TM5 <= TV1 * TM4)
and (TM3 >= TV2 TM5)
and (min123 >= TV1 * TM7);
std::cout << "Rule 5 " << goodResult << " " << result << std::endl;
if( result!=goodResult ) return EXIT_FAILURE;
return EXIT_SUCCESS;
}
<commit_msg>TEST: small correction<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkExceptionObject.h"
#include "itkFixedArray.h"
#include "otbLandsatTMIndices.h"
#include <vector>
#include <algorithm>
int otbLandsatTMKernelSpectralRules(int argc, char * argv[])
{
typedef double PrecisionType;
typedef itk::FixedArray< PrecisionType, 8 > InputPixelType;
double TM1 = (::atof(argv[1]));
double TM2 = (::atof(argv[2]));
double TM3 = (::atof(argv[3]));
double TM4 = (::atof(argv[4]));
double TM5 = (::atof(argv[5]));
double TM61 = (::atof(argv[6]));
double TM62 = (::atof(argv[7]));
double TM7 = (::atof(argv[8]));
InputPixelType pixel;
pixel[0] = TM1;
pixel[1] = TM2;
pixel[2] = TM3;
pixel[3] = TM4;
pixel[4] = TM5;
pixel[5] = TM61;
pixel[6] = TM62;
pixel[7] = TM7;
std::vector< PrecisionType > v123;
v123.push_back(TM1);
v123.push_back(TM2);
v123.push_back(TM3);
PrecisionType max123 = *(max_element ( v123.begin(), v123.end() ));
PrecisionType min123 = *(min_element ( v123.begin(), v123.end() ));
PrecisionType TV1 = 0.7;
PrecisionType TV2 = 0.5;
typedef otb::Functor::LandsatTM::ThickCloudsSpectralRule<InputPixelType> R1FunctorType;
R1FunctorType r1Funct = R1FunctorType();
bool result = r1Funct(pixel);
bool goodResult = (min123 >= (TV1 * max123))
and (max123 <= TV1 * TM4)
and (TM5 <= TV1 * TM4)
and (TM5 >= TV1 * max123)
and (TM7 <= TV1 * TM4);
std::cout << "Rule 1 " << goodResult << " " << result << std::endl;
if( result!=goodResult ) return EXIT_FAILURE;
typedef otb::Functor::LandsatTM::ThinCloudsSpectralRule<InputPixelType> R2FunctorType;
R2FunctorType r2Funct = R2FunctorType();
result = r2Funct(pixel);
goodResult = (min123 >= (TV1 * max123))
and (TM4 >= max123)
and !((TM1<=TM2 and TM2<=TM3 and TM3<=TM4) and TM3 >= TV1*TM4)
and (TM4 >= TV1*TM5) and (TM5 >= TV1*TM4)
and (TM5 >= TV1*max123) and (TM5 >= TV1*TM7);
std::cout << "Rule 2 " << goodResult << " " << result << std::endl;
if( result!=goodResult ) return EXIT_FAILURE;
typedef otb::Functor::LandsatTM::SnowOrIceSpectralRule<InputPixelType> R3FunctorType;
R3FunctorType r3Funct = R3FunctorType();
result = r3Funct(pixel);
goodResult = (min123 >= (TV1 * max123))
and (TM4 >= TV1 * max123)
and (TM5 <= TV2 * TM4)
and (TM5 <= TV1* min123)
and (TM7 <= TV2 * TM4)
and (TM7 <= TV1*min123);
std::cout << "Rule 3 " << goodResult << " " << result << std::endl;
if( result!=goodResult ) return EXIT_FAILURE;
typedef otb::Functor::LandsatTM::WaterOrShadowSpectralRule<InputPixelType> R4FunctorType;
R4FunctorType r4Funct = R4FunctorType();
result = r4Funct(pixel);
goodResult = (TM1 >= TM2) and (TM2 >= TM3) and (TM3 >= TM4) and (TM4 >= TM5) and (TM4 >= TM7);
std::cout << "Rule 4 " << goodResult << " " << result << std::endl;
if( result!=goodResult ) return EXIT_FAILURE;
typedef otb::Functor::LandsatTM::PitbogOrGreenhouseSpectralRule<InputPixelType> R5FunctorType;
R5FunctorType r5Funct = R5FunctorType();
result = r5Funct(pixel);
goodResult = (TM3 >= TV1 * TM1)
and (TM1 >= TV1 * TM3)
and (max123 <= TV1 * TM4)
and (TM5 <= TV1 * TM4)
and (TM3 >= TV2 * TM5)
and (min123 >= TV1 * TM7);
std::cout << "Rule 5 " << goodResult << " " << result << std::endl;
if( result!=goodResult ) return EXIT_FAILURE;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.com */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#include "../3rdparty/tristripper/tri_stripper.cpp"
#include "../3rdparty/tristripper/policy.cpp"
#include "../3rdparty/tristripper/connectivity_graph.cpp"
using namespace triangle_stripper;
#include <vl/TriangleStripGenerator.hpp>
#include <vl/Geometry.hpp>
#include <vl/DoubleVertexRemover.hpp>
#include <vl/Log.hpp>
#include <vl/Say.hpp>
using namespace vl;
namespace
{
void fillIndices(std::vector<unsigned int>& indices, const DrawCall* dc, bool substitute_quads)
{
indices.clear();
switch(dc->primitiveType())
{
case PT_TRIANGLES:
{
indices.reserve(dc->indexCount());
for(unsigned j=0; j<dc->indexCount(); j+=3)
{
int a = dc->index(j+0);
int b = dc->index(j+1);
int c = dc->index(j+2);
// skip degenerate triangles
if (a != b && b != c)
{
indices.push_back(a);
indices.push_back(b);
indices.push_back(c);
}
}
}
break;
case PT_QUADS:
{
if (substitute_quads)
{
indices.reserve(dc->indexCount()/4*6);
for(unsigned q=0; q<dc->indexCount(); q+=4)
{
int a = dc->index(q+0);
int b = dc->index(q+1);
int c = dc->index(q+2);
int d = dc->index(q+3);
if (a != b && a != c)
{
indices.push_back(a);
indices.push_back(b);
indices.push_back(c);
}
if (c!=d && d!=a)
{
indices.push_back(c);
indices.push_back(d);
indices.push_back(a);
}
}
break;
}
else
return;
}
default:
return;
}
}
} // namespace vl
void TriangleStripGenerator::stripfy(Geometry* geom, int cache_size, bool merge_strips, bool remove_doubles, bool substitute_quads)
{
if (remove_doubles)
{
DoubleVertexRemover dvr;
dvr.removeDoubles(geom);
}
for( int idraw=geom->drawCalls()->size(); idraw--; )
{
DrawCall* dc = geom->drawCalls()->at(idraw);
triangle_stripper::indices indices;
fillIndices(indices, dc, substitute_quads);
std::vector<unsigned int> algo2_strip;
std::vector<unsigned int> algo2_tris;
// stripfyAlgo2(algo2_strip, algo2_tris, indices, cache_size);
tri_stripper striper(indices);
striper.SetCacheSize(cache_size);
striper.SetMinStripSize(4);
primitive_vector out;
striper.Strip(&out);
// install new strip
if (out.size())
{
geom->drawCalls()->erase(idraw,1);
algo2_strip.reserve(indices.size());
for(unsigned s=0; s<out.size(); ++s)
{
if (out[s].Type == TRIANGLE_STRIP)
{
algo2_strip.clear();
for(unsigned p=0; p<out[s].Indices.size(); ++p)
algo2_strip.push_back(out[s].Indices[p]);
ref<DrawElementsUInt> draw_elems = new DrawElementsUInt(PT_TRIANGLE_STRIP);
draw_elems->indices()->resize(algo2_strip.size());
memcpy(draw_elems->indices()->ptr(), &algo2_strip[0], sizeof(unsigned int)*algo2_strip.size());
geom->drawCalls()->push_back(draw_elems.get());
}
else // TRIANGLES
{
algo2_tris.clear();
for(unsigned p=0; p<out[s].Indices.size(); ++p)
algo2_tris.push_back(out[s].Indices[p]);
ref<DrawElementsUInt> draw_elems = new DrawElementsUInt(PT_TRIANGLES);
draw_elems->indices()->resize(algo2_tris.size());
memcpy(draw_elems->indices()->ptr(), &algo2_tris[0], sizeof(unsigned int)*algo2_tris.size());
geom->drawCalls()->push_back(draw_elems.get());
}
}
}
}
if (merge_strips)
geom->mergeTriangleStrips();
geom->shrinkDrawElements();
}
<commit_msg>use universal TriangleIterator<commit_after>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.com */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#include "../3rdparty/tristripper/tri_stripper.cpp"
#include "../3rdparty/tristripper/policy.cpp"
#include "../3rdparty/tristripper/connectivity_graph.cpp"
using namespace triangle_stripper;
#include <vl/TriangleStripGenerator.hpp>
#include <vl/Geometry.hpp>
#include <vl/DoubleVertexRemover.hpp>
#include <vl/Log.hpp>
#include <vl/Say.hpp>
using namespace vl;
namespace
{
void fillIndices(std::vector<unsigned int>& indices, const DrawCall* dc, bool substitute_quads)
{
indices.clear();
if ( dc->primitiveType() == PT_QUADS && !substitute_quads )
return;
indices.reserve( 1000 );
for(TriangleIterator trit = dc->triangleIterator(); !trit.isEnd(); trit.next())
{
int a = trit.a();
int b = trit.b();
int c = trit.c();
// skip degenerate triangles
if (a != b && b != c)
{
indices.push_back(a);
indices.push_back(b);
indices.push_back(c);
}
}
}
}
void TriangleStripGenerator::stripfy(Geometry* geom, int cache_size, bool merge_strips, bool remove_doubles, bool substitute_quads)
{
if (remove_doubles)
{
DoubleVertexRemover dvr;
dvr.removeDoubles(geom);
}
for( int idraw=geom->drawCalls()->size(); idraw--; )
{
DrawCall* dc = geom->drawCalls()->at(idraw);
triangle_stripper::indices indices;
fillIndices(indices, dc, substitute_quads);
std::vector<unsigned int> algo2_strip;
std::vector<unsigned int> algo2_tris;
// stripfyAlgo2(algo2_strip, algo2_tris, indices, cache_size);
tri_stripper striper(indices);
striper.SetCacheSize(cache_size);
striper.SetMinStripSize(4);
primitive_vector out;
striper.Strip(&out);
// install new strip
if (out.size())
{
geom->drawCalls()->erase(idraw,1);
algo2_strip.reserve(indices.size());
for(unsigned s=0; s<out.size(); ++s)
{
if (out[s].Type == TRIANGLE_STRIP)
{
algo2_strip.clear();
for(unsigned p=0; p<out[s].Indices.size(); ++p)
algo2_strip.push_back(out[s].Indices[p]);
ref<DrawElementsUInt> draw_elems = new DrawElementsUInt(PT_TRIANGLE_STRIP);
draw_elems->indices()->resize(algo2_strip.size());
memcpy(draw_elems->indices()->ptr(), &algo2_strip[0], sizeof(unsigned int)*algo2_strip.size());
geom->drawCalls()->push_back(draw_elems.get());
}
else // TRIANGLES
{
algo2_tris.clear();
for(unsigned p=0; p<out[s].Indices.size(); ++p)
algo2_tris.push_back(out[s].Indices[p]);
ref<DrawElementsUInt> draw_elems = new DrawElementsUInt(PT_TRIANGLES);
draw_elems->indices()->resize(algo2_tris.size());
memcpy(draw_elems->indices()->ptr(), &algo2_tris[0], sizeof(unsigned int)*algo2_tris.size());
geom->drawCalls()->push_back(draw_elems.get());
}
}
}
}
if (merge_strips)
geom->mergeTriangleStrips();
}
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Dennis Nienhüser <[email protected]>
// Copyright 2012 Bernhard Beschow <[email protected]>
//
#include "SearchInputWidget.h"
#include "MarblePlacemarkModel.h"
#include <QtGui/QCompleter>
namespace Marble {
SearchInputWidget::SearchInputWidget( QWidget *parent ) :
MarbleLineEdit( parent ),
m_completer( new QCompleter( this ) )
{
setPlaceholderText( tr( "Search" ) );
QPixmap const decorator = QPixmap( ":/icons/16x16/edit-find.png" );
Q_ASSERT( !decorator.isNull() );
setDecorator( decorator );
connect( this, SIGNAL( clearButtonClicked() ), this, SLOT( search() ) );
connect( this, SIGNAL( returnPressed() ), this, SLOT( search() ) );
connect( this, SIGNAL( decoratorButtonClicked() ), this, SLOT( search() ) );
m_sortFilter.setSortRole( MarblePlacemarkModel::PopularityIndexRole );
m_sortFilter.sort( 0, Qt::DescendingOrder );
m_sortFilter.setDynamicSortFilter( true );
m_completer->setCompletionRole( Qt::DisplayRole );
m_completer->setCaseSensitivity( Qt::CaseInsensitive );
m_completer->setModel( &m_sortFilter );
setCompleter( m_completer );
connect( m_completer, SIGNAL( activated( QModelIndex ) ), this, SLOT( centerOnSearchSuggestion( QModelIndex ) ) );
}
void SearchInputWidget::setCompletionModel( QAbstractItemModel *completionModel )
{
m_sortFilter.setSourceModel( completionModel );
}
void SearchInputWidget::search()
{
QString const searchTerm = text();
if ( !searchTerm.isEmpty() ) {
setBusy( true );
}
emit search( searchTerm );
}
void SearchInputWidget::disableSearchAnimation()
{
setBusy( false );
}
void SearchInputWidget::centerOnSearchSuggestion(const QModelIndex &index )
{
QAbstractItemModel const * model = completer()->completionModel();
QVariant const value = model->data( index, MarblePlacemarkModel::CoordinateRole );
GeoDataCoordinates const coordinates = qVariantValue<GeoDataCoordinates>( value );
emit centerOn( coordinates );
}
}
#include "SearchInputWidget.moc"
<commit_msg>setPlaceholderText was introduced in Qt 4.7<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012 Dennis Nienhüser <[email protected]>
// Copyright 2012 Bernhard Beschow <[email protected]>
//
#include "SearchInputWidget.h"
#include "MarblePlacemarkModel.h"
#include <QtGui/QCompleter>
namespace Marble {
SearchInputWidget::SearchInputWidget( QWidget *parent ) :
MarbleLineEdit( parent ),
m_completer( new QCompleter( this ) )
{
#if QT_VERSION >= 0x40700
setPlaceholderText( tr( "Search" ) );
#endif
QPixmap const decorator = QPixmap( ":/icons/16x16/edit-find.png" );
Q_ASSERT( !decorator.isNull() );
setDecorator( decorator );
connect( this, SIGNAL( clearButtonClicked() ), this, SLOT( search() ) );
connect( this, SIGNAL( returnPressed() ), this, SLOT( search() ) );
connect( this, SIGNAL( decoratorButtonClicked() ), this, SLOT( search() ) );
m_sortFilter.setSortRole( MarblePlacemarkModel::PopularityIndexRole );
m_sortFilter.sort( 0, Qt::DescendingOrder );
m_sortFilter.setDynamicSortFilter( true );
m_completer->setCompletionRole( Qt::DisplayRole );
m_completer->setCaseSensitivity( Qt::CaseInsensitive );
m_completer->setModel( &m_sortFilter );
setCompleter( m_completer );
connect( m_completer, SIGNAL( activated( QModelIndex ) ), this, SLOT( centerOnSearchSuggestion( QModelIndex ) ) );
}
void SearchInputWidget::setCompletionModel( QAbstractItemModel *completionModel )
{
m_sortFilter.setSourceModel( completionModel );
}
void SearchInputWidget::search()
{
QString const searchTerm = text();
if ( !searchTerm.isEmpty() ) {
setBusy( true );
}
emit search( searchTerm );
}
void SearchInputWidget::disableSearchAnimation()
{
setBusy( false );
}
void SearchInputWidget::centerOnSearchSuggestion(const QModelIndex &index )
{
QAbstractItemModel const * model = completer()->completionModel();
QVariant const value = model->data( index, MarblePlacemarkModel::CoordinateRole );
GeoDataCoordinates const coordinates = qVariantValue<GeoDataCoordinates>( value );
emit centerOn( coordinates );
}
}
#include "SearchInputWidget.moc"
<|endoftext|> |
<commit_before>/*
* Copyright © 2012 Intel Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Benjamin Segovia <[email protected]>
*/
/**
* \file alloc.hpp
* \author Benjamin Segovia <[email protected]>
*/
#ifndef __GBE_ALLOC_HPP__
#define __GBE_ALLOC_HPP__
#include "sys/platform.hpp"
#include "sys/assert.hpp"
#include <algorithm>
#include <limits>
namespace gbe
{
/*! regular allocation */
void* memAlloc(size_t size);
void memFree(void *ptr);
/*! Aligned allocation */
void* alignedMalloc(size_t size, size_t align = 64);
void alignedFree(void* ptr);
/*! Monitor memory allocations */
#if GBE_DEBUG_MEMORY
void* MemDebuggerInsertAlloc(void*, const char*, const char*, int);
void MemDebuggerRemoveAlloc(void *ptr);
void MemDebuggerDumpAlloc(void);
void MemDebuggerInitializeMem(void *mem, size_t sz);
void MemDebuggerEnableMemoryInitialization(bool enabled);
#else
INLINE void* MemDebuggerInsertAlloc(void *ptr, const char*, const char*, int) {return ptr;}
INLINE void MemDebuggerRemoveAlloc(void *ptr) {}
INLINE void MemDebuggerDumpAlloc(void) {}
INLINE void MemDebuggerInitializeMem(void *mem, size_t sz) {}
INLINE void MemDebuggerEnableMemoryInitialization(bool enabled) {}
#endif /* GBE_DEBUG_MEMORY */
/*! Properly handle the allocated type */
template <typename T>
T* _MemDebuggerInsertAlloc(T *ptr, const char *file, const char *function, int line) {
MemDebuggerInsertAlloc(ptr, file, function, line);
return ptr;
}
} /* namespace gbe */
/*! Declare a class with custom allocators */
#define GBE_CLASS(TYPE) \
GBE_STRUCT(TYPE) \
private:
/*! Declare a structure with custom allocators */
#define GBE_STRUCT(TYPE) \
public: \
void* operator new(size_t size) { \
return gbe::alignedMalloc(size, GBE_DEFAULT_ALIGNMENT); \
} \
void operator delete(void* ptr) { return gbe::alignedFree(ptr); } \
void* operator new[](size_t size) { \
return gbe::alignedMalloc(size, GBE_DEFAULT_ALIGNMENT); \
} \
void operator delete[](void* ptr) { return gbe::alignedFree(ptr); } \
void* operator new(size_t size, void *p) { return p; } \
void operator delete(void* ptr, void *p) {/*do nothing*/} \
void* operator new[](size_t size, void *p) { return p; } \
void operator delete[](void* ptr, void *p) { /*do nothing*/ }
/*! Macros to handle allocation position */
#define GBE_NEW(T,...) \
gbe::_MemDebuggerInsertAlloc(new T(__VA_ARGS__), __FILE__, __FUNCTION__, __LINE__)
#define GBE_NEW_NO_ARG(T) \
gbe::_MemDebuggerInsertAlloc(new T, __FILE__, __FUNCTION__, __LINE__)
#define GBE_NEW_ARRAY(T,N,...) \
gbe::_MemDebuggerInsertAlloc(new T[N](__VA_ARGS__), __FILE__, __FUNCTION__, __LINE__)
#define GBE_NEW_ARRAY_NO_ARG(T,N)\
gbe::_MemDebuggerInsertAlloc(new T[N], __FILE__, __FUNCTION__, __LINE__)
#define GBE_NEW_P(T,X,...) \
gbe::_MemDebuggerInsertAlloc(new (X) T(__VA_ARGS__), __FILE__, __FUNCTION__, __LINE__)
#define GBE_DELETE(X) \
do { gbe::MemDebuggerRemoveAlloc(X); delete X; } while (0)
#define GBE_DELETE_ARRAY(X) \
do { gbe::MemDebuggerRemoveAlloc(X); delete[] X; } while (0)
#define GBE_MALLOC(SZ) \
gbe::MemDebuggerInsertAlloc(gbe::memAlloc(SZ),__FILE__, __FUNCTION__, __LINE__)
#define GBE_FREE(X) \
do { gbe::MemDebuggerRemoveAlloc(X); gbe::memFree(X); } while (0)
#define GBE_ALIGNED_FREE(X) \
do { gbe::MemDebuggerRemoveAlloc(X); gbe::alignedFree(X); } while (0)
#define GBE_ALIGNED_MALLOC(SZ,ALIGN) \
gbe::MemDebuggerInsertAlloc(gbe::alignedMalloc(SZ,ALIGN),__FILE__, __FUNCTION__, __LINE__)
namespace gbe
{
/*! STL compliant allocator to intercept all memory allocations */
template<typename T>
class Allocator {
public:
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef typename std::allocator<void>::const_pointer void_allocator_ptr;
template<typename U>
struct rebind { typedef Allocator<U> other; };
INLINE Allocator(void) {}
INLINE ~Allocator(void) {}
INLINE Allocator(Allocator const&) {}
template<typename U>
INLINE Allocator(Allocator<U> const&) {}
INLINE pointer address(reference r) { return &r; }
INLINE const_pointer address(const_reference r) { return &r; }
INLINE pointer allocate(size_type n, void_allocator_ptr = 0) {
if (ALIGNOF(T) > sizeof(uintptr_t))
return (pointer) GBE_ALIGNED_MALLOC(n*sizeof(T), ALIGNOF(T));
else
return (pointer) GBE_MALLOC(n * sizeof(T));
}
INLINE void deallocate(pointer p, size_type) {
if (ALIGNOF(T) > sizeof(uintptr_t))
GBE_ALIGNED_FREE(p);
else
GBE_FREE(p);
}
INLINE size_type max_size(void) const {
return std::numeric_limits<size_type>::max() / sizeof(T);
}
INLINE void construct(pointer p, const T& t = T()) { ::new(p) T(t); }
INLINE void destroy(pointer p) { p->~T(); }
INLINE bool operator==(Allocator const&) { return true; }
INLINE bool operator!=(Allocator const& a) { return !operator==(a); }
};
// Deactivate fast allocators
#ifndef GBE_DEBUG_SPECIAL_ALLOCATOR
#define GBE_DEBUG_SPECIAL_ALLOCATOR 0
#endif
/*! A growing pool never gives memory to the system but chain free elements
* together such as deallocation can be quickly done
*/
template <typename T>
class GrowingPool
{
public:
GrowingPool(uint32_t elemNum = 1) :
curr(GBE_NEW(GrowingPoolElem, elemNum <= 1 ? 1 : elemNum)),
free(NULL), full(NULL), freeList(NULL) {}
~GrowingPool(void) {
GBE_SAFE_DELETE(curr);
GBE_SAFE_DELETE(free);
GBE_SAFE_DELETE(full);
}
void *allocate(void) {
#if GBE_DEBUG_SPECIAL_ALLOCATOR
return GBE_ALIGNED_MALLOC(sizeof(T), ALIGNOF(T));
#else
// Pick up an element from the free list
if (this->freeList != NULL) {
void *data = (void*) freeList;
this->freeList = *(void**) freeList;
return data;
}
// Pick up an element from the current block (if not full)
if (this->curr->allocated < this->curr->maxElemNum) {
void *data = (T*) curr->data + curr->allocated++;
return data;
}
// Block is full
this->curr->next = this->full;
this->full = this->curr;
// Try to pick up a free block
if (this->free) this->getFreeBlock();
// No free block we must allocate a new one
else
this->curr = GBE_NEW(GrowingPoolElem, 2 * this->curr->maxElemNum);
void *data = (T*) curr->data + curr->allocated++;
return data;
#endif /* GBE_DEBUG_SPECIAL_ALLOCATOR */
}
void deallocate(void *t) {
if (t == NULL) return;
#if GBE_DEBUG_SPECIAL_ALLOCATOR
GBE_ALIGNED_FREE(t);
#else
*(void**) t = this->freeList;
this->freeList = t;
#endif /* GBE_DEBUG_SPECIAL_ALLOCATOR */
}
void rewind(void) {
#if GBE_DEBUG_SPECIAL_ALLOCATOR == 0
// All free elements return to their blocks
this->freeList = NULL;
// Put back current block in full list
if (this->curr) {
this->curr->next = this->full;
this->full = this->curr;
this->curr = NULL;
}
// Reverse the chain list and mark all blocks as empty
while (this->full) {
GrowingPoolElem *next = this->full->next;
this->full->allocated = 0;
this->full->next = this->free;
this->free = this->full;
this->full = next;
}
// Provide a valid current block
this->getFreeBlock();
#endif /* GBE_DEBUG_SPECIAL_ALLOCATOR */
}
private:
/*! Pick-up a free block */
INLINE void getFreeBlock(void) {
GBE_ASSERT(this->free);
this->curr = this->free;
this->free = this->free->next;
this->curr->next = NULL;
}
/*! Chunk of elements to allocate */
class GrowingPoolElem
{
friend class GrowingPool;
GrowingPoolElem(size_t elemNum) {
const size_t sz = std::max(sizeof(T), sizeof(void*));
this->data = (T*) GBE_ALIGNED_MALLOC(elemNum * sz, ALIGNOF(T));
this->next = NULL;
this->maxElemNum = elemNum;
this->allocated = 0;
}
~GrowingPoolElem(void) {
GBE_ALIGNED_FREE(this->data);
if (this->next) GBE_DELETE(this->next);
}
T *data;
GrowingPoolElem *next;
size_t allocated, maxElemNum;
};
GrowingPoolElem *curr; //!< To get new element from
GrowingPoolElem *free; //!< Blocks that can be reused (after rewind)
GrowingPoolElem *full; //!< Blocks fully used
void *freeList; //!< Elements that have been deallocated
GBE_CLASS(GrowingPool);
};
/*! Helper macros to build and destroy objects with a growing pool */
#define DECL_POOL(TYPE, POOL) \
GrowingPool<TYPE> POOL; \
template <typename... Args> \
TYPE *new##TYPE(Args&&... args) { \
return new (POOL.allocate()) TYPE(args...); \
} \
void delete##TYPE(TYPE *ptr) { \
ptr->~TYPE(); \
POOL.deallocate(ptr); \
}
/*! A linear allocator just grows and does not reuse freed memory. It can
* however allocate objects of any size
*/
class LinearAllocator
{
public:
/*! Initiate the linear allocator (one segment is allocated) */
LinearAllocator(size_t minSize = CACHE_LINE, size_t maxSize = 64*KB);
/*! Free up everything */
~LinearAllocator(void);
/*! Allocate size bytes */
void *allocate(size_t size);
/*! Nothing here */
INLINE void deallocate(void *ptr) {
#if GBE_DEBUG_SPECIAL_ALLOCATOR
if (ptr) GBE_ALIGNED_FREE(ptr);
#endif /* GBE_DEBUG_SPECIAL_ALLOCATOR */
}
private:
/*! Helds an allocated segment of memory */
struct Segment {
/*! Allocate a new segment */
Segment(size_t size);
/*! Destroy the segment and the next ones */
~Segment(void);
/* Size of the segment */
size_t size;
/*! Offset to the next free bytes (if any left) */
size_t offset;
/*! Pointer to valid data */
void *data;
/*! Pointer to the next segment */
Segment *next;
/*! Use internal allocator */
GBE_STRUCT(Segment);
};
/*! Points to the current segment we can allocate from */
Segment *curr;
/*! Maximum segment size */
size_t maxSize;
/*! Use internal allocator */
GBE_CLASS(LinearAllocator);
};
} /* namespace gbe */
#endif /* __GBE_ALLOC_HPP__ */
<commit_msg>Android: derived the Allocator from std::allocator.<commit_after>/*
* Copyright © 2012 Intel Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Benjamin Segovia <[email protected]>
*/
/**
* \file alloc.hpp
* \author Benjamin Segovia <[email protected]>
*/
#ifndef __GBE_ALLOC_HPP__
#define __GBE_ALLOC_HPP__
#include "sys/platform.hpp"
#include "sys/assert.hpp"
#include <algorithm>
#include <limits>
namespace gbe
{
/*! regular allocation */
void* memAlloc(size_t size);
void memFree(void *ptr);
/*! Aligned allocation */
void* alignedMalloc(size_t size, size_t align = 64);
void alignedFree(void* ptr);
/*! Monitor memory allocations */
#if GBE_DEBUG_MEMORY
void* MemDebuggerInsertAlloc(void*, const char*, const char*, int);
void MemDebuggerRemoveAlloc(void *ptr);
void MemDebuggerDumpAlloc(void);
void MemDebuggerInitializeMem(void *mem, size_t sz);
void MemDebuggerEnableMemoryInitialization(bool enabled);
#else
INLINE void* MemDebuggerInsertAlloc(void *ptr, const char*, const char*, int) {return ptr;}
INLINE void MemDebuggerRemoveAlloc(void *ptr) {}
INLINE void MemDebuggerDumpAlloc(void) {}
INLINE void MemDebuggerInitializeMem(void *mem, size_t sz) {}
INLINE void MemDebuggerEnableMemoryInitialization(bool enabled) {}
#endif /* GBE_DEBUG_MEMORY */
/*! Properly handle the allocated type */
template <typename T>
T* _MemDebuggerInsertAlloc(T *ptr, const char *file, const char *function, int line) {
MemDebuggerInsertAlloc(ptr, file, function, line);
return ptr;
}
} /* namespace gbe */
/*! Declare a class with custom allocators */
#define GBE_CLASS(TYPE) \
GBE_STRUCT(TYPE) \
private:
/*! Declare a structure with custom allocators */
#define GBE_STRUCT(TYPE) \
public: \
void* operator new(size_t size) { \
return gbe::alignedMalloc(size, GBE_DEFAULT_ALIGNMENT); \
} \
void operator delete(void* ptr) { return gbe::alignedFree(ptr); } \
void* operator new[](size_t size) { \
return gbe::alignedMalloc(size, GBE_DEFAULT_ALIGNMENT); \
} \
void operator delete[](void* ptr) { return gbe::alignedFree(ptr); } \
void* operator new(size_t size, void *p) { return p; } \
void operator delete(void* ptr, void *p) {/*do nothing*/} \
void* operator new[](size_t size, void *p) { return p; } \
void operator delete[](void* ptr, void *p) { /*do nothing*/ }
/*! Macros to handle allocation position */
#define GBE_NEW(T,...) \
gbe::_MemDebuggerInsertAlloc(new T(__VA_ARGS__), __FILE__, __FUNCTION__, __LINE__)
#define GBE_NEW_NO_ARG(T) \
gbe::_MemDebuggerInsertAlloc(new T, __FILE__, __FUNCTION__, __LINE__)
#define GBE_NEW_ARRAY(T,N,...) \
gbe::_MemDebuggerInsertAlloc(new T[N](__VA_ARGS__), __FILE__, __FUNCTION__, __LINE__)
#define GBE_NEW_ARRAY_NO_ARG(T,N)\
gbe::_MemDebuggerInsertAlloc(new T[N], __FILE__, __FUNCTION__, __LINE__)
#define GBE_NEW_P(T,X,...) \
gbe::_MemDebuggerInsertAlloc(new (X) T(__VA_ARGS__), __FILE__, __FUNCTION__, __LINE__)
#define GBE_DELETE(X) \
do { gbe::MemDebuggerRemoveAlloc(X); delete X; } while (0)
#define GBE_DELETE_ARRAY(X) \
do { gbe::MemDebuggerRemoveAlloc(X); delete[] X; } while (0)
#define GBE_MALLOC(SZ) \
gbe::MemDebuggerInsertAlloc(gbe::memAlloc(SZ),__FILE__, __FUNCTION__, __LINE__)
#define GBE_FREE(X) \
do { gbe::MemDebuggerRemoveAlloc(X); gbe::memFree(X); } while (0)
#define GBE_ALIGNED_FREE(X) \
do { gbe::MemDebuggerRemoveAlloc(X); gbe::alignedFree(X); } while (0)
#define GBE_ALIGNED_MALLOC(SZ,ALIGN) \
gbe::MemDebuggerInsertAlloc(gbe::alignedMalloc(SZ,ALIGN),__FILE__, __FUNCTION__, __LINE__)
namespace gbe
{
/*! STL compliant allocator to intercept all memory allocations */
template<typename T>
class Allocator : public std::allocator<T>
{
public:
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef typename std::allocator<void>::const_pointer void_allocator_ptr;
template<typename U>
struct rebind { typedef Allocator<U> other; };
INLINE Allocator(void) {}
INLINE ~Allocator(void) {}
INLINE Allocator(Allocator const&) {}
template<typename U>
INLINE Allocator(Allocator<U> const&) {}
INLINE pointer address(reference r) { return &r; }
INLINE const_pointer address(const_reference r) { return &r; }
INLINE pointer allocate(size_type n, void_allocator_ptr = 0) {
if (ALIGNOF(T) > sizeof(uintptr_t))
return (pointer) GBE_ALIGNED_MALLOC(n*sizeof(T), ALIGNOF(T));
else
return (pointer) GBE_MALLOC(n * sizeof(T));
}
INLINE void deallocate(pointer p, size_type) {
if (ALIGNOF(T) > sizeof(uintptr_t))
GBE_ALIGNED_FREE(p);
else
GBE_FREE(p);
}
INLINE size_type max_size(void) const {
return std::numeric_limits<size_type>::max() / sizeof(T);
}
INLINE void destroy(pointer p) { p->~T(); }
INLINE bool operator==(Allocator const&) { return true; }
INLINE bool operator!=(Allocator const& a) { return !operator==(a); }
};
// Deactivate fast allocators
#ifndef GBE_DEBUG_SPECIAL_ALLOCATOR
#define GBE_DEBUG_SPECIAL_ALLOCATOR 0
#endif
/*! A growing pool never gives memory to the system but chain free elements
* together such as deallocation can be quickly done
*/
template <typename T>
class GrowingPool
{
public:
GrowingPool(uint32_t elemNum = 1) :
curr(GBE_NEW(GrowingPoolElem, elemNum <= 1 ? 1 : elemNum)),
free(NULL), full(NULL), freeList(NULL) {}
~GrowingPool(void) {
GBE_SAFE_DELETE(curr);
GBE_SAFE_DELETE(free);
GBE_SAFE_DELETE(full);
}
void *allocate(void) {
#if GBE_DEBUG_SPECIAL_ALLOCATOR
return GBE_ALIGNED_MALLOC(sizeof(T), ALIGNOF(T));
#else
// Pick up an element from the free list
if (this->freeList != NULL) {
void *data = (void*) freeList;
this->freeList = *(void**) freeList;
return data;
}
// Pick up an element from the current block (if not full)
if (this->curr->allocated < this->curr->maxElemNum) {
void *data = (T*) curr->data + curr->allocated++;
return data;
}
// Block is full
this->curr->next = this->full;
this->full = this->curr;
// Try to pick up a free block
if (this->free) this->getFreeBlock();
// No free block we must allocate a new one
else
this->curr = GBE_NEW(GrowingPoolElem, 2 * this->curr->maxElemNum);
void *data = (T*) curr->data + curr->allocated++;
return data;
#endif /* GBE_DEBUG_SPECIAL_ALLOCATOR */
}
void deallocate(void *t) {
if (t == NULL) return;
#if GBE_DEBUG_SPECIAL_ALLOCATOR
GBE_ALIGNED_FREE(t);
#else
*(void**) t = this->freeList;
this->freeList = t;
#endif /* GBE_DEBUG_SPECIAL_ALLOCATOR */
}
void rewind(void) {
#if GBE_DEBUG_SPECIAL_ALLOCATOR == 0
// All free elements return to their blocks
this->freeList = NULL;
// Put back current block in full list
if (this->curr) {
this->curr->next = this->full;
this->full = this->curr;
this->curr = NULL;
}
// Reverse the chain list and mark all blocks as empty
while (this->full) {
GrowingPoolElem *next = this->full->next;
this->full->allocated = 0;
this->full->next = this->free;
this->free = this->full;
this->full = next;
}
// Provide a valid current block
this->getFreeBlock();
#endif /* GBE_DEBUG_SPECIAL_ALLOCATOR */
}
private:
/*! Pick-up a free block */
INLINE void getFreeBlock(void) {
GBE_ASSERT(this->free);
this->curr = this->free;
this->free = this->free->next;
this->curr->next = NULL;
}
/*! Chunk of elements to allocate */
class GrowingPoolElem
{
friend class GrowingPool;
GrowingPoolElem(size_t elemNum) {
const size_t sz = std::max(sizeof(T), sizeof(void*));
this->data = (T*) GBE_ALIGNED_MALLOC(elemNum * sz, ALIGNOF(T));
this->next = NULL;
this->maxElemNum = elemNum;
this->allocated = 0;
}
~GrowingPoolElem(void) {
GBE_ALIGNED_FREE(this->data);
if (this->next) GBE_DELETE(this->next);
}
T *data;
GrowingPoolElem *next;
size_t allocated, maxElemNum;
};
GrowingPoolElem *curr; //!< To get new element from
GrowingPoolElem *free; //!< Blocks that can be reused (after rewind)
GrowingPoolElem *full; //!< Blocks fully used
void *freeList; //!< Elements that have been deallocated
GBE_CLASS(GrowingPool);
};
/*! Helper macros to build and destroy objects with a growing pool */
#define DECL_POOL(TYPE, POOL) \
GrowingPool<TYPE> POOL; \
template <typename... Args> \
TYPE *new##TYPE(Args&&... args) { \
return new (POOL.allocate()) TYPE(args...); \
} \
void delete##TYPE(TYPE *ptr) { \
ptr->~TYPE(); \
POOL.deallocate(ptr); \
}
/*! A linear allocator just grows and does not reuse freed memory. It can
* however allocate objects of any size
*/
class LinearAllocator
{
public:
/*! Initiate the linear allocator (one segment is allocated) */
LinearAllocator(size_t minSize = CACHE_LINE, size_t maxSize = 64*KB);
/*! Free up everything */
~LinearAllocator(void);
/*! Allocate size bytes */
void *allocate(size_t size);
/*! Nothing here */
INLINE void deallocate(void *ptr) {
#if GBE_DEBUG_SPECIAL_ALLOCATOR
if (ptr) GBE_ALIGNED_FREE(ptr);
#endif /* GBE_DEBUG_SPECIAL_ALLOCATOR */
}
private:
/*! Helds an allocated segment of memory */
struct Segment {
/*! Allocate a new segment */
Segment(size_t size);
/*! Destroy the segment and the next ones */
~Segment(void);
/* Size of the segment */
size_t size;
/*! Offset to the next free bytes (if any left) */
size_t offset;
/*! Pointer to valid data */
void *data;
/*! Pointer to the next segment */
Segment *next;
/*! Use internal allocator */
GBE_STRUCT(Segment);
};
/*! Points to the current segment we can allocate from */
Segment *curr;
/*! Maximum segment size */
size_t maxSize;
/*! Use internal allocator */
GBE_CLASS(LinearAllocator);
};
} /* namespace gbe */
#endif /* __GBE_ALLOC_HPP__ */
<|endoftext|> |
<commit_before>// @(#)root/base:$Name: $:$Id: TContextMenu.cxx,v 1.5 2002/04/05 11:39:21 rdm Exp $
// Author: Nenad Buncic 08/02/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TContextMenu //
// //
// This class provides an interface to context sensitive popup menus. //
// These menus pop up when the user hits the right mouse button, and //
// are destroyed when the menu pops downs. //
// //
// Context Menus are automatically generated by ROOT using the //
// following convention: if the string // *MENU* is found in the //
// comment field of a member function. This function will be added to //
// the list of items in the menu. //
// //
// The picture below shows a canvas with a pop-up menu. //
// //
//Begin_Html <img src="gif/hsumMenu.gif"> End_Html //
// //
// The picture below shows a canvas with a pop-up menu and a dialog box.//
// //
//Begin_Html <img src="gif/hsumDialog.gif"> End_Html //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TContextMenu.h"
#include "TVirtualPad.h"
#include "TGuiFactory.h"
#include "TMethod.h"
#include "TMethodArg.h"
#include "TGlobal.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TToggle.h"
#include "TClassMenuItem.h"
ClassImp(TContextMenu)
//______________________________________________________________________________
TContextMenu::TContextMenu(const char *name, const char *title)
: TNamed(name, title)
{
// Create a context menu.
fSelectedObject = 0;
fSelectedMethod = 0;
fBrowser = 0;
fSelectedPad = 0;
fSelectedCanvas = 0;
fSelectedMenuItem = 0;
fContextMenuImp = gGuiFactory->CreateContextMenuImp(this, name, title);
}
//______________________________________________________________________________
TContextMenu::~TContextMenu()
{
// Destroy a context menu.
delete fContextMenuImp;
fSelectedMethod = 0;
fSelectedObject = 0;
fSelectedMenuItem = 0;
fContextMenuImp = 0;
}
//______________________________________________________________________________
void TContextMenu::Action(TObject *object, TMethod *method)
{
// Action to be performed when this menu item is selected.
// If the selected method requires arguments we popup an
// automatically generated dialog, otherwise the method is
// directly executed.
if (method) {
SetMethod( method );
SetSelectedMenuItem(0);
SetCalledObject(object);
if (method->GetListOfMethodArgs()->First())
fContextMenuImp->Dialog(object, method);
else {
#ifndef WIN32
Execute(object, method, "");
#else
#ifdef GDK_WIN32
Execute(object, method, "");
#else
// It is a workaround of the "Dead lock under Windows
char *cmd = Form("((TContextMenu *)0x%lx)->Execute((TObject *)0x%lx,"
"(TMethod *)0x%lx,(TObjArray *)0);",
(Long_t)this,(Long_t)object,(Long_t)method);
//Printf("%s", cmd);
gROOT->ProcessLine(cmd);
//Execute( object, method, (TObjArray *)NULL );
#endif
#endif
}
}
}
//______________________________________________________________________________
void TContextMenu::Action(TClassMenuItem *menuitem)
{
// Action to be performed when this menu item is selected.
// If the selected method requires arguments we popup an
// automatically generated dialog, otherwise the method is
// directly executed.
TObject* object;
TMethod* method;
SetSelectedMenuItem( menuitem );
// Get the object to be called
if (menuitem->IsCallSelf()) object=fSelectedObject;
else object=menuitem->GetCalledObject();
if (object) {
// If object deleted, remove from popup and return
if (!(object->TestBit(kNotDeleted))) {
menuitem->SetType(TClassMenuItem::kPopupSeparator);
menuitem->SetCall(0,"");
return;
}
method = object->IsA()->GetMethodWithPrototype(menuitem->GetFunctionName(),menuitem->GetArgs());
}
// if (!menuitem->IsCallSelf()) {
// funproto = menuitem->GetFunctionName();
// funproto = funproto + "(" + menuitem->GetArgs() + ")";
// }
// calling object, call the method directly
if (object) {
if (method) {
SetMethod(method);
SetCalledObject(object);
if ((method->GetListOfMethodArgs()->First()
&& menuitem->GetSelfObjectPos() < 0 ) ||
method->GetListOfMethodArgs()->GetSize() > 1)
fContextMenuImp->Dialog(object, method);
else {
if (menuitem->GetSelfObjectPos() < 0) {
#ifndef WIN32
Execute(object, method, "");
#else
// It is a workaround of the "Dead lock under Windows
char *cmd = Form("((TContextMenu *)0x%lx)->Execute((TObject *)0x%lx,"
"(TMethod *)0x%lx,(TObjArray *)0);",
(Long_t)this,(Long_t)object,(Long_t)method);
//Printf("%s", cmd);
gROOT->ProcessLine(cmd);
//Execute( object, method, (TObjArray *)NULL );
#endif
} else {
#ifndef WIN32
Execute(object, method, Form("(TObject*)0x%lx",(Long_t)fSelectedObject));
#else
// It is a workaround of the "Dead lock under Windows
char *cmd = Form("((TContextMenu *)0x%lx)->Execute((TObject *)0x%lx,"
"(TMethod *)0x%lx,(TObjArray *)0);",
(Long_t)this,(Long_t)object,(Long_t)method);
//Printf("%s", cmd);
gROOT->ProcessLine(cmd);
//Execute( object, method, (TObjArray *)NULL );
#endif
}
}
}
} else {
// Calling a standalone global function
TFunction* function = gROOT->GetGlobalFunctionWithPrototype(
menuitem->GetFunctionName());
//menuitem->GetArgs());
if (function) {
SetMethod(function);
SetCalledObject(0);
if ( (function->GetNargs() && menuitem->GetSelfObjectPos() < 0) ||
function->GetNargs() > 1) {
fContextMenuImp->Dialog(0,function);
} else {
char* cmd;
if (menuitem->GetSelfObjectPos() < 0) {
cmd = Form("%s();", menuitem->GetFunctionName());
} else {
cmd = Form("%s((TObject*)0x%lx);",
menuitem->GetFunctionName(), (Long_t)fSelectedObject);
}
gROOT->ProcessLine(cmd);
}
}
}
}
//______________________________________________________________________________
void TContextMenu::Action(TObject *object, TToggle *toggle)
{
// Action to be performed when this toggle menu item is selected.
if (object && toggle) {
TVirtualPad *savedPad = 0;
gROOT->SetSelectedPrimitive(object);
if (fSelectedPad) {
savedPad = (TVirtualPad *) gPad;
if (savedPad) fSelectedPad->cd();
}
gROOT->SetFromPopUp(kTRUE);
toggle->Toggle();
if (fSelectedCanvas && fSelectedCanvas->GetPadSave()->TestBit(kNotDeleted))
fSelectedCanvas->GetPadSave()->Modified();
if (fSelectedPad && fSelectedPad->TestBit(kNotDeleted))
fSelectedPad->Modified();
gROOT->SetFromPopUp(kFALSE);
if (fSelectedPad && savedPad) {
if (savedPad->TestBit(kNotDeleted)) savedPad->cd();
}
if (fSelectedCanvas && fSelectedCanvas->TestBit(kNotDeleted))
fSelectedCanvas->Update();
if (fSelectedCanvas && fSelectedCanvas->GetPadSave()->TestBit(kNotDeleted))
fSelectedCanvas->GetPadSave()->Update();
}
}
//______________________________________________________________________________
char *TContextMenu::CreateArgumentTitle(TMethodArg *argument)
{
// Create string describing argument (for use in dialog box).
static char argTitle[128];
if (argument) {
sprintf(argTitle, "(%s) %s", argument->GetTitle(), argument->GetName());
if (argument->GetDefault() && *(argument->GetDefault())) {
strcat(argTitle, " [default: ");
strcat(argTitle, argument->GetDefault());
strcat(argTitle, "]");
}
} else
*argTitle = 0;
return argTitle;
}
//______________________________________________________________________________
char *TContextMenu::CreateDialogTitle(TObject *object, TFunction *method)
{
// Create title for dialog box retrieving argument values.
static char methodTitle[128];
if (object && method)
sprintf(methodTitle, "%s::%s", object->ClassName(), method->GetName());
else if (!object && method)
sprintf(methodTitle, "%s", method->GetName());
else
*methodTitle = 0;
return methodTitle;
}
//______________________________________________________________________________
char *TContextMenu::CreatePopupTitle(TObject *object)
{
// Create title for popup menu.
static char popupTitle[128];
if (object) {
if (!*(object->GetName()) || !strcmp(object->GetName(), object->ClassName())) {
TGlobal *global = (TGlobal *) gROOT->GetGlobal(object);
if (global && *(global->GetName()))
sprintf(popupTitle, " %s::%s ", object->ClassName(), global->GetName());
else
sprintf(popupTitle, " %s ", object->ClassName());
} else
sprintf(popupTitle, " %s::%s ", object->ClassName(), object->GetName());
} else
*popupTitle = 0;
return popupTitle;
}
//______________________________________________________________________________
void TContextMenu::Execute(TObject *object, TFunction *method, const char *params)
{
// Execute method with specified arguments for specified object.
if (method) {
TVirtualPad *savedPad = 0;
gROOT->SetSelectedPrimitive(object);
if (fSelectedPad) {
savedPad = (TVirtualPad *) gPad;
if (savedPad) fSelectedPad->cd();
}
gROOT->SetFromPopUp(kTRUE);
// if (fSelectedCanvas) fSelectedCanvas->GetPadSave()->cd();
if (object) {
object->Execute((char *) method->GetName(), params);
} else {
char *cmd = Form("%s(%s);", method->GetName(),params);
gROOT->ProcessLine(cmd);
}
if (fSelectedCanvas && fSelectedCanvas->GetPadSave()->TestBit(kNotDeleted))
fSelectedCanvas->GetPadSave()->Modified();
if (fSelectedPad && fSelectedPad->TestBit(kNotDeleted))
fSelectedPad->Modified();
gROOT->SetFromPopUp( kFALSE );
if (fSelectedPad && savedPad) {
// fSelectedPad->Modified();
if (savedPad->TestBit(kNotDeleted)) savedPad->cd();
}
if (fSelectedCanvas && fSelectedCanvas->TestBit(kNotDeleted))
fSelectedCanvas->Update();
if (fSelectedCanvas && fSelectedCanvas->GetPadSave()->TestBit(kNotDeleted))
fSelectedCanvas->GetPadSave()->Update();
}
}
//______________________________________________________________________________
void TContextMenu::Execute(TObject *object, TFunction *method, TObjArray *params)
{
// Execute method with specified arguments for specified object.
if (method) {
TVirtualPad *savedPad = 0;
gROOT->SetSelectedPrimitive(object);
if (fSelectedPad) {
savedPad = (TVirtualPad *) gPad;
if (savedPad) fSelectedPad->cd();
}
gROOT->SetFromPopUp(kTRUE);
// if (fSelectedCanvas) fSelectedCanvas->GetPadSave()->cd();
if (object) {
object->Execute((TMethod*)method, params);
} else {
TString args;
TIter next(params);
TObjString *s;
while ((s = (TObjString*) next())) {
if (!args.IsNull()) args += ",";
args += s->String();
}
char *cmd = Form("%s(%s);", method->GetName(), args.Data());
gROOT->ProcessLine(cmd);
}
if (fSelectedCanvas && fSelectedCanvas->GetPadSave()->TestBit(kNotDeleted))
fSelectedCanvas->GetPadSave()->Modified();
gROOT->SetFromPopUp( kFALSE );
if (fSelectedPad && savedPad) {
// fSelectedPad->Modified();
if (savedPad->TestBit(kNotDeleted)) savedPad->cd();
}
if (fSelectedCanvas && fSelectedCanvas->TestBit(kNotDeleted))
fSelectedCanvas->Update();
}
}
//______________________________________________________________________________
void TContextMenu::Popup(Int_t x, Int_t y, TObject *obj, TVirtualPad *c, TVirtualPad *p)
{
// Popup context menu at given location in canvas c and pad p for selected
// object.
SetBrowser(0);
SetObject(obj);
SetCanvas(c);
SetPad(p);
DisplayPopUp(x,y);
}
//______________________________________________________________________________
void TContextMenu::Popup(Int_t x, Int_t y, TObject *obj, TBrowser *b)
{
// Popup context menu at given location in browser b for selected object.
SetBrowser(b);
SetObject(obj);
SetCanvas(0);
SetPad(0);
DisplayPopUp(x,y);
}
<commit_msg>Set local variable method t zero to avoid a compiler warning.<commit_after>// @(#)root/base:$Name: $:$Id: TContextMenu.cxx,v 1.6 2002/04/08 15:06:08 rdm Exp $
// Author: Nenad Buncic 08/02/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TContextMenu //
// //
// This class provides an interface to context sensitive popup menus. //
// These menus pop up when the user hits the right mouse button, and //
// are destroyed when the menu pops downs. //
// //
// Context Menus are automatically generated by ROOT using the //
// following convention: if the string // *MENU* is found in the //
// comment field of a member function. This function will be added to //
// the list of items in the menu. //
// //
// The picture below shows a canvas with a pop-up menu. //
// //
//Begin_Html <img src="gif/hsumMenu.gif"> End_Html //
// //
// The picture below shows a canvas with a pop-up menu and a dialog box.//
// //
//Begin_Html <img src="gif/hsumDialog.gif"> End_Html //
//////////////////////////////////////////////////////////////////////////
#include "TROOT.h"
#include "TContextMenu.h"
#include "TVirtualPad.h"
#include "TGuiFactory.h"
#include "TMethod.h"
#include "TMethodArg.h"
#include "TGlobal.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TToggle.h"
#include "TClassMenuItem.h"
ClassImp(TContextMenu)
//______________________________________________________________________________
TContextMenu::TContextMenu(const char *name, const char *title)
: TNamed(name, title)
{
// Create a context menu.
fSelectedObject = 0;
fSelectedMethod = 0;
fBrowser = 0;
fSelectedPad = 0;
fSelectedCanvas = 0;
fSelectedMenuItem = 0;
fContextMenuImp = gGuiFactory->CreateContextMenuImp(this, name, title);
}
//______________________________________________________________________________
TContextMenu::~TContextMenu()
{
// Destroy a context menu.
delete fContextMenuImp;
fSelectedMethod = 0;
fSelectedObject = 0;
fSelectedMenuItem = 0;
fContextMenuImp = 0;
}
//______________________________________________________________________________
void TContextMenu::Action(TObject *object, TMethod *method)
{
// Action to be performed when this menu item is selected.
// If the selected method requires arguments we popup an
// automatically generated dialog, otherwise the method is
// directly executed.
if (method) {
SetMethod( method );
SetSelectedMenuItem(0);
SetCalledObject(object);
if (method->GetListOfMethodArgs()->First())
fContextMenuImp->Dialog(object, method);
else {
#ifndef WIN32
Execute(object, method, "");
#else
#ifdef GDK_WIN32
Execute(object, method, "");
#else
// It is a workaround of the "Dead lock under Windows
char *cmd = Form("((TContextMenu *)0x%lx)->Execute((TObject *)0x%lx,"
"(TMethod *)0x%lx,(TObjArray *)0);",
(Long_t)this,(Long_t)object,(Long_t)method);
//Printf("%s", cmd);
gROOT->ProcessLine(cmd);
//Execute( object, method, (TObjArray *)NULL );
#endif
#endif
}
}
}
//______________________________________________________________________________
void TContextMenu::Action(TClassMenuItem *menuitem)
{
// Action to be performed when this menu item is selected.
// If the selected method requires arguments we popup an
// automatically generated dialog, otherwise the method is
// directly executed.
TObject* object;
TMethod* method = 0;
SetSelectedMenuItem( menuitem );
// Get the object to be called
if (menuitem->IsCallSelf()) object=fSelectedObject;
else object=menuitem->GetCalledObject();
if (object) {
// If object deleted, remove from popup and return
if (!(object->TestBit(kNotDeleted))) {
menuitem->SetType(TClassMenuItem::kPopupSeparator);
menuitem->SetCall(0,"");
return;
}
method = object->IsA()->GetMethodWithPrototype(menuitem->GetFunctionName(),menuitem->GetArgs());
}
// if (!menuitem->IsCallSelf()) {
// funproto = menuitem->GetFunctionName();
// funproto = funproto + "(" + menuitem->GetArgs() + ")";
// }
// calling object, call the method directly
if (object) {
if (method) {
SetMethod(method);
SetCalledObject(object);
if ((method->GetListOfMethodArgs()->First()
&& menuitem->GetSelfObjectPos() < 0 ) ||
method->GetListOfMethodArgs()->GetSize() > 1)
fContextMenuImp->Dialog(object, method);
else {
if (menuitem->GetSelfObjectPos() < 0) {
#ifndef WIN32
Execute(object, method, "");
#else
// It is a workaround of the "Dead lock under Windows
char *cmd = Form("((TContextMenu *)0x%lx)->Execute((TObject *)0x%lx,"
"(TMethod *)0x%lx,(TObjArray *)0);",
(Long_t)this,(Long_t)object,(Long_t)method);
//Printf("%s", cmd);
gROOT->ProcessLine(cmd);
//Execute( object, method, (TObjArray *)NULL );
#endif
} else {
#ifndef WIN32
Execute(object, method, Form("(TObject*)0x%lx",(Long_t)fSelectedObject));
#else
// It is a workaround of the "Dead lock under Windows
char *cmd = Form("((TContextMenu *)0x%lx)->Execute((TObject *)0x%lx,"
"(TMethod *)0x%lx,(TObjArray *)0);",
(Long_t)this,(Long_t)object,(Long_t)method);
//Printf("%s", cmd);
gROOT->ProcessLine(cmd);
//Execute( object, method, (TObjArray *)NULL );
#endif
}
}
}
} else {
// Calling a standalone global function
TFunction* function = gROOT->GetGlobalFunctionWithPrototype(
menuitem->GetFunctionName());
//menuitem->GetArgs());
if (function) {
SetMethod(function);
SetCalledObject(0);
if ( (function->GetNargs() && menuitem->GetSelfObjectPos() < 0) ||
function->GetNargs() > 1) {
fContextMenuImp->Dialog(0,function);
} else {
char* cmd;
if (menuitem->GetSelfObjectPos() < 0) {
cmd = Form("%s();", menuitem->GetFunctionName());
} else {
cmd = Form("%s((TObject*)0x%lx);",
menuitem->GetFunctionName(), (Long_t)fSelectedObject);
}
gROOT->ProcessLine(cmd);
}
}
}
}
//______________________________________________________________________________
void TContextMenu::Action(TObject *object, TToggle *toggle)
{
// Action to be performed when this toggle menu item is selected.
if (object && toggle) {
TVirtualPad *savedPad = 0;
gROOT->SetSelectedPrimitive(object);
if (fSelectedPad) {
savedPad = (TVirtualPad *) gPad;
if (savedPad) fSelectedPad->cd();
}
gROOT->SetFromPopUp(kTRUE);
toggle->Toggle();
if (fSelectedCanvas && fSelectedCanvas->GetPadSave()->TestBit(kNotDeleted))
fSelectedCanvas->GetPadSave()->Modified();
if (fSelectedPad && fSelectedPad->TestBit(kNotDeleted))
fSelectedPad->Modified();
gROOT->SetFromPopUp(kFALSE);
if (fSelectedPad && savedPad) {
if (savedPad->TestBit(kNotDeleted)) savedPad->cd();
}
if (fSelectedCanvas && fSelectedCanvas->TestBit(kNotDeleted))
fSelectedCanvas->Update();
if (fSelectedCanvas && fSelectedCanvas->GetPadSave()->TestBit(kNotDeleted))
fSelectedCanvas->GetPadSave()->Update();
}
}
//______________________________________________________________________________
char *TContextMenu::CreateArgumentTitle(TMethodArg *argument)
{
// Create string describing argument (for use in dialog box).
static char argTitle[128];
if (argument) {
sprintf(argTitle, "(%s) %s", argument->GetTitle(), argument->GetName());
if (argument->GetDefault() && *(argument->GetDefault())) {
strcat(argTitle, " [default: ");
strcat(argTitle, argument->GetDefault());
strcat(argTitle, "]");
}
} else
*argTitle = 0;
return argTitle;
}
//______________________________________________________________________________
char *TContextMenu::CreateDialogTitle(TObject *object, TFunction *method)
{
// Create title for dialog box retrieving argument values.
static char methodTitle[128];
if (object && method)
sprintf(methodTitle, "%s::%s", object->ClassName(), method->GetName());
else if (!object && method)
sprintf(methodTitle, "%s", method->GetName());
else
*methodTitle = 0;
return methodTitle;
}
//______________________________________________________________________________
char *TContextMenu::CreatePopupTitle(TObject *object)
{
// Create title for popup menu.
static char popupTitle[128];
if (object) {
if (!*(object->GetName()) || !strcmp(object->GetName(), object->ClassName())) {
TGlobal *global = (TGlobal *) gROOT->GetGlobal(object);
if (global && *(global->GetName()))
sprintf(popupTitle, " %s::%s ", object->ClassName(), global->GetName());
else
sprintf(popupTitle, " %s ", object->ClassName());
} else
sprintf(popupTitle, " %s::%s ", object->ClassName(), object->GetName());
} else
*popupTitle = 0;
return popupTitle;
}
//______________________________________________________________________________
void TContextMenu::Execute(TObject *object, TFunction *method, const char *params)
{
// Execute method with specified arguments for specified object.
if (method) {
TVirtualPad *savedPad = 0;
gROOT->SetSelectedPrimitive(object);
if (fSelectedPad) {
savedPad = (TVirtualPad *) gPad;
if (savedPad) fSelectedPad->cd();
}
gROOT->SetFromPopUp(kTRUE);
// if (fSelectedCanvas) fSelectedCanvas->GetPadSave()->cd();
if (object) {
object->Execute((char *) method->GetName(), params);
} else {
char *cmd = Form("%s(%s);", method->GetName(),params);
gROOT->ProcessLine(cmd);
}
if (fSelectedCanvas && fSelectedCanvas->GetPadSave()->TestBit(kNotDeleted))
fSelectedCanvas->GetPadSave()->Modified();
if (fSelectedPad && fSelectedPad->TestBit(kNotDeleted))
fSelectedPad->Modified();
gROOT->SetFromPopUp( kFALSE );
if (fSelectedPad && savedPad) {
// fSelectedPad->Modified();
if (savedPad->TestBit(kNotDeleted)) savedPad->cd();
}
if (fSelectedCanvas && fSelectedCanvas->TestBit(kNotDeleted))
fSelectedCanvas->Update();
if (fSelectedCanvas && fSelectedCanvas->GetPadSave()->TestBit(kNotDeleted))
fSelectedCanvas->GetPadSave()->Update();
}
}
//______________________________________________________________________________
void TContextMenu::Execute(TObject *object, TFunction *method, TObjArray *params)
{
// Execute method with specified arguments for specified object.
if (method) {
TVirtualPad *savedPad = 0;
gROOT->SetSelectedPrimitive(object);
if (fSelectedPad) {
savedPad = (TVirtualPad *) gPad;
if (savedPad) fSelectedPad->cd();
}
gROOT->SetFromPopUp(kTRUE);
// if (fSelectedCanvas) fSelectedCanvas->GetPadSave()->cd();
if (object) {
object->Execute((TMethod*)method, params);
} else {
TString args;
TIter next(params);
TObjString *s;
while ((s = (TObjString*) next())) {
if (!args.IsNull()) args += ",";
args += s->String();
}
char *cmd = Form("%s(%s);", method->GetName(), args.Data());
gROOT->ProcessLine(cmd);
}
if (fSelectedCanvas && fSelectedCanvas->GetPadSave()->TestBit(kNotDeleted))
fSelectedCanvas->GetPadSave()->Modified();
gROOT->SetFromPopUp( kFALSE );
if (fSelectedPad && savedPad) {
// fSelectedPad->Modified();
if (savedPad->TestBit(kNotDeleted)) savedPad->cd();
}
if (fSelectedCanvas && fSelectedCanvas->TestBit(kNotDeleted))
fSelectedCanvas->Update();
}
}
//______________________________________________________________________________
void TContextMenu::Popup(Int_t x, Int_t y, TObject *obj, TVirtualPad *c, TVirtualPad *p)
{
// Popup context menu at given location in canvas c and pad p for selected
// object.
SetBrowser(0);
SetObject(obj);
SetCanvas(c);
SetPad(p);
DisplayPopUp(x,y);
}
//______________________________________________________________________________
void TContextMenu::Popup(Int_t x, Int_t y, TObject *obj, TBrowser *b)
{
// Popup context menu at given location in browser b for selected object.
SetBrowser(b);
SetObject(obj);
SetCanvas(0);
SetPad(0);
DisplayPopUp(x,y);
}
<|endoftext|> |
<commit_before><commit_msg>fix windows DdePoke signature<commit_after><|endoftext|> |
<commit_before><commit_msg>Added prototype functions for various C++ surface operations to be benchmarked.<commit_after>//
//
//
//
// extern "C"
// #ifdef _WIN32
// __declspec(dllexport)
// #endif
int fill_surf(int* array_data, int array_width, int array_height);
int fill_surf_memest(){ return 0; }
int copy_surf(){ return 0; }
int copy_surf_memcpy(){ return 0; }
int rgbflag_horiz(){ return 0; }
int rgbflag_vert(){ return 0; }
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/wr_vref_workarounds.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file wr_vref_workarounds.C
/// @brief Workarounds for the WR VREF calibration logic
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Stephen Glancy <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/workarounds/wr_vref_workarounds.H>
namespace mss
{
namespace workarounds
{
namespace wr_vref
{
///
/// @brief Executes WR VREF workarounds
/// @param[in] i_target the fapi2 target of the port
/// @param[in] i_rp - the rank pair to execute the override on
/// @param[out] o_vrefdq_train_range - training range value
/// @param[out] o_vrefdq_train_value - training value value
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode execute( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const uint64_t& i_rp,
uint8_t& o_vrefdq_train_range,
uint8_t& o_vrefdq_train_value )
{
// TODO RTC:160353 - Need module/chip rev EC support for workarounds
FAPI_TRY(mss::workarounds::dp16::wr_vref::error_dram23(i_target));
FAPI_TRY(mss::workarounds::dp16::wr_vref::setup_values(i_target, i_rp, o_vrefdq_train_range, o_vrefdq_train_value));
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace wr_vref
} // close namespace workarounds
} // close namespace mss
<commit_msg>Add EC feature levels to MSS workarounds<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/wr_vref_workarounds.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file wr_vref_workarounds.C
/// @brief Workarounds for the WR VREF calibration logic
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Stephen Glancy <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/workarounds/wr_vref_workarounds.H>
namespace mss
{
namespace workarounds
{
namespace wr_vref
{
///
/// @brief Executes WR VREF workarounds
/// @param[in] i_target the fapi2 target of the port
/// @param[in] i_rp - the rank pair to execute the override on
/// @param[out] o_vrefdq_train_range - training range value
/// @param[out] o_vrefdq_train_value - training value value
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode execute( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const uint64_t& i_rp,
uint8_t& o_vrefdq_train_range,
uint8_t& o_vrefdq_train_value )
{
if (! mss::chip_ec_feature_mss_wr_vref(i_target) )
{
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_TRY(mss::workarounds::dp16::wr_vref::error_dram23(i_target));
FAPI_TRY(mss::workarounds::dp16::wr_vref::setup_values(i_target, i_rp, o_vrefdq_train_range, o_vrefdq_train_value));
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace wr_vref
} // close namespace workarounds
} // close namespace mss
<|endoftext|> |
<commit_before>/*
Copyright 2012 <copyright holder> <email>
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 "asset.hpp"
#include "manager.hpp"
#include <bithorded/lib/grandcentraldispatch.hpp>
using namespace bithorded::cache;
bithorded::cache::CachedAsset::CachedAsset(GrandCentralDispatch& gcd, const boost::filesystem::path& metaFolder) :
StoredAsset(gcd, metaFolder, RandomAccessFile::READWRITE)
{
setStatus(hasRootHash() ? bithorde::SUCCESS : bithorde::NOTFOUND);
}
bithorded::cache::CachedAsset::CachedAsset(GrandCentralDispatch& gcd, const boost::filesystem::path& metaFolder, uint64_t size) :
StoredAsset(gcd, metaFolder, RandomAccessFile::READWRITE, size)
{
setStatus(bithorde::SUCCESS);
}
void bithorded::cache::CachedAsset::inspect(bithorded::management::InfoList& target) const
{
target.append("type") << "Cached";
}
void bithorded::cache::CachedAsset::write(uint64_t offset, const std::string& data, const std::function< void() > whenDone)
{
auto job = boost::bind(&RandomAccessFile::write, &_file, offset, data);
auto completion = boost::bind(&StoredAsset::notifyValidRange, shared_from_this(), offset, _1, whenDone);
_gcd.submit(job, completion);
}
bithorded::cache::CachingAsset::CachingAsset(bithorded::cache::CacheManager& mgr, bithorded::router::ForwardedAsset::Ptr upstream, bithorded::cache::CachedAsset::Ptr cached) :
_manager(mgr),
_upstream(upstream),
_upstreamTracker(_upstream->statusChange.connect(boost::bind(&CachingAsset::upstreamStatusChange, this, _1))),
_cached(cached),
_delayedCreation(false)
{
setStatus(_upstream->status);
}
bithorded::cache::CachingAsset::~CachingAsset()
{
disconnect();
}
void bithorded::cache::CachingAsset::inspect(bithorded::management::InfoList& target) const
{
target.append("type") << "caching";
if (_upstream)
_upstream->inspect_upstreams(target);
}
void bithorded::cache::CachingAsset::async_read(uint64_t offset, size_t& size, uint32_t timeout, bithorded::IAsset::ReadCallback cb)
{
auto cached_ = cached();
if (cached_ && (cached_->can_read(offset, size) == size)) {
cached_->async_read(offset, size, timeout, cb);
} else if (_upstream) {
_upstream->async_read(offset, size, timeout, boost::bind(&CachingAsset::upstreamDataArrived, shared_from_this(), cb, size, _1, _2));
} else {
cb(-1, "");
}
}
bool bithorded::cache::CachingAsset::getIds(BitHordeIds& ids) const
{
if (_upstream)
return _upstream->getIds(ids);
else if (_cached)
return _cached->getIds(ids);
else
return false;
}
size_t bithorded::cache::CachingAsset::can_read(uint64_t offset, size_t size)
{
if (_upstream)
return _upstream->can_read(offset, size);
else if (auto cached_ = cached())
return (cached_->can_read(offset, size) == size) ? size : 0;
else
return 0;
}
uint64_t bithorded::cache::CachingAsset::size()
{
if (auto cached_ = cached())
return cached_->size();
else if (_upstream)
return _upstream->size();
else
return 0;
}
void bithorded::cache::CachingAsset::disconnect()
{
_upstreamTracker.disconnect();
_upstream.reset();
}
void bithorded::cache::CachingAsset::upstreamDataArrived(bithorded::IAsset::ReadCallback cb, std::size_t requested_size, int64_t offset, const std::string& data)
{
auto cached_ = cached();
if (data.size() >= requested_size) {
cb(offset, data);
} else if (cached_ && (cached_->can_read(offset, requested_size) == requested_size)) {
cached_->async_read(offset, requested_size, 0, cb);
}
if (data.size() && cached_)
cached_->write(offset, data, boost::bind(&CachingAsset::releaseIfCached, shared_from_this()));
}
void bithorded::cache::CachingAsset::upstreamStatusChange(bithorde::Status newStatus)
{
if ((newStatus == bithorde::Status::SUCCESS) && !_cached && _upstream->size() > 0) {
_delayedCreation = true;
}
if (_cached && _cached->hasRootHash())
newStatus = bithorde::Status::SUCCESS;
setStatus(newStatus);
}
void CachingAsset::releaseIfCached()
{
auto cached_ = cached();
if (cached_ && cached_->hasRootHash())
disconnect();
}
bithorded::cache::CachedAsset::Ptr bithorded::cache::CachingAsset::cached()
{
if (_delayedCreation && _upstream) {
BitHordeIds ids;
_delayedCreation = false;
_upstream->getIds(ids);
_cached = _manager.prepareUpload(_upstream->size(), ids);
}
return _cached;
}
<commit_msg>[bithorded/cache/asset]Don't forget to report failed reads.<commit_after>/*
Copyright 2012 <copyright holder> <email>
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 "asset.hpp"
#include "manager.hpp"
#include <bithorded/lib/grandcentraldispatch.hpp>
using namespace bithorded::cache;
bithorded::cache::CachedAsset::CachedAsset(GrandCentralDispatch& gcd, const boost::filesystem::path& metaFolder) :
StoredAsset(gcd, metaFolder, RandomAccessFile::READWRITE)
{
setStatus(hasRootHash() ? bithorde::SUCCESS : bithorde::NOTFOUND);
}
bithorded::cache::CachedAsset::CachedAsset(GrandCentralDispatch& gcd, const boost::filesystem::path& metaFolder, uint64_t size) :
StoredAsset(gcd, metaFolder, RandomAccessFile::READWRITE, size)
{
setStatus(bithorde::SUCCESS);
}
void bithorded::cache::CachedAsset::inspect(bithorded::management::InfoList& target) const
{
target.append("type") << "Cached";
}
void bithorded::cache::CachedAsset::write(uint64_t offset, const std::string& data, const std::function< void() > whenDone)
{
auto job = boost::bind(&RandomAccessFile::write, &_file, offset, data);
auto completion = boost::bind(&StoredAsset::notifyValidRange, shared_from_this(), offset, _1, whenDone);
_gcd.submit(job, completion);
}
bithorded::cache::CachingAsset::CachingAsset(bithorded::cache::CacheManager& mgr, bithorded::router::ForwardedAsset::Ptr upstream, bithorded::cache::CachedAsset::Ptr cached) :
_manager(mgr),
_upstream(upstream),
_upstreamTracker(_upstream->statusChange.connect(boost::bind(&CachingAsset::upstreamStatusChange, this, _1))),
_cached(cached),
_delayedCreation(false)
{
setStatus(_upstream->status);
}
bithorded::cache::CachingAsset::~CachingAsset()
{
disconnect();
}
void bithorded::cache::CachingAsset::inspect(bithorded::management::InfoList& target) const
{
target.append("type") << "caching";
if (_upstream)
_upstream->inspect_upstreams(target);
}
void bithorded::cache::CachingAsset::async_read(uint64_t offset, size_t& size, uint32_t timeout, bithorded::IAsset::ReadCallback cb)
{
auto cached_ = cached();
if (cached_ && (cached_->can_read(offset, size) == size)) {
cached_->async_read(offset, size, timeout, cb);
} else if (_upstream) {
_upstream->async_read(offset, size, timeout, boost::bind(&CachingAsset::upstreamDataArrived, shared_from_this(), cb, size, _1, _2));
} else {
cb(-1, "");
}
}
bool bithorded::cache::CachingAsset::getIds(BitHordeIds& ids) const
{
if (_upstream)
return _upstream->getIds(ids);
else if (_cached)
return _cached->getIds(ids);
else
return false;
}
size_t bithorded::cache::CachingAsset::can_read(uint64_t offset, size_t size)
{
if (_upstream)
return _upstream->can_read(offset, size);
else if (auto cached_ = cached())
return (cached_->can_read(offset, size) == size) ? size : 0;
else
return 0;
}
uint64_t bithorded::cache::CachingAsset::size()
{
if (auto cached_ = cached())
return cached_->size();
else if (_upstream)
return _upstream->size();
else
return 0;
}
void bithorded::cache::CachingAsset::disconnect()
{
_upstreamTracker.disconnect();
_upstream.reset();
}
void bithorded::cache::CachingAsset::upstreamDataArrived(bithorded::IAsset::ReadCallback cb, std::size_t requested_size, int64_t offset, const std::string& data)
{
auto cached_ = cached();
if (data.size() >= requested_size) {
if (cached_) {
cached_->write(offset, data, boost::bind(&CachingAsset::releaseIfCached, shared_from_this()));
}
cb(offset, data);
} else if (cached_ && (cached_->can_read(offset, requested_size) == requested_size)) {
cached_->async_read(offset, requested_size, 0, cb);
} else {
cb(offset, data);
}
}
void bithorded::cache::CachingAsset::upstreamStatusChange(bithorde::Status newStatus)
{
if ((newStatus == bithorde::Status::SUCCESS) && !_cached && _upstream->size() > 0) {
_delayedCreation = true;
}
if (_cached && _cached->hasRootHash())
newStatus = bithorde::Status::SUCCESS;
setStatus(newStatus);
}
void CachingAsset::releaseIfCached()
{
auto cached_ = cached();
if (cached_ && cached_->hasRootHash())
disconnect();
}
bithorded::cache::CachedAsset::Ptr bithorded::cache::CachingAsset::cached()
{
if (_delayedCreation && _upstream) {
BitHordeIds ids;
_delayedCreation = false;
_upstream->getIds(ids);
_cached = _manager.prepareUpload(_upstream->size(), ids);
}
return _cached;
}
<|endoftext|> |
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* 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 "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "passes/techmap/simplemap.h"
#include <stdlib.h>
#include <stdio.h>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
static SigBit get_bit_or_zero(const SigSpec &sig)
{
if (GetSize(sig) == 0)
return State::S0;
return sig[0];
}
static void run_ice40_opts(Module *module)
{
pool<SigBit> optimized_co;
vector<Cell*> sb_lut_cells;
SigMap sigmap(module);
for (auto cell : module->selected_cells())
{
if (cell->type == "\\SB_LUT4")
{
sb_lut_cells.push_back(cell);
continue;
}
if (cell->type == "\\SB_CARRY")
{
SigSpec non_const_inputs, replacement_output;
int count_zeros = 0, count_ones = 0;
SigBit inbit[3] = {
get_bit_or_zero(cell->getPort("\\I0")),
get_bit_or_zero(cell->getPort("\\I1")),
get_bit_or_zero(cell->getPort("\\CI"))
};
for (int i = 0; i < 3; i++)
if (inbit[i].wire == nullptr) {
if (inbit[i] == State::S1)
count_ones++;
else
count_zeros++;
} else
non_const_inputs.append(inbit[i]);
if (count_zeros >= 2)
replacement_output = State::S0;
else if (count_ones >= 2)
replacement_output = State::S1;
else if (GetSize(non_const_inputs) == 1)
replacement_output = non_const_inputs;
if (GetSize(replacement_output)) {
optimized_co.insert(sigmap(cell->getPort("\\CO")[0]));
module->connect(cell->getPort("\\CO")[0], replacement_output);
module->design->scratchpad_set_bool("opt.did_something", true);
log("Optimized away SB_CARRY cell %s.%s: CO=%s\n",
log_id(module), log_id(cell), log_signal(replacement_output));
module->remove(cell);
}
continue;
}
if (cell->type == "$__ICE40_CARRY_LUT4")
{
SigSpec non_const_inputs, replacement_output;
int count_zeros = 0, count_ones = 0;
SigBit inbit[3] = {
cell->getPort("\\A"),
cell->getPort("\\B"),
cell->getPort("\\CI")
};
for (int i = 0; i < 3; i++)
if (inbit[i].wire == nullptr) {
if (inbit[i] == State::S1)
count_ones++;
else
count_zeros++;
} else
non_const_inputs.append(inbit[i]);
if (count_zeros >= 2)
replacement_output = State::S0;
else if (count_ones >= 2)
replacement_output = State::S1;
else if (GetSize(non_const_inputs) == 1)
replacement_output = non_const_inputs;
if (GetSize(replacement_output)) {
optimized_co.insert(sigmap(cell->getPort("\\CO")[0]));
module->connect(cell->getPort("\\CO")[0], replacement_output);
module->design->scratchpad_set_bool("opt.did_something", true);
log("Optimized SB_CARRY from $__ICE40_CARRY_LUT4 cell (leaving behind SB_LUT4) %s.%s: CO=%s\n",
log_id(module), log_id(cell), log_signal(replacement_output));
cell->type = "\\SB_LUT4";
cell->setPort("\\I0", RTLIL::S0);
cell->setPort("\\I1", inbit[0]);
cell->setPort("\\I2", inbit[1]);
cell->setPort("\\I3", inbit[2]);
cell->unsetPort("\\A");
cell->unsetPort("\\B");
cell->unsetPort("\\CI");
cell->unsetPort("\\CO");
cell->setParam("\\LUT_INIT", RTLIL::Const::from_string("0110100110010110"));
sb_lut_cells.push_back(cell);
}
continue;
}
}
for (auto cell : sb_lut_cells)
{
SigSpec inbits;
inbits.append(get_bit_or_zero(cell->getPort("\\I0")));
inbits.append(get_bit_or_zero(cell->getPort("\\I1")));
inbits.append(get_bit_or_zero(cell->getPort("\\I2")));
inbits.append(get_bit_or_zero(cell->getPort("\\I3")));
sigmap.apply(inbits);
if (optimized_co.count(inbits[0])) goto remap_lut;
if (optimized_co.count(inbits[1])) goto remap_lut;
if (optimized_co.count(inbits[2])) goto remap_lut;
if (optimized_co.count(inbits[3])) goto remap_lut;
if (!sigmap(inbits).is_fully_const())
continue;
remap_lut:
module->design->scratchpad_set_bool("opt.did_something", true);
log("Mapping SB_LUT4 cell %s.%s back to logic.\n", log_id(module), log_id(cell));
cell->type ="$lut";
cell->setParam("\\WIDTH", 4);
cell->setParam("\\LUT", cell->getParam("\\LUT_INIT"));
cell->unsetParam("\\LUT_INIT");
cell->setPort("\\A", SigSpec({
get_bit_or_zero(cell->getPort("\\I3")),
get_bit_or_zero(cell->getPort("\\I2")),
get_bit_or_zero(cell->getPort("\\I1")),
get_bit_or_zero(cell->getPort("\\I0"))
}));
cell->setPort("\\Y", cell->getPort("\\O")[0]);
cell->unsetPort("\\I0");
cell->unsetPort("\\I1");
cell->unsetPort("\\I2");
cell->unsetPort("\\I3");
cell->unsetPort("\\O");
cell->check();
simplemap_lut(module, cell);
module->remove(cell);
}
}
struct Ice40OptPass : public Pass {
Ice40OptPass() : Pass("ice40_opt", "iCE40: perform simple optimizations") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" ice40_opt [options] [selection]\n");
log("\n");
log("This command executes the following script:\n");
log("\n");
log(" do\n");
log(" <ice40 specific optimizations>\n");
log(" opt_expr -mux_undef -undriven [-full]\n");
log(" opt_merge\n");
log(" opt_rmdff\n");
log(" opt_clean\n");
log(" while <changed design>\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
string opt_expr_args = "-mux_undef -undriven";
log_header(design, "Executing ICE40_OPT pass (performing simple optimizations).\n");
log_push();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-full") {
opt_expr_args += " -full";
continue;
}
break;
}
extra_args(args, argidx, design);
while (1)
{
design->scratchpad_unset("opt.did_something");
log_header(design, "Running ICE40 specific optimizations.\n");
for (auto module : design->selected_modules())
run_ice40_opts(module);
Pass::call(design, "opt_expr " + opt_expr_args);
Pass::call(design, "opt_merge");
Pass::call(design, "opt_rmdff");
Pass::call(design, "opt_clean");
if (design->scratchpad_get_bool("opt.did_something") == false)
break;
log_header(design, "Rerunning OPT passes. (Removed registers in this run.)\n");
}
design->optimize();
design->sort();
design->check();
log_header(design, "Finished OPT passes. (There is nothing left to do.)\n");
log_pop();
}
} Ice40OptPass;
PRIVATE_NAMESPACE_END
<commit_msg>ice40_opt to $__ICE40_CARRY_LUT4 into $lut not SB_LUT<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* 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 "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "passes/techmap/simplemap.h"
#include <stdlib.h>
#include <stdio.h>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
static SigBit get_bit_or_zero(const SigSpec &sig)
{
if (GetSize(sig) == 0)
return State::S0;
return sig[0];
}
static void run_ice40_opts(Module *module)
{
pool<SigBit> optimized_co;
vector<Cell*> sb_lut_cells;
SigMap sigmap(module);
for (auto cell : module->selected_cells())
{
if (cell->type == "\\SB_LUT4")
{
sb_lut_cells.push_back(cell);
continue;
}
if (cell->type == "\\SB_CARRY")
{
SigSpec non_const_inputs, replacement_output;
int count_zeros = 0, count_ones = 0;
SigBit inbit[3] = {
get_bit_or_zero(cell->getPort("\\I0")),
get_bit_or_zero(cell->getPort("\\I1")),
get_bit_or_zero(cell->getPort("\\CI"))
};
for (int i = 0; i < 3; i++)
if (inbit[i].wire == nullptr) {
if (inbit[i] == State::S1)
count_ones++;
else
count_zeros++;
} else
non_const_inputs.append(inbit[i]);
if (count_zeros >= 2)
replacement_output = State::S0;
else if (count_ones >= 2)
replacement_output = State::S1;
else if (GetSize(non_const_inputs) == 1)
replacement_output = non_const_inputs;
if (GetSize(replacement_output)) {
optimized_co.insert(sigmap(cell->getPort("\\CO")[0]));
module->connect(cell->getPort("\\CO")[0], replacement_output);
module->design->scratchpad_set_bool("opt.did_something", true);
log("Optimized away SB_CARRY cell %s.%s: CO=%s\n",
log_id(module), log_id(cell), log_signal(replacement_output));
module->remove(cell);
}
continue;
}
if (cell->type == "$__ICE40_CARRY_LUT4")
{
SigSpec non_const_inputs, replacement_output;
int count_zeros = 0, count_ones = 0;
SigBit inbit[3] = {
cell->getPort("\\A"),
cell->getPort("\\B"),
cell->getPort("\\CI")
};
for (int i = 0; i < 3; i++)
if (inbit[i].wire == nullptr) {
if (inbit[i] == State::S1)
count_ones++;
else
count_zeros++;
} else
non_const_inputs.append(inbit[i]);
if (count_zeros >= 2)
replacement_output = State::S0;
else if (count_ones >= 2)
replacement_output = State::S1;
else if (GetSize(non_const_inputs) == 1)
replacement_output = non_const_inputs;
if (GetSize(replacement_output)) {
optimized_co.insert(sigmap(cell->getPort("\\CO")[0]));
module->connect(cell->getPort("\\CO")[0], replacement_output);
module->design->scratchpad_set_bool("opt.did_something", true);
log("Optimized $__ICE40_CARRY_LUT4 cell into $lut (without SB_CARRY) %s.%s: CO=%s\n",
log_id(module), log_id(cell), log_signal(replacement_output));
cell->type = "$lut";
cell->setPort("\\A", { RTLIL::S0, inbit[0], inbit[1], inbit[2] });
cell->setPort("\\Y", cell->getPort("\\O"));
cell->unsetPort("\\B");
cell->unsetPort("\\CI");
cell->unsetPort("\\CO");
cell->unsetPort("\\O");
cell->setParam("\\LUT", RTLIL::Const::from_string("0110100110010110"));
cell->setParam("\\WIDTH", 4);
}
continue;
}
}
for (auto cell : sb_lut_cells)
{
SigSpec inbits;
inbits.append(get_bit_or_zero(cell->getPort("\\I0")));
inbits.append(get_bit_or_zero(cell->getPort("\\I1")));
inbits.append(get_bit_or_zero(cell->getPort("\\I2")));
inbits.append(get_bit_or_zero(cell->getPort("\\I3")));
sigmap.apply(inbits);
if (optimized_co.count(inbits[0])) goto remap_lut;
if (optimized_co.count(inbits[1])) goto remap_lut;
if (optimized_co.count(inbits[2])) goto remap_lut;
if (optimized_co.count(inbits[3])) goto remap_lut;
if (!sigmap(inbits).is_fully_const())
continue;
remap_lut:
module->design->scratchpad_set_bool("opt.did_something", true);
log("Mapping SB_LUT4 cell %s.%s back to logic.\n", log_id(module), log_id(cell));
cell->type ="$lut";
cell->setParam("\\WIDTH", 4);
cell->setParam("\\LUT", cell->getParam("\\LUT_INIT"));
cell->unsetParam("\\LUT_INIT");
cell->setPort("\\A", SigSpec({
get_bit_or_zero(cell->getPort("\\I3")),
get_bit_or_zero(cell->getPort("\\I2")),
get_bit_or_zero(cell->getPort("\\I1")),
get_bit_or_zero(cell->getPort("\\I0"))
}));
cell->setPort("\\Y", cell->getPort("\\O")[0]);
cell->unsetPort("\\I0");
cell->unsetPort("\\I1");
cell->unsetPort("\\I2");
cell->unsetPort("\\I3");
cell->unsetPort("\\O");
cell->check();
simplemap_lut(module, cell);
module->remove(cell);
}
}
struct Ice40OptPass : public Pass {
Ice40OptPass() : Pass("ice40_opt", "iCE40: perform simple optimizations") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" ice40_opt [options] [selection]\n");
log("\n");
log("This command executes the following script:\n");
log("\n");
log(" do\n");
log(" <ice40 specific optimizations>\n");
log(" opt_expr -mux_undef -undriven [-full]\n");
log(" opt_merge\n");
log(" opt_rmdff\n");
log(" opt_clean\n");
log(" while <changed design>\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
string opt_expr_args = "-mux_undef -undriven";
log_header(design, "Executing ICE40_OPT pass (performing simple optimizations).\n");
log_push();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-full") {
opt_expr_args += " -full";
continue;
}
break;
}
extra_args(args, argidx, design);
while (1)
{
design->scratchpad_unset("opt.did_something");
log_header(design, "Running ICE40 specific optimizations.\n");
for (auto module : design->selected_modules())
run_ice40_opts(module);
Pass::call(design, "opt_expr " + opt_expr_args);
Pass::call(design, "opt_merge");
Pass::call(design, "opt_rmdff");
Pass::call(design, "opt_clean");
if (design->scratchpad_get_bool("opt.did_something") == false)
break;
log_header(design, "Rerunning OPT passes. (Removed registers in this run.)\n");
}
design->optimize();
design->sort();
design->check();
log_header(design, "Finished OPT passes. (There is nothing left to do.)\n");
log_pop();
}
} Ice40OptPass;
PRIVATE_NAMESPACE_END
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "OpenwireCmsTemplateTest.h"
#include <integration/IntegrationCommon.h>
#include <decaf/lang/Thread.h>
#include <decaf/util/Properties.h>
#include <activemq/transport/TransportFactory.h>
#include <decaf/util/UUID.h>
#include <decaf/util/Properties.h>
#include <decaf/util/StringTokenizer.h>
#include <activemq/connector/ConnectorFactoryMap.h>
#include <decaf/net/SocketFactory.h>
#include <activemq/transport/TransportFactory.h>
#include <decaf/net/Socket.h>
#include <decaf/lang/exceptions/NullPointerException.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/core/ActiveMQConnection.h>
#include <activemq/core/ActiveMQConsumer.h>
#include <activemq/core/ActiveMQProducer.h>
#include <decaf/util/StringTokenizer.h>
#include <decaf/lang/Boolean.h>
#include <cms/Connection.h>
#include <cms/MessageConsumer.h>
#include <cms/MessageProducer.h>
#include <cms/MessageListener.h>
#include <cms/Startable.h>
#include <cms/Closeable.h>
#include <cms/MessageListener.h>
#include <cms/ExceptionListener.h>
#include <cms/Topic.h>
#include <cms/Queue.h>
#include <cms/TemporaryTopic.h>
#include <cms/TemporaryQueue.h>
#include <cms/Session.h>
#include <cms/BytesMessage.h>
#include <cms/TextMessage.h>
#include <cms/MapMessage.h>
using namespace activemq::transport;
using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::core;
using namespace activemq::connector;
using namespace activemq::exceptions;
using namespace decaf::net;
using namespace activemq::transport;
using namespace decaf::util::concurrent;
using namespace decaf::lang;
using namespace decaf::util;
using namespace integration;
using namespace integration::connector::openwire;
using namespace activemq::cmsutil;
////////////////////////////////////////////////////////////////////////////////
void OpenwireCmsTemplateTest::setUp() {
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireCmsTemplateTest::tearDown() {
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireCmsTemplateTest::testBasics()
{
try {
const unsigned int NUM_MESSAGES = IntegrationCommon::defaultMsgCount;
Receiver receiver( IntegrationCommon::getInstance().getOpenwireURL(),
false,
"testBasics1",
NUM_MESSAGES);
Thread rt(&receiver);
rt.start();
// Wait for receiver thread to start.
decaf::lang::Thread::sleep(100);
Sender sender( IntegrationCommon::getInstance().getOpenwireURL(),
false,
"testBasics1",
NUM_MESSAGES);
Thread st(&sender);
st.start();
st.join();
rt.join();
unsigned int numReceived = receiver.getNumReceived();
if( IntegrationCommon::debug ) {
printf("received: %d\n", numReceived );
}
CPPUNIT_ASSERT(
numReceived == NUM_MESSAGES );
} catch ( ActiveMQException e ) {
e.printStackTrace();
throw e;
}
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireCmsTemplateTest::testReceiveException()
{
try {
// First, try receiving from a bad url
activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666"); // Invalid URL (at least by default)
activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
cmsTemplate.setDefaultDestinationName("testReceive1");
try {
cmsTemplate.receive();
CPPUNIT_FAIL("failed to throw expected exception");
}
catch( ActiveMQException& ex) {
// Expected.
}
// Now change to a good url and verify that we can reuse the same
// CmsTemplate successfully.
activemq::core::ActiveMQConnectionFactory cf2(IntegrationCommon::getInstance().getOpenwireURL());
cmsTemplate.setConnectionFactory(&cf2);
// Send 1 message.
Sender sender( IntegrationCommon::getInstance().getOpenwireURL(),
false,
"testReceive1",
1);
Thread st(&sender);
st.start();
// Receive the message.
cms::Message* message = cmsTemplate.receive();
CPPUNIT_ASSERT(message != NULL);
delete message;
}
catch ( ActiveMQException e ) {
e.printStackTrace();
throw e;
}
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireCmsTemplateTest::testSendException()
{
try {
// First, try sending to a bad url.
activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666"); // Invalid URL (at least by default)
activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
cmsTemplate.setDefaultDestinationName("testSend1");
try {
TextMessageCreator msgCreator("hello world");
cmsTemplate.send(&msgCreator);
CPPUNIT_FAIL("failed to throw expected exception");
}
catch( ActiveMQException& ex) {
// Expected.
}
// Now change to a good url and verify that we can reuse the same
// CmsTemplate successfully.
activemq::core::ActiveMQConnectionFactory cf2(IntegrationCommon::getInstance().getOpenwireURL());
cmsTemplate.setConnectionFactory(&cf2);
TextMessageCreator msgCreator("hello world");
cmsTemplate.send(&msgCreator);
} catch ( ActiveMQException e ) {
e.printStackTrace();
throw e;
}
}
<commit_msg>Fix thread sync issues<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "OpenwireCmsTemplateTest.h"
#include <integration/IntegrationCommon.h>
#include <decaf/lang/Thread.h>
#include <decaf/util/Properties.h>
#include <activemq/transport/TransportFactory.h>
#include <decaf/util/UUID.h>
#include <decaf/util/Properties.h>
#include <decaf/util/StringTokenizer.h>
#include <activemq/connector/ConnectorFactoryMap.h>
#include <decaf/net/SocketFactory.h>
#include <activemq/transport/TransportFactory.h>
#include <decaf/net/Socket.h>
#include <decaf/lang/exceptions/NullPointerException.h>
#include <activemq/core/ActiveMQConnectionFactory.h>
#include <activemq/core/ActiveMQConnection.h>
#include <activemq/core/ActiveMQConsumer.h>
#include <activemq/core/ActiveMQProducer.h>
#include <decaf/util/StringTokenizer.h>
#include <decaf/lang/Boolean.h>
#include <cms/Connection.h>
#include <cms/MessageConsumer.h>
#include <cms/MessageProducer.h>
#include <cms/MessageListener.h>
#include <cms/Startable.h>
#include <cms/Closeable.h>
#include <cms/MessageListener.h>
#include <cms/ExceptionListener.h>
#include <cms/Topic.h>
#include <cms/Queue.h>
#include <cms/TemporaryTopic.h>
#include <cms/TemporaryQueue.h>
#include <cms/Session.h>
#include <cms/BytesMessage.h>
#include <cms/TextMessage.h>
#include <cms/MapMessage.h>
using namespace activemq::transport;
using namespace std;
using namespace cms;
using namespace activemq;
using namespace activemq::core;
using namespace activemq::connector;
using namespace activemq::exceptions;
using namespace decaf::net;
using namespace activemq::transport;
using namespace decaf::util::concurrent;
using namespace decaf::lang;
using namespace decaf::util;
using namespace integration;
using namespace integration::connector::openwire;
using namespace activemq::cmsutil;
////////////////////////////////////////////////////////////////////////////////
void OpenwireCmsTemplateTest::setUp() {
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireCmsTemplateTest::tearDown() {
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireCmsTemplateTest::testBasics()
{
try {
const unsigned int NUM_MESSAGES = IntegrationCommon::defaultMsgCount;
Receiver receiver( IntegrationCommon::getInstance().getOpenwireURL(),
false,
"testBasics1",
NUM_MESSAGES);
Thread rt(&receiver);
rt.start();
// Wait for receiver thread to start.
decaf::lang::Thread::sleep(100);
Sender sender( IntegrationCommon::getInstance().getOpenwireURL(),
false,
"testBasics1",
NUM_MESSAGES);
Thread st(&sender);
st.start();
st.join();
rt.join();
unsigned int numReceived = receiver.getNumReceived();
if( IntegrationCommon::debug ) {
printf("received: %d\n", numReceived );
}
CPPUNIT_ASSERT(
numReceived == NUM_MESSAGES );
} catch ( ActiveMQException e ) {
e.printStackTrace();
throw e;
}
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireCmsTemplateTest::testReceiveException()
{
try {
// First, try receiving from a bad url
activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666"); // Invalid URL (at least by default)
activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
cmsTemplate.setDefaultDestinationName("testReceive1");
try {
cmsTemplate.receive();
CPPUNIT_FAIL("failed to throw expected exception");
}
catch( ActiveMQException& ex) {
// Expected.
}
// Now change to a good url and verify that we can reuse the same
// CmsTemplate successfully.
activemq::core::ActiveMQConnectionFactory cf2(IntegrationCommon::getInstance().getOpenwireURL());
cmsTemplate.setConnectionFactory(&cf2);
// Send 1 message.
Sender sender( IntegrationCommon::getInstance().getOpenwireURL(),
false,
"testReceive1",
1);
Thread st(&sender);
st.start();
st.join();
// Receive the message.
cms::Message* message = cmsTemplate.receive();
CPPUNIT_ASSERT(message != NULL);
delete message;
}
catch ( ActiveMQException e ) {
e.printStackTrace();
throw e;
}
}
////////////////////////////////////////////////////////////////////////////////
void OpenwireCmsTemplateTest::testSendException()
{
try {
// First, try sending to a bad url.
activemq::core::ActiveMQConnectionFactory cf("tcp://localhost:61666"); // Invalid URL (at least by default)
activemq::cmsutil::CmsTemplate cmsTemplate(&cf);
cmsTemplate.setDefaultDestinationName("testSend1");
try {
TextMessageCreator msgCreator("hello world");
cmsTemplate.send(&msgCreator);
CPPUNIT_FAIL("failed to throw expected exception");
}
catch( ActiveMQException& ex) {
// Expected.
}
// Now change to a good url and verify that we can reuse the same
// CmsTemplate successfully.
activemq::core::ActiveMQConnectionFactory cf2(IntegrationCommon::getInstance().getOpenwireURL());
cmsTemplate.setConnectionFactory(&cf2);
TextMessageCreator msgCreator("hello world");
cmsTemplate.send(&msgCreator);
} catch ( ActiveMQException e ) {
e.printStackTrace();
throw e;
}
}
<|endoftext|> |
<commit_before>// Sh: A GPU metaprogramming language.
//
// Copyright 2003-2005 Serious Hack Inc.
//
// 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 "ShImage.hpp"
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <png.h>
#include <sstream>
#include "ShException.hpp"
#include "ShError.hpp"
#include "ShDebug.hpp"
namespace SH {
ShImage::ShImage()
: m_width(0), m_height(0), m_elements(0), m_memory(0)
{
}
ShImage::ShImage(int width, int height, int elements)
: m_width(width), m_height(height), m_elements(elements),
m_memory(new ShHostMemory(sizeof(float) * m_width * m_height * m_elements))
{
}
ShImage::ShImage(const ShImage& other)
: m_width(other.m_width), m_height(other.m_height), m_elements(other.m_elements),
m_memory(other.m_memory ? new ShHostMemory(sizeof(float) * m_width * m_height * m_elements) : 0)
{
if (m_memory) {
std::memcpy(m_memory->hostStorage()->data(),
other.m_memory->hostStorage()->data(),
m_width * m_height * m_elements * sizeof(float));
}
}
ShImage::~ShImage()
{
}
ShImage& ShImage::operator=(const ShImage& other)
{
m_width = other.m_width;
m_height = other.m_height;
m_elements = other.m_elements;
m_memory = (other.m_memory ? new ShHostMemory(sizeof(float) * m_width * m_height * m_elements) : 0);
std::memcpy(m_memory->hostStorage()->data(),
other.m_memory->hostStorage()->data(),
m_width * m_height * m_elements * sizeof(float));
return *this;
}
int ShImage::width() const
{
return m_width;
}
int ShImage::height() const
{
return m_height;
}
int ShImage::elements() const
{
return m_elements;
}
float ShImage::operator()(int x, int y, int i) const
{
SH_DEBUG_ASSERT(m_memory);
return data()[m_elements * (m_width * y + x) + i];
}
float& ShImage::operator()(int x, int y, int i)
{
return data()[m_elements * (m_width * y + x) + i];
}
void ShImage::savePng(const std::string& filename, int inverse_alpha)
{
FILE* fout = std::fopen(filename.c_str(), "wb");
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
png_infop info_ptr = png_create_info_struct(png_ptr);
setjmp(png_ptr->jmpbuf);
/* Setup PNG I/O */
png_init_io(png_ptr, fout);
/* Optionally setup a callback to indicate when a row has been
* written. */
/* Setup filtering. Use Paeth filtering */
png_set_filter(png_ptr, 0, PNG_FILTER_PAETH);
/* Setup compression level. */
png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
/* Setup PNG header information and write it to the file */
int color_type;
switch (m_elements) {
case 1:
color_type = PNG_COLOR_TYPE_GRAY;
break;
case 2:
color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
break;
case 3:
color_type = PNG_COLOR_TYPE_RGB;
break;
case 4:
color_type = PNG_COLOR_TYPE_RGBA;
break;
default:
throw ShImageException("Invalid element size");
}
png_set_IHDR(png_ptr, info_ptr,
m_width, m_height,
8,
color_type,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
// Actual writing
png_byte* tempLine = (png_byte*)malloc(m_width * sizeof(png_byte) * m_elements);
for(int i=0;i<m_height;i+=1){
for(int j=0;j<m_width;j+=1){
for(int k = 0;k<m_elements;k+=1)
tempLine[m_elements*j+k] = static_cast<png_byte>((*this)(j, i, k)*255.0);
// inverse alpha
if(inverse_alpha && m_elements == 4)
tempLine[m_elements*j+3] = 255 - tempLine[m_elements*j+3];
}
png_write_row(png_ptr, tempLine);
}
// closing and freeing the structs
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
free(tempLine);
fclose(fout);
}
void ShImage::loadPng(const std::string& filename)
{
// check that the file is a png file
png_byte buf[8];
FILE* in = std::fopen(filename.c_str(), "rb");
if (!in) shError( ShImageException("Unable to open " + filename) );
for (int i = 0; i < 8; i++) {
if (!(buf[i] = fgetc(in))) shError( ShImageException("Not a PNG file") );
}
if (png_sig_cmp(buf, 0, 8)) shError( ShImageException("Not a PNG file") );
png_structp png_ptr =
png_create_read_struct(PNG_LIBPNG_VER_STRING,
0, 0, 0); // FIXME: use error handlers
if (!png_ptr) shError( ShImageException("Error initialising libpng (png_ptr)") );
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, 0, 0);
shError( ShImageException("Error initialising libpng (info_ptr)") );
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, 0, 0);
shError( ShImageException("Error initialising libpng (setjmp/lngjmp)") );
}
// png_set_read_fn(png_ptr, reinterpret_cast<void*>(&in), my_istream_read_data);
png_init_io(png_ptr, in);
png_set_sig_bytes(png_ptr, 8);
png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, 0);
int bit_depth = png_get_bit_depth(png_ptr, info_ptr);
if (bit_depth % 8) {
png_destroy_read_struct(&png_ptr, 0, 0);
std::ostringstream os;
os << "Invalid bit elements " << bit_depth;
shError( ShImageException(os.str()) );
}
int colour_type = png_get_color_type(png_ptr, info_ptr);
if (colour_type == PNG_COLOR_TYPE_PALETTE) {
png_set_palette_to_rgb(png_ptr);
colour_type = PNG_COLOR_TYPE_RGB;
}
if (colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
png_set_gray_1_2_4_to_8(png_ptr);
}
if (colour_type != PNG_COLOR_TYPE_RGB
&& colour_type != PNG_COLOR_TYPE_GRAY
&& colour_type != PNG_COLOR_TYPE_RGBA) {
png_destroy_read_struct(&png_ptr, 0, 0);
shError( ShImageException("Invalid colour type") );
}
m_memory = 0;
m_width = png_get_image_width(png_ptr, info_ptr);
m_height = png_get_image_height(png_ptr, info_ptr);
switch (colour_type) {
case PNG_COLOR_TYPE_RGB:
m_elements = 3;
break;
case PNG_COLOR_TYPE_RGBA:
m_elements = 4;
break;
default:
m_elements = 1;
break;
}
png_bytep* row_pointers = png_get_rows(png_ptr, info_ptr);
m_memory = new ShHostMemory(sizeof(float) * m_width * m_height * m_elements);
for (int y = 0; y < m_height; y++) {
for (int x = 0; x < m_width; x++) {
for (int i = 0; i < m_elements; i++) {
png_byte *row = row_pointers[y];
int index = m_elements * (y * m_width + x) + i;
long element = 0;
for (int j = bit_depth/8 - 1; j >= 0; j--) {
element <<= 8;
element += row[(x * m_elements + i) * bit_depth/8 + j];
}
data()[index] = element / static_cast<float>((1 << bit_depth) - 1);
}
}
}
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
}
void ShImage::savePng16(const std::string& filename, int inverse_alpha)
{
FILE* fout = std::fopen(filename.c_str(), "w");
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
png_infop info_ptr = png_create_info_struct(png_ptr);
setjmp(png_ptr->jmpbuf);
/* Setup PNG I/O */
png_init_io(png_ptr, fout);
/* Optionally setup a callback to indicate when a row has been
* written. */
/* Setup filtering. Use Paeth filtering */
png_set_filter(png_ptr, 0, PNG_FILTER_PAETH);
/* Setup compression level. */
png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
/* Setup PNG header information and write it to the file */
int color_type;
switch (m_elements) {
case 1:
color_type = PNG_COLOR_TYPE_GRAY;
break;
case 2:
color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
break;
case 3:
color_type = PNG_COLOR_TYPE_RGB;
break;
case 4:
color_type = PNG_COLOR_TYPE_RGBA;
break;
default:
throw ShImageException("Invalid element size");
}
png_set_IHDR(png_ptr, info_ptr,
m_width, m_height,
16,
color_type,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
// Actual writing
png_uint_16* tempLine = (png_uint_16*)malloc(m_width * sizeof(png_uint_16) * m_elements);
for(int i=0;i<m_height;i+=1){
for(int j=0;j<m_width;j+=1){
for(int k = 0;k<m_elements;k+=1)
tempLine[m_elements*j+k] = static_cast<png_uint_16>((*this)(j, i, k)*65535.0);
// inverse alpha
if(inverse_alpha && m_elements == 4)
tempLine[m_elements*j+3] = 65535 - tempLine[m_elements*j+3];
}
png_write_row(png_ptr, (png_byte*)tempLine);
}
// closing and freeing the structs
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
free(tempLine);
fclose(fout);
}
ShImage ShImage::getNormalImage()
{
int w = width();
int h = height();
ShImage output_image(w,h,3);
for (int j = 0; j < h; j++) {
int jp1 = j + 1;
if (jp1 >= h) jp1 = 0;
int jm1 = (j - 1);
if (jm1 < 0) jm1 = h - 1;
for (int i = 0; i < w; i++) {
int ip1 = i + 1;
if (ip1 >= w) ip1 = 0;
int im1 = (i - 1);
if (im1 < 0) im1 = w - 1;
float x, y, z;
x = ((*this)(ip1,j,0) - (*this)(im1,j,0))/2.0f;
output_image(i,j,0) = x/2.0f + 0.5f;
y = ((*this)(i,jp1,0) - (*this)(i,jm1,0))/2.0f;
output_image(i,j,1) = y/2.0f + 0.5f;
z = x*x + y*y;
z = (z > 1.0f) ? z = 0.0f : sqrt(1 - z);
output_image(i,j,2) = z;
}
}
return output_image;
}
const float* ShImage::data() const
{
if (!m_memory) return 0;
return reinterpret_cast<const float*>(m_memory->hostStorage()->data());
}
float* ShImage::data()
{
if (!m_memory) return 0;
return reinterpret_cast<float*>(m_memory->hostStorage()->data());
}
void ShImage::dirty()
{
if (!m_memory) return;
m_memory->hostStorage()->dirty();
}
ShMemoryPtr ShImage::memory()
{
return m_memory;
}
ShPointer<const ShMemory> ShImage::memory() const
{
return m_memory;
}
}
<commit_msg>Fix compilation error<commit_after>// Sh: A GPU metaprogramming language.
//
// Copyright 2003-2005 Serious Hack Inc.
//
// 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 "ShImage.hpp"
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <png.h>
#include <sstream>
#include "ShException.hpp"
#include "ShError.hpp"
#include "ShDebug.hpp"
namespace SH {
ShImage::ShImage()
: m_width(0), m_height(0), m_elements(0), m_memory(0)
{
}
ShImage::ShImage(int width, int height, int elements)
: m_width(width), m_height(height), m_elements(elements),
m_memory(new ShHostMemory(sizeof(float) * m_width * m_height * m_elements))
{
}
ShImage::ShImage(const ShImage& other)
: m_width(other.m_width), m_height(other.m_height), m_elements(other.m_elements),
m_memory(other.m_memory ? new ShHostMemory(sizeof(float) * m_width * m_height * m_elements) : 0)
{
if (m_memory) {
std::memcpy(m_memory->hostStorage()->data(),
other.m_memory->hostStorage()->data(),
m_width * m_height * m_elements * sizeof(float));
}
}
ShImage::~ShImage()
{
}
ShImage& ShImage::operator=(const ShImage& other)
{
m_width = other.m_width;
m_height = other.m_height;
m_elements = other.m_elements;
m_memory = (other.m_memory ? new ShHostMemory(sizeof(float) * m_width * m_height * m_elements) : 0);
std::memcpy(m_memory->hostStorage()->data(),
other.m_memory->hostStorage()->data(),
m_width * m_height * m_elements * sizeof(float));
return *this;
}
int ShImage::width() const
{
return m_width;
}
int ShImage::height() const
{
return m_height;
}
int ShImage::elements() const
{
return m_elements;
}
float ShImage::operator()(int x, int y, int i) const
{
SH_DEBUG_ASSERT(m_memory);
return data()[m_elements * (m_width * y + x) + i];
}
float& ShImage::operator()(int x, int y, int i)
{
return data()[m_elements * (m_width * y + x) + i];
}
void ShImage::savePng(const std::string& filename, int inverse_alpha)
{
FILE* fout = std::fopen(filename.c_str(), "wb");
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
png_infop info_ptr = png_create_info_struct(png_ptr);
setjmp(png_ptr->jmpbuf);
/* Setup PNG I/O */
png_init_io(png_ptr, fout);
/* Optionally setup a callback to indicate when a row has been
* written. */
/* Setup filtering. Use Paeth filtering */
png_set_filter(png_ptr, 0, PNG_FILTER_PAETH);
/* Setup compression level. */
png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
/* Setup PNG header information and write it to the file */
int color_type;
switch (m_elements) {
case 1:
color_type = PNG_COLOR_TYPE_GRAY;
break;
case 2:
color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
break;
case 3:
color_type = PNG_COLOR_TYPE_RGB;
break;
case 4:
color_type = PNG_COLOR_TYPE_RGBA;
break;
default:
throw ShImageException("Invalid element size");
}
png_set_IHDR(png_ptr, info_ptr,
m_width, m_height,
8,
color_type,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
// Actual writing
png_byte* tempLine = (png_byte*)malloc(m_width * sizeof(png_byte) * m_elements);
for(int i=0;i<m_height;i+=1){
for(int j=0;j<m_width;j+=1){
for(int k = 0;k<m_elements;k+=1)
tempLine[m_elements*j+k] = static_cast<png_byte>((*this)(j, i, k)*255.0);
// inverse alpha
if(inverse_alpha && m_elements == 4)
tempLine[m_elements*j+3] = 255 - tempLine[m_elements*j+3];
}
png_write_row(png_ptr, tempLine);
}
// closing and freeing the structs
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
free(tempLine);
fclose(fout);
}
void ShImage::loadPng(const std::string& filename)
{
// check that the file is a png file
png_byte buf[8];
FILE* in = std::fopen(filename.c_str(), "rb");
if (!in) shError( ShImageException("Unable to open " + filename) );
for (int i = 0; i < 8; i++) {
if (!(buf[i] = fgetc(in))) shError( ShImageException("Not a PNG file") );
}
if (png_sig_cmp(buf, 0, 8)) shError( ShImageException("Not a PNG file") );
png_structp png_ptr =
png_create_read_struct(PNG_LIBPNG_VER_STRING,
0, 0, 0); // FIXME: use error handlers
if (!png_ptr) shError( ShImageException("Error initialising libpng (png_ptr)") );
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_read_struct(&png_ptr, 0, 0);
shError( ShImageException("Error initialising libpng (info_ptr)") );
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, 0, 0);
shError( ShImageException("Error initialising libpng (setjmp/lngjmp)") );
}
// png_set_read_fn(png_ptr, reinterpret_cast<void*>(&in), my_istream_read_data);
png_init_io(png_ptr, in);
png_set_sig_bytes(png_ptr, 8);
png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, 0);
int bit_depth = png_get_bit_depth(png_ptr, info_ptr);
if (bit_depth % 8) {
png_destroy_read_struct(&png_ptr, 0, 0);
std::ostringstream os;
os << "Invalid bit elements " << bit_depth;
shError( ShImageException(os.str()) );
}
int colour_type = png_get_color_type(png_ptr, info_ptr);
if (colour_type == PNG_COLOR_TYPE_PALETTE) {
png_set_palette_to_rgb(png_ptr);
colour_type = PNG_COLOR_TYPE_RGB;
}
if (colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
png_set_gray_1_2_4_to_8(png_ptr);
}
if (colour_type != PNG_COLOR_TYPE_RGB
&& colour_type != PNG_COLOR_TYPE_GRAY
&& colour_type != PNG_COLOR_TYPE_RGBA) {
png_destroy_read_struct(&png_ptr, 0, 0);
shError( ShImageException("Invalid colour type") );
}
m_memory = 0;
m_width = png_get_image_width(png_ptr, info_ptr);
m_height = png_get_image_height(png_ptr, info_ptr);
switch (colour_type) {
case PNG_COLOR_TYPE_RGB:
m_elements = 3;
break;
case PNG_COLOR_TYPE_RGBA:
m_elements = 4;
break;
default:
m_elements = 1;
break;
}
png_bytep* row_pointers = png_get_rows(png_ptr, info_ptr);
m_memory = new ShHostMemory(sizeof(float) * m_width * m_height * m_elements);
for (int y = 0; y < m_height; y++) {
for (int x = 0; x < m_width; x++) {
for (int i = 0; i < m_elements; i++) {
png_byte *row = row_pointers[y];
int index = m_elements * (y * m_width + x) + i;
long element = 0;
for (int j = bit_depth/8 - 1; j >= 0; j--) {
element <<= 8;
element += row[(x * m_elements + i) * bit_depth/8 + j];
}
data()[index] = element / static_cast<float>((1 << bit_depth) - 1);
}
}
}
png_destroy_read_struct(&png_ptr, &info_ptr, 0);
}
void ShImage::savePng16(const std::string& filename, int inverse_alpha)
{
FILE* fout = std::fopen(filename.c_str(), "w");
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
png_infop info_ptr = png_create_info_struct(png_ptr);
setjmp(png_ptr->jmpbuf);
/* Setup PNG I/O */
png_init_io(png_ptr, fout);
/* Optionally setup a callback to indicate when a row has been
* written. */
/* Setup filtering. Use Paeth filtering */
png_set_filter(png_ptr, 0, PNG_FILTER_PAETH);
/* Setup compression level. */
png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
/* Setup PNG header information and write it to the file */
int color_type;
switch (m_elements) {
case 1:
color_type = PNG_COLOR_TYPE_GRAY;
break;
case 2:
color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
break;
case 3:
color_type = PNG_COLOR_TYPE_RGB;
break;
case 4:
color_type = PNG_COLOR_TYPE_RGBA;
break;
default:
throw ShImageException("Invalid element size");
}
png_set_IHDR(png_ptr, info_ptr,
m_width, m_height,
16,
color_type,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
// Actual writing
png_uint_16* tempLine = (png_uint_16*)malloc(m_width * sizeof(png_uint_16) * m_elements);
for(int i=0;i<m_height;i+=1){
for(int j=0;j<m_width;j+=1){
for(int k = 0;k<m_elements;k+=1)
tempLine[m_elements*j+k] = static_cast<png_uint_16>((*this)(j, i, k)*65535.0);
// inverse alpha
if(inverse_alpha && m_elements == 4)
tempLine[m_elements*j+3] = 65535 - tempLine[m_elements*j+3];
}
png_write_row(png_ptr, (png_byte*)tempLine);
}
// closing and freeing the structs
png_write_end(png_ptr, info_ptr);
png_destroy_write_struct(&png_ptr, &info_ptr);
free(tempLine);
fclose(fout);
}
ShImage ShImage::getNormalImage()
{
int w = width();
int h = height();
ShImage output_image(w,h,3);
for (int j = 0; j < h; j++) {
int jp1 = j + 1;
if (jp1 >= h) jp1 = 0;
int jm1 = (j - 1);
if (jm1 < 0) jm1 = h - 1;
for (int i = 0; i < w; i++) {
int ip1 = i + 1;
if (ip1 >= w) ip1 = 0;
int im1 = (i - 1);
if (im1 < 0) im1 = w - 1;
float x, y, z;
x = ((*this)(ip1,j,0) - (*this)(im1,j,0))/2.0f;
output_image(i,j,0) = x/2.0f + 0.5f;
y = ((*this)(i,jp1,0) - (*this)(i,jm1,0))/2.0f;
output_image(i,j,1) = y/2.0f + 0.5f;
z = x*x + y*y;
z = (z > 1.0f) ? z = 0.0f : std::sqrt(1 - z);
output_image(i,j,2) = z;
}
}
return output_image;
}
const float* ShImage::data() const
{
if (!m_memory) return 0;
return reinterpret_cast<const float*>(m_memory->hostStorage()->data());
}
float* ShImage::data()
{
if (!m_memory) return 0;
return reinterpret_cast<float*>(m_memory->hostStorage()->data());
}
void ShImage::dirty()
{
if (!m_memory) return;
m_memory->hostStorage()->dirty();
}
ShMemoryPtr ShImage::memory()
{
return m_memory;
}
ShPointer<const ShMemory> ShImage::memory() const
{
return m_memory;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 1998 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <math.h>
#include <stdarg.h>
#include "sysdef.h"
#include "txtmgr.h"
#include "csutil/util.h"
#include "csutil/inifile.h"
#include "qint.h"
#include "iimage.h"
#include "isystem.h"
#include "lightdef.h"
/// This is not too good from theoretical point of view,
/// however I do not see other efficient solutions. An alternative could
/// be to store such a pointer into each csTextureMM, but this is definitely
/// a waste of memory.
static csTextureManager *texman = NULL;
//---------------------------------------------------------- csTextureMM -----//
IMPLEMENT_IBASE (csTextureMM)
IMPLEMENTS_INTERFACE (iTextureHandle)
IMPLEMENT_IBASE_END
csTextureMM::csTextureMM (iImage* Image, int Flags)
{
CONSTRUCT_IBASE (NULL);
(image = Image)->IncRef ();
flags = Flags;
tex [0] = tex [1] = tex [2] = tex [3] = NULL;
transp = false;
transp_color.red = transp_color.green = transp_color.blue = 0;
cachedata = NULL;
gamma_aplied = false;
}
csTextureMM::~csTextureMM ()
{
for (int i = 0; i < 4; i++)
CHKB (delete tex [i]);
free_image ();
}
void csTextureMM::free_image ()
{
if (!image) return;
image->DecRef ();
image = NULL;
}
void csTextureMM::create_mipmaps (bool verynice, bool blend_mipmap0)
{
if (!image) return;
// Delete existing mipmaps, if any
for (int i = 0; i < 4; i++)
CHKB (delete tex [i]);
int step = verynice ? 0 : 1;
RGBPixel *tc = transp ? &transp_color : (RGBPixel *)NULL;
if (flags & CS_TEXTURE_3D)
{
iImage *i0 = blend_mipmap0 ? image->MipMap (0, tc) : (image->IncRef (), image);
#if 1
// Create each new level by creating a level 2 mipmap from previous level
iImage *i1 = i0->MipMap (step, tc);
iImage *i2 = i1->MipMap (1, tc);
iImage *i3 = i2->MipMap (1, tc);
#else
// Create each mipmap level from original texture
iImage *i1 = image->MipMap (step++, tc);
iImage *i2 = image->MipMap (step++, tc);
iImage *i3 = image->MipMap (step++, tc);
#endif
tex [0] = new_texture (i0);
tex [1] = new_texture (i1);
tex [2] = new_texture (i2);
tex [3] = new_texture (i3);
}
else
{
// 2D textures uses just the top-level mipmap
image->IncRef ();
tex [0] = new_texture (image);
}
compute_mean_color ();
}
void csTextureMM::SetTransparent (bool Enable)
{
transp = Enable;
}
// This function must be called BEFORE calling TextureManager::Update().
void csTextureMM::SetTransparent (UByte red, UByte green, UByte blue)
{
transp_color.red = red;
transp_color.green = green;
transp_color.blue = blue;
transp = true;
}
/// Get the transparent color
void csTextureMM::GetTransparent (UByte &r, UByte &g, UByte &b)
{
r = transp_color.red;
g = transp_color.green;
b = transp_color.blue;
}
bool csTextureMM::GetTransparent ()
{
return transp;
}
void csTextureMM::GetMeanColor (UByte &r, UByte &g, UByte &b)
{
r = mean_color.red;
g = mean_color.green;
b = mean_color.blue;
}
csTexture* csTextureMM::get_texture (int lev)
{
return (lev >= 0) && (lev < 4) ? tex [lev] : NULL;
}
bool csTextureMM::GetMipMapDimensions (int mipmap, int& w, int& h)
{
csTexture *txt = get_texture (mipmap);
if (txt)
{
w = txt->get_width ();
h = txt->get_height ();
return true;
}
return false;
}
void *csTextureMM::GetMipMapData (int mipmap)
{
csTexture *txt = get_texture (mipmap);
return txt ? txt->get_bitmap () : NULL;
}
void csTextureMM::adjust_size_po2 ()
{
int newwidth = image->GetWidth();
int newheight = image->GetHeight();
if (!IsPowerOf2(newwidth))
newwidth = FindNearestPowerOf2 (image->GetWidth ()) / 2;
if (!IsPowerOf2 (newheight))
newheight = FindNearestPowerOf2 (image->GetHeight ()) / 2;
if (newwidth != image->GetWidth () || newheight != image->GetHeight ())
image->Rescale (newwidth, newheight);
}
void csTextureMM::apply_gamma ()
{
if (gamma_aplied || !image)
return;
gamma_aplied = true;
if (texman->Gamma == 1.0)
return;
RGBPixel *src = NULL;
int pixels = 0;
switch (image->GetFormat () & CS_IMGFMT_MASK)
{
case CS_IMGFMT_TRUECOLOR:
src = (RGBPixel *)image->GetImageData ();
pixels = image->GetWidth () * image->GetHeight ();
break;
case CS_IMGFMT_PALETTED8:
src = image->GetPalette ();
pixels = 256;
break;
}
if (!src) return;
while (pixels--)
{
src->red = texman->GammaTable [src->red];
src->green = texman->GammaTable [src->green];
src->blue = texman->GammaTable [src->blue];
src++;
}
}
//------------------------------------------------------------ csTexture -----//
void csTexture::compute_masks ()
{
shf_w = csLog2 (w);
and_w = (1 << shf_w) - 1;
shf_h = csLog2 (h);
and_h = (1 << shf_h) - 1;
}
//----------------------------------------------------- csTextureManager -----//
IMPLEMENT_IBASE (csTextureManager)
IMPLEMENTS_INTERFACE (iTextureManager)
IMPLEMENT_IBASE_END
csTextureManager::csTextureManager (iSystem* iSys, iGraphics2D *iG2D)
: textures (16, 16)
{
texman = this;
System = iSys;
verbose = false;
Gamma = 1.0;
mipmap_mode = MIPMAP_NICE;
do_blend_mipmap0 = false;
pfmt = *iG2D->GetPixelFormat ();
}
csTextureManager::~csTextureManager()
{
Clear ();
}
void csTextureManager::read_config (csIniFile *config)
{
Gamma = config->GetFloat ("TextureManager", "GAMMA", 1.0);
do_blend_mipmap0 = config->GetYesNo ("TextureManager", "BLEND_MIPMAP", false);
const char *p = config->GetStr ("TextureManager", "MIPMAP_MODE", "nice");
if (!strcmp (p, "nice"))
{
mipmap_mode = MIPMAP_NICE;
if (verbose)
System->Printf (MSG_INITIALIZATION, "Mipmap calculation 'nice'.\n");
}
else if (!strcmp (p, "verynice"))
{
mipmap_mode = MIPMAP_VERYNICE;
if (verbose)
System->Printf (MSG_INITIALIZATION, "Mipmap calculation 'verynice'\n");
}
else
System->Printf (MSG_FATAL_ERROR, "Bad value '%s' for MIPMAP_MODE!\n(Use 'verynice' or 'nice')\n", p);
compute_gamma_table ();
}
void csTextureManager::FreeImages ()
{
for (int i = 0 ; i < textures.Length () ; i++)
textures.Get (i)->free_image ();
}
int csTextureManager::GetTextureFormat ()
{
return CS_IMGFMT_TRUECOLOR;
}
void csTextureManager::compute_gamma_table ()
{
for (int i = 0; i < 256; i++)
GammaTable [i] = QRound (255 * pow (i / 255.0, Gamma));
}
int csTextureManager::FindRGB (int r, int g, int b)
{
if (r > 255) r = 255; else if (r < 0) r = 0;
if (g > 255) g = 255; else if (g < 0) g = 0;
if (b > 255) b = 255; else if (b < 0) b = 0;
return
((r >> (8-pfmt.RedBits)) << pfmt.RedShift) |
((g >> (8-pfmt.GreenBits)) << pfmt.GreenShift) |
((b >> (8-pfmt.BlueBits)) << pfmt.BlueShift);
}
void csTextureManager::ReserveColor (int /*r*/, int /*g*/, int /*b*/)
{
}
void csTextureManager::SetPalette ()
{
}
void csTextureManager::ResetPalette ()
{
}
<commit_msg>Adjusted create_mipmap to reflect the new flag CS_TEXTURE_MMLEVEL_MASK.<commit_after>/*
Copyright (C) 1998 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <math.h>
#include <stdarg.h>
#include "sysdef.h"
#include "txtmgr.h"
#include "csutil/util.h"
#include "csutil/inifile.h"
#include "qint.h"
#include "iimage.h"
#include "isystem.h"
#include "lightdef.h"
/// This is not too good from theoretical point of view,
/// however I do not see other efficient solutions. An alternative could
/// be to store such a pointer into each csTextureMM, but this is definitely
/// a waste of memory.
static csTextureManager *texman = NULL;
//---------------------------------------------------------- csTextureMM -----//
IMPLEMENT_IBASE (csTextureMM)
IMPLEMENTS_INTERFACE (iTextureHandle)
IMPLEMENT_IBASE_END
csTextureMM::csTextureMM (iImage* Image, int Flags)
{
CONSTRUCT_IBASE (NULL);
(image = Image)->IncRef ();
flags = Flags;
tex [0] = tex [1] = tex [2] = tex [3] = NULL;
transp = false;
transp_color.red = transp_color.green = transp_color.blue = 0;
cachedata = NULL;
gamma_aplied = false;
}
csTextureMM::~csTextureMM ()
{
for (int i = 0; i < 4; i++)
CHKB (delete tex [i]);
free_image ();
}
void csTextureMM::free_image ()
{
if (!image) return;
image->DecRef ();
image = NULL;
}
void csTextureMM::create_mipmaps (bool verynice, bool blend_mipmap0)
{
if (!image) return;
// Delete existing mipmaps, if any
for (int i = 0; i < 4; i++)
CHKB (delete tex [i]);
int step = verynice ? 0 : 1;
RGBPixel *tc = transp ? &transp_color : (RGBPixel *)NULL;
if (flags & CS_TEXTURE_3D)
{
int n=1;
int maxMM = CS_GET_TEXTURE_MMLEVEL(flags);
maxMM = maxMM == 0 ? 4 : MIN( maxMM, 4 );
iImage *i0 = blend_mipmap0 ? image->MipMap (0, tc) : (image->IncRef (), image);
#if 1
// Create each new level by creating a level 2 mipmap from previous level
iImage *i1 = ++n <= maxMM ? i0->MipMap (step, tc) : NULL;
iImage *i2 = ++n <= maxMM ? i1->MipMap (1, tc) : NULL;
iImage *i3 = ++n <= maxMM ? i2->MipMap (1, tc) : NULL;
#else
// Create each mipmap level from original texture
iImage *i1 = ++n <= maxMM ? image->MipMap (step++, tc) : NULL;
iImage *i2 = ++n <= maxMM ? image->MipMap (step++, tc) : NULL;
iImage *i3 = ++n <= maxMM ? image->MipMap (step++, tc) : NULL;
#endif
tex [0] = new_texture (i0);
tex [1] = i1 ? new_texture (i1) : NULL;
tex [2] = i2 ? new_texture (i2) : NULL;
tex [3] = i3 ? new_texture (i3) : NULL;
}
else
{
// 2D textures uses just the top-level mipmap
image->IncRef ();
tex [0] = new_texture (image);
}
compute_mean_color ();
}
void csTextureMM::SetTransparent (bool Enable)
{
transp = Enable;
}
// This function must be called BEFORE calling TextureManager::Update().
void csTextureMM::SetTransparent (UByte red, UByte green, UByte blue)
{
transp_color.red = red;
transp_color.green = green;
transp_color.blue = blue;
transp = true;
}
/// Get the transparent color
void csTextureMM::GetTransparent (UByte &r, UByte &g, UByte &b)
{
r = transp_color.red;
g = transp_color.green;
b = transp_color.blue;
}
bool csTextureMM::GetTransparent ()
{
return transp;
}
void csTextureMM::GetMeanColor (UByte &r, UByte &g, UByte &b)
{
r = mean_color.red;
g = mean_color.green;
b = mean_color.blue;
}
csTexture* csTextureMM::get_texture (int lev)
{
return (lev >= 0) && (lev < 4) ? tex [lev] : NULL;
}
bool csTextureMM::GetMipMapDimensions (int mipmap, int& w, int& h)
{
csTexture *txt = get_texture (mipmap);
if (txt)
{
w = txt->get_width ();
h = txt->get_height ();
return true;
}
return false;
}
void *csTextureMM::GetMipMapData (int mipmap)
{
csTexture *txt = get_texture (mipmap);
return txt ? txt->get_bitmap () : NULL;
}
void csTextureMM::adjust_size_po2 ()
{
int newwidth = image->GetWidth();
int newheight = image->GetHeight();
if (!IsPowerOf2(newwidth))
newwidth = FindNearestPowerOf2 (image->GetWidth ()) / 2;
if (!IsPowerOf2 (newheight))
newheight = FindNearestPowerOf2 (image->GetHeight ()) / 2;
if (newwidth != image->GetWidth () || newheight != image->GetHeight ())
image->Rescale (newwidth, newheight);
}
void csTextureMM::apply_gamma ()
{
if (gamma_aplied || !image)
return;
gamma_aplied = true;
if (texman->Gamma == 1.0)
return;
RGBPixel *src = NULL;
int pixels = 0;
switch (image->GetFormat () & CS_IMGFMT_MASK)
{
case CS_IMGFMT_TRUECOLOR:
src = (RGBPixel *)image->GetImageData ();
pixels = image->GetWidth () * image->GetHeight ();
break;
case CS_IMGFMT_PALETTED8:
src = image->GetPalette ();
pixels = 256;
break;
}
if (!src) return;
while (pixels--)
{
src->red = texman->GammaTable [src->red];
src->green = texman->GammaTable [src->green];
src->blue = texman->GammaTable [src->blue];
src++;
}
}
//------------------------------------------------------------ csTexture -----//
void csTexture::compute_masks ()
{
shf_w = csLog2 (w);
and_w = (1 << shf_w) - 1;
shf_h = csLog2 (h);
and_h = (1 << shf_h) - 1;
}
//----------------------------------------------------- csTextureManager -----//
IMPLEMENT_IBASE (csTextureManager)
IMPLEMENTS_INTERFACE (iTextureManager)
IMPLEMENT_IBASE_END
csTextureManager::csTextureManager (iSystem* iSys, iGraphics2D *iG2D)
: textures (16, 16)
{
texman = this;
System = iSys;
verbose = false;
Gamma = 1.0;
mipmap_mode = MIPMAP_NICE;
do_blend_mipmap0 = false;
pfmt = *iG2D->GetPixelFormat ();
}
csTextureManager::~csTextureManager()
{
Clear ();
}
void csTextureManager::read_config (csIniFile *config)
{
Gamma = config->GetFloat ("TextureManager", "GAMMA", 1.0);
do_blend_mipmap0 = config->GetYesNo ("TextureManager", "BLEND_MIPMAP", false);
const char *p = config->GetStr ("TextureManager", "MIPMAP_MODE", "nice");
if (!strcmp (p, "nice"))
{
mipmap_mode = MIPMAP_NICE;
if (verbose)
System->Printf (MSG_INITIALIZATION, "Mipmap calculation 'nice'.\n");
}
else if (!strcmp (p, "verynice"))
{
mipmap_mode = MIPMAP_VERYNICE;
if (verbose)
System->Printf (MSG_INITIALIZATION, "Mipmap calculation 'verynice'\n");
}
else
System->Printf (MSG_FATAL_ERROR, "Bad value '%s' for MIPMAP_MODE!\n(Use 'verynice' or 'nice')\n", p);
compute_gamma_table ();
}
void csTextureManager::FreeImages ()
{
for (int i = 0 ; i < textures.Length () ; i++)
textures.Get (i)->free_image ();
}
int csTextureManager::GetTextureFormat ()
{
return CS_IMGFMT_TRUECOLOR;
}
void csTextureManager::compute_gamma_table ()
{
for (int i = 0; i < 256; i++)
GammaTable [i] = QRound (255 * pow (i / 255.0, Gamma));
}
int csTextureManager::FindRGB (int r, int g, int b)
{
if (r > 255) r = 255; else if (r < 0) r = 0;
if (g > 255) g = 255; else if (g < 0) g = 0;
if (b > 255) b = 255; else if (b < 0) b = 0;
return
((r >> (8-pfmt.RedBits)) << pfmt.RedShift) |
((g >> (8-pfmt.GreenBits)) << pfmt.GreenShift) |
((b >> (8-pfmt.BlueBits)) << pfmt.BlueShift);
}
void csTextureManager::ReserveColor (int /*r*/, int /*g*/, int /*b*/)
{
}
void csTextureManager::SetPalette ()
{
}
void csTextureManager::ResetPalette ()
{
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <cstring>
#include <fstream>
#include <string>
#include <memory>
#include <GraphMol/FileParsers/MolSupplier.h>
#include <sqlite3ext.h>
extern const sqlite3_api_routines *sqlite3_api;
#include "utils.hpp"
#include "sdf_io.hpp"
#include "mol.hpp"
// static const int SDF_INDEX_COLUMN = 0;
// static const int SDF_MOLECULE_COLUMN = 1;
static const int SDF_FILEPATH_COLUMN = 2;
static int sdfReaderConnect(sqlite3 *db, void */*pAux*/,
int /*argc*/, const char * const */*argv*/,
sqlite3_vtab **ppVTab,
char **pzErr)
{
int rc = sqlite3_declare_vtab(db, "CREATE TABLE x("
"idx INTEGER, molecule MOL, "
"file_path HIDDEN"
")");
if (rc == SQLITE_OK) {
sqlite3_vtab *vtab = *ppVTab = (sqlite3_vtab *) sqlite3_malloc(sizeof(sqlite3_vtab));
if (!vtab) {
rc = SQLITE_NOMEM;
}
else {
memset(vtab, 0, sizeof(sqlite3_vtab));
}
}
if (rc != SQLITE_OK) {
*pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
}
return rc;
}
int sdfReaderBestIndex(sqlite3_vtab */*pVTab*/, sqlite3_index_info *pIndexInfo)
{
// At this time the only arg passed to the SDF parser is the input file path
// this function is consequently very simple. it might become more complex
// when/if support for more args/options is implemented.
int file_path_index = -1;
for (int index = 0; index < pIndexInfo->nConstraint; ++index) {
if (pIndexInfo->aConstraint[index].usable == 0) {
continue;
}
if (pIndexInfo->aConstraint[index].iColumn == SDF_FILEPATH_COLUMN &&
pIndexInfo->aConstraint[index].op == SQLITE_INDEX_CONSTRAINT_EQ) {
file_path_index = index;
}
}
if (file_path_index < 0) {
// The SDF file path is not available, or it's not usable,
// This plan is unusable for this table
return SQLITE_CONSTRAINT;
}
pIndexInfo->idxNum = 1; // Not really meaningful a this time
pIndexInfo->aConstraintUsage[file_path_index].argvIndex = 1; // will be argv[0] for xFilter
pIndexInfo->aConstraintUsage[file_path_index].omit = 1; // no need for SQLite to verify
pIndexInfo->estimatedCost = 1000000;
return SQLITE_OK;
}
static int sdfReaderDisconnect(sqlite3_vtab *pVTab)
{
sqlite3_free(pVTab);
return SQLITE_OK;
}
struct SdfReaderCursor : public sqlite3_vtab_cursor {
std::unique_ptr<RDKit::ForwardSDMolSupplier> supplier;
sqlite3_int64 rowid;
std::unique_ptr<RDKit::ROMol> mol;
};
static int sdfReaderOpen(sqlite3_vtab */*pVTab*/, sqlite3_vtab_cursor **ppCursor)
{
int rc = SQLITE_OK;
SdfReaderCursor *pCsr = new SdfReaderCursor; //FIXME
*ppCursor = (sqlite3_vtab_cursor *)pCsr;
return rc;
}
static int sdfReaderClose(sqlite3_vtab_cursor *pCursor)
{
SdfReaderCursor *p = (SdfReaderCursor *)pCursor;
delete p;
return SQLITE_OK;
}
static int sdfReaderFilter(sqlite3_vtab_cursor *pCursor, int /*idxNum*/, const char */*idxStr*/,
int argc, sqlite3_value **argv)
{
SdfReaderCursor *p = (SdfReaderCursor *)pCursor;
if (argc != 1) {
// at present we always expect the input file path as the only arg
return SQLITE_ERROR;
}
sqlite3_value *arg = argv[0];
if (sqlite3_value_type(arg) != SQLITE_TEXT) {
return SQLITE_MISMATCH;
}
const char * file_path = (const char *) sqlite3_value_text(arg);
std::unique_ptr<std::ifstream> pins(new std::ifstream(file_path));
if (!pins->is_open()) {
// Maybe log something
return SQLITE_ERROR;
}
p->supplier.reset(new RDKit::ForwardSDMolSupplier(pins.release(), true));
if (!p->supplier->atEnd()) {
p->rowid = 1;
p->mol.reset(p->supplier->next());
}
return SQLITE_OK;
}
static int sdfReaderNext(sqlite3_vtab_cursor *pCursor)
{
SdfReaderCursor * p = (SdfReaderCursor *)pCursor;
if (!p->supplier->atEnd()) {
p->rowid += 1;
p->mol.reset(p->supplier->next());
}
return SQLITE_OK;
}
static int sdfReaderEof(sqlite3_vtab_cursor *pCursor)
{
SdfReaderCursor * p = (SdfReaderCursor *)pCursor;
return p->supplier->atEnd() ? 1 : 0;
}
static int sdfReaderColumn(sqlite3_vtab_cursor *pCursor, sqlite3_context *ctx, int N)
{
SdfReaderCursor * p = (SdfReaderCursor *)pCursor;
switch (N) {
case 0:
// row id
sqlite3_result_int(ctx, p->rowid);
break;
case 1:
// the molecule
if (p->mol) {
int rc = SQLITE_OK;
Blob blob = mol_to_blob(*p->mol, &rc);
if (rc == SQLITE_OK) {
sqlite3_result_blob(ctx, blob.data(), blob.size(), SQLITE_TRANSIENT);
}
else {
sqlite3_result_error_code(ctx, rc);
}
}
else {
sqlite3_result_null(ctx);
}
break;
default:
assert(!"unexpected column number");
sqlite3_result_null(ctx);
}
return SQLITE_OK;
}
static int sdfReaderRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid)
{
SdfReaderCursor * p = (SdfReaderCursor *)pCursor;
*pRowid = p->rowid;
return SQLITE_OK;
}
/*
** The SDF reader module, collecting the methods that operate on the PeriodicTable vtab
*/
static sqlite3_module sdfReaderModule = {
0, /* iVersion */
0, /* xCreate - create a table */ /* null because eponymous-only */
sdfReaderConnect, /* xConnect - connect to an existing table */
sdfReaderBestIndex, /* xBestIndex - Determine search strategy */
sdfReaderDisconnect, /* xDisconnect - Disconnect from a table */
0, /* xDestroy - Drop a table */
sdfReaderOpen, /* xOpen - open a cursor */
sdfReaderClose, /* xClose - close a cursor */
sdfReaderFilter, /* xFilter - configure scan constraints */
sdfReaderNext, /* xNext - advance a cursor */
sdfReaderEof, /* xEof */
sdfReaderColumn, /* xColumn - read data */
sdfReaderRowid, /* xRowid - read data */
0, /* xUpdate - write data */
0, /* xBegin - begin transaction */
0, /* xSync - sync transaction */
0, /* xCommit - commit transaction */
0, /* xRollback - rollback transaction */
0, /* xFindFunction - function overloading */
0, /* xRename - rename the table */
0, /* xSavepoint */
0, /* xRelease */
0, /* xRollbackTo */
0 /* xShadowName */
};
int chemicalite_init_sdf_io(sqlite3 *db)
{
int rc = SQLITE_OK;
if (rc == SQLITE_OK) {
rc = sqlite3_create_module_v2(db, "sdf_reader", &sdfReaderModule,
0, /* Client data for xCreate/xConnect */
0 /* Module destructor function */
);
}
return rc;
}
<commit_msg>remove the explicit rowid/index column<commit_after>#include <cassert>
#include <cstring>
#include <fstream>
#include <string>
#include <memory>
#include <GraphMol/FileParsers/MolSupplier.h>
#include <sqlite3ext.h>
extern const sqlite3_api_routines *sqlite3_api;
#include "utils.hpp"
#include "sdf_io.hpp"
#include "mol.hpp"
// static const int SDF_MOLECULE_COLUMN = 0;
static const int SDF_FILEPATH_COLUMN = 1;
static int sdfReaderConnect(sqlite3 *db, void */*pAux*/,
int /*argc*/, const char * const */*argv*/,
sqlite3_vtab **ppVTab,
char **pzErr)
{
int rc = sqlite3_declare_vtab(db, "CREATE TABLE x("
"molecule MOL, "
"file_path HIDDEN"
")");
if (rc == SQLITE_OK) {
sqlite3_vtab *vtab = *ppVTab = (sqlite3_vtab *) sqlite3_malloc(sizeof(sqlite3_vtab));
if (!vtab) {
rc = SQLITE_NOMEM;
}
else {
memset(vtab, 0, sizeof(sqlite3_vtab));
}
}
if (rc != SQLITE_OK) {
*pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
}
return rc;
}
int sdfReaderBestIndex(sqlite3_vtab */*pVTab*/, sqlite3_index_info *pIndexInfo)
{
// At this time the only arg passed to the SDF parser is the input file path
// this function is consequently very simple. it might become more complex
// when/if support for more args/options is implemented.
int file_path_index = -1;
for (int index = 0; index < pIndexInfo->nConstraint; ++index) {
if (pIndexInfo->aConstraint[index].usable == 0) {
continue;
}
if (pIndexInfo->aConstraint[index].iColumn == SDF_FILEPATH_COLUMN &&
pIndexInfo->aConstraint[index].op == SQLITE_INDEX_CONSTRAINT_EQ) {
file_path_index = index;
}
}
if (file_path_index < 0) {
// The SDF file path is not available, or it's not usable,
// This plan is unusable for this table
return SQLITE_CONSTRAINT;
}
pIndexInfo->idxNum = 1; // Not really meaningful a this time
pIndexInfo->aConstraintUsage[file_path_index].argvIndex = 1; // will be argv[0] for xFilter
pIndexInfo->aConstraintUsage[file_path_index].omit = 1; // no need for SQLite to verify
pIndexInfo->estimatedCost = 1000000;
return SQLITE_OK;
}
static int sdfReaderDisconnect(sqlite3_vtab *pVTab)
{
sqlite3_free(pVTab);
return SQLITE_OK;
}
struct SdfReaderCursor : public sqlite3_vtab_cursor {
std::unique_ptr<RDKit::ForwardSDMolSupplier> supplier;
sqlite3_int64 rowid;
std::unique_ptr<RDKit::ROMol> mol;
};
static int sdfReaderOpen(sqlite3_vtab */*pVTab*/, sqlite3_vtab_cursor **ppCursor)
{
int rc = SQLITE_OK;
SdfReaderCursor *pCsr = new SdfReaderCursor; //FIXME
*ppCursor = (sqlite3_vtab_cursor *)pCsr;
return rc;
}
static int sdfReaderClose(sqlite3_vtab_cursor *pCursor)
{
SdfReaderCursor *p = (SdfReaderCursor *)pCursor;
delete p;
return SQLITE_OK;
}
static int sdfReaderFilter(sqlite3_vtab_cursor *pCursor, int /*idxNum*/, const char */*idxStr*/,
int argc, sqlite3_value **argv)
{
SdfReaderCursor *p = (SdfReaderCursor *)pCursor;
if (argc != 1) {
// at present we always expect the input file path as the only arg
return SQLITE_ERROR;
}
sqlite3_value *arg = argv[0];
if (sqlite3_value_type(arg) != SQLITE_TEXT) {
return SQLITE_MISMATCH;
}
const char * file_path = (const char *) sqlite3_value_text(arg);
std::unique_ptr<std::ifstream> pins(new std::ifstream(file_path));
if (!pins->is_open()) {
// Maybe log something
return SQLITE_ERROR;
}
p->supplier.reset(new RDKit::ForwardSDMolSupplier(pins.release(), true));
if (!p->supplier->atEnd()) {
p->rowid = 1;
p->mol.reset(p->supplier->next());
}
return SQLITE_OK;
}
static int sdfReaderNext(sqlite3_vtab_cursor *pCursor)
{
SdfReaderCursor * p = (SdfReaderCursor *)pCursor;
if (!p->supplier->atEnd()) {
p->rowid += 1;
p->mol.reset(p->supplier->next());
}
return SQLITE_OK;
}
static int sdfReaderEof(sqlite3_vtab_cursor *pCursor)
{
SdfReaderCursor * p = (SdfReaderCursor *)pCursor;
return p->supplier->atEnd() ? 1 : 0;
}
static int sdfReaderColumn(sqlite3_vtab_cursor *pCursor, sqlite3_context *ctx, int N)
{
SdfReaderCursor * p = (SdfReaderCursor *)pCursor;
switch (N) {
case 0:
// the molecule
if (p->mol) {
int rc = SQLITE_OK;
Blob blob = mol_to_blob(*p->mol, &rc);
if (rc == SQLITE_OK) {
sqlite3_result_blob(ctx, blob.data(), blob.size(), SQLITE_TRANSIENT);
}
else {
sqlite3_result_error_code(ctx, rc);
}
}
else {
sqlite3_result_null(ctx);
}
break;
default:
assert(!"unexpected column number");
sqlite3_result_null(ctx);
}
return SQLITE_OK;
}
static int sdfReaderRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid)
{
SdfReaderCursor * p = (SdfReaderCursor *)pCursor;
*pRowid = p->rowid;
return SQLITE_OK;
}
/*
** The SDF reader module, collecting the methods that operate on the PeriodicTable vtab
*/
static sqlite3_module sdfReaderModule = {
0, /* iVersion */
0, /* xCreate - create a table */ /* null because eponymous-only */
sdfReaderConnect, /* xConnect - connect to an existing table */
sdfReaderBestIndex, /* xBestIndex - Determine search strategy */
sdfReaderDisconnect, /* xDisconnect - Disconnect from a table */
0, /* xDestroy - Drop a table */
sdfReaderOpen, /* xOpen - open a cursor */
sdfReaderClose, /* xClose - close a cursor */
sdfReaderFilter, /* xFilter - configure scan constraints */
sdfReaderNext, /* xNext - advance a cursor */
sdfReaderEof, /* xEof */
sdfReaderColumn, /* xColumn - read data */
sdfReaderRowid, /* xRowid - read data */
0, /* xUpdate - write data */
0, /* xBegin - begin transaction */
0, /* xSync - sync transaction */
0, /* xCommit - commit transaction */
0, /* xRollback - rollback transaction */
0, /* xFindFunction - function overloading */
0, /* xRename - rename the table */
0, /* xSavepoint */
0, /* xRelease */
0, /* xRollbackTo */
0 /* xShadowName */
};
int chemicalite_init_sdf_io(sqlite3 *db)
{
int rc = SQLITE_OK;
if (rc == SQLITE_OK) {
rc = sqlite3_create_module_v2(db, "sdf_reader", &sdfReaderModule,
0, /* Client data for xCreate/xConnect */
0 /* Module destructor function */
);
}
return rc;
}
<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------
/// \file es/storage.hpp
/// \brief The entity/component data store
//
// Copyright 2013, [email protected] Released under the MIT License.
//---------------------------------------------------------------------------
#pragma once
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cstdint>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <vector>
#include <unordered_map>
#include "component.hpp"
#include "entity.hpp"
#include "traits.hpp"
namespace es {
/** A storage ties entities and components together.
* Storage associates two other bits of data with every entity:
* - A 64-bit mask that keeps track of which components are defined
* - A vector of bytes, holding the actual data
*
* The vector of bytes tries to pack the component data as tightly as
* possible. It is really fast for plain old datatypes, but it also
* handles nontrivial types safely. It packs a virtual table and a
* pointer to some heap space in the vector, and calls the constructor
* and destructor as needed.
*/
class storage
{
// It is assumed the first few components will be accessed the
// most often. We keep a cache of the first 12.
static constexpr uint32_t cache_size = 12;
static constexpr uint32_t cache_mask = (1 << cache_size) - 1;
/** This data gets associated with every entity. */
struct elem
{
/** Bitmask to keep track of which components are held in \a data. */
std::bitset<64> components;
/** Component data for this entity. */
std::vector<char> data;
};
typedef component::placeholder placeholder;
/** Data types that do not have a flat memory layout are kept in the
** elem::data buffer in a placeholder object. */
template <typename t>
class holder : public placeholder
{
public:
holder () { }
holder (t init) : held_(std::move(init)) { }
const t& held() const { return held_; }
t& held() { return held_; }
placeholder* clone() const { return new holder<t>(held_); }
private:
t held_;
};
typedef std::unordered_map<uint32_t, elem> stor_impl;
public:
typedef uint8_t component_id;
typedef stor_impl::iterator iterator;
typedef stor_impl::const_iterator const_iterator;
public:
/** Variable references are used by systems to access an entity's data.
* It keeps track of the elem::data buffer and the offset inside that
* buffer. */
template <typename type>
class var_ref
{
friend class storage;
type& get()
{
if (is_flat<type>::value)
return *reinterpret_cast<type*>(&*e_.data.begin() + offset_);
auto ptr (reinterpret_cast<holder<type>*>(&*e_.data.begin() + offset_));
return ptr->held();
}
public:
operator const type& () const
{
if (is_flat<type>::value)
return *reinterpret_cast<const type*>(&*e_.data.begin() + offset_);
auto ptr (reinterpret_cast<const holder<type>*>(&*e_.data.begin() + offset_));
return ptr->held();
}
var_ref& operator= (type assign)
{
if (is_flat<type>::value)
{
new (&*e_.data.begin() + offset_) type(std::move(assign));
}
else
{
auto ptr (reinterpret_cast<holder<type>*>(&*e_.data.begin() + offset_));
new (ptr) holder<type>(std::move(assign));
}
return *this;
}
template <typename s>
var_ref& operator+= (s val)
{ get() += val; return *this; }
template <typename s>
var_ref& operator-= (s val)
{ get() -= val; return *this; }
template <typename s>
var_ref& operator*= (s val)
{ get() *= val; return *this; }
template <typename s>
var_ref& operator/= (s val)
{ get() /= val; return *this; }
protected:
var_ref (size_t offset, elem& e)
: offset_(offset), e_(e)
{ }
private:
size_t offset_;
elem& e_;
};
public:
storage()
: next_id_(0)
{
component_offsets_.push_back(0);
}
template <typename type>
component_id register_component (std::string name)
{
size_t size;
if (is_flat<type>::value)
{
size = sizeof(type);
components_.emplace_back(name, size, nullptr);
}
else
{
flat_mask_.set(components_.size());
size = sizeof(holder<type>);
components_.emplace_back(name, size,
std::unique_ptr<placeholder>(new holder<type>()));
}
if (components_.size() < cache_size)
{
size_t i (component_offsets_.size());
component_offsets_.resize(i * 2);
for (size_t j (i); j != i * 2; ++j)
component_offsets_[j] = component_offsets_[j-i] + size;
}
return components_.size() - 1;
}
component_id find_component (const std::string& name) const
{
auto found (std::find(components_.begin(), components_.end(), name));
if (found == components_.end())
throw std::logic_error("component does not exist");
return std::distance(components_.begin(), found);
}
const component& operator[] (component_id id) const
{ return components_[id]; }
const std::vector<component>& components() const
{ return components_; }
public:
entity new_entity()
{
entities_[next_id_++];
return next_id_ - 1;
}
/** Get an entity with a given ID, or create it if it didn't exist yet. */
iterator make (uint32_t id)
{
if (next_id_ <= id)
next_id_ = id + 1;
return entities_.insert(entities_.end(), std::make_pair(id, elem()));
}
/** Create a whole bunch of empty entities in one go.
* @param count The number of entities to create
* @return The range of entities created */
std::pair<entity, entity> new_entities (size_t count)
{
auto range_begin (next_id_);
for (; count > 0; --count)
entities_[next_id_++];
return std::make_pair(range_begin, next_id_);
}
entity clone_entity (iterator f)
{
elem& e (f->second);
entities_[next_id_++] = e;
// Quick check if we need to make deep copies
if ((e.components & flat_mask_).any())
{
size_t off (0);
for (int c_id (0); c_id < 64 && off < e.data.size(); ++c_id)
{
if (e.components[c_id])
{
if (!components_[c_id].is_flat())
{
auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
ptr = ptr->clone();
}
off += components_[c_id].size();
}
}
}
return next_id_ - 1;
}
iterator find (entity en)
{
auto found (entities_.find(en));
if (found == entities_.end())
throw std::logic_error("unknown entity");
return found;
}
const_iterator find (entity en) const
{
auto found (entities_.find(en));
if (found == entities_.end())
throw std::logic_error("unknown entity");
return found;
}
void delete_entity (entity en)
{ delete_entity(find(en)); }
void delete_entity (iterator f)
{
elem& e (f->second);
// Quick check if we'll have to call any destructors.
if ((e.components & flat_mask_).any())
{
size_t off (0);
for (int search (0); search < 64 && off < e.data.size(); ++search)
{
if (e.components[search])
{
if (!components_[search].is_flat())
{
auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
ptr->~placeholder();
}
off += components_[search].size();
}
}
}
entities_.erase(f);
}
void remove_component_from_entity (iterator en, component_id c)
{
auto& e (en->second);
if (!e.components[c])
return;
size_t off (offset(e, c));
auto& comp_info (components_[c]);
if (!comp_info.is_flat())
{
auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
ptr->~placeholder();
}
auto o (e.data.begin() + off);
e.data.erase(o, o + comp_info.size());
e.components.reset(c);
}
/** Call a function for every entity that has a given component.
* The callee can then query and change the value of the component through
* a var_ref object, or remove the entity.
* @param c The component to look for.
* @param func The function to call. This function will be passed an
* iterator to the current entity, and a var_ref corresponding
* to the component value in this entity. */
template <typename t>
void for_each (component_id c, std::function<void(iterator, var_ref<t>)> func)
{
std::bitset<64> mask;
mask.set(c);
for (auto i (entities_.begin()); i != entities_.end(); )
{
auto next (std::next(i));
elem& e (i->second);
if ((e.components & mask) == mask)
func(i, var_ref<t>(offset(e, c), e));
i = next;
}
}
template <typename t1, typename t2>
void for_each (component_id c1, component_id c2,
std::function<void(iterator, var_ref<t1>, var_ref<t2>)> func)
{
std::bitset<64> mask;
mask.set(c1);
mask.set(c2);
for (auto i (entities_.begin()); i != entities_.end(); )
{
auto next (std::next(i));
elem& e (i->second);
if ((e.components & mask) == mask)
{
func(i, var_ref<t1>(offset(e, c1), e),
var_ref<t2>(offset(e, c2), e));
}
i = next;
}
}
template <typename t1, typename t2, typename t3>
void for_each (component_id c1, component_id c2, component_id c3,
std::function<void(iterator, var_ref<t1>, var_ref<t2>, var_ref<t3>)> func)
{
std::bitset<64> mask;
mask.set(c1);
mask.set(c2);
mask.set(c3);
for (auto i (entities_.begin()); i != entities_.end(); )
{
auto next (std::next(i));
elem& e (i->second);
if ((e.components & mask) == mask)
{
func(i, var_ref<t1>(offset(e, c1), e),
var_ref<t2>(offset(e, c2), e),
var_ref<t3>(offset(e, c3), e));
}
i = next;
}
}
bool exists (entity en) const
{ return entities_.count(en); }
template <typename type>
void set (entity en, component_id c_id, type val)
{ return set<type>(find(en), c_id, std::move(val)); }
template <typename type>
void set (iterator en, component_id c_id, type val)
{
const component& c (components_[c_id]);
elem& e (en->second);
size_t off (offset(e, c_id));
if (!e.components[c_id])
{
if (e.data.size() < off)
e.data.resize(off + c.size());
else
e.data.insert(e.data.begin() + off, c.size(), 0);
e.components.set(c_id);
}
if (is_flat<type>::value)
{
assert(e.data.size() >= off + sizeof(type));
new (&*e.data.begin() + off) type(std::move(val));
}
else
{
assert(e.data.size() >= off + sizeof(holder<type>));
auto ptr (reinterpret_cast<holder<type>*>(&*e.data.begin() + off));
new (ptr) holder<type>(std::move(val));
}
}
template <typename type>
const type& get (entity en, component_id c_id) const
{ return get<type>(find(en), c_id); }
template <typename type>
const type& get (const_iterator en, component_id c_id) const
{
auto& e (en->second);
if (!e.components[c_id])
throw std::logic_error("entity does not have component");
return get<type>(e, c_id);
}
private:
template <typename type>
const type& get (const elem& e, component_id c_id) const
{
size_t off (offset(e, c_id));
if (is_flat<type>::value)
return *reinterpret_cast<const type*>(&*e.data.begin() + off);
auto ptr (reinterpret_cast<const holder<type>*>(&*e.data.begin() + off));
return ptr->held();
}
size_t offset (const elem& e, component_id c) const
{
assert(c < components_.size());
assert((c & cache_mask) < component_offsets_.size());
size_t result (component_offsets_[c & cache_mask]);
for (component_id search (cache_size); search < c; ++search)
{
if (e.components[search])
result += components_[search].size();
}
return result;
}
private:
/** Keeps track of entity IDs to give out. */
uint32_t next_id_;
/** The list of registered components. */
std::vector<component> components_;
/** Mapping entity IDs to their data. */
std::unordered_map<uint32_t, elem> entities_;
/** A lookup table for the data offsets of components.
* The index is the bitmask as used in elem::components. */
std::vector<size_t> component_offsets_;
/** A bitmask to quickly determine whether a certain combination of
** components has a flat memory layout or not. */
std::bitset<64> flat_mask_;
};
} // namespace es
<commit_msg>Make sure entities exist before deleting them<commit_after>//---------------------------------------------------------------------------
/// \file es/storage.hpp
/// \brief The entity/component data store
//
// Copyright 2013, [email protected] Released under the MIT License.
//---------------------------------------------------------------------------
#pragma once
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cstdint>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <vector>
#include <unordered_map>
#include "component.hpp"
#include "entity.hpp"
#include "traits.hpp"
namespace es {
/** A storage ties entities and components together.
* Storage associates two other bits of data with every entity:
* - A 64-bit mask that keeps track of which components are defined
* - A vector of bytes, holding the actual data
*
* The vector of bytes tries to pack the component data as tightly as
* possible. It is really fast for plain old datatypes, but it also
* handles nontrivial types safely. It packs a virtual table and a
* pointer to some heap space in the vector, and calls the constructor
* and destructor as needed.
*/
class storage
{
// It is assumed the first few components will be accessed the
// most often. We keep a cache of the first 12.
static constexpr uint32_t cache_size = 12;
static constexpr uint32_t cache_mask = (1 << cache_size) - 1;
/** This data gets associated with every entity. */
struct elem
{
/** Bitmask to keep track of which components are held in \a data. */
std::bitset<64> components;
/** Component data for this entity. */
std::vector<char> data;
};
typedef component::placeholder placeholder;
/** Data types that do not have a flat memory layout are kept in the
** elem::data buffer in a placeholder object. */
template <typename t>
class holder : public placeholder
{
public:
holder () { }
holder (t init) : held_(std::move(init)) { }
const t& held() const { return held_; }
t& held() { return held_; }
placeholder* clone() const { return new holder<t>(held_); }
private:
t held_;
};
typedef std::unordered_map<uint32_t, elem> stor_impl;
public:
typedef uint8_t component_id;
typedef stor_impl::iterator iterator;
typedef stor_impl::const_iterator const_iterator;
public:
/** Variable references are used by systems to access an entity's data.
* It keeps track of the elem::data buffer and the offset inside that
* buffer. */
template <typename type>
class var_ref
{
friend class storage;
type& get()
{
if (is_flat<type>::value)
return *reinterpret_cast<type*>(&*e_.data.begin() + offset_);
auto ptr (reinterpret_cast<holder<type>*>(&*e_.data.begin() + offset_));
return ptr->held();
}
public:
operator const type& () const
{
if (is_flat<type>::value)
return *reinterpret_cast<const type*>(&*e_.data.begin() + offset_);
auto ptr (reinterpret_cast<const holder<type>*>(&*e_.data.begin() + offset_));
return ptr->held();
}
var_ref& operator= (type assign)
{
if (is_flat<type>::value)
{
new (&*e_.data.begin() + offset_) type(std::move(assign));
}
else
{
auto ptr (reinterpret_cast<holder<type>*>(&*e_.data.begin() + offset_));
new (ptr) holder<type>(std::move(assign));
}
return *this;
}
template <typename s>
var_ref& operator+= (s val)
{ get() += val; return *this; }
template <typename s>
var_ref& operator-= (s val)
{ get() -= val; return *this; }
template <typename s>
var_ref& operator*= (s val)
{ get() *= val; return *this; }
template <typename s>
var_ref& operator/= (s val)
{ get() /= val; return *this; }
protected:
var_ref (size_t offset, elem& e)
: offset_(offset), e_(e)
{ }
private:
size_t offset_;
elem& e_;
};
public:
storage()
: next_id_(0)
{
component_offsets_.push_back(0);
}
template <typename type>
component_id register_component (std::string name)
{
size_t size;
if (is_flat<type>::value)
{
size = sizeof(type);
components_.emplace_back(name, size, nullptr);
}
else
{
flat_mask_.set(components_.size());
size = sizeof(holder<type>);
components_.emplace_back(name, size,
std::unique_ptr<placeholder>(new holder<type>()));
}
if (components_.size() < cache_size)
{
size_t i (component_offsets_.size());
component_offsets_.resize(i * 2);
for (size_t j (i); j != i * 2; ++j)
component_offsets_[j] = component_offsets_[j-i] + size;
}
return components_.size() - 1;
}
component_id find_component (const std::string& name) const
{
auto found (std::find(components_.begin(), components_.end(), name));
if (found == components_.end())
throw std::logic_error("component does not exist");
return std::distance(components_.begin(), found);
}
const component& operator[] (component_id id) const
{ return components_[id]; }
const std::vector<component>& components() const
{ return components_; }
public:
entity new_entity()
{
entities_[next_id_++];
return next_id_ - 1;
}
/** Get an entity with a given ID, or create it if it didn't exist yet. */
iterator make (uint32_t id)
{
if (next_id_ <= id)
next_id_ = id + 1;
return entities_.insert(entities_.end(), std::make_pair(id, elem()));
}
/** Create a whole bunch of empty entities in one go.
* @param count The number of entities to create
* @return The range of entities created */
std::pair<entity, entity> new_entities (size_t count)
{
auto range_begin (next_id_);
for (; count > 0; --count)
entities_[next_id_++];
return std::make_pair(range_begin, next_id_);
}
entity clone_entity (iterator f)
{
elem& e (f->second);
entities_[next_id_++] = e;
// Quick check if we need to make deep copies
if ((e.components & flat_mask_).any())
{
size_t off (0);
for (int c_id (0); c_id < 64 && off < e.data.size(); ++c_id)
{
if (e.components[c_id])
{
if (!components_[c_id].is_flat())
{
auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
ptr = ptr->clone();
}
off += components_[c_id].size();
}
}
}
return next_id_ - 1;
}
iterator find (entity en)
{
auto found (entities_.find(en));
if (found == entities_.end())
throw std::logic_error("unknown entity");
return found;
}
const_iterator find (entity en) const
{
auto found (entities_.find(en));
if (found == entities_.end())
throw std::logic_error("unknown entity");
return found;
}
void delete_entity (entity en)
{
auto found (find(en));
if (found != entities_.end())
delete_entity(found);
}
void delete_entity (iterator f)
{
elem& e (f->second);
// Quick check if we'll have to call any destructors.
if ((e.components & flat_mask_).any())
{
size_t off (0);
for (int search (0); search < 64 && off < e.data.size(); ++search)
{
if (e.components[search])
{
if (!components_[search].is_flat())
{
auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
ptr->~placeholder();
}
off += components_[search].size();
}
}
}
entities_.erase(f);
}
void remove_component_from_entity (iterator en, component_id c)
{
auto& e (en->second);
if (!e.components[c])
return;
size_t off (offset(e, c));
auto& comp_info (components_[c]);
if (!comp_info.is_flat())
{
auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
ptr->~placeholder();
}
auto o (e.data.begin() + off);
e.data.erase(o, o + comp_info.size());
e.components.reset(c);
}
/** Call a function for every entity that has a given component.
* The callee can then query and change the value of the component through
* a var_ref object, or remove the entity.
* @param c The component to look for.
* @param func The function to call. This function will be passed an
* iterator to the current entity, and a var_ref corresponding
* to the component value in this entity. */
template <typename t>
void for_each (component_id c, std::function<void(iterator, var_ref<t>)> func)
{
std::bitset<64> mask;
mask.set(c);
for (auto i (entities_.begin()); i != entities_.end(); )
{
auto next (std::next(i));
elem& e (i->second);
if ((e.components & mask) == mask)
func(i, var_ref<t>(offset(e, c), e));
i = next;
}
}
template <typename t1, typename t2>
void for_each (component_id c1, component_id c2,
std::function<void(iterator, var_ref<t1>, var_ref<t2>)> func)
{
std::bitset<64> mask;
mask.set(c1);
mask.set(c2);
for (auto i (entities_.begin()); i != entities_.end(); )
{
auto next (std::next(i));
elem& e (i->second);
if ((e.components & mask) == mask)
{
func(i, var_ref<t1>(offset(e, c1), e),
var_ref<t2>(offset(e, c2), e));
}
i = next;
}
}
template <typename t1, typename t2, typename t3>
void for_each (component_id c1, component_id c2, component_id c3,
std::function<void(iterator, var_ref<t1>, var_ref<t2>, var_ref<t3>)> func)
{
std::bitset<64> mask;
mask.set(c1);
mask.set(c2);
mask.set(c3);
for (auto i (entities_.begin()); i != entities_.end(); )
{
auto next (std::next(i));
elem& e (i->second);
if ((e.components & mask) == mask)
{
func(i, var_ref<t1>(offset(e, c1), e),
var_ref<t2>(offset(e, c2), e),
var_ref<t3>(offset(e, c3), e));
}
i = next;
}
}
bool exists (entity en) const
{ return entities_.count(en); }
template <typename type>
void set (entity en, component_id c_id, type val)
{ return set<type>(find(en), c_id, std::move(val)); }
template <typename type>
void set (iterator en, component_id c_id, type val)
{
const component& c (components_[c_id]);
elem& e (en->second);
size_t off (offset(e, c_id));
if (!e.components[c_id])
{
if (e.data.size() < off)
e.data.resize(off + c.size());
else
e.data.insert(e.data.begin() + off, c.size(), 0);
e.components.set(c_id);
}
if (is_flat<type>::value)
{
assert(e.data.size() >= off + sizeof(type));
new (&*e.data.begin() + off) type(std::move(val));
}
else
{
assert(e.data.size() >= off + sizeof(holder<type>));
auto ptr (reinterpret_cast<holder<type>*>(&*e.data.begin() + off));
new (ptr) holder<type>(std::move(val));
}
}
template <typename type>
const type& get (entity en, component_id c_id) const
{ return get<type>(find(en), c_id); }
template <typename type>
const type& get (const_iterator en, component_id c_id) const
{
auto& e (en->second);
if (!e.components[c_id])
throw std::logic_error("entity does not have component");
return get<type>(e, c_id);
}
private:
template <typename type>
const type& get (const elem& e, component_id c_id) const
{
size_t off (offset(e, c_id));
if (is_flat<type>::value)
return *reinterpret_cast<const type*>(&*e.data.begin() + off);
auto ptr (reinterpret_cast<const holder<type>*>(&*e.data.begin() + off));
return ptr->held();
}
size_t offset (const elem& e, component_id c) const
{
assert(c < components_.size());
assert((c & cache_mask) < component_offsets_.size());
size_t result (component_offsets_[c & cache_mask]);
for (component_id search (cache_size); search < c; ++search)
{
if (e.components[search])
result += components_[search].size();
}
return result;
}
private:
/** Keeps track of entity IDs to give out. */
uint32_t next_id_;
/** The list of registered components. */
std::vector<component> components_;
/** Mapping entity IDs to their data. */
std::unordered_map<uint32_t, elem> entities_;
/** A lookup table for the data offsets of components.
* The index is the bitmask as used in elem::components. */
std::vector<size_t> component_offsets_;
/** A bitmask to quickly determine whether a certain combination of
** components has a flat memory layout or not. */
std::bitset<64> flat_mask_;
};
} // namespace es
<|endoftext|> |
<commit_before>/*
* Actuator.cc
*
* Author: Lunatic
*/
#include <cstring>
#include <cstdlib>
#include "actuator.h"
#include "lexer.h"
#include "alarm.h"
namespace Script {
bool Env::contains(const std::string& name) {
return vars.find(name) != vars.end();
}
std::string Env::get(const std::string& name) {
return vars.find(name)->second;
}
void Env::put(const std::string& name, const std::string& value) {
vars[name] = value;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
Actuator::Actuator(Parser& _parser) :
parser(_parser) {
}
Actuator::~Actuator() {
}
void Actuator::load() {
Instruction inst;
while (parser.has_next()) {
parser.next(inst);
if (inst.type == kLabel) {
std::map<std::string, size_t>::iterator it = labels.find(inst.name);
if (it == labels.end())
labels[inst.name] = insts.size();
} else
insts.push_back(inst);
}
}
/*
* 将Token转换为Instruction{type, name, params}
*
void Actuator::load(const std::string& script_code) {
Lexer lexer(script_code);
std::vector<Token> tokens;
while (!lexer.finish()) {
Log::info("新的一行");
Instruction inst;
tokens.clear();
for (;;) {
Token token;
int stat = lexer.next_token(token);
if (stat >= 0)
break;
Log::info(token.to_str());
tokens.push_back(token);
}
if (tokens.empty())
continue;
if (tokens[0].type != kName) {
error("语法错误load", tokens[0].pos);
}
inst.name = tokens[0].token;
inst.pos = tokens[0].pos;
if (tokens.size() == 1) {
inst.type = kInstruction;
} else if (tokens[1].type == kColon) {
inst.type = kLabel;
} else { //处理指令参数
inst.type = kInstruction;
for (size_t i = 1; i < tokens.size(); ++i) {
switch (tokens[i].type) {
case kInt:
case kReal:
case kString:
case kName:
case KCmp:
inst.params.push_back(tokens[i]);
break;
default:
Log::error("%zu", i);
Log::error(tokens[i].to_str());
error("参数不符合要求!", tokens[i].pos);
}
}
}
if (inst.type == kLabel) {
std::map<std::string, size_t>::iterator it = labels.find(inst.name);
if (it == labels.end())
labels[inst.name] = insts.size();
} else
insts.push_back(inst);
}
Log::info("加载完毕!");
}
*/
/*
* 如果是变量 存在则直接取出 否则报错 ?不太妥当
* 其他直接返回
*
*/
std::string get_val_or_var(Env& env, Token& token) {
if (token.type == kName) { //处理变量
if (env.contains(token.token)) {
return env.get(token.token);
} else
error("变量未定义" + token.token, token.pos); //?不太妥当
}
return token.token;
}
bool is_real(const std::string& number) {
return std::string::npos != number.find('.');
}
bool is_int(const std::string& number) {
return !is_real(number);
}
long long str2int(const std::string& val) {
//char *err = NULL;
//long long retval = std::strtoll(val.c_str(), &err, 10);
//if (*err == '\0')
//return retval;
//忽略错误
return std::strtoll(val.c_str(), NULL, 10);
}
long double str2double(const std::string& val) {
//char *err = NULL;
//long double retval = std::strtold(val.c_str(), &err);
//if (*err == '\0')
//return retval;
//else
//
//error!
//return 0.0;
return std::strtold(val.c_str(), NULL);
}
//3.3333
bool is_zero(const std::string& vfloat) {
bool left = true, right = true;
size_t start = 0, pos = vfloat.find('.');
if (pos == std::string::npos)
pos = vfloat.size();
while (start < pos) {
if (vfloat[start++] != '0') {
left = false;
}
}
while (++pos < vfloat.size()) {
if (vfloat[pos] != '0') {
right = false;
}
}
return left && right;
}
std::string eval(const std::string& cmd, const std::string& arg1,
const std::string& arg2) {
#define EVAL(RES, X, Y, OP) \
do { \
if(is_real(X) || is_real(Y)) { \
RES << (str2double(X) OP str2double(Y)); \
} else { \
RES << (str2int(X) OP str2int(Y)); \
} \
}while(0) \
std::stringstream ss;
if (cmd == "add") { // +
EVAL(ss, arg1, arg2, +);
} else if (cmd == "min") { //-
EVAL(ss, arg1, arg2, -);
} else if (cmd == "mul") { // *
EVAL(ss, arg1, arg2, *);
} else if (cmd == "div") { // /
if (is_zero(arg2)) {
error("除数不能为0!");
}
EVAL(ss, arg1, arg2, /);
}
return ss.str();
#undef EVAL
}
/*
*
* 依次处理指令
* exit
* goto
* set
*
*
*
*/
void Actuator::run(Env& env) {
for (size_t idx = 0; idx < insts.size(); /*++idx*/) {
Instruction& pc = insts[idx]; //模拟PC寄存器
Log::info(pc.to_str());
if (pc.name == "exit") {
if (pc.params.empty())
break;
else
error("exit不能有参数", pc.pos);
} else if (pc.name == "goto") {
if (pc.params.size() == 1 && pc.params[0].type == kName) {
//处理指令跳转
std::map<std::string, size_t>::iterator it = labels.find(
pc.params[0].token);
if (it == labels.end()) {
error("找不到带跳转位置", pc.pos);
} else {
idx = it->second; //更新到下一条指令
continue;
}
} else {
error("goto语句后面必须带有一个跳转Label", pc.pos);
}
} else if (pc.name == "mov") {
if (pc.params.size() == 2 && pc.params[0].type == kName) {
std::string val = get_val_or_var(env, pc.params[1]);
env.put(pc.params[0].token, val);
} else {
error("set语句必须是一个变量和一个对象参数", pc.pos);
}
} else if (pc.name == "add" || pc.name == "min" || pc.name == "mul"
|| pc.name == "div") {
//add a b 1 => a = b + 1
if (pc.params.size() == 3 && pc.params[0].type == kName) {
//把param1和param2求值 把结果放入param0为key结果为value的环境map中
std::string arg1 = get_val_or_var(env, pc.params[1]);
std::string arg2 = get_val_or_var(env, pc.params[2]);
env.put(pc.params[0].token, eval(pc.name, arg1, arg2));
} else {
error(pc.name + "命令需要一个变量和两个参数", pc.pos);
}
} else if (pc.name == "if") { //if value1 [opcode value2] goto label
bool jmp = false;
if (pc.params.size() == 5 && pc.params[1].type == KCmp) { //if val goto label
std::string left = get_val_or_var(env, pc.params[0]);
std::string right = get_val_or_var(env, pc.params[2]);
if (pc.params[1].token == "==") {
jmp = left == right;
} else if (pc.params[1].token == "!=") {
jmp = left != right;
} else if (pc.params[1].token == "<") {
jmp = str2double(left) < str2double(right);
} else if (pc.params[1].token == ">") {
jmp = str2double(left) > str2double(right);
} else if (pc.params[1].token == "<=") {
jmp = str2double(left) <= str2double(right);
} else if (pc.params[1].token == ">=") {
jmp = str2double(left) < str2double(right);
}
if (jmp && pc.params[3].type == kName
&& pc.params[3].token == "goto"
&& pc.params[4].type == kName) {
//处理指令跳转
std::map<std::string, size_t>::iterator it = labels.find(
pc.params[4].token);
if (it == labels.end()) {
error("找不到带跳转位置", pc.params[4].pos);
} else {
idx = it->second; //更新到下一条指令
continue;
}
} else if (jmp) {
error("goto语句后面必须带有一个跳转Label", pc.params[4].pos);
}
}
} else if (pc.name == "print") {
for (std::vector<Token>::iterator it = pc.params.begin();
it != pc.params.end(); ++it) {
if (it->type == kName) {
if (env.contains(it->token)) {
std::cout << env.get(it->token);
} else
error("变量未定义!", it->pos);
} else
std::cout << it->token;
std::cout << std::endl;
}
} else if (pc.name == "read") {
for (std::vector<Token>::iterator it = pc.params.begin();
it != pc.params.end(); ++it) {
if (it->type != kName) {
error("必须是变量!", it->pos);
}
std::string temp;
std::cin >> temp;
env.put(it->token, temp);
}
}
idx++;
}
}
} /* namespace Script */
<commit_msg>精确除0报错行列<commit_after>/*
* Actuator.cc
*
* Author: Lunatic
*/
#include <cstring>
#include <cstdlib>
#include "actuator.h"
#include "lexer.h"
#include "alarm.h"
namespace Script {
bool Env::contains(const std::string& name) {
return vars.find(name) != vars.end();
}
std::string Env::get(const std::string& name) {
return vars.find(name)->second;
}
void Env::put(const std::string& name, const std::string& value) {
vars[name] = value;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
Actuator::Actuator(Parser& _parser) :
parser(_parser) {
}
Actuator::~Actuator() {
}
void Actuator::load() {
Instruction inst;
while (parser.has_next()) {
parser.next(inst);
if (inst.type == kLabel) {
std::map<std::string, size_t>::iterator it = labels.find(inst.name);
if (it == labels.end())
labels[inst.name] = insts.size();
} else
insts.push_back(inst);
}
}
/*
* 将Token转换为Instruction{type, name, params}
*
void Actuator::load(const std::string& script_code) {
Lexer lexer(script_code);
std::vector<Token> tokens;
while (!lexer.finish()) {
Log::info("新的一行");
Instruction inst;
tokens.clear();
for (;;) {
Token token;
int stat = lexer.next_token(token);
if (stat >= 0)
break;
Log::info(token.to_str());
tokens.push_back(token);
}
if (tokens.empty())
continue;
if (tokens[0].type != kName) {
error("语法错误load", tokens[0].pos);
}
inst.name = tokens[0].token;
inst.pos = tokens[0].pos;
if (tokens.size() == 1) {
inst.type = kInstruction;
} else if (tokens[1].type == kColon) {
inst.type = kLabel;
} else { //处理指令参数
inst.type = kInstruction;
for (size_t i = 1; i < tokens.size(); ++i) {
switch (tokens[i].type) {
case kInt:
case kReal:
case kString:
case kName:
case KCmp:
inst.params.push_back(tokens[i]);
break;
default:
Log::error("%zu", i);
Log::error(tokens[i].to_str());
error("参数不符合要求!", tokens[i].pos);
}
}
}
if (inst.type == kLabel) {
std::map<std::string, size_t>::iterator it = labels.find(inst.name);
if (it == labels.end())
labels[inst.name] = insts.size();
} else
insts.push_back(inst);
}
Log::info("加载完毕!");
}
*/
/*
* 如果是变量 存在则直接取出 否则报错 ?不太妥当
* 其他直接返回
*
*/
std::string get_val_or_var(Env& env, Token& token) {
if (token.type == kName) { //处理变量
if (env.contains(token.token)) {
return env.get(token.token);
} else
error("变量未定义" + token.token, token.pos); //?不太妥当
}
return token.token;
}
bool is_real(const std::string& number) {
return std::string::npos != number.find('.');
}
bool is_int(const std::string& number) {
return !is_real(number);
}
long long str2int(const std::string& val) {
//char *err = NULL;
//long long retval = std::strtoll(val.c_str(), &err, 10);
//if (*err == '\0')
//return retval;
//忽略错误
return std::strtoll(val.c_str(), NULL, 10);
}
long double str2double(const std::string& val) {
//char *err = NULL;
//long double retval = std::strtold(val.c_str(), &err);
//if (*err == '\0')
//return retval;
//else
//
//error!
//return 0.0;
return std::strtold(val.c_str(), NULL);
}
//3.3333
bool is_zero(const std::string& vfloat) {
bool left = true, right = true;
size_t start = 0, pos = vfloat.find('.');
if (pos == std::string::npos)
pos = vfloat.size();
while (start < pos) {
if (vfloat[start++] != '0') {
left = false;
}
}
while (++pos < vfloat.size()) {
if (vfloat[pos] != '0') {
right = false;
}
}
return left && right;
}
std::string eval(const std::string& cmd, const std::string& arg1,
const std::string& arg2, const Position& pos) {
#define EVAL(RES, X, Y, OP) \
do { \
if(is_real(X) || is_real(Y)) { \
RES << (str2double(X) OP str2double(Y)); \
} else { \
RES << (str2int(X) OP str2int(Y)); \
} \
}while(0) \
std::stringstream ss;
if (cmd == "add") { // +
EVAL(ss, arg1, arg2, +);
} else if (cmd == "min") { //-
EVAL(ss, arg1, arg2, -);
} else if (cmd == "mul") { // *
EVAL(ss, arg1, arg2, *);
} else if (cmd == "div") { // /
if (is_zero(arg2)) {
error("除数不能为0!", pos);
}
EVAL(ss, arg1, arg2, /);
}
return ss.str();
#undef EVAL
}
/*
*
* 依次处理指令
* exit
* goto
* set
*
*
*
*/
void Actuator::run(Env& env) {
for (size_t idx = 0; idx < insts.size(); /*++idx*/) {
Instruction& pc = insts[idx]; //模拟PC寄存器
Log::info(pc.to_str());
if (pc.name == "exit") {
if (pc.params.empty())
break;
else
error("exit不能有参数", pc.pos);
} else if (pc.name == "goto") {
if (pc.params.size() == 1 && pc.params[0].type == kName) {
//处理指令跳转
std::map<std::string, size_t>::iterator it = labels.find(
pc.params[0].token);
if (it == labels.end()) {
error("找不到带跳转位置", pc.pos);
} else {
idx = it->second; //更新到下一条指令
continue;
}
} else {
error("goto语句后面必须带有一个跳转Label", pc.pos);
}
} else if (pc.name == "mov") {
if (pc.params.size() == 2 && pc.params[0].type == kName) {
std::string val = get_val_or_var(env, pc.params[1]);
env.put(pc.params[0].token, val);
} else {
error("set语句必须是一个变量和一个对象参数", pc.pos);
}
} else if (pc.name == "add" || pc.name == "min" || pc.name == "mul"
|| pc.name == "div") {
//add a b 1 => a = b + 1
if (pc.params.size() == 3 && pc.params[0].type == kName) {
//把param1和param2求值 把结果放入param0为key结果为value的环境map中
std::string arg1 = get_val_or_var(env, pc.params[1]);
std::string arg2 = get_val_or_var(env, pc.params[2]);
env.put(pc.params[0].token, eval(pc.name, arg1, arg2, pc.params[2].pos));
} else {
error(pc.name + "命令需要一个变量和两个参数", pc.pos);
}
} else if (pc.name == "if") { //if value1 [opcode value2] goto label
bool jmp = false;
if (pc.params.size() == 5 && pc.params[1].type == KCmp) { //if val goto label
std::string left = get_val_or_var(env, pc.params[0]);
std::string right = get_val_or_var(env, pc.params[2]);
if (pc.params[1].token == "==") {
jmp = left == right;
} else if (pc.params[1].token == "!=") {
jmp = left != right;
} else if (pc.params[1].token == "<") {
jmp = str2double(left) < str2double(right);
} else if (pc.params[1].token == ">") {
jmp = str2double(left) > str2double(right);
} else if (pc.params[1].token == "<=") {
jmp = str2double(left) <= str2double(right);
} else if (pc.params[1].token == ">=") {
jmp = str2double(left) < str2double(right);
}
if (jmp && pc.params[3].type == kName
&& pc.params[3].token == "goto"
&& pc.params[4].type == kName) {
//处理指令跳转
std::map<std::string, size_t>::iterator it = labels.find(
pc.params[4].token);
if (it == labels.end()) {
error("找不到带跳转位置", pc.params[4].pos);
} else {
idx = it->second; //更新到下一条指令
continue;
}
} else if (jmp) {
error("goto语句后面必须带有一个跳转Label", pc.params[4].pos);
}
}
} else if (pc.name == "print") {
for (std::vector<Token>::iterator it = pc.params.begin();
it != pc.params.end(); ++it) {
if (it->type == kName) {
if (env.contains(it->token)) {
std::cout << env.get(it->token);
} else
error("变量未定义!", it->pos);
} else
std::cout << it->token;
std::cout << std::endl;
}
} else if (pc.name == "read") {
for (std::vector<Token>::iterator it = pc.params.begin();
it != pc.params.end(); ++it) {
if (it->type != kName) {
error("必须是变量!", it->pos);
}
std::string temp;
std::cin >> temp;
env.put(it->token, temp);
}
}
idx++;
}
}
} /* namespace Script */
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <functional>
// template<CopyConstructible Fn, CopyConstructible... Types>
// unspecified bind(Fn, Types...);
// template<Returnable R, CopyConstructible Fn, CopyConstructible... Types>
// unspecified bind(Fn, Types...);
#include <stdio.h>
#include <functional>
#include <cassert>
int count = 0;
// 1 arg, return void
void f_void_1(int i)
{
count += i;
}
struct A_void_1
{
void operator()(int i)
{
count += i;
}
void mem1() {++count;}
void mem2() const {count += 2;}
};
void
test_void_1()
{
using namespace std::placeholders;
int save_count = count;
// function
{
int i = 2;
std::bind(f_void_1, _1)(i);
assert(count == save_count + 2);
save_count = count;
}
{
int i = 2;
std::bind(f_void_1, i)();
assert(count == save_count + 2);
save_count = count;
}
// function pointer
{
void (*fp)(int) = f_void_1;
int i = 3;
std::bind(fp, _1)(i);
assert(count == save_count+3);
save_count = count;
}
{
void (*fp)(int) = f_void_1;
int i = 3;
std::bind(fp, i)();
assert(count == save_count+3);
save_count = count;
}
// functor
{
A_void_1 a0;
int i = 4;
std::bind(a0, _1)(i);
assert(count == save_count+4);
save_count = count;
}
{
A_void_1 a0;
int i = 4;
std::bind(a0, i)();
assert(count == save_count+4);
save_count = count;
}
// member function pointer
{
void (A_void_1::*fp)() = &A_void_1::mem1;
A_void_1 a;
std::bind(fp, _1)(a);
assert(count == save_count+1);
save_count = count;
A_void_1* ap = &a;
std::bind(fp, _1)(ap);
assert(count == save_count+1);
save_count = count;
}
{
void (A_void_1::*fp)() = &A_void_1::mem1;
A_void_1 a;
std::bind(fp, a)();
assert(count == save_count+1);
save_count = count;
A_void_1* ap = &a;
std::bind(fp, ap)();
assert(count == save_count+1);
save_count = count;
}
// const member function pointer
{
void (A_void_1::*fp)() const = &A_void_1::mem2;
A_void_1 a;
std::bind(fp, _1)(a);
assert(count == save_count+2);
save_count = count;
A_void_1* ap = &a;
std::bind(fp, _1)(ap);
assert(count == save_count+2);
save_count = count;
}
{
void (A_void_1::*fp)() const = &A_void_1::mem2;
A_void_1 a;
std::bind(fp, a)();
assert(count == save_count+2);
save_count = count;
A_void_1* ap = &a;
std::bind(fp, ap)();
assert(count == save_count+2);
save_count = count;
}
}
// 1 arg, return int
int f_int_1(int i)
{
return i + 1;
}
struct A_int_1
{
A_int_1() : data_(5) {}
int operator()(int i)
{
return i - 1;
}
int mem1() {return 3;}
int mem2() const {return 4;}
int data_;
};
void
test_int_1()
{
using namespace std::placeholders;
// function
{
int i = 2;
assert(std::bind(f_int_1, _1)(i) == 3);
assert(std::bind(f_int_1, i)() == 3);
}
// function pointer
{
int (*fp)(int) = f_int_1;
int i = 3;
assert(std::bind(fp, _1)(i) == 4);
assert(std::bind(fp, i)() == 4);
}
// functor
{
int i = 4;
assert(std::bind(A_int_1(), _1)(i) == 3);
assert(std::bind(A_int_1(), i)() == 3);
}
// member function pointer
{
A_int_1 a;
assert(std::bind(&A_int_1::mem1, _1)(a) == 3);
assert(std::bind(&A_int_1::mem1, a)() == 3);
A_int_1* ap = &a;
assert(std::bind(&A_int_1::mem1, _1)(ap) == 3);
assert(std::bind(&A_int_1::mem1, ap)() == 3);
}
// const member function pointer
{
A_int_1 a;
assert(std::bind(&A_int_1::mem2, _1)(A_int_1()) == 4);
assert(std::bind(&A_int_1::mem2, A_int_1())() == 4);
A_int_1* ap = &a;
assert(std::bind(&A_int_1::mem2, _1)(ap) == 4);
assert(std::bind(&A_int_1::mem2, ap)() == 4);
}
// member data pointer
{
A_int_1 a;
assert(std::bind(&A_int_1::data_, _1)(a) == 5);
assert(std::bind(&A_int_1::data_, a)() == 5);
A_int_1* ap = &a;
assert(std::bind(&A_int_1::data_, _1)(a) == 5);
std::bind(&A_int_1::data_, _1)(a) = 6;
assert(std::bind(&A_int_1::data_, _1)(a) == 6);
assert(std::bind(&A_int_1::data_, _1)(ap) == 6);
std::bind(&A_int_1::data_, _1)(ap) = 7;
assert(std::bind(&A_int_1::data_, _1)(ap) == 7);
}
}
// 2 arg, return void
void f_void_2(int i, int j)
{
count += i+j;
}
struct A_void_2
{
void operator()(int i, int j)
{
count += i+j;
}
void mem1(int i) {count += i;}
void mem2(int i) const {count += i;}
};
void
test_void_2()
{
using namespace std::placeholders;
int save_count = count;
// function
{
int i = 2;
int j = 3;
std::bind(f_void_2, _1, _2)(i, j);
assert(count == save_count+5);
save_count = count;
std::bind(f_void_2, i, _1)(j);
assert(count == save_count+5);
save_count = count;
std::bind(f_void_2, i, j)();
assert(count == save_count+5);
save_count = count;
}
// member function pointer
{
int j = 3;
std::bind(&A_void_2::mem1, _1, _2)(A_void_2(), j);
assert(count == save_count+3);
save_count = count;
std::bind(&A_void_2::mem1, _2, _1)(j, A_void_2());
assert(count == save_count+3);
save_count = count;
}
}
int main()
{
test_void_1();
test_int_1();
test_void_2();
}
<commit_msg>Remove cv qualifiers from member pointers in the __member_pointer_traits test. This was causing a const-qualified bind result to malfunction. This was a recent regression due to the new use of __member_pointer_traits in restricting the __invokable and __invoke_of tests.<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <functional>
// template<CopyConstructible Fn, CopyConstructible... Types>
// unspecified bind(Fn, Types...);
// template<Returnable R, CopyConstructible Fn, CopyConstructible... Types>
// unspecified bind(Fn, Types...);
#include <stdio.h>
#include <functional>
#include <cassert>
int count = 0;
// 1 arg, return void
void f_void_1(int i)
{
count += i;
}
struct A_void_1
{
void operator()(int i)
{
count += i;
}
void mem1() {++count;}
void mem2() const {count += 2;}
};
void
test_void_1()
{
using namespace std::placeholders;
int save_count = count;
// function
{
int i = 2;
std::bind(f_void_1, _1)(i);
assert(count == save_count + 2);
save_count = count;
}
{
int i = 2;
std::bind(f_void_1, i)();
assert(count == save_count + 2);
save_count = count;
}
// function pointer
{
void (*fp)(int) = f_void_1;
int i = 3;
std::bind(fp, _1)(i);
assert(count == save_count+3);
save_count = count;
}
{
void (*fp)(int) = f_void_1;
int i = 3;
std::bind(fp, i)();
assert(count == save_count+3);
save_count = count;
}
// functor
{
A_void_1 a0;
int i = 4;
std::bind(a0, _1)(i);
assert(count == save_count+4);
save_count = count;
}
{
A_void_1 a0;
int i = 4;
std::bind(a0, i)();
assert(count == save_count+4);
save_count = count;
}
// member function pointer
{
void (A_void_1::*fp)() = &A_void_1::mem1;
A_void_1 a;
std::bind(fp, _1)(a);
assert(count == save_count+1);
save_count = count;
A_void_1* ap = &a;
std::bind(fp, _1)(ap);
assert(count == save_count+1);
save_count = count;
}
{
void (A_void_1::*fp)() = &A_void_1::mem1;
A_void_1 a;
std::bind(fp, a)();
assert(count == save_count+1);
save_count = count;
A_void_1* ap = &a;
std::bind(fp, ap)();
assert(count == save_count+1);
save_count = count;
}
// const member function pointer
{
void (A_void_1::*fp)() const = &A_void_1::mem2;
A_void_1 a;
std::bind(fp, _1)(a);
assert(count == save_count+2);
save_count = count;
A_void_1* ap = &a;
std::bind(fp, _1)(ap);
assert(count == save_count+2);
save_count = count;
}
{
void (A_void_1::*fp)() const = &A_void_1::mem2;
A_void_1 a;
std::bind(fp, a)();
assert(count == save_count+2);
save_count = count;
A_void_1* ap = &a;
std::bind(fp, ap)();
assert(count == save_count+2);
save_count = count;
}
}
// 1 arg, return int
int f_int_1(int i)
{
return i + 1;
}
struct A_int_1
{
A_int_1() : data_(5) {}
int operator()(int i)
{
return i - 1;
}
int mem1() {return 3;}
int mem2() const {return 4;}
int data_;
};
void
test_int_1()
{
using namespace std::placeholders;
// function
{
int i = 2;
assert(std::bind(f_int_1, _1)(i) == 3);
assert(std::bind(f_int_1, i)() == 3);
}
// function pointer
{
int (*fp)(int) = f_int_1;
int i = 3;
assert(std::bind(fp, _1)(i) == 4);
assert(std::bind(fp, i)() == 4);
}
// functor
{
int i = 4;
assert(std::bind(A_int_1(), _1)(i) == 3);
assert(std::bind(A_int_1(), i)() == 3);
}
// member function pointer
{
A_int_1 a;
assert(std::bind(&A_int_1::mem1, _1)(a) == 3);
assert(std::bind(&A_int_1::mem1, a)() == 3);
A_int_1* ap = &a;
assert(std::bind(&A_int_1::mem1, _1)(ap) == 3);
assert(std::bind(&A_int_1::mem1, ap)() == 3);
}
// const member function pointer
{
A_int_1 a;
assert(std::bind(&A_int_1::mem2, _1)(A_int_1()) == 4);
assert(std::bind(&A_int_1::mem2, A_int_1())() == 4);
A_int_1* ap = &a;
assert(std::bind(&A_int_1::mem2, _1)(ap) == 4);
assert(std::bind(&A_int_1::mem2, ap)() == 4);
}
// member data pointer
{
A_int_1 a;
assert(std::bind(&A_int_1::data_, _1)(a) == 5);
assert(std::bind(&A_int_1::data_, a)() == 5);
A_int_1* ap = &a;
assert(std::bind(&A_int_1::data_, _1)(a) == 5);
std::bind(&A_int_1::data_, _1)(a) = 6;
assert(std::bind(&A_int_1::data_, _1)(a) == 6);
assert(std::bind(&A_int_1::data_, _1)(ap) == 6);
std::bind(&A_int_1::data_, _1)(ap) = 7;
assert(std::bind(&A_int_1::data_, _1)(ap) == 7);
}
}
// 2 arg, return void
void f_void_2(int i, int j)
{
count += i+j;
}
struct A_void_2
{
void operator()(int i, int j)
{
count += i+j;
}
void mem1(int i) {count += i;}
void mem2(int i) const {count += i;}
};
void
test_void_2()
{
using namespace std::placeholders;
int save_count = count;
// function
{
int i = 2;
int j = 3;
std::bind(f_void_2, _1, _2)(i, j);
assert(count == save_count+5);
save_count = count;
std::bind(f_void_2, i, _1)(j);
assert(count == save_count+5);
save_count = count;
std::bind(f_void_2, i, j)();
assert(count == save_count+5);
save_count = count;
}
// member function pointer
{
int j = 3;
std::bind(&A_void_2::mem1, _1, _2)(A_void_2(), j);
assert(count == save_count+3);
save_count = count;
std::bind(&A_void_2::mem1, _2, _1)(j, A_void_2());
assert(count == save_count+3);
save_count = count;
}
}
struct TFENode
{
bool foo(unsigned long long) const
{
return true;
}
};
void
test3()
{
using namespace std;
using namespace std::placeholders;
const auto f = bind(&TFENode::foo, _1, 0UL);
const TFENode n = TFENode{};
bool b = f(n);
}
int main()
{
test_void_1();
test_int_1();
test_void_2();
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/wr_vref_workarounds.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file wr_vref_workarounds.C
/// @brief Workarounds for the WR VREF calibration logic
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Stephen Glancy <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/workarounds/wr_vref_workarounds.H>
namespace mss
{
namespace workarounds
{
namespace wr_vref
{
///
/// @brief Executes WR VREF workarounds
/// @param[in] i_target the fapi2 target of the port
/// @param[in] i_rp - the rank pair to execute the override on
/// @param[in] i_cal_steps_enabled - cal steps to exectue, used to see if WR VREF needs to be exectued
/// @param[out] o_vrefdq_train_range - training range value
/// @param[out] o_vrefdq_train_value - training value value
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode execute( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const uint64_t i_rp,
const fapi2::buffer<uint32_t>& i_cal_steps_enabled,
uint8_t& o_vrefdq_train_range,
uint8_t& o_vrefdq_train_value )
{
// Skip running WR VREF workarounds if:
// 1) the chip does not need to have the workaround run
// 2) WR VREF has not been requested in the calibration steps
if ((! mss::chip_ec_feature_mss_wr_vref(i_target)) || (!i_cal_steps_enabled.getBit<WRITE_CTR_2D_VREF>()))
{
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_TRY(mss::workarounds::dp16::wr_vref::error_dram23(i_target));
FAPI_TRY(mss::workarounds::dp16::wr_vref::setup_values(i_target, i_rp, o_vrefdq_train_range, o_vrefdq_train_value));
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace wr_vref
} // close namespace workarounds
} // close namespace mss
<commit_msg>Update HPW Level for MSS API library<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/wr_vref_workarounds.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file wr_vref_workarounds.C
/// @brief Workarounds for the WR VREF calibration logic
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Stephen Glancy <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/workarounds/wr_vref_workarounds.H>
namespace mss
{
namespace workarounds
{
namespace wr_vref
{
///
/// @brief Executes WR VREF workarounds
/// @param[in] i_target the fapi2 target of the port
/// @param[in] i_rp - the rank pair to execute the override on
/// @param[in] i_cal_steps_enabled - cal steps to exectue, used to see if WR VREF needs to be exectued
/// @param[out] o_vrefdq_train_range - training range value
/// @param[out] o_vrefdq_train_value - training value value
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode execute( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const uint64_t i_rp,
const fapi2::buffer<uint32_t>& i_cal_steps_enabled,
uint8_t& o_vrefdq_train_range,
uint8_t& o_vrefdq_train_value )
{
// Skip running WR VREF workarounds if:
// 1) the chip does not need to have the workaround run
// 2) WR VREF has not been requested in the calibration steps
if ((! mss::chip_ec_feature_mss_wr_vref(i_target)) || (!i_cal_steps_enabled.getBit<WRITE_CTR_2D_VREF>()))
{
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_TRY(mss::workarounds::dp16::wr_vref::error_dram23(i_target));
FAPI_TRY(mss::workarounds::dp16::wr_vref::setup_values(i_target, i_rp, o_vrefdq_train_range, o_vrefdq_train_value));
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace wr_vref
} // close namespace workarounds
} // close namespace mss
<|endoftext|> |
<commit_before>/**
* machina
*
* Copyright (c) 2014, drmats
* All rights reserved.
*
* https://github.com/drmats/machina
*/
#ifndef __SHADER_CPP_
#define __SHADER_CPP_ 1
#include "shader.hpp"
namespace machina {
/**
* Shader source helper macro.
*/
#define GLSL(version, src) "#version " #version "\n" #src
/**
* OpenGL messages buffer.
*/
GLchar Shader::message_buffer[GL_INFO_LOG_LENGTH] = { 0 };
/**
* Some shader sources.
*/
// basic vertex shader -- care about vertex position
const std::string Shader::vs_basic = GLSL(130,
uniform mat4 mvp_matrix;
in vec4 vertex_position;
void main (void) {
gl_Position = mvp_matrix * vertex_position;
}
);
// basic fragment shader -- care about fragment color (from uniform)
const std::string Shader::fs_basic_color_uniform = GLSL(130,
uniform vec4 uniform_color;
out vec4 fragment_color;
void main (void) {
fragment_color = uniform_color;
}
);
// basic vertex shader -- care about vertex position and color
const std::string Shader::vs_basic_attribute_color = GLSL(130,
uniform mat4 mvp_matrix;
in vec4 vertex_position;
in vec4 vertex_color;
smooth out vec4 vertex_fragment_color;
void main (void) {
vertex_fragment_color = vertex_color;
gl_Position = mvp_matrix * vertex_position;
}
);
// basic fragment shader -- care about fragment color (from vs)
const std::string Shader::fs_basic_color_in = GLSL(130,
smooth in vec4 vertex_fragment_color;
out vec4 fragment_color;
void main (void) {
fragment_color = vertex_fragment_color;
}
);
/**
* Initialization with attribute binding.
* Example invocation:
* Shader some_shader(
* shader::vs_basic,
* shader::fs_basic, {
* std::make_tuple(
* "vertex_position", Shader::attrib_index::vertex
* )
* });
*/
Shader::Shader (
const std::string &vs, const std::string &fs,
const std::initializer_list<
std::tuple<std::string, Shader::attrib_index>
> binding
) throw (std::runtime_error) {
// temporary shader objects (load and compile from sources)
GLuint
vertex_shader = this->load_shader(GL_VERTEX_SHADER, vs),
fragment_shader = this->load_shader(GL_FRAGMENT_SHADER, fs);
// status variable (for testing errors)
GLint status;
// binding iterator
std::initializer_list<
std::tuple<std::string, Shader::attrib_index>
>::iterator it;
// attach shaders to gl program
this->program = glCreateProgram();
glAttachShader(this->program, vertex_shader);
glAttachShader(this->program, fragment_shader);
// bind attributes to the gl program
for (it = binding.begin(); it != binding.end(); it++) {
glBindAttribLocation(
this->program,
std::get<1>(*it),
std::get<0>(*it).data()
);
}
// link gl program
glLinkProgram(this->program);
// temporary shaders are no longer needed
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
// check for link errors
glGetProgramiv(this->program, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
std::string error_message(this->get_program_info_log(this->program));
glDeleteProgram(this->program);
throw std::runtime_error(error_message);
}
}
/**
* Clean-up.
*/
Shader::~Shader () {
if (this->program != 0) {
glDeleteProgram(this->program);
this->program = 0;
}
}
/**
* Assign uniforms and use shader.
* Example invocation:
* some_shader.use({
* std::make_tuple("mvp_matrix", [&] (GLuint location) {
* glUniformMatrix4fv(location, 1, GL_FALSE, *mvp_matrix);
* })
* });
*/
const Shader& Shader::use (
std::initializer_list<
std::tuple<std::string, std::function<void (GLint)>>
> uniforms
) const {
std::initializer_list<
std::tuple<std::string, std::function<void (GLint)>>
>::iterator it;
glUseProgram(this->program);
for (it = uniforms.begin(); it != uniforms.end(); it++) {
std::get<1>(*it)(
glGetUniformLocation(this->program, std::get<0>(*it).data())
);
}
return *this;
}
/**
* Compile shader from a given source.
*/
GLuint Shader::load_shader (
GLenum shader_type,
const std::string &shader_src
) throw (std::runtime_error) {
GLuint shader = glCreateShader(shader_type);
const GLchar *src = (GLchar*)shader_src.data();
GLint status;
glShaderSource(shader, 1, &src, NULL);
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
std::string error_message(this->get_shader_info_log(shader));
glDeleteShader(shader);
throw std::runtime_error(error_message);
}
return shader;
}
/**
* Get shader compilation log message.
*/
std::string Shader::get_shader_info_log (GLuint shader) {
glGetShaderInfoLog(
shader, GL_INFO_LOG_LENGTH, NULL, Shader::message_buffer
);
return "GLSL shader: " + std::string(Shader::message_buffer);
}
/**
* Get program linking log.
*/
std::string Shader::get_program_info_log (GLuint program) {
glGetProgramInfoLog(
program, GL_INFO_LOG_LENGTH, NULL, Shader::message_buffer
);
return "GLSL program: " + std::string(Shader::message_buffer);
}
} // namespace machina
#endif
<commit_msg>Shader::use -- missing cast added.<commit_after>/**
* machina
*
* Copyright (c) 2014, drmats
* All rights reserved.
*
* https://github.com/drmats/machina
*/
#ifndef __SHADER_CPP_
#define __SHADER_CPP_ 1
#include "shader.hpp"
namespace machina {
/**
* Shader source helper macro.
*/
#define GLSL(version, src) "#version " #version "\n" #src
/**
* OpenGL messages buffer.
*/
GLchar Shader::message_buffer[GL_INFO_LOG_LENGTH] = { 0 };
/**
* Some shader sources.
*/
// basic vertex shader -- care about vertex position
const std::string Shader::vs_basic = GLSL(130,
uniform mat4 mvp_matrix;
in vec4 vertex_position;
void main (void) {
gl_Position = mvp_matrix * vertex_position;
}
);
// basic fragment shader -- care about fragment color (from uniform)
const std::string Shader::fs_basic_color_uniform = GLSL(130,
uniform vec4 uniform_color;
out vec4 fragment_color;
void main (void) {
fragment_color = uniform_color;
}
);
// basic vertex shader -- care about vertex position and color
const std::string Shader::vs_basic_attribute_color = GLSL(130,
uniform mat4 mvp_matrix;
in vec4 vertex_position;
in vec4 vertex_color;
smooth out vec4 vertex_fragment_color;
void main (void) {
vertex_fragment_color = vertex_color;
gl_Position = mvp_matrix * vertex_position;
}
);
// basic fragment shader -- care about fragment color (from vs)
const std::string Shader::fs_basic_color_in = GLSL(130,
smooth in vec4 vertex_fragment_color;
out vec4 fragment_color;
void main (void) {
fragment_color = vertex_fragment_color;
}
);
/**
* Initialization with attribute binding.
* Example invocation:
* Shader some_shader(
* shader::vs_basic,
* shader::fs_basic, {
* std::make_tuple(
* "vertex_position", Shader::attrib_index::vertex
* )
* });
*/
Shader::Shader (
const std::string &vs, const std::string &fs,
const std::initializer_list<
std::tuple<std::string, Shader::attrib_index>
> binding
) throw (std::runtime_error) {
// temporary shader objects (load and compile from sources)
GLuint
vertex_shader = this->load_shader(GL_VERTEX_SHADER, vs),
fragment_shader = this->load_shader(GL_FRAGMENT_SHADER, fs);
// status variable (for testing errors)
GLint status;
// binding iterator
std::initializer_list<
std::tuple<std::string, Shader::attrib_index>
>::iterator it;
// attach shaders to gl program
this->program = glCreateProgram();
glAttachShader(this->program, vertex_shader);
glAttachShader(this->program, fragment_shader);
// bind attributes to the gl program
for (it = binding.begin(); it != binding.end(); it++) {
glBindAttribLocation(
this->program,
std::get<1>(*it),
std::get<0>(*it).data()
);
}
// link gl program
glLinkProgram(this->program);
// temporary shaders are no longer needed
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
// check for link errors
glGetProgramiv(this->program, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
std::string error_message(this->get_program_info_log(this->program));
glDeleteProgram(this->program);
throw std::runtime_error(error_message);
}
}
/**
* Clean-up.
*/
Shader::~Shader () {
if (this->program != 0) {
glDeleteProgram(this->program);
this->program = 0;
}
}
/**
* Assign uniforms and use shader.
* Example invocation:
* some_shader.use({
* std::make_tuple("mvp_matrix", [&] (GLuint location) {
* glUniformMatrix4fv(location, 1, GL_FALSE, *mvp_matrix);
* })
* });
*/
const Shader& Shader::use (
std::initializer_list<
std::tuple<std::string, std::function<void (GLint)>>
> uniforms
) const {
std::initializer_list<
std::tuple<std::string, std::function<void (GLint)>>
>::iterator it;
glUseProgram(this->program);
for (it = uniforms.begin(); it != uniforms.end(); it++) {
std::get<1>(*it)(
glGetUniformLocation(
this->program, (GLchar*)std::get<0>(*it).data()
)
);
}
return *this;
}
/**
* Compile shader from a given source.
*/
GLuint Shader::load_shader (
GLenum shader_type,
const std::string &shader_src
) throw (std::runtime_error) {
GLuint shader = glCreateShader(shader_type);
const GLchar *src = (GLchar*)shader_src.data();
GLint status;
glShaderSource(shader, 1, &src, NULL);
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
std::string error_message(this->get_shader_info_log(shader));
glDeleteShader(shader);
throw std::runtime_error(error_message);
}
return shader;
}
/**
* Get shader compilation log message.
*/
std::string Shader::get_shader_info_log (GLuint shader) {
glGetShaderInfoLog(
shader, GL_INFO_LOG_LENGTH, NULL, Shader::message_buffer
);
return "GLSL shader: " + std::string(Shader::message_buffer);
}
/**
* Get program linking log.
*/
std::string Shader::get_program_info_log (GLuint program) {
glGetProgramInfoLog(
program, GL_INFO_LOG_LENGTH, NULL, Shader::message_buffer
);
return "GLSL program: " + std::string(Shader::message_buffer);
}
} // namespace machina
#endif
<|endoftext|> |
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2006 Artem Pavlenko
*
* Mapnik 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 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.
*/
//$Id$
// stl
#include <iostream>
// qt
#include <QtGui>
#include <QSplitter>
#include <QTreeView>
#include <QListView>
#include <QTabWidget>
#include <QList>
#include <QItemDelegate>
#include <QSlider>
// mapnik
#include <mapnik/config_error.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/save_map.hpp>
// qt
#include "mainwindow.hpp"
#include "layerlistmodel.hpp"
#include "styles_model.hpp"
#include "layerwidget.hpp"
#include "layerdelegate.hpp"
#include "about_dialog.hpp"
MainWindow::MainWindow()
: filename_(),
default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428)
{
mapWidget_ = new MapWidget(this);
QSplitter *splitter = new QSplitter(this);
QTabWidget *tabWidget=new QTabWidget;
layerTab_ = new LayerTab;
layerTab_->setFocusPolicy(Qt::NoFocus);
layerTab_->setIconSize(QSize(16,16));
//LayerDelegate *delegate = new LayerDelegate(this);
//layerTab_->setItemDelegate(delegate);
//layerTab_->setItemDelegate(new QItemDelegate(this));
//layerTab_->setViewMode(QListView::IconMode);
layerTab_->setFlow(QListView::TopToBottom);
tabWidget->addTab(layerTab_,tr("Layers"));
// Styles tab
styleTab_ = new StyleTab;
tabWidget->addTab(styleTab_,tr("Styles"));
splitter->addWidget(tabWidget);
splitter->addWidget(mapWidget_);
QList<int> list;
list.push_back(200);
list.push_back(600);
splitter->setSizes(list);
mapWidget_->setFocusPolicy(Qt::StrongFocus);
mapWidget_->setFocus();
//setCentralWidget(mapWidget_);
setCentralWidget(splitter);
createActions();
createMenus();
createToolBars();
createContextMenu();
setWindowTitle(tr("Mapnik Viewer"));
status=new QStatusBar(this);
status->showMessage(tr(""));
setStatusBar(status);
resize(800,600);
//connect mapview to layerlist
connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update()));
// slider
connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int)));
//
connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap()));
connect(layerTab_,SIGNAL(layerSelected(int)),
mapWidget_,SLOT(layerSelected(int)));
}
MainWindow::~MainWindow()
{
delete mapWidget_;
}
void MainWindow::closeEvent(QCloseEvent* event)
{
event->accept();
}
void MainWindow::createContextMenu()
{
layerTab_->setContextMenuPolicy(Qt::ActionsContextMenu);
layerTab_->addAction(openAct);
layerTab_->addAction(layerInfo);
}
void MainWindow::open(QString const& path)
{
if (path.isNull())
{
filename_ = QFileDialog::getOpenFileName(this,tr("Open Mapnik file"),
currentPath,"*.xml");
}
else
{
filename_ = path;
}
if (!filename_.isEmpty())
{
load_map_file(filename_);
setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_));
}
}
void MainWindow::reload()
{
if (!filename_.isEmpty())
{
mapnik::box2d<double> bbox = mapWidget_->getMap()->getCurrentExtent();
load_map_file(filename_);
mapWidget_->zoomToBox(bbox);
setWindowTitle(tr("%1 - *Reloaded*").arg(filename_));
}
}
void MainWindow::save()
{
QString initialPath = QDir::currentPath() + "/untitled.xml";
QString filename = QFileDialog::getSaveFileName(this, tr("Save"),
initialPath,
tr("%1 Files (*.xml)")
.arg(QString("Mapnik definition")));
if (!filename.isEmpty())
{
std::cout<<"saving "<< filename.toStdString() << std::endl;
mapnik::save_map(*mapWidget_->getMap(),filename.toStdString());
}
}
void MainWindow::load_map_file(QString const& filename)
{
std::cout<<"loading "<< filename.toStdString() << std::endl;
unsigned width = mapWidget_->width();
unsigned height = mapWidget_->height();
boost::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height));
mapWidget_->setMap(map);
try
{
mapnik::load_map(*map,filename.toStdString());
}
catch (mapnik::config_error & ex)
{
std::cout << ex.what() << "\n";
}
layerTab_->setModel(new LayerListModel(map,this));
styleTab_->setModel(new StyleModel(map,this));
}
void MainWindow::zoom_to_box()
{
mapWidget_->setTool(MapWidget::ZoomToBox);
}
void MainWindow::pan()
{
mapWidget_->setTool(MapWidget::Pan);
}
void MainWindow::info()
{
mapWidget_->setTool(MapWidget::Info);
}
void MainWindow::pan_left()
{
mapWidget_->panLeft();
}
void MainWindow::pan_right()
{
mapWidget_->panRight();
}
void MainWindow::pan_up()
{
mapWidget_->panUp();
}
void MainWindow::pan_down()
{
mapWidget_->panDown();
}
void MainWindow::about()
{
about_dialog dlg;
dlg.exec();
}
void MainWindow::export_as()
{
QAction *action = qobject_cast<QAction *>(sender());
QByteArray fileFormat = action->data().toByteArray();
QString initialPath = QDir::currentPath() + "/map." + fileFormat;
QString fileName = QFileDialog::getSaveFileName(this, tr("Export As"),
initialPath,
tr("%1 Files (*.%2);;All Files (*)")
.arg(QString(fileFormat.toUpper()))
.arg(QString(fileFormat)));
if (!fileName.isEmpty())
{
QPixmap const& pix = mapWidget_->pixmap();
pix.save(fileName);
}
}
void MainWindow::print()
{
//Q_ASSERT(mapWidget_->pixmap());
//QPrintDialog dialog(&printer, this);
//if (dialog.exec()) {
// QPainter painter(&printer);
// QRect rect = painter.viewport();
// QSize size = mapWidget_->pixmap()->size();
// size.scale(rect.size(), Qt::KeepAspectRatio);
// painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
// painter.setWindow(mapWidget_->pixmap()->rect());
// painter.drawPixmap(0, 0, *mapWidget_->pixmap());
//}
}
void MainWindow::createActions()
{
//exportAct = new QAction(tr("&Export as ..."),this);
//exportAct->setShortcut(tr("Ctrl+E"));
//connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as()));
zoomAllAct = new QAction(QIcon(":/images/home.png"),tr("Zoom All"),this);
connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all()));
zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"),tr("Zoom To Box"),this);
zoomBoxAct->setCheckable(true);
connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box()));
panAct = new QAction(QIcon(":/images/pan.png"),tr("Pan"),this);
panAct->setCheckable(true);
connect(panAct, SIGNAL(triggered()), this, SLOT(pan()));
infoAct = new QAction(QIcon(":/images/info.png"),tr("Info"),this);
infoAct->setCheckable(true);
connect(infoAct, SIGNAL(triggered()), this, SLOT(info()));
toolsGroup=new QActionGroup(this);
toolsGroup->addAction(zoomBoxAct);
toolsGroup->addAction(panAct);
toolsGroup->addAction(infoAct);
zoomBoxAct->setChecked(true);
openAct=new QAction(tr("Open Map definition"),this);
connect(openAct,SIGNAL(triggered()),this,SLOT(open()));
saveAct=new QAction(tr("Save Map definition"),this);
connect(saveAct,SIGNAL(triggered()),this,SLOT(save()));
panLeftAct = new QAction(QIcon(":/images/left.png"),tr("&Pan Left"),this);
connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left()));
panRightAct = new QAction(QIcon(":/images/right.png"),tr("&Pan Right"),this);
connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right()));
panUpAct = new QAction(QIcon(":/images/up.png"),tr("&Pan Up"),this);
connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up()));
panDownAct = new QAction(QIcon(":/images/down.png"),tr("&Pan Down"),this);
connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down()));
reloadAct = new QAction(QIcon(":/images/reload.png"),tr("Reload"),this);
connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload()));
layerInfo = new QAction(QIcon(":/images/info.png"),tr("&Layer info"),layerTab_);
connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo()));
connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&)));
foreach (QByteArray format, QImageWriter::supportedImageFormats())
{
QString text = tr("%1...").arg(QString(format).toUpper());
QAction *action = new QAction(text, this);
action->setData(format);
connect(action, SIGNAL(triggered()), this, SLOT(export_as()));
exportAsActs.append(action);
}
printAct = new QAction(QIcon(":/images/print.png"),tr("&Print ..."),this);
printAct->setShortcut(tr("Ctrl+E"));
connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
aboutAct = new QAction(QIcon(":/images/about.png"),tr("&About"), this);
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
}
void MainWindow::createMenus()
{
exportMenu = new QMenu(tr("&Export As"), this);
foreach (QAction *action, exportAsActs)
exportMenu->addAction(action);
fileMenu = new QMenu(tr("&File"),this);
fileMenu->addAction(openAct);
fileMenu->addAction(saveAct);
fileMenu->addMenu(exportMenu);
fileMenu->addAction(printAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
menuBar()->addMenu(fileMenu);
helpMenu = new QMenu(tr("&Help"), this);
helpMenu->addAction(aboutAct);
menuBar()->addMenu(helpMenu);
}
void MainWindow::createToolBars()
{
fileToolBar = addToolBar(tr("Actions"));
fileToolBar->addAction(zoomAllAct);
fileToolBar->addAction(zoomBoxAct);
fileToolBar->addAction(panAct);
fileToolBar->addAction(panLeftAct);
fileToolBar->addAction(panRightAct);
fileToolBar->addAction(panUpAct);
fileToolBar->addAction(panDownAct);
fileToolBar->addAction(infoAct);
fileToolBar->addAction(reloadAct);
fileToolBar->addAction(printAct);
slider_ = new QSlider(Qt::Horizontal,fileToolBar);
slider_->setRange(1,18);
slider_->setTickPosition(QSlider::TicksBelow);
slider_->setTickInterval(1);
slider_->setTracking(false);
fileToolBar->addWidget(slider_);
fileToolBar->addAction(aboutAct);
}
void MainWindow::set_default_extent(double x0,double y0, double x1, double y1)
{
try
{
boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();
if (map_ptr)
{
mapnik::projection prj(map_ptr->srs());
prj.forward(x0,y0);
prj.forward(x1,y1);
default_extent_=mapnik::box2d<double>(x0,y0,x1,y1);
mapWidget_->zoomToBox(default_extent_);
std::cout << "SET DEFAULT EXT\n";
}
}
catch (...) {}
}
void MainWindow::set_scaling_factor(double scaling_factor)
{
mapWidget_->set_scaling_factor(scaling_factor);
}
void MainWindow::zoom_all()
{
boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();
if (map_ptr)
{
map_ptr->zoom_all();
mapnik::box2d<double> const& ext = map_ptr->getCurrentExtent();
mapWidget_->zoomToBox(ext);
}
}
<commit_msg>+ catch all exceptions in load_map_file<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2006 Artem Pavlenko
*
* Mapnik 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 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.
*/
//$Id$
// stl
#include <iostream>
// qt
#include <QtGui>
#include <QSplitter>
#include <QTreeView>
#include <QListView>
#include <QTabWidget>
#include <QList>
#include <QItemDelegate>
#include <QSlider>
// mapnik
#include <mapnik/config_error.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/save_map.hpp>
// qt
#include "mainwindow.hpp"
#include "layerlistmodel.hpp"
#include "styles_model.hpp"
#include "layerwidget.hpp"
#include "layerdelegate.hpp"
#include "about_dialog.hpp"
MainWindow::MainWindow()
: filename_(),
default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428)
{
mapWidget_ = new MapWidget(this);
QSplitter *splitter = new QSplitter(this);
QTabWidget *tabWidget=new QTabWidget;
layerTab_ = new LayerTab;
layerTab_->setFocusPolicy(Qt::NoFocus);
layerTab_->setIconSize(QSize(16,16));
//LayerDelegate *delegate = new LayerDelegate(this);
//layerTab_->setItemDelegate(delegate);
//layerTab_->setItemDelegate(new QItemDelegate(this));
//layerTab_->setViewMode(QListView::IconMode);
layerTab_->setFlow(QListView::TopToBottom);
tabWidget->addTab(layerTab_,tr("Layers"));
// Styles tab
styleTab_ = new StyleTab;
tabWidget->addTab(styleTab_,tr("Styles"));
splitter->addWidget(tabWidget);
splitter->addWidget(mapWidget_);
QList<int> list;
list.push_back(200);
list.push_back(600);
splitter->setSizes(list);
mapWidget_->setFocusPolicy(Qt::StrongFocus);
mapWidget_->setFocus();
//setCentralWidget(mapWidget_);
setCentralWidget(splitter);
createActions();
createMenus();
createToolBars();
createContextMenu();
setWindowTitle(tr("Mapnik Viewer"));
status=new QStatusBar(this);
status->showMessage(tr(""));
setStatusBar(status);
resize(800,600);
//connect mapview to layerlist
connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update()));
// slider
connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int)));
//
connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap()));
connect(layerTab_,SIGNAL(layerSelected(int)),
mapWidget_,SLOT(layerSelected(int)));
}
MainWindow::~MainWindow()
{
delete mapWidget_;
}
void MainWindow::closeEvent(QCloseEvent* event)
{
event->accept();
}
void MainWindow::createContextMenu()
{
layerTab_->setContextMenuPolicy(Qt::ActionsContextMenu);
layerTab_->addAction(openAct);
layerTab_->addAction(layerInfo);
}
void MainWindow::open(QString const& path)
{
if (path.isNull())
{
filename_ = QFileDialog::getOpenFileName(this,tr("Open Mapnik file"),
currentPath,"*.xml");
}
else
{
filename_ = path;
}
if (!filename_.isEmpty())
{
load_map_file(filename_);
setWindowTitle(tr("%1 - Mapnik Viewer").arg(filename_));
}
}
void MainWindow::reload()
{
if (!filename_.isEmpty())
{
mapnik::box2d<double> bbox = mapWidget_->getMap()->getCurrentExtent();
load_map_file(filename_);
mapWidget_->zoomToBox(bbox);
setWindowTitle(tr("%1 - *Reloaded*").arg(filename_));
}
}
void MainWindow::save()
{
QString initialPath = QDir::currentPath() + "/untitled.xml";
QString filename = QFileDialog::getSaveFileName(this, tr("Save"),
initialPath,
tr("%1 Files (*.xml)")
.arg(QString("Mapnik definition")));
if (!filename.isEmpty())
{
std::cout<<"saving "<< filename.toStdString() << std::endl;
mapnik::save_map(*mapWidget_->getMap(),filename.toStdString());
}
}
void MainWindow::load_map_file(QString const& filename)
{
std::cout<<"loading "<< filename.toStdString() << std::endl;
unsigned width = mapWidget_->width();
unsigned height = mapWidget_->height();
boost::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height));
mapWidget_->setMap(map);
try
{
mapnik::load_map(*map,filename.toStdString());
}
catch (mapnik::config_error & ex)
{
std::cout << ex.what() << "\n";
}
catch (...)
{
std::cerr << "Exception caught in load_map\n";
}
layerTab_->setModel(new LayerListModel(map,this));
styleTab_->setModel(new StyleModel(map,this));
}
void MainWindow::zoom_to_box()
{
mapWidget_->setTool(MapWidget::ZoomToBox);
}
void MainWindow::pan()
{
mapWidget_->setTool(MapWidget::Pan);
}
void MainWindow::info()
{
mapWidget_->setTool(MapWidget::Info);
}
void MainWindow::pan_left()
{
mapWidget_->panLeft();
}
void MainWindow::pan_right()
{
mapWidget_->panRight();
}
void MainWindow::pan_up()
{
mapWidget_->panUp();
}
void MainWindow::pan_down()
{
mapWidget_->panDown();
}
void MainWindow::about()
{
about_dialog dlg;
dlg.exec();
}
void MainWindow::export_as()
{
QAction *action = qobject_cast<QAction *>(sender());
QByteArray fileFormat = action->data().toByteArray();
QString initialPath = QDir::currentPath() + "/map." + fileFormat;
QString fileName = QFileDialog::getSaveFileName(this, tr("Export As"),
initialPath,
tr("%1 Files (*.%2);;All Files (*)")
.arg(QString(fileFormat.toUpper()))
.arg(QString(fileFormat)));
if (!fileName.isEmpty())
{
QPixmap const& pix = mapWidget_->pixmap();
pix.save(fileName);
}
}
void MainWindow::print()
{
//Q_ASSERT(mapWidget_->pixmap());
//QPrintDialog dialog(&printer, this);
//if (dialog.exec()) {
// QPainter painter(&printer);
// QRect rect = painter.viewport();
// QSize size = mapWidget_->pixmap()->size();
// size.scale(rect.size(), Qt::KeepAspectRatio);
// painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
// painter.setWindow(mapWidget_->pixmap()->rect());
// painter.drawPixmap(0, 0, *mapWidget_->pixmap());
//}
}
void MainWindow::createActions()
{
//exportAct = new QAction(tr("&Export as ..."),this);
//exportAct->setShortcut(tr("Ctrl+E"));
//connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as()));
zoomAllAct = new QAction(QIcon(":/images/home.png"),tr("Zoom All"),this);
connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all()));
zoomBoxAct = new QAction(QIcon(":/images/zoombox.png"),tr("Zoom To Box"),this);
zoomBoxAct->setCheckable(true);
connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box()));
panAct = new QAction(QIcon(":/images/pan.png"),tr("Pan"),this);
panAct->setCheckable(true);
connect(panAct, SIGNAL(triggered()), this, SLOT(pan()));
infoAct = new QAction(QIcon(":/images/info.png"),tr("Info"),this);
infoAct->setCheckable(true);
connect(infoAct, SIGNAL(triggered()), this, SLOT(info()));
toolsGroup=new QActionGroup(this);
toolsGroup->addAction(zoomBoxAct);
toolsGroup->addAction(panAct);
toolsGroup->addAction(infoAct);
zoomBoxAct->setChecked(true);
openAct=new QAction(tr("Open Map definition"),this);
connect(openAct,SIGNAL(triggered()),this,SLOT(open()));
saveAct=new QAction(tr("Save Map definition"),this);
connect(saveAct,SIGNAL(triggered()),this,SLOT(save()));
panLeftAct = new QAction(QIcon(":/images/left.png"),tr("&Pan Left"),this);
connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left()));
panRightAct = new QAction(QIcon(":/images/right.png"),tr("&Pan Right"),this);
connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right()));
panUpAct = new QAction(QIcon(":/images/up.png"),tr("&Pan Up"),this);
connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up()));
panDownAct = new QAction(QIcon(":/images/down.png"),tr("&Pan Down"),this);
connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down()));
reloadAct = new QAction(QIcon(":/images/reload.png"),tr("Reload"),this);
connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload()));
layerInfo = new QAction(QIcon(":/images/info.png"),tr("&Layer info"),layerTab_);
connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo()));
connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&)));
foreach (QByteArray format, QImageWriter::supportedImageFormats())
{
QString text = tr("%1...").arg(QString(format).toUpper());
QAction *action = new QAction(text, this);
action->setData(format);
connect(action, SIGNAL(triggered()), this, SLOT(export_as()));
exportAsActs.append(action);
}
printAct = new QAction(QIcon(":/images/print.png"),tr("&Print ..."),this);
printAct->setShortcut(tr("Ctrl+E"));
connect(printAct, SIGNAL(triggered()), this, SLOT(print()));
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
aboutAct = new QAction(QIcon(":/images/about.png"),tr("&About"), this);
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
}
void MainWindow::createMenus()
{
exportMenu = new QMenu(tr("&Export As"), this);
foreach (QAction *action, exportAsActs)
exportMenu->addAction(action);
fileMenu = new QMenu(tr("&File"),this);
fileMenu->addAction(openAct);
fileMenu->addAction(saveAct);
fileMenu->addMenu(exportMenu);
fileMenu->addAction(printAct);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
menuBar()->addMenu(fileMenu);
helpMenu = new QMenu(tr("&Help"), this);
helpMenu->addAction(aboutAct);
menuBar()->addMenu(helpMenu);
}
void MainWindow::createToolBars()
{
fileToolBar = addToolBar(tr("Actions"));
fileToolBar->addAction(zoomAllAct);
fileToolBar->addAction(zoomBoxAct);
fileToolBar->addAction(panAct);
fileToolBar->addAction(panLeftAct);
fileToolBar->addAction(panRightAct);
fileToolBar->addAction(panUpAct);
fileToolBar->addAction(panDownAct);
fileToolBar->addAction(infoAct);
fileToolBar->addAction(reloadAct);
fileToolBar->addAction(printAct);
slider_ = new QSlider(Qt::Horizontal,fileToolBar);
slider_->setRange(1,18);
slider_->setTickPosition(QSlider::TicksBelow);
slider_->setTickInterval(1);
slider_->setTracking(false);
fileToolBar->addWidget(slider_);
fileToolBar->addAction(aboutAct);
}
void MainWindow::set_default_extent(double x0,double y0, double x1, double y1)
{
try
{
boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();
if (map_ptr)
{
mapnik::projection prj(map_ptr->srs());
prj.forward(x0,y0);
prj.forward(x1,y1);
default_extent_=mapnik::box2d<double>(x0,y0,x1,y1);
mapWidget_->zoomToBox(default_extent_);
std::cout << "SET DEFAULT EXT\n";
}
}
catch (...) {}
}
void MainWindow::set_scaling_factor(double scaling_factor)
{
mapWidget_->set_scaling_factor(scaling_factor);
}
void MainWindow::zoom_all()
{
boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();
if (map_ptr)
{
map_ptr->zoom_all();
mapnik::box2d<double> const& ext = map_ptr->getCurrentExtent();
mapWidget_->zoomToBox(ext);
}
}
<|endoftext|> |
<commit_before>#include <string>
#include <nds.h>
#include <nds/debug.h>
#include "./math.h"
#include "./sprite.h"
#include "./debug.h"
namespace FMAW {
//------------------------------------------------------------------------------
// Common sprite helpers.
//------------------------------------------------------------------------------
void clearAllSprites() {
for ( sprite_id id = 0; id < TOTAL_SPRITES; id++ ) {
Sprite sprite (id);
sprite.clear();
}
}
//------------------------------------------------------------------------------
// Sprite class.
//------------------------------------------------------------------------------
uint8 Sprite::nextEmptySprite = 0;
//----------//------------------------------------------------------------------
//----------// Position.
//----------//------------------------------------------------------------------
bool Sprite::setXPosition( int x ) {
bool isNegative = x < 0;
if ( isNegative ) x = -x;
uint16 xCapped = x & 0x00FF;
printf("X Original: %d New: %u", x, xCapped);
if ( x != xCapped ) return false;
// If x was negative we have to apply 2's complement.
if ( isNegative ) x = twosComplement9B(x);
// We have to set the upper part of the half-word to 1 so AND doesn't
// break anything.
x |= 0xFE00;
// We have to set position's bits to 1 so we can then make an AND.
sprites[this->id].attr1 |= 0x01FF;
// Now we can set position with a simple AND.
sprites[this->id].attr1 &= x;
return true;
}
bool Sprite::setYPosition( int y ) {
bool isNegative = y < 0;
if ( isNegative ) y = -y;
uint16 yCapped = y & 0x007F;
printf("Y Original: %d New: %u", y, yCapped);
if ( y != yCapped ) return false;
// If x was negative we have to apply 2's complement.
if ( isNegative ) y = twosComplement8B(y);
// We have to set the upper part of the half-word to 1 so AND doesn't
// break anything.
y |= 0xFF00;
// We have to set position's bits to 1 so we can then make an AND.
sprites[this->id].attr0 |= 0x00FF;
// Now we can set position with a simple AND.
sprites[this->id].attr0 &= y;
return true;
}
bool Sprite::setPosition( int x, int y ) {
Point previousPosition = this->getPosition();
if ( this->setXPosition( x ) && this->setYPosition( y ) ) return true;
else {
this->setXPosition( previousPosition.x );
this->setYPosition( previousPosition.y );
return false;
}
return true;
}
bool Sprite::setPosition( Point point ) {
return this->setPosition( point.x, point.y );
}
int Sprite::getXPosition() {
uint8 x = sprites[this->id].attr1 & 0x01FF;
// If x-position was a negative number...
if ( (x & 0x0100) != 0 ) return -twosComplement9B(x);
return x;
}
int Sprite::getYPosition() {
uint8 y = sprites[this->id].attr0 & 0x00FF;
// If y-position was a negative number...
if ( (y & 0x0080) != 0 ) return -twosComplement8B(y);
return y;
}
Point Sprite::getPosition() {
Point p {};
p.x = this->getXPosition();
p.y = this->getYPosition();
return p;
}
//----------//------------------------------------------------------------------
//----------// Tile & palette settings.
//----------//------------------------------------------------------------------
bool Sprite::setTile( uint16 tileIndex ) {
uint16 tileIndexCapped = tileIndex & 0x01FF;
if ( tileIndex != tileIndexCapped ) return false;
// We first set tile bits to 1 so we can apply an AND later.
sprites[this->id].attr2 |= 0x01FF;
// We apply and AND to set the bits properly.
sprites[this->id].attr2 &= tileIndexCapped;
return true;
}
uint16 Sprite::getTile() {
return sprites[this->id].attr2 & 0x01FF;
}
bool Sprite::setPalette( uint8 paletteIndex ) {
uint8 paletteIndexCapped = paletteIndex & 0x000F;
if ( paletteIndex != paletteIndexCapped ) return false;
// We first set tile bits to 1 so we can apply an AND later.
sprites[this->id].attr2 |= 0xF000;
// We apply and AND to set the bits properly.
sprites[this->id].attr2 &= paletteIndexCapped << 12;
return true;
}
uint8 Sprite::getPalette() {
return (sprites[this->id].attr2 & 0xF000) >> 12;
}
//----------//------------------------------------------------------------------
//----------// Rotation & scale settings.
//----------//------------------------------------------------------------------
void Sprite::enableRotationAndScale() {
sprites[this->id].attr0 |= 0x0100;
}
void Sprite::disableRotationAndScale() {
sprites[this->id].attr0 &= 0xFEFF;
}
bool Sprite::rotationAndScaleAreEnabled() {
return (sprites[this->id].attr0 & 0x0100) != 0 ;
}
bool Sprite::rotationAndScaleAreDisabled() {
return !this->rotationAndScaleAreEnabled();
}
void Sprite::enableDoubleSize() {
sprites[this->id].attr0 |= 0x0200;
}
void Sprite::disableDoubleSize() {
sprites[this->id].attr0 &= 0xFDFF;
}
bool Sprite::doubleSizeEnabled() {
return (sprites[this->id].attr0 = 0x0200) != 0;
}
bool Sprite::doubleSizeDisabled() {
return !this->doubleSizeEnabled();
}
//----------//------------------------------------------------------------------
//----------// Object mode settings.
//----------//------------------------------------------------------------------
void Sprite::setObjectMode( SpriteObjectMode newMode ) {
sprites[this->id].attr0 |= 0x0C00;
sprites[this->id].attr0 &= newMode;
}
SpriteObjectMode Sprite::getObjectMode() {
uint16 half_word = sprites[this->id].attr0 | 0xF3FF;
switch (half_word) {
case normal:
return normal;
case alpha_first_target:
return normal;
case add_to_window:
return add_to_window;
case bitmap:
return bitmap;
default:
// This won't happen ever.
return normal;
}
}
//----------//------------------------------------------------------------------
//----------// Mosaic & color settings.
//----------//------------------------------------------------------------------
void Sprite::enableMosaic() {
sprites[this->id].attr0 |= 0x1000;
}
void Sprite::disableMosaic() {
sprites[this->id].attr0 &= 0xEFFF;
}
bool Sprite::mosaicIsEnabled() {
return (sprites[this->id].attr0 & 0x1000) != 0;
}
bool Sprite::mosaicIsDisabled() {
return !this->mosaicIsEnabled();
}
void Sprite::use16BitColors() {
sprites[this->id].attr0 &= 0xDFFF;
}
void Sprite::use256BitColors() {
sprites[this->id].attr0 |= 0x2000;
}
bool Sprite::isUsing16BitColors() {
return (sprites[this->id].attr0 & 0x2000) != 0;
}
bool Sprite::isUsing256BitColors() {
return !this->isUsing16BitColors();
}
//----------//------------------------------------------------------------------
//----------// Shape & size settings.
//----------//------------------------------------------------------------------
bool Sprite::setSizeMode( SpriteSizeMode newMode ) {
uint16 attr0mask;
uint16 attr1mask;
switch ( newMode ) {
case square8x8:
case square16x16:
case square32x32:
case square64x64:
attr0mask = 0x3FFF;
break;
case wide16x8:
case wide32x8:
case wide32x16:
case wide64x32:
attr0mask = 0x7FFF;
break;
case tall8x16:
case tall8x32:
case tall16x32:
case tall32x64:
attr0mask = 0xBFFF;
break;
default:
return false;
}
switch ( newMode ) {
case square8x8:
case wide16x8:
case tall8x16:
attr1mask = 0x3FFF;
break;
case square16x16:
case wide32x8:
case tall8x32:
attr1mask = 0x7FFF;
break;
case square32x32:
case wide32x16:
case tall16x32:
attr1mask = 0xBFFF;
break;
case square64x64:
case wide64x32:
case tall32x64:
attr1mask = 0xFFFF;
break;
default:
return false;
}
// We first set the size bits to 1.
sprites[this->id].attr0 |= 0XC000;
sprites[this->id].attr1 |= 0XC000;
// And then we apply the mask.
sprites[this->id].attr0 &= attr0mask;
sprites[this->id].attr1 &= attr1mask;
return true;
}
SpriteSizeMode Sprite::getSizeMode() {
uint16 shape = sprites[this->id].attr0 & 0xC000;
uint16 size = sprites[this->id].attr1 & 0xC000;
SpriteSizeMode sizeMode;
switch ( shape ) {
// Square.
case 0x0000:
switch (size) {
case 0x0000:
sizeMode = square8x8;
break;
case 0x4000:
sizeMode = square16x16;
break;
case 0x8000:
sizeMode = square32x32;
break;
case 0xC000:
sizeMode = square64x64;
break;
default:
sizeMode = unknown;
break;
}
break;
// Wide.
case 0x4000:
switch (size) {
case 0x0000:
sizeMode = wide16x8;
break;
case 0x4000:
sizeMode = wide32x8;
break;
case 0x8000:
sizeMode = wide32x16;
break;
case 0xC000:
sizeMode = wide64x32;
break;
default:
sizeMode = unknown;
break;
}
break;
// Tall.
case 0x8000:
switch (size) {
case 0x0000:
sizeMode = tall8x16;
break;
case 0x4000:
sizeMode = tall8x32;
break;
case 0x8000:
sizeMode = tall16x32;
break;
case 0xC000:
sizeMode = tall32x64;
break;
default:
sizeMode = unknown;
break;
}
break;
// Not used.
case 0xC000:
default:
sizeMode = unknown;
break;
}
return sizeMode;
}
//----------//------------------------------------------------------------------
//----------// Flip settings.
//----------//------------------------------------------------------------------
void Sprite::enableHorizontalFlip() {
this->disableRotationAndScale();
sprites[this->id].attr1 |= 0x1000;
}
void Sprite::disableHorizontalFlip() {
this->disableRotationAndScale();
sprites[this->id].attr1 &= 0xEFFF;
}
// If rotation/scaling is disabled it'll return false.
bool Sprite::horizontalFlipIsEnabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x1000) != 0;
}
// If rotation/scaling is disabled it'll return false.
// THIS IS NOT EQUIVALENT TO !horizontalFlipIsEnabled() !!
bool Sprite::horizontalFlipIsDisabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x1000) == 0;
}
void Sprite::enableVerticalFlip() {
sprites[this->id].attr1 |= 0x2000;
}
void Sprite::disableVerticalFlip() {
sprites[this->id].attr1 &= 0xDFFF;
}
// If rotation/scaling is disabled it'll return false.
bool Sprite::verticalFlipIsEnabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x2000) != 0;
}
// If rotation/scaling is disabled it'll return false.
// THIS IS NOT EQUIVALENT TO !verticalFlipIsEnabled() !!
bool Sprite::verticalFlipIsDisabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x2000) == 0;
}
//----------//------------------------------------------------------------------
//----------// Priority settings.
//----------//------------------------------------------------------------------
void Sprite::setPriority( SpritePriority priority ) {
TO_BE_IMPLEMENTED
}
SpritePriority Sprite::getPriority() {
TO_BE_IMPLEMENTED
return spLOW;
}
//----------//------------------------------------------------------------------
//----------// Other settings.
//----------//------------------------------------------------------------------
void Sprite::clear() {
sprites[this->id].attr0 = ATTR0_DISABLED;
sprites[this->id].attr1 = 0;
sprites[this->id].attr2 = 0;
sprites[this->id].affine_data = 0;
}
void Sprite::disable() {
uint16 disableMask = 0xFEFF;
sprites[this->id].attr0 &= disableMask;
}
void Sprite::enable() {
uint16 enableMask = 0xFCFF;
sprites[this->id].attr0 &= enableMask;
}
void Sprite::print() {
FMAW::printf("%s\r\n Sprite %u:%s\r\n|%s|",
"\r\n|----------------|", this->id, "\r\n|----------------|",
half_word_to_binary(sprites[this->id].attr0).c_str());
FMAW::printf("|%s|\r\n|%s|",
half_word_to_binary(sprites[this->id].attr1).c_str(),
half_word_to_binary(sprites[this->id].attr2).c_str());
FMAW::printf("|%s|\r\n%s",
half_word_to_binary(sprites[this->id].affine_data).c_str(),
"|----------------|");
}
}<commit_msg>Sprite class completely implemented<commit_after>#include <string>
#include <nds.h>
#include <nds/debug.h>
#include "./math.h"
#include "./sprite.h"
#include "./debug.h"
namespace FMAW {
//------------------------------------------------------------------------------
// Common sprite helpers.
//------------------------------------------------------------------------------
void clearAllSprites() {
for ( sprite_id id = 0; id < TOTAL_SPRITES; id++ ) {
Sprite sprite (id);
sprite.clear();
}
}
//------------------------------------------------------------------------------
// Sprite class.
//------------------------------------------------------------------------------
uint8 Sprite::nextEmptySprite = 0;
//----------//------------------------------------------------------------------
//----------// Position.
//----------//------------------------------------------------------------------
bool Sprite::setXPosition( int x ) {
bool isNegative = x < 0;
if ( isNegative ) x = -x;
uint16 xCapped = x & 0x00FF;
printf("X Original: %d New: %u", x, xCapped);
if ( x != xCapped ) return false;
// If x was negative we have to apply 2's complement.
if ( isNegative ) x = twosComplement9B(x);
// We have to set the upper part of the half-word to 1 so AND doesn't
// break anything.
x |= 0xFE00;
// We have to set position's bits to 1 so we can then make an AND.
sprites[this->id].attr1 |= 0x01FF;
// Now we can set position with a simple AND.
sprites[this->id].attr1 &= x;
return true;
}
bool Sprite::setYPosition( int y ) {
bool isNegative = y < 0;
if ( isNegative ) y = -y;
uint16 yCapped = y & 0x007F;
printf("Y Original: %d New: %u", y, yCapped);
if ( y != yCapped ) return false;
// If x was negative we have to apply 2's complement.
if ( isNegative ) y = twosComplement8B(y);
// We have to set the upper part of the half-word to 1 so AND doesn't
// break anything.
y |= 0xFF00;
// We have to set position's bits to 1 so we can then make an AND.
sprites[this->id].attr0 |= 0x00FF;
// Now we can set position with a simple AND.
sprites[this->id].attr0 &= y;
return true;
}
bool Sprite::setPosition( int x, int y ) {
Point previousPosition = this->getPosition();
if ( this->setXPosition( x ) && this->setYPosition( y ) ) return true;
else {
this->setXPosition( previousPosition.x );
this->setYPosition( previousPosition.y );
return false;
}
return true;
}
bool Sprite::setPosition( Point point ) {
return this->setPosition( point.x, point.y );
}
int Sprite::getXPosition() {
uint8 x = sprites[this->id].attr1 & 0x01FF;
// If x-position was a negative number...
if ( (x & 0x0100) != 0 ) return -twosComplement9B(x);
return x;
}
int Sprite::getYPosition() {
uint8 y = sprites[this->id].attr0 & 0x00FF;
// If y-position was a negative number...
if ( (y & 0x0080) != 0 ) return -twosComplement8B(y);
return y;
}
Point Sprite::getPosition() {
Point p {};
p.x = this->getXPosition();
p.y = this->getYPosition();
return p;
}
//----------//------------------------------------------------------------------
//----------// Tile & palette settings.
//----------//------------------------------------------------------------------
bool Sprite::setTile( uint16 tileIndex ) {
uint16 tileIndexCapped = tileIndex & 0x01FF;
if ( tileIndex != tileIndexCapped ) return false;
// We first set tile bits to 1 so we can apply an AND later.
sprites[this->id].attr2 |= 0x01FF;
// We apply and AND to set the bits properly.
sprites[this->id].attr2 &= tileIndexCapped;
return true;
}
uint16 Sprite::getTile() {
return sprites[this->id].attr2 & 0x01FF;
}
bool Sprite::setPalette( uint8 paletteIndex ) {
uint8 paletteIndexCapped = paletteIndex & 0x000F;
if ( paletteIndex != paletteIndexCapped ) return false;
// We first set tile bits to 1 so we can apply an AND later.
sprites[this->id].attr2 |= 0xF000;
// We apply and AND to set the bits properly.
sprites[this->id].attr2 &= paletteIndexCapped << 12;
return true;
}
uint8 Sprite::getPalette() {
return (sprites[this->id].attr2 & 0xF000) >> 12;
}
//----------//------------------------------------------------------------------
//----------// Rotation & scale settings.
//----------//------------------------------------------------------------------
void Sprite::enableRotationAndScale() {
sprites[this->id].attr0 |= 0x0100;
}
void Sprite::disableRotationAndScale() {
sprites[this->id].attr0 &= 0xFEFF;
}
bool Sprite::rotationAndScaleAreEnabled() {
return (sprites[this->id].attr0 & 0x0100) != 0 ;
}
bool Sprite::rotationAndScaleAreDisabled() {
return !this->rotationAndScaleAreEnabled();
}
void Sprite::enableDoubleSize() {
sprites[this->id].attr0 |= 0x0200;
}
void Sprite::disableDoubleSize() {
sprites[this->id].attr0 &= 0xFDFF;
}
bool Sprite::doubleSizeEnabled() {
return (sprites[this->id].attr0 = 0x0200) != 0;
}
bool Sprite::doubleSizeDisabled() {
return !this->doubleSizeEnabled();
}
//----------//------------------------------------------------------------------
//----------// Object mode settings.
//----------//------------------------------------------------------------------
void Sprite::setObjectMode( SpriteObjectMode newMode ) {
sprites[this->id].attr0 |= 0x0C00;
sprites[this->id].attr0 &= newMode;
}
SpriteObjectMode Sprite::getObjectMode() {
uint16 half_word = sprites[this->id].attr0 | 0xF3FF;
switch (half_word) {
case normal:
return normal;
case alpha_first_target:
return normal;
case add_to_window:
return add_to_window;
case bitmap:
return bitmap;
default:
// This won't ever happen.
return normal;
}
}
//----------//------------------------------------------------------------------
//----------// Mosaic & color settings.
//----------//------------------------------------------------------------------
void Sprite::enableMosaic() {
sprites[this->id].attr0 |= 0x1000;
}
void Sprite::disableMosaic() {
sprites[this->id].attr0 &= 0xEFFF;
}
bool Sprite::mosaicIsEnabled() {
return (sprites[this->id].attr0 & 0x1000) != 0;
}
bool Sprite::mosaicIsDisabled() {
return !this->mosaicIsEnabled();
}
void Sprite::use16BitColors() {
sprites[this->id].attr0 &= 0xDFFF;
}
void Sprite::use256BitColors() {
sprites[this->id].attr0 |= 0x2000;
}
bool Sprite::isUsing16BitColors() {
return (sprites[this->id].attr0 & 0x2000) != 0;
}
bool Sprite::isUsing256BitColors() {
return !this->isUsing16BitColors();
}
//----------//------------------------------------------------------------------
//----------// Shape & size settings.
//----------//------------------------------------------------------------------
bool Sprite::setSizeMode( SpriteSizeMode newMode ) {
uint16 attr0mask;
uint16 attr1mask;
switch ( newMode ) {
case square8x8:
case square16x16:
case square32x32:
case square64x64:
attr0mask = 0x3FFF;
break;
case wide16x8:
case wide32x8:
case wide32x16:
case wide64x32:
attr0mask = 0x7FFF;
break;
case tall8x16:
case tall8x32:
case tall16x32:
case tall32x64:
attr0mask = 0xBFFF;
break;
default:
return false;
}
switch ( newMode ) {
case square8x8:
case wide16x8:
case tall8x16:
attr1mask = 0x3FFF;
break;
case square16x16:
case wide32x8:
case tall8x32:
attr1mask = 0x7FFF;
break;
case square32x32:
case wide32x16:
case tall16x32:
attr1mask = 0xBFFF;
break;
case square64x64:
case wide64x32:
case tall32x64:
attr1mask = 0xFFFF;
break;
default:
return false;
}
// We first set the size bits to 1.
sprites[this->id].attr0 |= 0XC000;
sprites[this->id].attr1 |= 0XC000;
// And then we apply the mask.
sprites[this->id].attr0 &= attr0mask;
sprites[this->id].attr1 &= attr1mask;
return true;
}
SpriteSizeMode Sprite::getSizeMode() {
uint16 shape = sprites[this->id].attr0 & 0xC000;
uint16 size = sprites[this->id].attr1 & 0xC000;
SpriteSizeMode sizeMode;
switch ( shape ) {
// Square.
case 0x0000:
switch (size) {
case 0x0000:
sizeMode = square8x8;
break;
case 0x4000:
sizeMode = square16x16;
break;
case 0x8000:
sizeMode = square32x32;
break;
case 0xC000:
sizeMode = square64x64;
break;
default:
sizeMode = unknown;
break;
}
break;
// Wide.
case 0x4000:
switch (size) {
case 0x0000:
sizeMode = wide16x8;
break;
case 0x4000:
sizeMode = wide32x8;
break;
case 0x8000:
sizeMode = wide32x16;
break;
case 0xC000:
sizeMode = wide64x32;
break;
default:
sizeMode = unknown;
break;
}
break;
// Tall.
case 0x8000:
switch (size) {
case 0x0000:
sizeMode = tall8x16;
break;
case 0x4000:
sizeMode = tall8x32;
break;
case 0x8000:
sizeMode = tall16x32;
break;
case 0xC000:
sizeMode = tall32x64;
break;
default:
sizeMode = unknown;
break;
}
break;
// Not used.
case 0xC000:
default:
sizeMode = unknown;
break;
}
return sizeMode;
}
//----------//------------------------------------------------------------------
//----------// Flip settings.
//----------//------------------------------------------------------------------
void Sprite::enableHorizontalFlip() {
this->disableRotationAndScale();
sprites[this->id].attr1 |= 0x1000;
}
void Sprite::disableHorizontalFlip() {
this->disableRotationAndScale();
sprites[this->id].attr1 &= 0xEFFF;
}
// If rotation/scaling is disabled it'll return false.
bool Sprite::horizontalFlipIsEnabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x1000) != 0;
}
// If rotation/scaling is disabled it'll return false.
// THIS IS NOT EQUIVALENT TO !horizontalFlipIsEnabled() !!
bool Sprite::horizontalFlipIsDisabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x1000) == 0;
}
void Sprite::enableVerticalFlip() {
sprites[this->id].attr1 |= 0x2000;
}
void Sprite::disableVerticalFlip() {
sprites[this->id].attr1 &= 0xDFFF;
}
// If rotation/scaling is disabled it'll return false.
bool Sprite::verticalFlipIsEnabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x2000) != 0;
}
// If rotation/scaling is disabled it'll return false.
// THIS IS NOT EQUIVALENT TO !verticalFlipIsEnabled() !!
bool Sprite::verticalFlipIsDisabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x2000) == 0;
}
//----------//------------------------------------------------------------------
//----------// Priority settings.
//----------//------------------------------------------------------------------
void Sprite::setPriority( SpritePriority priority ) {
sprites[this->id].attr2 |= 0x0C00;
sprites[this->id].attr2 &= priority;
}
SpritePriority Sprite::getPriority() {
uint16 half_word = sprites[this->id].attr2 | 0xF3FF;
switch (half_word) {
case spHIGHEST:
return spHIGHEST;
case spHIGH:
return spHIGH;
case spLOW:
return spLOW;
case spLOWEST:
return spLOWEST;
default:
// This won't ever happen.
return spHIGHEST;
}
}
//----------//------------------------------------------------------------------
//----------// Other settings.
//----------//------------------------------------------------------------------
void Sprite::clear() {
sprites[this->id].attr0 = ATTR0_DISABLED;
sprites[this->id].attr1 = 0;
sprites[this->id].attr2 = 0;
sprites[this->id].affine_data = 0;
}
void Sprite::disable() {
uint16 disableMask = 0xFEFF;
sprites[this->id].attr0 &= disableMask;
}
void Sprite::enable() {
uint16 enableMask = 0xFCFF;
sprites[this->id].attr0 &= enableMask;
}
void Sprite::print() {
FMAW::printf("%s\r\n Sprite %u:%s\r\n|%s|",
"\r\n|----------------|", this->id, "\r\n|----------------|",
half_word_to_binary(sprites[this->id].attr0).c_str());
FMAW::printf("|%s|\r\n|%s|",
half_word_to_binary(sprites[this->id].attr1).c_str(),
half_word_to_binary(sprites[this->id].attr2).c_str());
FMAW::printf("|%s|\r\n%s",
half_word_to_binary(sprites[this->id].affine_data).c_str(),
"|----------------|");
}
}<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-------------------------------------------------------------------------
// Implementation of the cascade vertexer class
// Reads V0s and tracks, writes out cascade vertices
// Fills the ESD with the cascades
// Origin: Christian Kuhn, IReS, Strasbourg, [email protected]
//-------------------------------------------------------------------------
//modified by R. Vernet 30/6/2006 : daughter label
//modified by R. Vernet 3/7/2006 : causality
//modified by I. Belikov 24/11/2006 : static setter for the default cuts
#include "TRandom3.h"
#include "AliESDEvent.h"
#include "AliESDcascade.h"
#include "AliCascadeVertexerUncheckedCharges.h"
ClassImp(AliCascadeVertexerUncheckedCharges)
//A set of loose cuts
Double_t
AliCascadeVertexerUncheckedCharges::fgChi2max=33.; //maximal allowed chi2
Double_t
AliCascadeVertexerUncheckedCharges::fgDV0min=0.01; //min V0 impact parameter
Double_t
AliCascadeVertexerUncheckedCharges::fgMassWin=0.008; //"window" around the Lambda mass
Double_t
AliCascadeVertexerUncheckedCharges::fgDBachMin=0.01; //min bachelor impact parameter
Double_t
AliCascadeVertexerUncheckedCharges::fgDCAmax=2.0; //max DCA between the V0 and the track
Double_t
AliCascadeVertexerUncheckedCharges::fgCPAmin=0.98; //min cosine of the cascade pointing angle
Double_t
AliCascadeVertexerUncheckedCharges::fgRmin=0.2; //min radius of the fiducial volume
Double_t
AliCascadeVertexerUncheckedCharges::fgRmax=100.; //max radius of the fiducial volume
Double_t AliCascadeVertexerUncheckedCharges::fgMaxEta=0.8; //max |eta|
Int_t AliCascadeVertexerUncheckedCharges::fgMinClusters=70; //min clusters (>=)
Bool_t AliCascadeVertexerUncheckedCharges::fgSwitchCharges=kFALSE; //
Bool_t AliCascadeVertexerUncheckedCharges::fgUseOnTheFlyV0=kFALSE; //HIGHLY EXPERIMENTAL
Int_t AliCascadeVertexerUncheckedCharges::V0sTracks2CascadeVertices(AliESDEvent *event) {
//--------------------------------------------------------------------
// This function reconstructs cascade vertices
// Adapted to the ESD by I.Belikov ([email protected])
//--------------------------------------------------------------------
const AliESDVertex *vtxT3D=event->GetPrimaryVertex();
Double_t xPrimaryVertex=vtxT3D->GetX();
Double_t yPrimaryVertex=vtxT3D->GetY();
Double_t zPrimaryVertex=vtxT3D->GetZ();
Double_t b=event->GetMagneticField();
Int_t nV0=(Int_t)event->GetNumberOfV0s();
TRandom3 lPRNG;
lPRNG.SetSeed(0);
//stores relevant V0s in an array
TObjArray vtcs(nV0);
Int_t i;
for (i=0; i<nV0; i++) {
AliESDv0 *v=event->GetV0(i);
if ( v->GetOnFlyStatus() && !fUseOnTheFlyV0) continue;
if (!v->GetOnFlyStatus() && fUseOnTheFlyV0) continue;
//Fix incorrect storing of charges in on-the-fly V0s
if( fUseOnTheFlyV0 ){
//Fix charge ordering
CheckChargeV0( v );
//Remove like-sign
if( v->GetParamN()->Charge() > 0 && v->GetParamP()->Charge() > 0 ) continue;
if( v->GetParamN()->Charge() < 0 && v->GetParamP()->Charge() < 0 ) continue;
}
if (v->GetD(xPrimaryVertex,yPrimaryVertex,zPrimaryVertex)<fDV0min) continue;
vtcs.AddLast(v);
}
nV0=vtcs.GetEntriesFast();
// stores relevant tracks in another array
Int_t nentr=(Int_t)event->GetNumberOfTracks();
TArrayI trk(nentr); Int_t ntr=0;
for (i=0; i<nentr; i++) {
AliESDtrack *esdtr=event->GetTrack(i);
ULong_t status=esdtr->GetStatus();
if ((status&AliESDtrack::kITSrefit)==0)
if ((status&AliESDtrack::kTPCrefit)==0) continue;
//Track pre-selection: clusters
if (esdtr->GetTPCNcls() < fMinClusters ) continue;
if (TMath::Abs(esdtr->GetD(xPrimaryVertex,yPrimaryVertex,b))<fDBachMin) continue;
trk[ntr++]=i;
}
Double_t massLambda=1.11568;
Int_t ncasc=0;
// Looking for both cascades and anti-cascades simultaneously
for (i=0; i<nV0; i++) { //loop on V0s
AliESDv0 *v=(AliESDv0*)vtcs.UncheckedAt(i);
AliESDv0 v0(*v);
Float_t lMassAsLambda = 0;
Float_t lMassAsAntiLambda = 0;
v0.ChangeMassHypothesis(kLambda0); // the v0 must be Lambda
lMassAsLambda = v0.GetEffMass();
v0.ChangeMassHypothesis(kLambda0Bar); // the v0 must be Lambda
lMassAsAntiLambda = v0.GetEffMass();
//Only disregard if it does not pass any of the desired hypotheses
if (TMath::Abs(lMassAsLambda-massLambda)>fMassWin &&
TMath::Abs(lMassAsAntiLambda-massLambda)>fMassWin) continue;
for (Int_t j=0; j<ntr; j++) {//loop on tracks
Int_t bidx=trk[j];
//Check if different tracks are used all times
if (bidx==v0.GetIndex(0)) continue; //Bo: consistency 0 for neg
if (bidx==v0.GetIndex(1)) continue; //Bo: consistency 0 for neg
if (v0.GetIndex(0)==v0.GetIndex(1)) continue; //Bo: consistency 0 for neg
AliESDtrack *btrk=event->GetTrack(bidx);
//Do not check charges!
AliESDv0 *pv0=&v0;
AliExternalTrackParam bt(*btrk), *pbt=&bt;
Double_t dca=PropagateToDCA(pv0,pbt,b);
if (dca > fDCAmax) continue;
//eta cut - test
if (TMath::Abs(pbt->Eta())>fMaxEta) continue;
AliESDcascade cascade(*pv0,*pbt,bidx);//constucts a cascade candidate
Double_t x,y,z; cascade.GetXYZcascade(x,y,z); // Bo: bug correction
Double_t r2=x*x + y*y;
if (r2 > fRmax*fRmax) continue; // condition on fiducial zone
if (r2 < fRmin*fRmin) continue;
Double_t pxV0,pyV0,pzV0;
pv0->GetPxPyPz(pxV0,pyV0,pzV0);
if (x*pxV0+y*pyV0+z*pzV0 < 0) continue; //causality
Double_t x1,y1,z1; pv0->GetXYZ(x1,y1,z1);
if (r2 > (x1*x1+y1*y1)) continue;
if (cascade.GetCascadeCosineOfPointingAngle(xPrimaryVertex,yPrimaryVertex,zPrimaryVertex) <fCPAmin) continue; //condition on the cascade pointing angle
cascade.SetDcaXiDaughters(dca);
event->AddCascade(&cascade);
ncasc++;
} // end loop tracks
} // end loop V0s
Info("V0sTracks2CascadeVertices","Number of reconstructed cascades: %d",ncasc);
return 0;
}
Double_t AliCascadeVertexerUncheckedCharges::Det(Double_t a00, Double_t a01, Double_t a10, Double_t a11) const {
//--------------------------------------------------------------------
// This function calculates locally a 2x2 determinant
//--------------------------------------------------------------------
return a00*a11 - a01*a10;
}
Double_t AliCascadeVertexerUncheckedCharges::Det(Double_t a00,Double_t a01,Double_t a02,
Double_t a10,Double_t a11,Double_t a12,
Double_t a20,Double_t a21,Double_t a22) const {
//--------------------------------------------------------------------
// This function calculates locally a 3x3 determinant
//--------------------------------------------------------------------
return a00*Det(a11,a12,a21,a22)-a01*Det(a10,a12,a20,a22)+a02*Det(a10,a11,a20,a21);
}
Double_t AliCascadeVertexerUncheckedCharges::PropagateToDCA(AliESDv0 *v, AliExternalTrackParam *t, Double_t b) {
//--------------------------------------------------------------------
// This function returns the DCA between the V0 and the track
//--------------------------------------------------------------------
Double_t alpha=t->GetAlpha(), cs1=TMath::Cos(alpha), sn1=TMath::Sin(alpha);
Double_t r[3]; t->GetXYZ(r);
Double_t x1=r[0], y1=r[1], z1=r[2];
Double_t p[3]; t->GetPxPyPz(p);
Double_t px1=p[0], py1=p[1], pz1=p[2];
Double_t x2,y2,z2; // position and momentum of V0
Double_t px2,py2,pz2;
v->GetXYZ(x2,y2,z2);
v->GetPxPyPz(px2,py2,pz2);
// calculation dca
Double_t dd= Det(x2-x1,y2-y1,z2-z1,px1,py1,pz1,px2,py2,pz2);
Double_t ax= Det(py1,pz1,py2,pz2);
Double_t ay=-Det(px1,pz1,px2,pz2);
Double_t az= Det(px1,py1,px2,py2);
Double_t dca=TMath::Abs(dd)/TMath::Sqrt(ax*ax + ay*ay + az*az);
//points of the DCA
Double_t t1 = Det(x2-x1,y2-y1,z2-z1,px2,py2,pz2,ax,ay,az)/
Det(px1,py1,pz1,px2,py2,pz2,ax,ay,az);
x1 += px1*t1; y1 += py1*t1; //z1 += pz1*t1;
//propagate track to the points of DCA
x1=x1*cs1 + y1*sn1;
if (!t->PropagateTo(x1,b)) {
Error("PropagateToDCA","Propagation failed !");
return 1.e+33;
}
return dca;
}
//________________________________________________________________________
void AliCascadeVertexerUncheckedCharges::CheckChargeV0(AliESDv0 *v0)
{
// This function checks charge of negative and positive daughter tracks.
// If incorrectly defined (onfly vertexer), swaps out.
if( v0->GetParamN()->Charge() > 0 && v0->GetParamP()->Charge() < 0 ) {
//V0 daughter track swapping is required! Note: everything is swapped here... P->N, N->P
Long_t lCorrectNidx = v0->GetPindex();
Long_t lCorrectPidx = v0->GetNindex();
Double32_t lCorrectNmom[3];
Double32_t lCorrectPmom[3];
v0->GetPPxPyPz( lCorrectNmom[0], lCorrectNmom[1], lCorrectNmom[2] );
v0->GetNPxPyPz( lCorrectPmom[0], lCorrectPmom[1], lCorrectPmom[2] );
AliExternalTrackParam lCorrectParamN(
v0->GetParamP()->GetX() ,
v0->GetParamP()->GetAlpha() ,
v0->GetParamP()->GetParameter() ,
v0->GetParamP()->GetCovariance()
);
AliExternalTrackParam lCorrectParamP(
v0->GetParamN()->GetX() ,
v0->GetParamN()->GetAlpha() ,
v0->GetParamN()->GetParameter() ,
v0->GetParamN()->GetCovariance()
);
lCorrectParamN.SetMostProbablePt( v0->GetParamP()->GetMostProbablePt() );
lCorrectParamP.SetMostProbablePt( v0->GetParamN()->GetMostProbablePt() );
//Get Variables___________________________________________________
Double_t lDcaV0Daughters = v0 -> GetDcaV0Daughters();
Double_t lCosPALocal = v0 -> GetV0CosineOfPointingAngle();
Bool_t lOnFlyStatusLocal = v0 -> GetOnFlyStatus();
//Create Replacement Object_______________________________________
AliESDv0 *v0correct = new AliESDv0(lCorrectParamN,lCorrectNidx,lCorrectParamP,lCorrectPidx);
v0correct->SetDcaV0Daughters ( lDcaV0Daughters );
v0correct->SetV0CosineOfPointingAngle ( lCosPALocal );
v0correct->ChangeMassHypothesis ( kK0Short );
v0correct->SetOnFlyStatus ( lOnFlyStatusLocal );
//Reverse Cluster info..._________________________________________
v0correct->SetClusters( v0->GetClusters( 1 ), v0->GetClusters ( 0 ) );
*v0 = *v0correct;
//Proper cleanup..._______________________________________________
v0correct->Delete();
v0correct = 0x0;
//Just another cross-check and output_____________________________
if( v0->GetParamN()->Charge() > 0 && v0->GetParamP()->Charge() < 0 ) {
AliWarning("Found Swapped Charges, tried to correct but something FAILED!");
} else {
//AliWarning("Found Swapped Charges and fixed.");
}
//________________________________________________________________
} else {
//Don't touch it! ---
//Printf("Ah, nice. Charges are already ordered...");
}
return;
}
<commit_msg>Revert to no checking of charges in unchecked charge version of vertexer<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-------------------------------------------------------------------------
// Implementation of the cascade vertexer class
// Reads V0s and tracks, writes out cascade vertices
// Fills the ESD with the cascades
// Origin: Christian Kuhn, IReS, Strasbourg, [email protected]
//-------------------------------------------------------------------------
//modified by R. Vernet 30/6/2006 : daughter label
//modified by R. Vernet 3/7/2006 : causality
//modified by I. Belikov 24/11/2006 : static setter for the default cuts
#include "TRandom3.h"
#include "AliESDEvent.h"
#include "AliESDcascade.h"
#include "AliCascadeVertexerUncheckedCharges.h"
ClassImp(AliCascadeVertexerUncheckedCharges)
//A set of loose cuts
Double_t
AliCascadeVertexerUncheckedCharges::fgChi2max=33.; //maximal allowed chi2
Double_t
AliCascadeVertexerUncheckedCharges::fgDV0min=0.01; //min V0 impact parameter
Double_t
AliCascadeVertexerUncheckedCharges::fgMassWin=0.008; //"window" around the Lambda mass
Double_t
AliCascadeVertexerUncheckedCharges::fgDBachMin=0.01; //min bachelor impact parameter
Double_t
AliCascadeVertexerUncheckedCharges::fgDCAmax=2.0; //max DCA between the V0 and the track
Double_t
AliCascadeVertexerUncheckedCharges::fgCPAmin=0.98; //min cosine of the cascade pointing angle
Double_t
AliCascadeVertexerUncheckedCharges::fgRmin=0.2; //min radius of the fiducial volume
Double_t
AliCascadeVertexerUncheckedCharges::fgRmax=100.; //max radius of the fiducial volume
Double_t AliCascadeVertexerUncheckedCharges::fgMaxEta=0.8; //max |eta|
Int_t AliCascadeVertexerUncheckedCharges::fgMinClusters=70; //min clusters (>=)
Bool_t AliCascadeVertexerUncheckedCharges::fgSwitchCharges=kFALSE; //
Bool_t AliCascadeVertexerUncheckedCharges::fgUseOnTheFlyV0=kFALSE; //HIGHLY EXPERIMENTAL
Int_t AliCascadeVertexerUncheckedCharges::V0sTracks2CascadeVertices(AliESDEvent *event) {
//--------------------------------------------------------------------
// This function reconstructs cascade vertices
// Adapted to the ESD by I.Belikov ([email protected])
//--------------------------------------------------------------------
const AliESDVertex *vtxT3D=event->GetPrimaryVertex();
Double_t xPrimaryVertex=vtxT3D->GetX();
Double_t yPrimaryVertex=vtxT3D->GetY();
Double_t zPrimaryVertex=vtxT3D->GetZ();
Double_t b=event->GetMagneticField();
Int_t nV0=(Int_t)event->GetNumberOfV0s();
TRandom3 lPRNG;
lPRNG.SetSeed(0);
//stores relevant V0s in an array
TObjArray vtcs(nV0);
Int_t i;
for (i=0; i<nV0; i++) {
AliESDv0 *v=event->GetV0(i);
if ( v->GetOnFlyStatus() && !fUseOnTheFlyV0) continue;
if (!v->GetOnFlyStatus() && fUseOnTheFlyV0) continue;
//Fix incorrect storing of charges in on-the-fly V0s
if( fUseOnTheFlyV0 ){
//Fix charge ordering
CheckChargeV0( v );
//Remove like-sign --- COMMENTED: THIS IS UNCHECKED CHARGES VERSION, user must check himself later!
//if( v->GetParamN()->Charge() > 0 && v->GetParamP()->Charge() > 0 ) continue;
//if( v->GetParamN()->Charge() < 0 && v->GetParamP()->Charge() < 0 ) continue;
}
if (v->GetD(xPrimaryVertex,yPrimaryVertex,zPrimaryVertex)<fDV0min) continue;
vtcs.AddLast(v);
}
nV0=vtcs.GetEntriesFast();
// stores relevant tracks in another array
Int_t nentr=(Int_t)event->GetNumberOfTracks();
TArrayI trk(nentr); Int_t ntr=0;
for (i=0; i<nentr; i++) {
AliESDtrack *esdtr=event->GetTrack(i);
ULong_t status=esdtr->GetStatus();
if ((status&AliESDtrack::kITSrefit)==0)
if ((status&AliESDtrack::kTPCrefit)==0) continue;
//Track pre-selection: clusters
if (esdtr->GetTPCNcls() < fMinClusters ) continue;
if (TMath::Abs(esdtr->GetD(xPrimaryVertex,yPrimaryVertex,b))<fDBachMin) continue;
trk[ntr++]=i;
}
Double_t massLambda=1.11568;
Int_t ncasc=0;
// Looking for both cascades and anti-cascades simultaneously
for (i=0; i<nV0; i++) { //loop on V0s
AliESDv0 *v=(AliESDv0*)vtcs.UncheckedAt(i);
AliESDv0 v0(*v);
Float_t lMassAsLambda = 0;
Float_t lMassAsAntiLambda = 0;
v0.ChangeMassHypothesis(kLambda0); // the v0 must be Lambda
lMassAsLambda = v0.GetEffMass();
v0.ChangeMassHypothesis(kLambda0Bar); // the v0 must be Lambda
lMassAsAntiLambda = v0.GetEffMass();
//Only disregard if it does not pass any of the desired hypotheses
if (TMath::Abs(lMassAsLambda-massLambda)>fMassWin &&
TMath::Abs(lMassAsAntiLambda-massLambda)>fMassWin) continue;
for (Int_t j=0; j<ntr; j++) {//loop on tracks
Int_t bidx=trk[j];
//Check if different tracks are used all times
if (bidx==v0.GetIndex(0)) continue; //Bo: consistency 0 for neg
if (bidx==v0.GetIndex(1)) continue; //Bo: consistency 0 for neg
if (v0.GetIndex(0)==v0.GetIndex(1)) continue; //Bo: consistency 0 for neg
AliESDtrack *btrk=event->GetTrack(bidx);
//Do not check charges!
AliESDv0 *pv0=&v0;
AliExternalTrackParam bt(*btrk), *pbt=&bt;
Double_t dca=PropagateToDCA(pv0,pbt,b);
if (dca > fDCAmax) continue;
//eta cut - test
if (TMath::Abs(pbt->Eta())>fMaxEta) continue;
AliESDcascade cascade(*pv0,*pbt,bidx);//constucts a cascade candidate
Double_t x,y,z; cascade.GetXYZcascade(x,y,z); // Bo: bug correction
Double_t r2=x*x + y*y;
if (r2 > fRmax*fRmax) continue; // condition on fiducial zone
if (r2 < fRmin*fRmin) continue;
Double_t pxV0,pyV0,pzV0;
pv0->GetPxPyPz(pxV0,pyV0,pzV0);
if (x*pxV0+y*pyV0+z*pzV0 < 0) continue; //causality
Double_t x1,y1,z1; pv0->GetXYZ(x1,y1,z1);
if (r2 > (x1*x1+y1*y1)) continue;
if (cascade.GetCascadeCosineOfPointingAngle(xPrimaryVertex,yPrimaryVertex,zPrimaryVertex) <fCPAmin) continue; //condition on the cascade pointing angle
cascade.SetDcaXiDaughters(dca);
event->AddCascade(&cascade);
ncasc++;
} // end loop tracks
} // end loop V0s
Info("V0sTracks2CascadeVertices","Number of reconstructed cascades: %d",ncasc);
return 0;
}
Double_t AliCascadeVertexerUncheckedCharges::Det(Double_t a00, Double_t a01, Double_t a10, Double_t a11) const {
//--------------------------------------------------------------------
// This function calculates locally a 2x2 determinant
//--------------------------------------------------------------------
return a00*a11 - a01*a10;
}
Double_t AliCascadeVertexerUncheckedCharges::Det(Double_t a00,Double_t a01,Double_t a02,
Double_t a10,Double_t a11,Double_t a12,
Double_t a20,Double_t a21,Double_t a22) const {
//--------------------------------------------------------------------
// This function calculates locally a 3x3 determinant
//--------------------------------------------------------------------
return a00*Det(a11,a12,a21,a22)-a01*Det(a10,a12,a20,a22)+a02*Det(a10,a11,a20,a21);
}
Double_t AliCascadeVertexerUncheckedCharges::PropagateToDCA(AliESDv0 *v, AliExternalTrackParam *t, Double_t b) {
//--------------------------------------------------------------------
// This function returns the DCA between the V0 and the track
//--------------------------------------------------------------------
Double_t alpha=t->GetAlpha(), cs1=TMath::Cos(alpha), sn1=TMath::Sin(alpha);
Double_t r[3]; t->GetXYZ(r);
Double_t x1=r[0], y1=r[1], z1=r[2];
Double_t p[3]; t->GetPxPyPz(p);
Double_t px1=p[0], py1=p[1], pz1=p[2];
Double_t x2,y2,z2; // position and momentum of V0
Double_t px2,py2,pz2;
v->GetXYZ(x2,y2,z2);
v->GetPxPyPz(px2,py2,pz2);
// calculation dca
Double_t dd= Det(x2-x1,y2-y1,z2-z1,px1,py1,pz1,px2,py2,pz2);
Double_t ax= Det(py1,pz1,py2,pz2);
Double_t ay=-Det(px1,pz1,px2,pz2);
Double_t az= Det(px1,py1,px2,py2);
Double_t dca=TMath::Abs(dd)/TMath::Sqrt(ax*ax + ay*ay + az*az);
//points of the DCA
Double_t t1 = Det(x2-x1,y2-y1,z2-z1,px2,py2,pz2,ax,ay,az)/
Det(px1,py1,pz1,px2,py2,pz2,ax,ay,az);
x1 += px1*t1; y1 += py1*t1; //z1 += pz1*t1;
//propagate track to the points of DCA
x1=x1*cs1 + y1*sn1;
if (!t->PropagateTo(x1,b)) {
Error("PropagateToDCA","Propagation failed !");
return 1.e+33;
}
return dca;
}
//________________________________________________________________________
void AliCascadeVertexerUncheckedCharges::CheckChargeV0(AliESDv0 *v0)
{
// This function checks charge of negative and positive daughter tracks.
// If incorrectly defined (onfly vertexer), swaps out.
if( v0->GetParamN()->Charge() > 0 && v0->GetParamP()->Charge() < 0 ) {
//V0 daughter track swapping is required! Note: everything is swapped here... P->N, N->P
Long_t lCorrectNidx = v0->GetPindex();
Long_t lCorrectPidx = v0->GetNindex();
Double32_t lCorrectNmom[3];
Double32_t lCorrectPmom[3];
v0->GetPPxPyPz( lCorrectNmom[0], lCorrectNmom[1], lCorrectNmom[2] );
v0->GetNPxPyPz( lCorrectPmom[0], lCorrectPmom[1], lCorrectPmom[2] );
AliExternalTrackParam lCorrectParamN(
v0->GetParamP()->GetX() ,
v0->GetParamP()->GetAlpha() ,
v0->GetParamP()->GetParameter() ,
v0->GetParamP()->GetCovariance()
);
AliExternalTrackParam lCorrectParamP(
v0->GetParamN()->GetX() ,
v0->GetParamN()->GetAlpha() ,
v0->GetParamN()->GetParameter() ,
v0->GetParamN()->GetCovariance()
);
lCorrectParamN.SetMostProbablePt( v0->GetParamP()->GetMostProbablePt() );
lCorrectParamP.SetMostProbablePt( v0->GetParamN()->GetMostProbablePt() );
//Get Variables___________________________________________________
Double_t lDcaV0Daughters = v0 -> GetDcaV0Daughters();
Double_t lCosPALocal = v0 -> GetV0CosineOfPointingAngle();
Bool_t lOnFlyStatusLocal = v0 -> GetOnFlyStatus();
//Create Replacement Object_______________________________________
AliESDv0 *v0correct = new AliESDv0(lCorrectParamN,lCorrectNidx,lCorrectParamP,lCorrectPidx);
v0correct->SetDcaV0Daughters ( lDcaV0Daughters );
v0correct->SetV0CosineOfPointingAngle ( lCosPALocal );
v0correct->ChangeMassHypothesis ( kK0Short );
v0correct->SetOnFlyStatus ( lOnFlyStatusLocal );
//Reverse Cluster info..._________________________________________
v0correct->SetClusters( v0->GetClusters( 1 ), v0->GetClusters ( 0 ) );
*v0 = *v0correct;
//Proper cleanup..._______________________________________________
v0correct->Delete();
v0correct = 0x0;
//Just another cross-check and output_____________________________
if( v0->GetParamN()->Charge() > 0 && v0->GetParamP()->Charge() < 0 ) {
AliWarning("Found Swapped Charges, tried to correct but something FAILED!");
} else {
//AliWarning("Found Swapped Charges and fixed.");
}
//________________________________________________________________
} else {
//Don't touch it! ---
//Printf("Ah, nice. Charges are already ordered...");
}
return;
}
<|endoftext|> |
<commit_before>//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2019 Ryo Suzuki
// Copyright (c) 2016-2019 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <GL/glew.h>
# include <GLFW/glfw3.h>
# include "GLRasterizerState.hpp"
namespace s3d
{
//namespace detail
//{
// static constexpr uint32 blendOpTable[6] =
// {
// 0,
// GL_FUNC_ADD,
// GL_FUNC_SUBTRACT,
// GL_FUNC_REVERSE_SUBTRACT,
// GL_MIN,
// GL_MAX
// };
// static constexpr uint32 blendTable[20] =
// {
// 0,
// GL_ZERO,
// GL_ONE,
// GL_SRC_COLOR,
// GL_ONE_MINUS_SRC_COLOR,
// GL_SRC_ALPHA,
// GL_ONE_MINUS_SRC_ALPHA,
// GL_DST_ALPHA,
// GL_ONE_MINUS_DST_ALPHA,
// GL_DST_COLOR,
// GL_ONE_MINUS_DST_COLOR,
// GL_SRC_ALPHA_SATURATE,
// 0,
// 0,
// GL_CONSTANT_COLOR,
// GL_ONE_MINUS_CONSTANT_COLOR,
// GL_SRC1_COLOR,
// GL_ONE_MINUS_SRC1_COLOR,
// GL_SRC1_ALPHA,
// GL_ONE_MINUS_SRC1_ALPHA,
// };
//}
GLRasterizerState::GLRasterizerState()
{
::glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
::glDisable(GL_CULL_FACE);
::glDisable(GL_SCISSOR_TEST);
::glDisable(GL_POLYGON_OFFSET_LINE);
::glDisable(GL_POLYGON_OFFSET_FILL);
}
void GLRasterizerState::set(const RasterizerState& state)
{
if (state == m_currentState)
{
return;
}
if (state.fillMode != m_currentState.fillMode)
{
::glPolygonMode(GL_FRONT_AND_BACK, state.fillMode == FillMode::Solid ? GL_FILL : GL_LINE);
}
if (state.cullMode != m_currentState.cullMode)
{
if (state.cullMode == CullMode::None)
{
::glDisable(GL_CULL_FACE);
}
else
{
::glEnable(GL_CULL_FACE);
::glFrontFace(GL_CW);
::glCullFace(state.cullMode == CullMode::Front ? GL_FRONT : GL_BACK);
}
}
if (state.scissorEnable != m_currentState.scissorEnable)
{
if (state.scissorEnable)
{
::glEnable(GL_SCISSOR_TEST);
}
else
{
::glDisable(GL_SCISSOR_TEST);
}
}
if (state.depthBias != m_currentState.depthBias)
{
if (state.depthBias)
{
::glEnable(GL_POLYGON_OFFSET_LINE);
::glEnable(GL_POLYGON_OFFSET_FILL);
::glPolygonOffset(0, state.depthBias);
}
else
{
::glDisable(GL_POLYGON_OFFSET_LINE);
::glDisable(GL_POLYGON_OFFSET_FILL);
}
}
m_currentState = state;
}
}
<commit_msg>OpenGL Cull 修正<commit_after>//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2019 Ryo Suzuki
// Copyright (c) 2016-2019 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <GL/glew.h>
# include <GLFW/glfw3.h>
# include "GLRasterizerState.hpp"
namespace s3d
{
GLRasterizerState::GLRasterizerState()
{
::glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
::glDisable(GL_CULL_FACE);
::glDisable(GL_SCISSOR_TEST);
::glDisable(GL_POLYGON_OFFSET_LINE);
::glDisable(GL_POLYGON_OFFSET_FILL);
}
void GLRasterizerState::set(const RasterizerState& state)
{
if (state == m_currentState)
{
return;
}
if (state.fillMode != m_currentState.fillMode)
{
::glPolygonMode(GL_FRONT_AND_BACK, state.fillMode == FillMode::Solid ? GL_FILL : GL_LINE);
}
if (state.cullMode != m_currentState.cullMode)
{
if (state.cullMode == CullMode::None)
{
::glDisable(GL_CULL_FACE);
}
else
{
::glEnable(GL_CULL_FACE);
::glFrontFace(GL_CW);
// CullMode::Front = GL_BACK, CullMode::Back = GL_FRONT
::glCullFace(state.cullMode == CullMode::Front ? GL_BACK : GL_FRONT);
}
}
if (state.scissorEnable != m_currentState.scissorEnable)
{
if (state.scissorEnable)
{
::glEnable(GL_SCISSOR_TEST);
}
else
{
::glDisable(GL_SCISSOR_TEST);
}
}
if (state.depthBias != m_currentState.depthBias)
{
if (state.depthBias)
{
::glEnable(GL_POLYGON_OFFSET_LINE);
::glEnable(GL_POLYGON_OFFSET_FILL);
::glPolygonOffset(0, state.depthBias);
}
else
{
::glDisable(GL_POLYGON_OFFSET_LINE);
::glDisable(GL_POLYGON_OFFSET_FILL);
}
}
m_currentState = state;
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.