code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
#include <UnitTest++.h>
#include <Utility/CheckPoint.hpp>
#include <3rdParty/TaucsWrapper.hpp>
#include <zMat.hpp>
using namespace zzz;
#ifdef ZZZ_LIB_TAUCS
SUITE(TaucsTest)
{
TEST(SymmetricTest)
{
// 1 0.5 0 0
// 0.5 1 0.5 0
// 0 0.5 1 0.5
// 0 0 0.5 1
zMatrix<double> a(Zerosd(4,4));
a(0,0)=1;
a(0,1)=0.5;
a(1,0)=0.5;
a(1,1)=1;
a(1,2)=0.5;
a(2,1)=0.5;
a(2,2)=1;
a(2,3)=0.5;
a(3,2)=0.5;
a(3,3)=1;
zVector<double> b(4);
b(0)=1;
b(1)=2;
b(2)=3;
b(3)=4;
zVector<double> x(Inv(a)*b);
// TaucsSolver accepts and only accepts symmetric matrix with only lower part filled
zSparseMatrix<double> sa(Tril(a));
TaucsCholeskySolver solver;
CHECK(solver.Creater(sa,"none"));
zVector<double> sx(4);
CHECK(solver.Solve(sx.Data(), b.Data()));
for (zuint i = 0; i < x.Size(1); i++) {
CHECK_CLOSE(x[i], sx[i], EPSILON);
}
}
TEST(NonSymmetricTest)
{
// 0 2 1
// 2 0 1
// 0 1 2
// 3 0 0
zMatrix<double> a(Zerosd(4,3));
a(0,1)=2;
a(0,2)=1;
a(1,0)=2;
a(1,2)=1;
a(2,1)=1;
a(2,2)=2;
a(3,0)=3;
zVector<double> b(4);
b(0)=2;
b(0)=3;
b(0)=4;
b(0)=5;
zVector<double> x(Inv(Trans(a)*a)*Trans(a)*b);
// TaucsSolver accepts and only accepts symmetric matrix with only lower part filled
zSparseMatrix<double> sa(Tril(Trans(a)*a));
TaucsCholeskySolver solver;
CHECK(solver.Creater(sa,"none"));
zVector<double> atb(Trans(a)*b);
zVector<double> sx(4);
CHECK(solver.Solve(sx.Data(), atb.Data()));
for (zuint i = 0; i < x.Size(1); i++) {
CHECK_CLOSE(x[i], sx[i], EPSILON);
}
}
}
#endif // ZZZ_LIB_TAUCS
|
zzz-engine
|
EngineTest/MathTest/TaucsTest.cpp
|
C++
|
gpl3
| 1,845
|
#include <UnitTest++.h>
#include <Utility/Global.hpp>
using namespace zzz;
SUITE(GlobalTest)
{
TEST(AssignAndRetrieve)
{
ZGLOBAL_DEFINE(int, global_x, 10);
*(Global::Instance().Get<int*>("global_x"))=100;
CHECK_EQUAL(100,global_x);
}
}
|
zzz-engine
|
EngineTest/MathTest/GlobalTest.cpp
|
C++
|
gpl3
| 268
|
#include <UnitTest++.h>
#include <3rdParty/CGALDelaunay.hpp>
#include <Math/Vector3.hpp>
#include <Math/Vector2.hpp>
#include <Utility/TextProgressBar.hpp>
#include <vector>
using namespace zzz;
#ifdef ZZZ_LIB_CGAL
SUITE(CGALTest)
{
bool CheckInVector(const Vector3i &t, const int i) {
if (t[0]==i) return true;
if (t[1]==i) return true;
if (t[2]==i) return true;
return false;
}
bool CheckVectorEqual(const Vector3i &t1, const Vector3i &t2) {
if (CheckInVector(t1, t2[0]) &&
CheckInVector(t1, t2[1]) &&
CheckInVector(t1, t2[2])) return true;
return false;
}
bool CheckTriangle(const vector<Vector3i> &tri, const Vector3i &t)
{
for (zuint i=0; i<tri.size(); i++) {
if (CheckVectorEqual(tri[i],t)) return true;
}
return false;
}
TEST(DelaunayTest)
{
//6* * *
//5 * * *
//4* *
//3 * *
//2 * * *
//1* * *
//0 1 2 3 4 5 6
vector<Vector2f> pos;
pos.push_back(Vector2f(2, 4));
pos.push_back(Vector2f(3.5, 3));
pos.push_back(Vector2f(5, 3));
pos.push_back(Vector2f(1.5, 2));
pos.push_back(Vector2f(3.5, 2));
pos.push_back(Vector2f(5, 2));
pos.push_back(Vector2f(0.5, 1));
pos.push_back(Vector2f(2.5, 1));
pos.push_back(Vector2f(4.5, 1));
pos.push_back(Vector2f(0.5, 6));
pos.push_back(Vector2f(2, 6));
pos.push_back(Vector2f(5.5, 6));
pos.push_back(Vector2f(1.5, 5));
pos.push_back(Vector2f(3, 5));
pos.push_back(Vector2f(5, 5));
pos.push_back(Vector2f(0.5, 4));
vector<Vector3i> tset;
VerboseLevel::Set(ZVERBOSE_PROGRESS_BAR + 1);
CGALDelaunayTriangulate(pos, tset);
VerboseLevel::Restore();
CHECK_EQUAL(22, tset.size());
CHECK(CheckTriangle(tset, Vector3i(9,10,12)));
CHECK(CheckTriangle(tset, Vector3i(10,11,13)));
CHECK(CheckTriangle(tset, Vector3i(11,13,14)));
CHECK(CheckTriangle(tset, Vector3i(10,12,13)));
CHECK(CheckTriangle(tset, Vector3i(9,12,15)));
CHECK(CheckTriangle(tset, Vector3i(12,15,0)));
CHECK(CheckTriangle(tset, Vector3i(12,13,0)));
CHECK(CheckTriangle(tset, Vector3i(0,1,13)));
CHECK(CheckTriangle(tset, Vector3i(1,13,14)));
CHECK(CheckTriangle(tset, Vector3i(1,2,14)));
CHECK(CheckTriangle(tset, Vector3i(0,3,15)));
CHECK(CheckTriangle(tset, Vector3i(0,1,3)));
CHECK(CheckTriangle(tset, Vector3i(1,2,4)));
CHECK(CheckTriangle(tset, Vector3i(1,3,4)));
CHECK(CheckTriangle(tset, Vector3i(3,6,15)));
CHECK(CheckTriangle(tset, Vector3i(3,6,7)));
CHECK(CheckTriangle(tset, Vector3i(2,4,5)));
CHECK(CheckTriangle(tset, Vector3i(3,4,7)));
CHECK(CheckTriangle(tset, Vector3i(4,7,8)));
CHECK(CheckTriangle(tset, Vector3i(4,5,8)));
}
}
#endif // ZZZ_LIB_CGAL
|
zzz-engine
|
EngineTest/MathTest/CGALDelaunayTest.cpp
|
C++
|
gpl3
| 2,850
|
#include <UnitTest++.h>
#include <XML/RapidXML.hpp>
#ifdef ZZZ_LIB_RAPIDXML
using namespace zzz;
/*
<?xml version="1.0" ?>
<MyApp>
<Messages>
<Welcome>Welcome to MyApp</Welcome>
<Farewell>Thank you for using MyApp</Farewell>
</Messages>
<Windows>
<Window name="MainFrame" x="5" y="15" w="400" h="250" />
</Windows>
<Connection ip="192.168.0.1" timeout="123.456000" />
</MyApp>
*/
SUITE(RapidXMLTest)
{
TEST(XMLWrite)
{
RapidXML xml;
//write
RapidXMLNode head=xml.AppendNode("MyApp");
RapidXMLNode messages=head.AppendNode("Messages");
RapidXMLNode welcome=messages.AppendNode("Welcome");
welcome<<"Welcome to MyApp";
RapidXMLNode farewell=messages.AppendNode("Farewell");
farewell.SetText("Thank you for using MyApp");
RapidXMLNode windows=head.AppendNode("Windows");
RapidXMLNode window=windows.AppendNode("Window");
window<<make_pair("name","MainFrame");
window<<make_pair("x",5);
window<<make_pair("y",15);
window<<make_pair("w","400");
window<<make_pair("h","250");
RapidXMLNode connection=head.AppendNode("Connection");
connection.SetAttribute("ip","192.168.0.1");
connection.SetAttribute("timeout","123.456000");
xml.SaveFile("testrapid.xml");
}
TEST(XMLRead)
{
//read
RapidXML xml;
xml.LoadFile("testrapid.xml");
CHECK_EQUAL(1,xml.NodeNumber());
RapidXMLNode rhead=xml.GetNode("MyApp");
CHECK(rhead.IsValid());
CHECK_EQUAL(3,rhead.NodeNumber());
RapidXMLNode rmessages=rhead.GetNode((zuint)0);
CHECK(rmessages.IsValid());
CHECK_EQUAL(2,rmessages.NodeNumber());
RapidXMLNode rwelcome=rmessages.GetNode("Welcome");
CHECK(rwelcome.IsValid());
CHECK(strcmp(rwelcome.GetText(),"Welcome to MyApp")==0);
string str(rmessages.GetNode("Farewell").GetText());
CHECK(str=="Thank you for using MyApp");
RapidXMLNode rwindows=rhead.GetNode("Windows");
CHECK(rwindows.IsValid());
RapidXMLNode rwindow=rwindows.GetNode((zuint)0);
CHECK(rwindow.IsValid());
CHECK(strcmp(rwindow.GetAttribute("name"),"MainFrame")==0);
CHECK_EQUAL(5,FromString<int>(rwindow.GetAttribute("x")));
CHECK_EQUAL(15,FromString<int>(rwindow.GetAttribute("y")));
CHECK_EQUAL(400,FromString<int>(rwindow.GetAttribute("w")));
CHECK_EQUAL(250,FromString<int>(rwindow.GetAttribute("h")));
RapidXMLNode rconnection=rhead.GetNode("Connection");
CHECK(rconnection.IsValid());
CHECK(strcmp(rconnection.GetAttribute("ip"),"192.168.0.1")==0);
CHECK_EQUAL(123.456,FromString<double>(rconnection.GetAttribute("timeout")));
CHECK(!rhead.HasNode("not exist"));
}
}
#endif // ZZZ_LIB_RAPIDXML
|
zzz-engine
|
EngineTest/MathTest/RapidXMLTest.cpp
|
C++
|
gpl3
| 2,753
|
#include <UnitTest++.h>
#include <3rdParty/ANNChar4Vector.hpp>
// using namespace zzz;
// SUITE(ANNTest)
// {
// TEST(ANNCharTest)
// {
// RandomInteger<zuint> r(0,255);
// ANNChar4Vector<128> ann;
// vector<Vector<128,zuchar> > pool;
// pool.reserve(20000);
// for (zuint i=0; i<20000; i++)
// {
// Vector<128,zuchar> a;
// for (zuint j=0; j<128; j++)
// a[j]=r.Rand();
// pool.push_back(a);
// }
//
// Timer timer;
// ann.SetData(pool);
// zout<<"ANN Init used: "<<timer.Elapsed()<<endl;
// timer.Restart();
// vector<int> idx,dist;
// idx.assign(2,0);
// dist.assign(2,0);
// ann.SetMaxPointVisit(200);
// for (zuint i=0; i<20000; i++)
// {
// Vector<128,zuchar> a;
// for (zuint j=0; j<128; j++)
// a[j]=r.Rand();
// ann.Query(a,2,idx,dist);
// }
// zout<<"Query used: "<<timer.Elapsed()<<endl;
// }
// }
|
zzz-engine
|
EngineTest/MathTest/ANNTest.cpp
|
C++
|
gpl3
| 983
|
#include <UnitTest++.h>
#include <GraphicsAlgo/Delaunay.hpp>
#include <Math/Vector2.hpp>
using namespace zzz;
SUITE(DelaunayTest)
{
bool CheckInVector(const Vector3i &t, const int i) {
if (t[0]==i) return true;
if (t[1]==i) return true;
if (t[2]==i) return true;
return false;
}
bool CheckVectorEqual(const Vector3i &t1, const Vector3i &t2) {
if (CheckInVector(t1, t2[0]) &&
CheckInVector(t1, t2[1]) &&
CheckInVector(t1, t2[2])) return true;
return false;
}
bool CheckTriangle(const vector<Vector3i> &tri, const Vector3i &t)
{
for (zuint i=0; i<tri.size(); i++) {
if (CheckVectorEqual(tri[i],t)) return true;
}
return false;
}
TEST(DelaunayTest)
{
//6* * *
//5 * * *
//4* *
//3 * *
//2 * * *
//1* * *
//0 1 2 3 4 5 6
vector<Vector2f> pos;
pos.push_back(Vector2f(2, 4));
pos.push_back(Vector2f(3.5, 3));
pos.push_back(Vector2f(5, 3));
pos.push_back(Vector2f(1.5, 2));
pos.push_back(Vector2f(3.5, 2));
pos.push_back(Vector2f(5, 2));
pos.push_back(Vector2f(0.5, 1));
pos.push_back(Vector2f(2.5, 1));
pos.push_back(Vector2f(4.5, 1));
pos.push_back(Vector2f(0.5, 6));
pos.push_back(Vector2f(2, 6));
pos.push_back(Vector2f(5.5, 6));
pos.push_back(Vector2f(1.5, 5));
pos.push_back(Vector2f(3, 5));
pos.push_back(Vector2f(5, 5));
pos.push_back(Vector2f(0.5, 4));
vector<Vector3i> tset;
Delaunay del;
VerboseLevel::Set(ZINFO + 1); // avoid progress bar display
del.Triangulate(pos, tset);
VerboseLevel::Restore();
CHECK_EQUAL(20, tset.size());
CHECK(CheckTriangle(tset, Vector3i(9,10,12)));
CHECK(CheckTriangle(tset, Vector3i(10,11,13)));
CHECK(CheckTriangle(tset, Vector3i(11,13,14)));
CHECK(CheckTriangle(tset, Vector3i(10,12,13)));
CHECK(CheckTriangle(tset, Vector3i(9,12,15)));
CHECK(CheckTriangle(tset, Vector3i(12,15,0)));
CHECK(CheckTriangle(tset, Vector3i(12,13,0)));
CHECK(CheckTriangle(tset, Vector3i(0,1,13)));
CHECK(CheckTriangle(tset, Vector3i(1,13,14)));
CHECK(CheckTriangle(tset, Vector3i(1,2,14)));
CHECK(CheckTriangle(tset, Vector3i(0,3,15)));
CHECK(CheckTriangle(tset, Vector3i(0,1,3)));
CHECK(CheckTriangle(tset, Vector3i(1,2,4)));
CHECK(CheckTriangle(tset, Vector3i(1,3,4)));
CHECK(CheckTriangle(tset, Vector3i(3,6,15)));
CHECK(CheckTriangle(tset, Vector3i(3,6,7)));
CHECK(CheckTriangle(tset, Vector3i(2,4,5)));
CHECK(CheckTriangle(tset, Vector3i(3,4,7)));
CHECK(CheckTriangle(tset, Vector3i(4,7,8)));
CHECK(CheckTriangle(tset, Vector3i(4,5,8)));
}
}
|
zzz-engine
|
EngineTest/MathTest/DelaunayTest.cpp
|
C++
|
gpl3
| 2,748
|
#pragma once
#include <UnitTest++.h>
#include <Math/DVector.hpp>
using namespace zzz;
SUITE(DVectorTest)
{
TEST(Construct)
{
DVector<int,true> x(10);
}
}
|
zzz-engine
|
EngineTest/MathTest/DVectorTest.cpp
|
C++
|
gpl3
| 175
|
#define SCL_SECURE_NO_WARNINGS
#include <UnitTest++.h>
#include <Utility/CmdParser.hpp>
using namespace zzz;
ZFLAGS_STRING2(istr,"","Input string",'s');
ZFLAGS_DOUBLE2(idbl,50,"Input double",'d');
ZFLAGS_INT2(iint,1,"Input int",'i');
ZFLAGS_SWITCH2(iswt,"Input switch",'w');
ZFLAGS_BOOL2(ibool,true,"Input bool",'b');
SUITE(CmdParserTest)
{
TEST(ParseTest)
{
char *argv[10];
for (int i=0; i<9; i++)
argv[i]=new char[100];
argv[9]=NULL;
strcpy(argv[0],"HAHA");
strcpy(argv[1],"--no_ibool");
strcpy(argv[2],"--idbl");
strcpy(argv[3],"49.9");
strcpy(argv[4],"-s");
strcpy(argv[5],"abcde");
strcpy(argv[6],"--iint");
strcpy(argv[7],"123");
strcpy(argv[8],"-w");
int argc=9;
CHECK_EQUAL("",ZFLAG_istr);
CHECK_EQUAL(50,ZFLAG_idbl);
CHECK_EQUAL(1,ZFLAG_iint);
CHECK_EQUAL(false,ZFLAG_iswt);
CHECK_EQUAL(true,ZFLAG_ibool);
ZCMDPARSE(argv[0]);
CHECK_EQUAL("abcde",ZFLAG_istr);
CHECK_EQUAL(49.9,ZFLAG_idbl);
CHECK_EQUAL(123,ZFLAG_iint);
CHECK_EQUAL(true,ZFLAG_iswt);
CHECK_EQUAL(false,ZFLAG_ibool);
}
}
|
zzz-engine
|
EngineTest/MathTest/CmdParserTest.cpp
|
C++
|
gpl3
| 1,147
|
#include <UnitTest++.h>
#include <3rdparty/RegularExpression.hpp>
#ifdef ZZZ_LIB_BOOST
using namespace zzz;
SUITE(RegularExpressionTest)
{
TEST(MatchTest)
{
RegularExpression re;
//credit card
re.Compile("(\\d{4}[- ])(\\d{4}[- ]){2}(\\d{4})");
CHECK_EQUAL(true,re.Match("1234 5678 9183 1234"));
CHECK_EQUAL(true,re.Match("1234-5678-9183-1234"));
CHECK_EQUAL(false,re.Match("123a-5678-9183-1234"));
vector<string> res;
re.Match("1234-5678-9183-1234",res);
CHECK_EQUAL(string("1234-"),res[0]);
CHECK_EQUAL(string("9183-"),res[1]);
CHECK_EQUAL(string("1234"),res[2]);
}
TEST(SearchTest)
{
RegularExpression re;
//credit card
re.Compile("(\\d{4}[- ])(\\d{4}[- ]){2}(\\d{4})");
CHECK_EQUAL(9,re.Search("fdsarewfd1234-5678-9183-1234",0));
vector<string> res;
re.Search("fdsarewfd1234-5678-9183-1234",0,res);
CHECK_EQUAL(string("1234-"),res[0]);
CHECK_EQUAL(string("9183-"),res[1]);
CHECK_EQUAL(string("1234"),res[2]);
}
TEST(ReplaceTest)
{
RegularExpression re;
//credit card
re.Compile("(\\d{4}[- ])(\\d{4}[- ]){2}(\\d{4})");
CHECK_EQUAL(string("1234 9183 xyzw 1234"),re.Replace("1234 5678 9183 1234","\\1\\2xyzw \\3"));
}
}
#endif // ZZZ_LIB_BOOST
|
zzz-engine
|
EngineTest/MathTest/RegularExpressTest.cpp
|
C++
|
gpl3
| 1,301
|
#include <UnitTest++.h>
#include <vector>
#include <Math/Vector3.hpp>
#include <SfM/Homography.hpp>
#include <SfM/Affine.hpp>
using namespace zzz;
#if defined(ZZZ_LIB_LAPACK)
SUITE(HomographyTest)
{
TEST(AffineTest)
{
vector<Vector2d> a,b;
a.push_back(Vector2d(0,0)); b.push_back(Vector2d(1,1));
a.push_back(Vector2d(10,1)); b.push_back(Vector2d(5,2));
a.push_back(Vector2d(3,-8)); b.push_back(Vector2d(-7,10));
Affine h;
h.Create(a,b);
CHECK_CLOSE(h.ToB(a[0]).Len(),b[0].Len(),EPSILON);
CHECK_CLOSE(h.ToB(a[1]).Len(),b[1].Len(),EPSILON);
CHECK_CLOSE(h.ToB(a[2]).Len(),b[2].Len(),EPSILON);
}
TEST(Full)
{
vector<Vector3d> a,b;
a.push_back(Vector3d(0,0,1)); b.push_back(Vector3d(0,0,1));
a.push_back(Vector3d(1,2,1)); b.push_back(Vector3d(1,33,1));
a.push_back(Vector3d(5,3,1)); b.push_back(Vector3d(0,3,1));
a.push_back(Vector3d(65,10,1)); b.push_back(Vector3d(12,42,1));
Homography h;
h.Create(a,b);
CHECK_CLOSE(h.ToB(a[0]).Len(),b[0].Len(),EPSILON);
CHECK_CLOSE(h.ToB(a[1]).Len(),b[1].Len(),EPSILON);
CHECK_CLOSE(h.ToB(a[2]).Len(),b[2].Len(),EPSILON);
CHECK_CLOSE(h.ToB(a[3]).Len(),b[3].Len(),EPSILON);
}
TEST(Less)
{
vector<Vector3d> a,b;
a.push_back(Vector3d(0,0,1)); b.push_back(Vector3d(0,0,1));
a.push_back(Vector3d(1,2,1)); b.push_back(Vector3d(1,33,1));
a.push_back(Vector3d(5,3,1)); b.push_back(Vector3d(0,3,1));
Homography h;
h.Create(a,b);
CHECK_CLOSE(h.ToB(a[0]).Len(),b[0].Len(),EPSILON);
CHECK_CLOSE(h.ToB(a[1]).Len(),b[1].Len(),EPSILON);
CHECK_CLOSE(h.ToB(a[2]).Len(),b[2].Len(),EPSILON);
}
TEST(Over)
{
vector<Vector3d> a,b;
a.push_back(Vector3d(0,0,1)); b.push_back(Vector3d(0,0,1));
a.push_back(Vector3d(11,22,1)); b.push_back(Vector3d(13,53,1));
a.push_back(Vector3d(1,2,1)); b.push_back(Vector3d(1,33,1));
a.push_back(Vector3d(5,3,1)); b.push_back(Vector3d(0,3,1));
a.push_back(Vector3d(231,22,1)); b.push_back(Vector3d(41,33,1));
a.push_back(Vector3d(52,13,1)); b.push_back(Vector3d(10,323,1));
Homography h;
h.Create(a,b);
}
}
#endif
|
zzz-engine
|
EngineTest/MathTest/HomographyTest.cpp
|
C++
|
gpl3
| 2,155
|
#include <UnitTest++.h>
#include <zCoreAutoLink.hpp>
#include <zGraphicsAutoLink.hpp>
#include <Utility/CmdParser.hpp>
int main(int argc, char** argv)
{
ZCMDPARSE(argv[0]);
return UnitTest::RunAllTests();
}
|
zzz-engine
|
EngineTest/MathTest/main.cpp
|
C++
|
gpl3
| 213
|
#include <zMat.hpp>
#include <UnitTest++.h>
namespace zzz{
struct ClassA{
int x;
void operator =(const ClassA &other) {x=other.x+1;}
};
template<>
class IOObject<ClassA> {
public:
static void CopyData(ClassA* dst, const ClassA* src, zsize size) {
memcpy(dst,src,sizeof(ClassA)*size);
}
};
struct ClassB{
int x;
void operator =(const ClassB &other) {x=other.x+1;}
};
}
using namespace zzz;
SUITE(ZMATRIXTEST)
{
TEST(CONSTRUCT)
{
zMatrix<double> v1(3,3);
CHECK_EQUAL(3,v1.Size(0));
CHECK_EQUAL(3,v1.Size(1));
zMatrix<double> v2(Ones<double>(3,3));
for (int r=0; r<3; r++) for (int c=0; c<3; c++)
{
CHECK_EQUAL(1,v2(r,c));
}
zMatrix<double> v3(Zeros<double>(3,3));
for (int r=0; r<3; r++) for (int c=0; c<3; c++)
{
CHECK_EQUAL(0,v3(r,c));
}
zMatrix<double> v4(Diag<double>(Ones<double>(3,1)));
for (int r=0; r<3; r++) for (int c=0; c<3; c++)
{
if (r==c) CHECK_EQUAL(1,v4(r,c));
else CHECK_EQUAL(0,v4(r,c));
}
//correct construct, not simply memcpy
v1(0,0)=2;
CHECK_EQUAL(1,v2(0,0));
zMatrix<double> v5(3);
CHECK_EQUAL(3,v5.Size(0));
CHECK_EQUAL(1,v5.Size(1));
}
TEST(COPY)
{
zMatrix<double> v(Ones<double>(3,3));
zMatrix<double> v2;
v2=v;
for (int r=0; r<3; r++) for (int c=0; c<3; c++)
{
CHECK_EQUAL(1,v2(r,c));
}
}
TEST(SMART_COPY)
{
zMatrix<ClassA> a(1,1);
a(0,0).x=0;
zMatrix<ClassA> a2(a);
CHECK_EQUAL(0,a2(0,0).x);
zMatrix<ClassB> b(1,1);
b(0,0).x=0;
zMatrix<ClassB> b2(b);
CHECK_EQUAL(1,b2(0,0).x);
}
TEST(EQUALS)
{
zMatrix<double> v1(Ones<double>(3,3));
zMatrix<double> v2(Ones<double>(3,3));
CHECK(v1==v2);
}
TEST(CONSTANT_EXPRESSION)
{
zMatrix<double> v1(Ones<double>(3,3)); //v1=1
zMatrix<double> v2(v1*2.0); //v2=2
for (int r=0; r<3; r++) for (int c=0; c<3; c++)
{
CHECK_EQUAL(2,v2(r,c));
}
zMatrix<double> v3(Ones<double>(3,3)*3.0); //v3=3
zMatrix<double> v4(v2+v3); //v4=5
for (int r=0; r<3; r++) for (int c=0; c<3; c++)
{
CHECK_EQUAL(2+3,v4(r,c));
}
}
TEST(MATRIX_EXPRESSION)
{
zMatrix<double> v1(Rand(3,3));
zMatrix<double> v2(Rand(3,3)*2.0);
zMatrix<double> v3(Rand(3,3)*3.0);
zMatrix<double> v4(Rand(3,3)*4.0);
zMatrix<double> v5(v1+DotTimes(v2,v3)-v4);
for (int r=0; r<3; r++) for (int c=0; c<3; c++)
{
CHECK_CLOSE(v1(r,c)+v2(r,c)*v3(r,c)-v4(r,c), v5(r,c), EPSILON);
}
}
TEST(MATRIX_COMPARE)
{
zMatrix<double> v1(Rand(3,3));
zMatrix<double> v2(Rand(3,3));
zMatrix<double> v3(v1<v2);
for (zuint i=0; i<v3.size(); i++)
if(v1[i]<v2[i]) CHECK(v3[i]==1);
else CHECK(v3[i]==0);
}
TEST(FUNCTION_EXPRESSION)
{
zMatrix<double> v1(Ones<double>(3,3)); //v1=1
zMatrix<double> v2(Sin(v1));
for (int r=0; r<3; r++) for (int c=0; c<3; c++)
CHECK_EQUAL(sin(v1(r,c)),v2(r,c));
zMatrix<double> v3,v4;
v3=+v1;
v4=-v1;
for (int r=0; r<3; r++) for (int c=0; c<3; c++)
CHECK_EQUAL(-v3(r,c),v4(r,c));
}
TEST(MATRIX_PRODUCT)
{
zMatrix<double> v1(3,3);
v1(0,0)=1;
v1(0,1)=1;
v1(0,2)=2;
v1(1,0)=1;
v1(1,1)=3;
v1(1,2)=1;
v1(2,0)=4;
v1(2,1)=1;
v1(2,2)=1;
zMatrix<double> v2(3,2);
v2(0,0)=1;
v2(0,1)=2;
v2(1,0)=3;
v2(1,1)=3;
v2(2,0)=2;
v2(2,1)=1;
zMatrix<double> v3(v1*v2);
CHECK_EQUAL(3,v3.Size(0));
CHECK_EQUAL(2,v3.Size(1));
CHECK_EQUAL(8,v3(0,0));
CHECK_EQUAL(7,v3(0,1));
CHECK_EQUAL(12,v3(1,0));
CHECK_EQUAL(12,v3(1,1));
CHECK_EQUAL(9,v3(2,0));
CHECK_EQUAL(12,v3(2,1));
}
TEST(SUB_MATRIX)
{
zMatrix<double> v1(Ones<double>(1,1));
zMatrix<double> v2(Zeros<double>(2,3));
zMatrix<double> v3(Ones<double>(1,2)*2.0);
zMatrix<double> v4(3,3);
v4(Colon(0,1),Colon())=v2;
v4(2,Colon(2,2))=v1;
v4(Colon(2,2),Colon(0,1))=v3;
CHECK_EQUAL(0,v4(0,0));
CHECK_EQUAL(0,v4(0,1));
CHECK_EQUAL(0,v4(0,2));
CHECK_EQUAL(0,v4(1,0));
CHECK_EQUAL(0,v4(1,1));
CHECK_EQUAL(0,v4(1,2));
CHECK_EQUAL(2,v4(2,0));
CHECK_EQUAL(2,v4(2,1));
CHECK_EQUAL(1,v4(2,2));
zMatrix<double> v5(Ones<double>(10,10)(Colon(3,5),Colon(6,9)));
CHECK_EQUAL(3,v5.Size(0));
CHECK_EQUAL(4,v5.Size(1));
for (int r=0; r<3; r++) for (int c=0; c<4; c++)
CHECK_EQUAL(1,v5(r,c));
zMatrix<double> v6(Ones<double>(10,10)(3,Colon(0,9)));
CHECK_EQUAL(1,v6.Size(0));
CHECK_EQUAL(10,v6.Size(1));
for (int r=0; r<1; r++) for (int c=0; c<10; c++)
CHECK_EQUAL(1,v6(r,c));
}
TEST(FANCY_SUB_MATRIX)
{
//block assign
zMatrix<double> v(3,3);
v(0,Colon())=Trans(Colond(1.0, 2.0, 0.5));
v(1,Colon())=Trans(Colond(3.0, 7.0, 2.0));
v(2,Colon())=Trans(Colond(100.0, 80.0, -10.0));
//reverse
zMatrix<double> v2(3,3);
v2=v(Colon(2,0,-1), Colon(2,0,-1));
for (int r=0; r<3; r++) for (int c=0; c<3; c++)
CHECK_EQUAL(v(r,c),v2(2-r,2-c));
//block copy
zMatrix<double> v3(Zeros<double>(4,4));
v3(Colon(0,1),Colon(0,1))=Ones<double>(2,2);
v3(Colon(2,3),Colon(2,3))=v3(Colon(0,1),Colon(0,1));
CHECK_EQUAL(1,v3(2,2));
CHECK_EQUAL(1,v3(2,3));
CHECK_EQUAL(1,v3(3,2));
CHECK_EQUAL(1,v3(3,3));
}
TEST(TRANSPOSE)
{
zMatrix<double> v1(2,3);
v1(0,0)=1;
v1(0,1)=2;
v1(0,2)=3;
v1(1,0)=4;
v1(1,1)=5;
v1(1,2)=6;
zMatrix<double> v2(Trans(v1));
CHECK_EQUAL(1,v2(0,0));
CHECK_EQUAL(2,v2(1,0));
CHECK_EQUAL(3,v2(2,0));
CHECK_EQUAL(4,v2(0,1));
CHECK_EQUAL(5,v2(1,1));
CHECK_EQUAL(6,v2(2,1));
}
TEST(ZVECTOR)
{
zVector<double> x(10);
for (int i=0; i<10; i++)
x(i)=i;
for (int r=0; r<10; r++) for (int c=0; c<1; c++)
CHECK_EQUAL(r,x(r,c));
zVector<double> y(x);
x(0)=100;
CHECK_EQUAL(0,y(0));
}
TEST(MatrixOpe)
{
zMatrix<double> a(Ones<double>(2,3));
CHECK_EQUAL(6,Sum(a));
CHECK_EQUAL(6,Dot(a,a));
CHECK_EQUAL(Sqrt<double>(6),Norm(a));
}
TEST(MatrixCombine)
{
zMatrix<double> a;
a=(Ones<double>(1,3),Zeros<double>(1,2),Dress(100.0));
CHECK_EQUAL(1,a.Size(0));
CHECK_EQUAL(6,a.Size(1));
CHECK_EQUAL(1,a(0,0));
CHECK_EQUAL(1,a(0,1));
CHECK_EQUAL(1,a(0,2));
CHECK_EQUAL(0,a(0,3));
CHECK_EQUAL(0,a(0,4));
CHECK_EQUAL(100,a(0,5));
a=(Trans(Colond(1.0,3.0)) % Zeros<double>(1,3));
CHECK_EQUAL(2,a.Size(0));
CHECK_EQUAL(3,a.Size(1));
CHECK_EQUAL(1,a(0,0));
CHECK_EQUAL(2,a(0,1));
CHECK_EQUAL(3,a(0,2));
CHECK_EQUAL(0,a(1,0));
CHECK_EQUAL(0,a(1,1));
CHECK_EQUAL(0,a(1,2));
}
TEST(MatrixPow)
{
zMatrixd mat(Colond(1,3)%Colond(2,4));
zMatrixd mat2(mat^2.0);
for (zuint r=0; r<mat2.Size(0); r++) for (zuint c=0; c<mat2.Size(1); c++)
CHECK_EQUAL(Pow(mat(r,c),2.0),mat2(r,c));
zMatrixd mat3(2.0^mat);
for (zuint r=0; r<mat3.Size(0); r++) for (zuint c=0; c<mat3.Size(1); c++)
CHECK_EQUAL(Pow(2.0,mat(r,c)),mat3(r,c));
zMatrixd mat4(mat^mat);
for (zuint r=0; r<mat4.Size(0); r++) for (zuint c=0; c<mat4.Size(1); c++)
CHECK_EQUAL(Pow(mat(r,c),mat(r,c)),mat4(r,c));
}
TEST(MatrixGradient)
{
zMatrixd mat(3,4);
mat(0,0)=1; mat(0,1)=2; mat(0,2)=5; mat(0,3)=4;
mat(1,0)=2; mat(1,1)=2; mat(1,2)=3; mat(1,3)=5;
mat(2,0)=6; mat(2,1)=6; mat(2,2)=6; mat(2,3)=8;
zMatrixd gradx(GradientX(mat));
CHECK_EQUAL(1,gradx(0,0));
CHECK_EQUAL(2,gradx(0,1));
CHECK_EQUAL(1,gradx(0,2));
CHECK_EQUAL(-1,gradx(0,3));
CHECK_EQUAL(0,gradx(1,0));
CHECK_EQUAL(0.5,gradx(1,1));
CHECK_EQUAL(1.5,gradx(1,2));
CHECK_EQUAL(2,gradx(1,3));
CHECK_EQUAL(0,gradx(2,0));
CHECK_EQUAL(0,gradx(2,1));
CHECK_EQUAL(1,gradx(2,2));
CHECK_EQUAL(2,gradx(2,3));
zMatrixd grady(GradientY(mat));
CHECK_EQUAL(1,grady(0,0));
CHECK_EQUAL(0,grady(0,1));
CHECK_EQUAL(-2,grady(0,2));
CHECK_EQUAL(1,grady(0,3));
CHECK_EQUAL(2.5,grady(1,0));
CHECK_EQUAL(2,grady(1,1));
CHECK_EQUAL(0.5,grady(1,2));
CHECK_EQUAL(2,grady(1,3));
CHECK_EQUAL(4,grady(2,0));
CHECK_EQUAL(4,grady(2,1));
CHECK_EQUAL(3,grady(2,2));
CHECK_EQUAL(3,grady(2,3));
}
TEST(MatrixReshape)
{
zMatrix<double> A(1,9);
for (zuint i=0; i<9; i++) A(0,i)=i;
zMatrix<double> B(Reshape(A,3,3));
CHECK_EQUAL(0,B(0,0));
CHECK_EQUAL(1,B(1,0));
CHECK_EQUAL(2,B(2,0));
CHECK_EQUAL(3,B(0,1));
CHECK_EQUAL(4,B(1,1));
CHECK_EQUAL(5,B(2,1));
CHECK_EQUAL(6,B(0,2));
CHECK_EQUAL(7,B(1,2));
CHECK_EQUAL(8,B(2,2));
}
}
|
zzz-engine
|
EngineTest/MathTest/zMatrixTest.cpp
|
C++
|
gpl3
| 9,101
|
#include <UnitTest++.h>
#include <vector>
#include <Math/Vector2.hpp>
#include <Math/Vector3.hpp>
#include <Graphics/GeometryHelper.hpp>
#include <Graphics/Quaternion.hpp>
using namespace zzz;
using namespace std;
SUITE(GeometryHelperTest)
{
TEST(PolygonToTriangles)
{
// 101 |-|
// 1 ______| |______ 201
// | |
// 0 ------- -------
// | |
// -100 |_|
vector<Vector2d> p;
p.push_back(Vector2d(0,0));
p.push_back(Vector2d(100,0));
p.push_back(Vector2d(100,-100));
p.push_back(Vector2d(101,-100));
p.push_back(Vector2d(101,0));
p.push_back(Vector2d(201,0));
p.push_back(Vector2d(201,1));
p.push_back(Vector2d(101,1));
p.push_back(Vector2d(101,101));
p.push_back(Vector2d(100,101));
p.push_back(Vector2d(100,1));
p.push_back(Vector2d(0,1));
vector<Vector3i> triangles;
GeometryHelper::PolygonToTriangles(p,triangles);
// for (zuint i=0; i<triangles.size(); i++)
// zout<<triangles[i]<<endl;
}
TEST(PointInTriangle2D)
{
Vector2f t1(0,3), t2(4,0), t3(5,6);
CHECK(!GeometryHelper::PointInTriangle2D(t1, t2, t3, Vector2f(1,1)));
CHECK(GeometryHelper::PointInTriangle2D(t1, t2, t3, Vector2f(1,3)));
CHECK(GeometryHelper::PointInTriangle2D(t1, t2, t3, Vector2f(2,3)));
CHECK(GeometryHelper::PointInTriangle2D(t1, t2, t3, Vector2f(0.01,3)));
CHECK(GeometryHelper::PointInTriangle2D(t1, t2, t3, Vector2f(4,1)));
CHECK(!GeometryHelper::PointInTriangle2D(t1, t2, t3, Vector2f(4.01,0)));
}
TEST(PointInTriangle3D)
{
Vector3f t1(0,0,0), t2(4,0,4), t3(0,4,4);
CHECK(GeometryHelper::PointInTriangle3D(t1, t2, t3, Vector3f(1,1,1)));
CHECK(GeometryHelper::PointInTriangle3D(t1, t2, t3, Vector3f(1,1,1.1)));
CHECK(GeometryHelper::PointInTriangle3D(t1, t2, t3, Vector3f(0,0,1.1)));
CHECK(!GeometryHelper::PointInTriangle3D(t1, t2, t3, Vector3f(-1,0,1.1)));
CHECK(GeometryHelper::PointInTriangle3D(t1, t2, t3, Vector3f(2,2,3.99)));
CHECK(!GeometryHelper::PointInTriangle3D(t1, t2, t3, Vector3f(2,2,4.01)));
CHECK(GeometryHelper::PointInTriangle3D(t1, t2, t3, Vector3f(2.01,2.01,3.89)));
CHECK(!GeometryHelper::PointInTriangle3D(t1, t2, t3, Vector3f(2.01,2.01,4.01)));
}
TEST(Barycentric)
{
Vector2f t1(0,0), t2(0,4), t3(2,2);
Vector3f b;
GeometryHelper::Barycentric(t1,t1,t2,t3,b);
CHECK_EQUAL(Vector3f(1,0,0),b);
GeometryHelper::Barycentric(t2,t1,t2,t3,b);
CHECK_EQUAL(Vector3f(0,1,0),b);
GeometryHelper::Barycentric(t3,t1,t2,t3,b);
CHECK_EQUAL(Vector3f(0,0,1),b);
GeometryHelper::Barycentric((t1+t2)/2,t1,t2,t3,b);
CHECK_EQUAL(Vector3f(0.5,0.5,0),b);
GeometryHelper::Barycentric((t1+t2+t3)/3,t1,t2,t3,b);
CHECK_CLOSE(0.333333333,b[0],EPSILON);
CHECK_CLOSE(0.333333333,b[1],EPSILON);
CHECK_CLOSE(0.333333333,b[2],EPSILON);
}
void TestRotate(Vector3f v1, Vector3f v2) {
v1.Normalize();
v2.Normalize();
Vector3f axis = Cross(v1,v2);
double angle = GeometryHelper::AngleFrom2Vectors(v1,v2);
Quaternionf q(axis, angle);
Vector3f v3=q.RotateVector(v1);
CHECK_CLOSE(0, v3.DistTo(v2), EPSILON5);
}
TEST(AngleFrom2VectorsTest)
{
TestRotate(Vector3f(0,0.1,1), Vector3f(0,0.1,-1));
TestRotate(Vector3f(0.3,0.1,1), Vector3f(0.5,0.1,-1));
TestRotate(Vector3f(20,0.5,1), Vector3f(-30,0.1,-1));
TestRotate(Vector3f(7,6,8), Vector3f(-5, -3, -2));
}
TEST(TriangleArea2)
{
Vector2f v0(1,1), v1(1,3), v2(5,4);
CHECK_EQUAL(4, GeometryHelper::TriangleArea(v0, v1, v2));
}
TEST(TriangleArea3)
{
Vector3f v0(3,0,0), v1(3,4,-3), v2(0,4,-3);
CHECK_EQUAL(7.5, GeometryHelper::TriangleArea(v0, v1, v2));
}
}
|
zzz-engine
|
EngineTest/MathTest/GeometryHelperTest.cpp
|
C++
|
gpl3
| 3,841
|
#include <UnitTest++.h>
#include <3rdParty/AlglibPolyfit.hpp>
#ifdef ZZZ_LIB_ALGLIB
#include <Utility/StringTools.hpp>
#include <Math/Vector4.hpp>
using namespace zzz;
TEST(AlglibPolyFitTest)
{
vector<float> x,y;
FromString("0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000 1.1000 1.2000 1.3000\
1.4000 1.5000 1.6000 1.7000 1.8000 1.9000 2.0000 2.1000 2.2000 2.3000 2.4000 2.5000", x);
FromString("0 0.1125 0.2227 0.3286 0.4284 0.5205 0.6039 0.6778 0.7421 0.7969 0.8427 0.8802\
0.9103 0.9340 0.9523 0.9661 0.9763 0.9838 0.9891 0.9928 0.9953 0.9970 0.9981 0.9989 0.9993 0.9996", y);
Vector<4,double> p = AlglibPolyFit<4,float>(x,y);
CHECK_CLOSE(p[0], -0.019930, EPSILON5);
CHECK_CLOSE(p[1], 1.384353, EPSILON5);
CHECK_CLOSE(p[2], -0.623189, EPSILON5);
CHECK_CLOSE(p[3], 0.092849, EPSILON5);
Vector<9,double> p2 = AlglibPolyFit<9,float>(x,y);
for (zuint i=0; i<x.size(); i++) {
float y2 = AlglibPolyVal(p2,x[i]);
CHECK_CLOSE(y[i], y2, 0.0000999999999);
}
}
#endif // ZZZ_LIB_ALGLIB
|
zzz-engine
|
EngineTest/MathTest/AlglibPolyFitTest.cpp
|
C++
|
gpl3
| 1,100
|
#include <UnitTest++.h>
#include <yaml-cpp/yaml.h>
#include <common.hpp>
#include <Math/Vector3.hpp>
using namespace std;
using namespace zzz;
SUITE(YamlTest) {
const string file_content = ""
"- name: Ogre\n"
" position:\n"
" - 0\n"
" - 5\n"
" - 0\n"
" powers:\n"
" - name: Club\n"
" damage: 10\n"
" - name: Fist\n"
" damage: 8\n"
"- name: Dragon\n"
" position: [1, 0, 10]\n"
" powers:\n"
" - name: Fire Breath\n"
" damage: 25\n"
" - name: Claws\n"
" damage: 15\n"
"- name: Wizard\n"
" position: [5, -3, 0]\n"
" powers:\n"
" - name: Acid Rain\n"
" damage: 50\n"
" - name: Staff\n"
" damage: 3\n";
struct Power {
string name;
int damage;
};
struct Monster {
std::string name;
Vector3f position;
std::vector <Power> powers;
};
// now the extraction operators for these types
void operator >> (const YAML::Node& node, Vector3f& v) {
node[0] >> v.x();
node[1] >> v.y();
node[2] >> v.z();
}
void operator >> (const YAML::Node& node, Power& power) {
node["name"] >> power.name;
node["damage"] >> power.damage;
}
void operator >> (const YAML::Node& node, Monster& monster) {
node["name"] >> monster.name;
node["position"] >> monster.position;
const YAML::Node& powers = node["powers"];
monster.powers.clear();
for(unsigned i=0;i<powers.size();i++) {
Power power;
powers[i] >> power;
monster.powers.push_back(power);
}
}
TEST(ParseTest) {
istringstream fin(file_content);
YAML::Parser parser(fin);
YAML::Node doc;
parser.GetNextDocument(doc);
CHECK_EQUAL(3, doc.size());
Monster monster;
doc[0] >> monster;
CHECK_EQUAL(Vector3f(0,5,0), monster.position);
CHECK_EQUAL(string("Ogre"), monster.name);
CHECK_EQUAL(2, monster.powers.size());
CHECK_EQUAL(string("Club"), monster.powers[0].name);
CHECK_EQUAL(10, monster.powers[0].damage);
CHECK_EQUAL(string("Fist"), monster.powers[1].name);
CHECK_EQUAL(8, monster.powers[1].damage);
doc[1] >> monster;
CHECK_EQUAL(Vector3f(1,0,10), monster.position);
CHECK_EQUAL(string("Dragon"), monster.name);
CHECK_EQUAL(2, monster.powers.size());
CHECK_EQUAL(string("Fire Breath"), monster.powers[0].name);
CHECK_EQUAL(25, monster.powers[0].damage);
CHECK_EQUAL(string("Claws"), monster.powers[1].name);
CHECK_EQUAL(15, monster.powers[1].damage);
doc[2] >> monster;
CHECK_EQUAL(Vector3f(5,-3,0), monster.position);
CHECK_EQUAL(string("Wizard"), monster.name);
CHECK_EQUAL(2, monster.powers.size());
CHECK_EQUAL(string("Acid Rain"), monster.powers[0].name);
CHECK_EQUAL(50, monster.powers[0].damage);
CHECK_EQUAL(string("Staff"), monster.powers[1].name);
CHECK_EQUAL(3, monster.powers[1].damage);
}
}
|
zzz-engine
|
EngineTest/MathTest/YamlTest.cpp
|
C++
|
gpl3
| 2,845
|
#include <Utility/STLVector.hpp>
#include <Utility/STLString.hpp>
#include <UnitTest++.h>
using namespace zzz;
SUITE(STLHelperTest)
{
TEST(STLVectorTest)
{
// constructor
STLVector<int> x, x1;
STLVector<int> y(10);
STLVector<int> z(5,1);
std::vector<int> wv;
for (int i=0; i<10; i++) wv.push_back(i);
STLVector<int> w(wv);
STLVector<int> v(w);
// iterator
x1 = v;
for (STLVector<int>::iterator vi = w.begin(); vi != w.end(); vi++)
*vi = -*vi;
int ii=0;
for (STLVector<int>::const_iterator vi = w.begin(); vi != w.end(); vi++)
CHECK_EQUAL(-(ii++), *vi);
for (STLVector<int>::reverse_iterator vi = w.rbegin(); vi != w.rend(); vi++)
*vi = -*vi;
ii=9;
for (STLVector<int>::const_reverse_iterator vi = w.rbegin(); vi != w.rend(); vi++)
CHECK_EQUAL(ii--, *vi);
// capacity
CHECK_EQUAL(y.max_size(), static_cast<std::vector<int>&>(y).max_size());
CHECK_EQUAL(y.capacity(), static_cast<std::vector<int>&>(y).capacity());
CHECK_EQUAL(10, y.size());
y.resize(5);
CHECK_EQUAL(5, y.size());
CHECK(x.empty());
y.reserve(100);
CHECK(100 <= y.capacity());
// element access
for (int i=0; i<5; i++) CHECK_EQUAL(1, z[i]);
for (int i=0; i<5; i++) CHECK_EQUAL(1, z.at(i));
CHECK_EQUAL(0, w.front());
CHECK_EQUAL(9, w.back());
// modifiers
z.assign(10,1);
for (int i=0; i<10; i++) CHECK_EQUAL(1, z[i]);
z.assign(w.begin(), w.end());
for (int i=0; i<10; i++) CHECK_EQUAL(i, z[i]);
for (int i=0; i<5; i++) x.push_back(i+10);
for (int i=5; i<10; i++) x.insert(x.end(), i+10);
for (int i=0; i<10; i++) CHECK_EQUAL(i+10, x[i]);
for (int i=0; i<5; i++) x.pop_back();
CHECK_EQUAL(5, x.size());
x.erase(x.begin(), x.begin()+2);
CHECK_EQUAL(3, x.size());
x.clear();
CHECK(x.empty());
x.swap(z);
for (int i=0; i<10; i++) CHECK_EQUAL(i, x[i]);
CHECK(z.empty());
}
TEST(STLStringTest)
{
// constructor
STLString x("hello");
CHECK_EQUAL("hello", x);
STLString x1(x);
CHECK_EQUAL(x1, x);
STLString z(5,'c');
CHECK_EQUAL("ccccc", z);
std::string z1("ccccc");
CHECK_EQUAL(z1, z);
// iterator
STLString rx(x.rbegin(), x.rend());
CHECK_EQUAL("olleh", rx);
// capacity
CHECK_EQUAL(x.max_size(), static_cast<std::string>(x).max_size());
CHECK_EQUAL(x.capacity(), static_cast<std::string>(x).capacity());
CHECK_EQUAL(5, x.size());
CHECK(!x.empty());
x.reserve(100);
CHECK(100 <= x.capacity());
// element access
for (int i=0; i<5; i++) CHECK_EQUAL(x[i], x1[i]);
for (int i=0; i<5; i++) CHECK_EQUAL(x[i], x1.at(i));
// modifiers
z.assign(10,'x');
CHECK_EQUAL(std::string("xxxxxxxxxx"), z);
}
}
|
zzz-engine
|
EngineTest/MathTest/STLHelperTest.cpp
|
C++
|
gpl3
| 2,883
|
#include <UnitTest++.h>
#include <Math/Vector.hpp>
#include <Math/Array1.hpp>
#include <Math/Array2.hpp>
#include <Math/Random.hpp>
using namespace zzz;
SUITE(ArrayTest)
{
TEST(Constructor)
{
Vector<2,zuint> sizes(2,2);
Array<2,float> x(2,2);
}
TEST(InterpolateTest2)
{
RandomReal<double> r;
//2D imsymmetric
Array<2,double> data2(2,2);
for (zuint i=0; i<data2.size(); i++) data2[i]=r.Rand();
Vector<2,double> coord;
coord[0]=0.7; coord[1]=0.1;
double ans=(data2(Vector2ui(0,0))*0.3+data2(Vector2ui(1,0))*0.7)*0.9+(data2(Vector2ui(0,1))*0.3+data2(Vector2ui(1,1))*0.7)*0.1;
CHECK_CLOSE(ans,data2.Interpolate(coord),EPSILON);
}
TEST(InterpolateTest)
{
RandomReal<double> r;
//1D
Array<1,double> data1(2);
for (zuint i=0; i<data1.size(); i++) data1[i]=r.Rand();
CHECK_EQUAL(data1.Sum()/data1.size(),data1.Interpolate(0.5));
//2D
Array<2,double> data2(Vector<2,zuint>(2));
for (zuint i=0; i<data2.size(); i++) data2[i]=r.Rand();
CHECK_EQUAL(data2.Sum()/data2.size(),data2.Interpolate(Vector<2,double>(0.5)));
//3D
Array<3,double> data3(Vector<3,zuint>(2));
for (zuint i=0; i<data3.size(); i++) data3[i]=r.Rand();
CHECK_EQUAL(data3.Sum()/data3.size(),data3.Interpolate(Vector<3,double>(0.5)));
//8D
Array<8,double> data8(Vector<8,zuint>(2));
for (zuint i=0; i<data8.size(); i++) data8[i]=r.Rand();
CHECK_EQUAL(data8.Sum()/data8.size(),data8.Interpolate(Vector<8,double>(0.5)));
}
}
|
zzz-engine
|
EngineTest/MathTest/ArrayTest.cpp
|
C++
|
gpl3
| 1,510
|
#include <Math/Array2.hpp>
#include <3rdparty/FFTW3Wrapper.hpp>
#include <UnitTest++.h>
#include <Math/Random.hpp>
#include <vector>
using namespace zzz;
#ifdef ZZZ_LIB_FFTW
SUITE(FFTWTest)
{
TEST(2DFFTWTest)
{
RandomReal<double> r;
Array<2,double> v(4,6),v2;
for (zuint i=0; i<v.size(); i++)
v[i]=r.Rand();
Array<2,Complex<double> > coeff,shift;
FFT2(v,coeff);
FFTShift(coeff,shift);
FFTShift(shift,coeff);
IFFT2(coeff,v2);
for (zuint i=0; i<v.size(); i++)
CHECK_CLOSE(v[i],v2[i],EPSILON);
}
TEST(1DFFTWTest)
{
RandomReal<double> r;
vector<double> v(10,0),v2;
for (zuint i=0; i<v.size(); i++)
v[i]=r.Rand();
vector<Complex<double> > coeff,shift;
FFT(v,coeff);
IFFT(coeff,v2);
for (zuint i=0; i<v.size(); i++)
CHECK_CLOSE(v[i],v2[i],EPSILON);
}
}
#endif
|
zzz-engine
|
EngineTest/MathTest/FFTWTest.cpp
|
C++
|
gpl3
| 894
|
#include <UnitTest++.h>
#include <Graphics/Quaternion.hpp>
#include <Math/Random.hpp>
#include <Math/Vector3.hpp>
#include <Graphics/Rotation.hpp>
using namespace zzz;
SUITE(QuaternionTest)
{
TEST(MultiplyTest)
{
RandomReal<float> r;
r.SeedFromTime();
Vector3f v(r.Rand(), r.Rand(), r.Rand());
v.Normalize();
Quaternionf q(r.Rand(), r.Rand(), r.Rand(), r.Rand());
q.Normalize();
Quaternionf q2(v[0],v[1],v[2],0);
Quaternionf q3 = q*q2;
Vector3f v2 = (q*v).XYZ();
CHECK_EQUAL(q3.XYZ(), v2);
}
TEST(RotationTest)
{
RandomReal<float> r;
r.SeedFromTime();
Vector3f v(r.Rand(), r.Rand(), r.Rand());
Quaternionf q(r.Rand(), r.Rand(), r.Rand(), r.Rand());
q.Normalize();
Vector3f v2(q.RotateVector(v));
Rotation<float> rot(q);
Vector3f v3(rot * v);
CHECK_CLOSE(0, v2.DistTo(v3), BIG_EPSILON);
}
TEST(BackRotationTest)
{
RandomReal<float> r;
r.SeedFromTime();
Vector3f v(r.Rand(), r.Rand(), r.Rand());
Quaternionf q(r.Rand(), r.Rand(), r.Rand(), r.Rand());
q.Normalize();
Vector3f v2(q.RotateBackVector(v));
Rotation<float> rot(q);
Vector3f v3(rot.Inverted() * v);
CHECK_CLOSE(0, v2.DistTo(v3), BIG_EPSILON);
}
TEST(RotateBackTest)
{
RandomReal<float> r;
r.SeedFromTime();
Vector3f v(r.Rand(), r.Rand(), r.Rand());
v.Normalize();
Quaternionf q(r.Rand(), r.Rand(), r.Rand(), r.Rand());
q.Normalize();
Vector3f v2(q.RotateBackVector(q.RotateVector(v)));
CHECK_CLOSE(0, v2.DistTo(v), BIG_EPSILON);
}
TEST(QuaternionSlerpTest)
{
RandomReal<float> r;
r.SeedFromTime();
Vector3f v(r.Rand(), r.Rand(), r.Rand());
Quaternionf q1(v, 30 * C_D2R);
Quaternionf q2(v, 50 * C_D2R);
Quaternionf q = Quaternionf::Slerp(q1, q2, 0.25);
CHECK_CLOSE(q.Angle(), 35*C_D2R, BIG_EPSILON);
}
}
|
zzz-engine
|
EngineTest/MathTest/QuaternionTest.cpp
|
C++
|
gpl3
| 1,956
|
#define ZOPTIMIZE_ABS
#define ZOPTIMIZE_SIGN
#define ZOPTIMIZE_MINMAX
#define ZOPTIMIZE_SETCLEARBIT
#include <UnitTest++.h>
#include <Math/Math.hpp>
#include <Utility/Tools.hpp>
using namespace zzz;
SUITE(MathOptTest)
{
TEST(AbsOptIntTest)
{
int x=0;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=-0;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=1;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=-1;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=MAX_INT;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=-MAX_INT;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
}
TEST(AbsOptShortTest)
{
short x=0;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=-0;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=1;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=-1;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=MAX_SHORT;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=-MAX_SHORT;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
}
TEST(AbsOptCharTest)
{
char x=0;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=-0;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=1;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=-1;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=MAX_CHAR;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
x=-MAX_CHAR;
CHECK_EQUAL(std::abs(x),Abs(x));
CHECK_EQUAL((x>=0)?1:-1,Sign(x));
}
TEST(MinMaxOptIntTest)
{
int x=0,y=1;
CHECK_EQUAL(std::max(x,y),Max(x,y));
CHECK_EQUAL(std::min(x,y),Min(x,y));
y=-1;
CHECK_EQUAL(std::max(x,y),Max(x,y));
CHECK_EQUAL(std::min(x,y),Min(x,y));
x=1;
CHECK_EQUAL(std::max(x,y),Max(x,y));
CHECK_EQUAL(std::min(x,y),Min(x,y));
x=MAX_INT/2;
CHECK_EQUAL(std::max(x,y),Max(x,y));
CHECK_EQUAL(std::min(x,y),Min(x,y));
y=-MAX_INT/2;
CHECK_EQUAL(std::max(x,y),Max(x,y));
CHECK_EQUAL(std::min(x,y),Min(x,y));
}
TEST(SetClearBitOptTest)
{
int x=0, y=1<<3, x2=x;
x2|=y;
SetClearBit(x,y,true);
CHECK_EQUAL(x2,x);
x2&=~y;
SetClearBit(x,y,false);
CHECK_EQUAL(x2,x);
x=MAX_INT;x2=x;
x2|=y;
SetClearBit(x,y,true);
CHECK_EQUAL(x2,x);
x2&=~y;
SetClearBit(x,y,false);
CHECK_EQUAL(x2,x);
}
TEST(SetClearBitOptUTest)
{
zuint x=0, y=1<<3, x2=x;
x2|=y;
SetClearBit(x,y,true);
CHECK_EQUAL(x2,x);
x2&=~y;
SetClearBit(x,y,false);
CHECK_EQUAL(x2,x);
x=MAX_INT;x2=x;
x2|=y;
SetClearBit(x,y,true);
CHECK_EQUAL(x2,x);
x2&=~y;
SetClearBit(x,y,false);
CHECK_EQUAL(x2,x);
}
}
|
zzz-engine
|
EngineTest/MathTest/MathOptTest.cpp
|
C++
|
gpl3
| 3,212
|
#include <Math/Vector2.hpp>
#include <Math/Vector3.hpp>
#include <Math/Vector4.hpp>
#include <Math/Math.hpp>
#include <UnitTest++.h>
namespace zzz{
struct ClassA{
int x;
void operator =(const ClassA &other) {x=other.x+1;}
};
template<>
class IOObject<ClassA> {
public:
static void CopyData(ClassA* dst, const ClassA* src, zsize size) {
memcpy(dst,src,sizeof(ClassA)*size);
}
};
struct ClassB {
int x;
void operator =(const ClassB &other) {x=other.x+1;}
};
}
using namespace zzz;
SUITE(VectorTest)
{
TEST(Constructor)
{
CHECK_EQUAL(sizeof(Vector3f),sizeof(float)*3);
Vector3f a(1,2,3);
CHECK_EQUAL(a.x(),1);
CHECK_EQUAL(a.y(),2);
CHECK_EQUAL(a.z(),3);
Vector3f b(a);
CHECK_EQUAL(b,a);
int vi[]={5,6,7};
float vf[]={8,9,10};
Vector3f c(vi),d(vf);
CHECK_ARRAY_EQUAL(vi,c.Data(),3);
CHECK_ARRAY_EQUAL(vf,d.Data(),3);
}
TEST(Assign_RawCopy)
{
ClassB aa;
aa.x=0;
Vector<5,ClassB> a,b;
a[0]=aa;
CHECK_EQUAL(a[0].x,1);
b[0].x=1;
a=b; //will call operator=
CHECK_EQUAL(a[0].x,2);
a.RawCopy(b); //force raw copy
CHECK_EQUAL(a[0].x,1);
}
TEST(SmartAssignCopy)
{
ClassA aa;
aa.x=0;
Vector<2,Vector<2,ClassA> > a,b;
a[0][0].x=0;
a[0][1].x=1;
a[1][0].x=2;
a[1][1].x=3;
b=a;
CHECK_EQUAL(0,b[0][0].x);
CHECK_EQUAL(1,b[0][1].x);
CHECK_EQUAL(2,b[1][0].x);
CHECK_EQUAL(3,b[1][1].x);
}
TEST(Math)
{
Vector3f a(1,2,3);
CHECK_EQUAL(a,Vector3f(1,2,3));
a=-a;
CHECK_EQUAL(a,Vector3f(-1,-2,-3));
a=a+a;
CHECK_EQUAL(a,Vector3f(-2,-4,-6));
a=a*a;
CHECK_EQUAL(a,Vector3f(4,16,36));
Vector3f b=a.Normalized();
CHECK_CLOSE(1,b.Len(),0.1);
a.Normalize();
CHECK_EQUAL(a,b);
CHECK_CLOSE(a.DistTo(b),0,0);
Vector3f c=a.RandomPerpendicularUnitVec();
CHECK_CLOSE(c.Len(),1,EPS);
CHECK_CLOSE(a.Dot(c),0,EPS);
}
TEST(CompareTest)
{
Vector3f a(1,2,3), b(1,2,3), c(1,3,2), d(-3,1,2);
CHECK(a==b);
CHECK(a<c);
CHECK(a>d);
CHECK_EQUAL(3,a.Max());
CHECK_EQUAL(1,a.Min());
CHECK_EQUAL(0,a.MinPos());
CHECK_EQUAL(2,a.MaxPos());
CHECK_EQUAL(-3,d.Min());
CHECK_EQUAL(1,d.AbsMin());
CHECK_EQUAL(0,d.AbsMaxPos());
a.KeepMax(c);
CHECK_EQUAL(Vector3f(1,3,3), a);
b.KeepMin(d);
CHECK_EQUAL(Vector3f(-3,1,2), b);
}
TEST(STL)
{
Vector<6,float> x;
for (zuint i=0; i<x.size(); i++)
x[i]=i;
for (Vector<6,float>::iterator vi=x.begin();vi!=x.end();vi++)
CHECK_EQUAL(vi-x.begin(),*vi);
Vector4d x1;
for (Vector4d::reverse_iterator vi=x1.rbegin();vi!=x1.rend();vi++)
*vi=vi-x1.rbegin();
CHECK_EQUAL(6,accumulate(x1.begin(),x1.end(),0));
}
TEST(MetaDot)
{
Vector<6,float> x,y;
for (size_t i=0; i<6; i++)
x[i]=y[i]=i;
CHECK_EQUAL(x.Dot(y),FastDot(x,y));
}
}
|
zzz-engine
|
EngineTest/MathTest/VectorTest.cpp
|
C++
|
gpl3
| 3,064
|
#include <UnitTest++.h>
#include <Math/IterExitCond.hpp>
using namespace zzz;
SUITE(IterExitCondTest)
{
TEST(ResidueTest)
{
IterExitCond<double> cond;
cond.SetCondResidue(0.1);
CHECK(!cond.IsSatisfied(10));
CHECK(!cond.IsSatisfied(-5));
CHECK(!cond.IsSatisfied(1));
CHECK(!cond.IsSatisfied(0.11));
CHECK(cond.IsSatisfied(0.1));
cond.Reset();
CHECK(cond.IsSatisfied(-0.01));
cond.Reset();
CHECK(cond.IsSatisfied(0));
}
TEST(CountTest)
{
IterExitCond<double> cond;
cond.SetCondIterCount(3);
CHECK(!cond.IsSatisfied(10));
CHECK(!cond.IsSatisfied(10));
CHECK(cond.IsSatisfied(10));
}
TEST(RepeatTest)
{
IterExitCond<double> cond;
cond.SetCondRepeat(3,3);
CHECK(!cond.IsSatisfied(10));
CHECK(!cond.IsSatisfied(11));
CHECK(!cond.IsSatisfied(9));
CHECK(!cond.IsSatisfied(10));
CHECK(!cond.IsSatisfied(8));
CHECK(!cond.IsSatisfied(9));
CHECK(!cond.IsSatisfied(10));
CHECK(!cond.IsSatisfied(8));
CHECK(!cond.IsSatisfied(9));
CHECK(!cond.IsSatisfied(10));
CHECK(cond.IsSatisfied(8));
}
}
|
zzz-engine
|
EngineTest/MathTest/IterExitCondTest.cpp
|
C++
|
gpl3
| 1,162
|
#include <UnitTest++.h>
#include <Utility/AutoloadCacheSet.hpp>
#include <vector>
using namespace zzz;
using namespace std;
SUITE(CacheSetTest)
{
struct Content
{
Content(int i):x(i){construct_seq.push_back(i);}
~Content(){destruct_seq.push_back(x);}
int x;
static vector<int> construct_seq;
static vector<int> destruct_seq;
};
vector<int> Content::construct_seq, Content::destruct_seq;
TEST(CacheSetTest)
{
class ContentCacheSet : public AutoloadCacheSet<Content*, pair<int, int> > {
public:
ContentCacheSet(){SetSize(10);}
Content* Load(const pair<int, int> &i){return new Content(i.first+i.second);}
};
ContentCacheSet *s = new ContentCacheSet;
int sequence[]={100,1,0,8,200,3,10};
for (int i=0; i<sizeof(sequence)/sizeof(int); i++)
Content *c=s->Get(make_pair(sequence[i]-i, i));
delete s;
CHECK_ARRAY_EQUAL(sequence, &(Content::construct_seq[0]), sizeof(sequence)/sizeof(int));
CHECK_EQUAL(sizeof(sequence)/sizeof(int), static_cast<int>(Content::destruct_seq.size()));
}
}
|
zzz-engine
|
EngineTest/MathTest/CacheSetTest.cpp
|
C++
|
gpl3
| 1,105
|
#include <UnitTest++.h>
#include <Utility/FileTools.hpp>
using namespace std;
using namespace zzz;
SUITE(PathTest)
{
#ifdef ZZZ_OS_WIN
TEST(PathTest)
{
string p="c:\\wzx\\sub\\..\\abcd.txt";
CHECK_EQUAL("abcd.txt",GetFilename(p));
CHECK_EQUAL(".txt",GetExt(p));
CHECK_EQUAL("abcd",GetBase(p));
CHECK_EQUAL("c:\\wzx\\sub\\..\\",GetPath(p));
#ifdef ZZZ_LIB_BOOST
NormalizePath(p);
CHECK_EQUAL("c:\\wzx\\abcd.txt",p);
#endif // ZZZ_LIB_BOOST
string p2="c:\\wzx\\sub\\";
CHECK_EQUAL(".",GetExt(p2));
CHECK_EQUAL("",GetBase(p2));
CHECK_EQUAL("c:\\wzx\\sub\\",GetPath(p2));
string f("123.456");
p="c:\\wzx\\abcd.txt";
CHECK_EQUAL("c:\\wzx\\123.456",PathFile(p,f));
CHECK_EQUAL(".\\",GetPath(f));
f="xyz\\123.456";
CHECK_EQUAL("c:\\wzx\\xyz\\123.456",PathFile(p,f));
f="c:\\wzx\\xyz\\123.456";
CHECK_EQUAL("c:\\wzx\\xyz\\123.456",PathFile(p,f));
#ifdef ZZZ_LIB_BOOST
f="c:\\wzx\\xyz";
CHECK_EQUAL("..\\xyz",RelativeTo(GetPath(p2),f));
CHECK_EQUAL("xyz",RelativeTo(GetPath(p),f));
CHECK_EQUAL("..\\xyz",RelativeTo(p2,f));
CHECK_EQUAL("xyz",RelativeTo(p,f));
f="c:\\wzx\\xyz\\";
CHECK_EQUAL("..\\xyz\\.",RelativeTo(GetPath(p2),f));
CHECK_EQUAL("xyz\\.",RelativeTo(GetPath(p),f));
CHECK_EQUAL("..\\xyz\\.",RelativeTo(p2,f));
CHECK_EQUAL("xyz\\.",RelativeTo(p,f));
#endif // ZZZ_LIB_BOOST
f="c:\\wzx\\xyz\\";
vector<string> s = SplitPath(f);
CHECK_EQUAL(5, s.size());
CHECK_EQUAL("c:", s[0]);
CHECK_EQUAL("/", s[1]);
CHECK_EQUAL("wzx", s[2]);
CHECK_EQUAL("xyz", s[3]);
CHECK_EQUAL(".", s[4]);
s = SplitPath(p);
CHECK_EQUAL(4, s.size());
CHECK_EQUAL("c:", s[0]);
CHECK_EQUAL("/", s[1]);
CHECK_EQUAL("wzx", s[2]);
CHECK_EQUAL("abcd.txt", s[3]);
}
#endif
}
|
zzz-engine
|
EngineTest/MathTest/PathTest.cpp
|
C++
|
gpl3
| 1,898
|
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(zzzEngineBuild)
SET(EXECUTABLE_OUTPUT_PATH, bin)
SET(LIBRARY_OUTPUT_PATH, lib)
ADD_SUBDIRECTORY(zCore)
ADD_SUBDIRECTORY(zGraphics)
ADD_SUBDIRECTORY(zVision)
ADD_SUBDIRECTORY(zMatrix)
ADD_SUBDIRECTORY(zImage)
ADD_SUBDIRECTORY(zVisualization)
#ADD_SUBDIRECTORY(zAi)
|
zzz-engine
|
zzzEngine/CMakeLists.txt
|
CMake
|
gpl3
| 323
|
SET(THISLIB zAi)
FILE(GLOB_RECURSE LibSrc *.cpp)
IF( "${DEBUG_MODE}" EQUAL "1")
SET(THISLIB ${THISLIB}D)
ENDIF()
IF( "${BIT_MODE}" EQUAL "64" )
SET(THISLIB ${THISLIB}_X64)
ENDIF()
ADD_LIBRARY(${THISLIB} STATIC ${LibSrc})
|
zzz-engine
|
zzzEngine/zAI/CMakeLists.txt
|
CMake
|
gpl3
| 232
|
#pragma once
namespace zzz{
template<typename T>
struct RTreeFunction
{
typedef RTreeFunction<T> *(*RTreeFuncGenerator)(void*);
virtual int operator()(const T *v)=0;
virtual void print()=0;
};
#define MAX_LEVEL 12
#define MIN_NELEMENT 1
}
|
zzz-engine
|
zzzEngine/zAI/zAI/RTree/RTreeFunction.hpp
|
C++
|
gpl3
| 263
|
#pragma once
#include "../common.hpp"
#include "RTreeFunction.hpp"
namespace zzz{
template <typename T>
struct RTreeNodeBase
{
typedef enum{NODE,LEAF} NODETYPE;
const NODETYPE type_;
RTreeNodeBase(const int level,NODETYPE type, typename RTreeFunction<T>::RTreeFuncGenerator funcgen)
:level_(level),type_(type),funcgen_(funcgen){}
virtual ~RTreeNodeBase(){}
virtual void GrowTrain(const T *v, const int tag)=0;
virtual void Train(const T *v, const int tag)=0;
virtual const double *Classify(const T *v) const =0;
virtual void ClearData(const int ntag)=0;
virtual void UpdateP()=0;
virtual void Print(string str)=0;
int level_;
typename RTreeFunction<T>::RTreeFuncGenerator funcgen_;
};
//Randomized Tree non-leaf node
template <typename T,int RTREE_NODE_SPLIT>
struct RTreeNode : public RTreeNodeBase<T>
{
RTreeNode(const int level,int ntag, typename RTreeFunction<T>::RTreeFuncGenerator funcgen):RTreeNodeBase(level,NODE,funcgen),ntag_(ntag)
{
Decide=funcgen_(NULL);
for (int i=0; i<RTREE_NODE_SPLIT; i++)
node_[i]=new RTreeLeaf<T,RTREE_NODE_SPLIT>(level_+1,ntag_,funcgen_);
}
~RTreeNode()
{
for (int i=0; i<RTREE_NODE_SPLIT; i++)
delete node_[i];
delete Decide;
}
void GrowTrain(const T *v, const int tag){node_[(*Decide)(v)]->GrowTrain(v,tag);}
void Train(const T *v, const int tag){node_[(*Decide)(v)]->Train(v,tag);}
const double *Classify(const T *v) const {return node_[(*Decide)(v)]->Classify(v);}
//grow
void Grow()
{
for (int i=0; i<RTREE_NODE_SPLIT; i++)
{
if (node_[i]->type_==NODE)
((RTreeNode<T,RTREE_NODE_SPLIT>*)node_[i])->Grow();
else //leaf
{
if (level_>=MAX_LEVEL-1) return;
RTreeNode<T,RTREE_NODE_SPLIT>* newnode=((RTreeLeaf<T,RTREE_NODE_SPLIT>*)node_[i])->Grow();
if (newnode==NULL) continue;
delete node_[i];
node_[i]=newnode;
((RTreeNode<T,RTREE_NODE_SPLIT>*)node_[i])->Grow();
}
}
}
//evaluate the partition
double Gain()
{
const double LOG2=log(2.0);
double E=0;
int nS=0;
for (int i=0; i<RTREE_NODE_SPLIT; i++)
{
RTreeLeaf<T,RTREE_NODE_SPLIT> *leaf=(RTreeLeaf<T,RTREE_NODE_SPLIT>*)node_[i];
leaf->UpdateP();
int nSi=leaf->allcount_;
if (nSi==0) return 0;
nS+=nSi;
double ESi=0;
for (int j=0; j<ntag_; j++)
if (leaf->p_[j]!=0) ESi-=leaf->p_[j]*log(leaf->p_[j]);
ESi/=LOG2;
E+=nSi*ESi;
}
return E/nS;
}
// clear data, after grow tree and before train real data
void ClearData(const int ntag){for (int i=0; i<RTREE_NODE_SPLIT; i++) node_[i]->ClearData(ntag);}
//update probability, before classify after train
void UpdateP(){for (int i=0; i<RTREE_NODE_SPLIT; i++) node_[i]->UpdateP();}
//for debug
virtual void Print(string str)
{
zout<<str;
zout<<"|-";
Decide->print();
zout<<endl;
for (int i=0; i<RTREE_NODE_SPLIT; i++)
node_[i]->Print(str+"| ");
}
RTreeNodeBase<T> *node_[RTREE_NODE_SPLIT];
int ntag_;
RTreeFunction<T> *Decide;
};
//Randomized Tree Leaf
template <typename T,int RTREE_NODE_SPLIT>
struct RTreeLeaf : public RTreeNodeBase<T>
{
RTreeLeaf(const int level, const int ntag, typename RTreeFunction<T>::RTreeFuncGenerator funcgen)
:RTreeNodeBase(level,LEAF,funcgen)
{
ntag_=ntag;
count_=new int[ntag];
memset(count_,0,sizeof(int)*ntag);
p_=new double[ntag];
}
~RTreeLeaf()
{
delete[] count_;
delete[] p_;
growtraindata_.clear();
}
void ClearData(const int ntag)
{
if (ntag!=ntag_)
{
delete[] count_;
delete[] p_;
count_=new int[ntag];
p_=new double[ntag];
}
growtraindata_.clear();
ntag_=ntag;
memset(count_,0,sizeof(int)*ntag);
}
void UpdateP()
{
availntag_=0;
allcount_=0;
for (int i=0; i<ntag_; i++)
if (count_[i]!=0)
{
availntag_++;
allcount_+=count_[i];
}
for (int i=0; i<ntag_; i++)
if (count_[i]!=0)
p_[i]=count_[i]/(double)allcount_;
else
p_[i]=0;
}
//////////////////////////////////////////////////////////////////////////
//train while remember the data, for growing
void GrowTrain(const T *v, const int tag)
{
Train(v,tag);
growtraindata_.push_back(make_pair(v,tag));
}
//this leaf grow to a node which hold new leaves
RTreeNode<T,RTREE_NODE_SPLIT> *Grow()
{
// too few to grow
if (availntag_<=MIN_NELEMENT) return NULL;
int n; //try time
if (level_==0) n=10;
else n=100*level_;
RTreeNode<T,RTREE_NODE_SPLIT> *newnode=NULL;
double MaxGain=0;
for (int i=0; i<n; i++)
{
//build new node
RTreeNode<T,RTREE_NODE_SPLIT> *thisnode=new RTreeNode<T,RTREE_NODE_SPLIT>(level_,ntag_,funcgen_);
int growtraindatasize=growtraindata_.size();
for (int j=0; j<growtraindatasize; j++) thisnode->GrowTrain(growtraindata_[j].first,growtraindata_[j].second);
double thisgain=thisnode->Gain();
if (thisgain>MaxGain)
{
MaxGain=thisgain;
delete newnode;
newnode=thisnode;
}
else
delete thisnode;
}
if (newnode) newnode->Grow();
return newnode;
}
//////////////////////////////////////////////////////////////////////////
//real train
void Train(const T *v, const int tag){count_[tag]++;}
const double *Classify(const T *v) const{return p_;}
virtual void Print(string str)
{
zout<<str;
zout<<"|-";
zout<<'['<<allcount_<<']'<<endl;
}
int *count_;
double *p_;
int allcount_;
int ntag_;
int availntag_;
vector<pair<const T*,int> > growtraindata_;
};
}
|
zzz-engine
|
zzzEngine/zAI/zAI/RTree/RTreeNodeLeaf.hpp
|
C++
|
gpl3
| 5,915
|
#pragma once
#include "RTreeNodeLeaf.hpp"
namespace zzz{
//Randomized Tree
//To classify T
template <typename T,int RTREE_NODE_SPLIT=2>
class RTree
{
public:
RTree(typename RTreeFunction<T>::RTreeFuncGenerator funcgen):ntag_(0),funcgen_(funcgen)
{
head_=new RTreeLeaf<T,RTREE_NODE_SPLIT>(0,0,funcgen_);
}
~RTree(void)
{
delete head_;
}
//train and classify
void GrowTrain(const T *v, const int tag){head_->GrowTrain(v,tag);}
void Grow()
{
head_->UpdateP();
RTreeNode<T,RTREE_NODE_SPLIT> *newnode=((RTreeLeaf<T,RTREE_NODE_SPLIT>*)head_)->Grow();
delete head_;
head_=newnode;
}
void ClearData(const int ntag){ntag_=ntag;head_->ClearData(ntag);}
void Train(const T *v, const int tag){head_->Train(v,tag);}
const double *Classify(const T *v) const {return head_->Classify(v);}
void UpdateP(){head_->UpdateP();}
//debug
void Print()
{
zout<<"|-\n";
head_->Print("| ");
}
//private:
RTreeNodeBase<T> *head_;
int ntag_;
int ntrained_;
int height_;
typename RTreeFunction<T>::RTreeFuncGenerator funcgen_;
};
//Randomized Multiple Tree structure
template <typename T,int RTREE_NODE_SPLIT=2>
class RTrees
{
public:
RTrees(typename RTreeFunction<T>::RTreeFuncGenerator funcgen):ntag_(0),ntree_(0),trees_(NULL),funcgen_(funcgen)
{
}
~RTrees()
{
for (int i=0; i<ntree_; i++)
delete trees_[i];
delete trees_;
}
void BuildTrees(const int ntree,vector<pair<const T*,int> > &traindata,const int trainntag)
{
ntag_=trainntag;
for (int i=0; i<ntree_; i++)
delete trees_[i];
delete trees_;
ntree_=ntree;
trees_=new RTree<T,RTREE_NODE_SPLIT>*[ntree_];
ntree_=ntree;
for (int i=0; i<ntree; i++)
{
zout<<"BuildTree: "<<i<<endl;
trees_[i]=new RTree<T,RTREE_NODE_SPLIT>(funcgen_);
trees_[i]->ClearData(trainntag);
for (size_t j=0; j<traindata.size(); j++)
trees_[i]->GrowTrain(traindata[j].first,traindata[j].second);
trees_[i]->Grow();
}
}
void ClearData(const int ntag)
{
ntag_=ntag;
for (int i=0; i<ntree_; i++)
trees_[i]->ClearData(ntag);
}
int Classify(const T *v, double *possibility) const
{
double *p=new double[ntag_];
memset(p,0,sizeof(double)*ntag_);
for (int i=0; i<ntree_; i++)
{
const double *thisp=trees_[i]->Classify(v);
for (int j=0; j<ntag_; j++) p[j]+=thisp[j];
}
double maxp=0;
int maxi=0;
for (int i=0; i<ntag_; i++)
{
if (p[i]>maxp)
{
maxp=p[i];
maxi=i;
}
}
*possibility=maxp;
delete[] p;
return maxi;
}
void Train(const T *v, const int tag)
{
for (int i=0; i<ntree_; i++)
trees_[i]->Train(v,tag);
}
void Train( vector<pair<const T*,int> > &traindata)
{
for (size_t i=0; i<traindata.size(); i++)
Train(traindata[i].first,traindata[i].second);
UpdateP();
}
void UpdateP()
{
for (int i=0; i<ntree_; i++)
trees_[i]->UpdateP();
}
void Print()
{
for (int i=0; i<ntree_; i++)
{
zout<<"Tree: "<<i<<endl;
trees_[i]->Print();
}
}
RTree<T,RTREE_NODE_SPLIT> **trees_;
int ntree_;
int ntag_;
typename RTreeFunction<T>::RTreeFuncGenerator funcgen_;
};
}
|
zzz-engine
|
zzzEngine/zAI/zAI/RTree/RTree.hpp
|
C++
|
gpl3
| 3,412
|
#pragma once
#include <zCoreConfig.hpp>
#ifdef ZZZ_DEBUG
#pragma comment(lib,"zAID.lib")
#else
#pragma comment(lib,"zAI.lib")
#endif
|
zzz-engine
|
zzzEngine/zAI/zAI/zAI.hpp
|
C++
|
gpl3
| 138
|
#pragma once
#include "SupervisedDimensionReduction.hpp"
namespace zzz {
template<zuint N, typename T>
class LDA : public SupervisedDimensionReduction<N,T>
{
public:
template<zuint N2>
void DimensionReduce(const vector<Vector<N,T> > &data, vector<Vector<N2,T> > &newdata)
{
newdata.clear();
}
private:
/// INFO: THIS FUNCTION IS NOT FINISHED, NEED TO GO THROUGH AGAIN
void DoTrain(const /*vector<Vector<N,T> >*/zMatrixBaseR<double> &data, const vector<int> &label)
{
vector<Vector<N,T> > means(label_count_, Vector<N,T>(0));
vector<int> count(label_count_,0);
// calculate mean for each label
for (zuint i=0; i<data.size(); i++) {
means[label[i]] += data[i];
count[label[i]] ++;
}
for (zuint i=0; i<label_count_; i++) {
means[i] /= count[i];
}
// calculate within class scatter matrix
zMatrix<double> Sw=Zeros(label_count_, label_count_);
for (zuint i=0; i<data.size(); i++) {
zVector<double> diff = Dress(data[i] - means[label[i]]);
Sw += diff * Trans(diff);
}
// calculate between class scatter matrix
zMatrix<double> Sb=Zeros(label_count_, label_count_);
Vector<N,T> means_mean = Mean(means);
for (zuint i=0; i<label_count_; i++) {
zVector<double> diff = Dress(means[i] - means_mean);
Sb += diff * Trans(diff) * count[i];
}
EigenVec=Invert(Sw) * Sb;
ZCHECK(EigenSym(EigenVec, EigenVal));
}
zMatrix<double> EigenVec, EigenVal;
};
}; // namespace zzz
|
zzz-engine
|
zzzEngine/zAI/zAI/LDA.hpp
|
C++
|
gpl3
| 1,550
|
#pragma once
namespace zzz {
template<zuint N, typename T>
class SupervisedDimensionReduction
{
public:
void Train(const zMatrixBaseR<double> &data, const vector<int> &label) {
// normalize label, make them 0, 1, 2,...
label_count_=0;
for (zuint i=0; i<label; i++) {
if (labelmap_.find(label[i])!=labelmap_.end()) {
// label already in label map
continue;
} else {
// add new normalized label in label map
labelmap_[label[i]]=label_count_++;
}
}
// assign new label
norlabels__.clear();
norlabels__.reserve(label.size());
for (zuint i=0; i<label.size(); i++) {
norlabels__[i]=labelmap_[label[i]];
}
// call real train function
DoTrain(data, norlabels__);
}
template<zuint N2>
void DimensionReduce(const vector<Vector<N,T> > &data, vector<Vector<N2,T> > &newdata)=0;
}
protected:
/// This should be implemented by derived class, can assume norlabel_ is continuous zero-based integers (0, 1, 2,..)
void DoTrain(const vector<Vector<N,T> > &data, const vector<int> &norlabel_)=0;
map<int, int> labelmap_;
vector<int> norlabels__;
int label_count_;
};
}; // namespace zzz
|
zzz-engine
|
zzzEngine/zAI/zAI/SupervisedDimensionReduction.hpp
|
C++
|
gpl3
| 1,236
|
SET(THISLIB zMatrix)
FILE(GLOB_RECURSE LibSrc *.cpp)
#MESSAGE(STATUS "files ${LibSrc}")
IF( "${DEBUG_MODE}" EQUAL "1")
SET(THISLIB ${THISLIB}D)
ENDIF()
IF( "${BIT_MODE}" EQUAL "64" )
SET(THISLIB ${THISLIB}_X64)
ENDIF()
ADD_LIBRARY(${THISLIB} STATIC ${LibSrc})
|
zzz-engine
|
zzzEngine/zMatrix/CMakeLists.txt
|
CMake
|
gpl3
| 272
|
#pragma once
#include "zMatrixBase.hpp"
//for mat1+mat2, two matricies
namespace zzz{
#define MATRIX_EXPRESSION(name,ope) \
template<typename T,class Major>\
class zMatrix##name##Expression : public zMatrixBaseR<T,Major>\
{\
public:\
explicit zMatrix##name##Expression(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)\
:zMatrixBaseR<T,Major>(mat1.rows_,mat1.cols_),Mat1_(mat1),Mat2_(mat2)\
{\
ZCHECK_EQ(mat1.rows_, mat2.rows_); \
ZCHECK_EQ(mat1.cols_, mat2.cols_); \
}\
using zMatrixBaseR<T,Major>::operator(); \
const T operator()(zuint r, zuint c) const\
{\
CheckRange(r, c); \
return (Mat1_(r,c) ope Mat2_(r,c)); \
}\
public:\
const zMatrixBaseR<T,Major> &Mat1_, &Mat2_; \
};
MATRIX_EXPRESSION(Plus,+)
MATRIX_EXPRESSION(Minus,-)
MATRIX_EXPRESSION(Times,*)
MATRIX_EXPRESSION(DividedBy,/)
template<typename T,class Major>
const zMatrixPlusExpression<T,Major> operator+(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return zMatrixPlusExpression<T,Major>(mat1,mat2);}
template<typename T,class Major>
const zMatrixMinusExpression<T,Major> operator-(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return zMatrixMinusExpression<T,Major>(mat1,mat2);}
template<typename T,class Major>
const zMatrixTimesExpression<T,Major> DotTimes(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return zMatrixTimesExpression<T,Major>(mat1,mat2);}
template<typename T,class Major>
const zMatrixDividedByExpression<T,Major> DotDividedBy(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return zMatrixDividedByExpression<T,Major>(mat1,mat2);}
MATRIX_EXPRESSION(EQ,==)
MATRIX_EXPRESSION(NE,!=)
MATRIX_EXPRESSION(LT,<)
MATRIX_EXPRESSION(LE,<=)
MATRIX_EXPRESSION(GT,>)
MATRIX_EXPRESSION(GE,>=)
template<typename T,class Major>
const zMatrixEQExpression<T,Major> operator==(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return zMatrixEQExpression<T,Major>(mat1,mat2);}
template<typename T,class Major>
const zMatrixNEExpression<T,Major> operator!=(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return zMatrixNEExpression<T,Major>(mat1,mat2);}
template<typename T,class Major>
const zMatrixLTExpression<T,Major> operator<(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return zMatrixLTExpression<T,Major>(mat1,mat2);}
template<typename T,class Major>
const zMatrixLEExpression<T,Major> operator<=(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return zMatrixLEExpression<T,Major>(mat1,mat2);}
template<typename T,class Major>
const zMatrixGTExpression<T,Major> operator>(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return zMatrixGTExpression<T,Major>(mat1,mat2);}
template<typename T,class Major>
const zMatrixGEExpression<T,Major> operator>=(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return zMatrixGEExpression<T,Major>(mat1,mat2);}
template<typename T,class Major>
class zMatrixProductExpression : public zMatrixBaseR<T,Major>
{
public:
explicit zMatrixProductExpression(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
:zMatrixBaseR<T,Major>(mat1.rows_,mat2.cols_),Mat1_(mat1),Mat2_(mat2),commonLength_(mat1.cols_)
{
ZCHECK_EQ(mat1.cols_, mat2.rows_);
}
using zMatrixBaseR<T,Major>::operator();
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
T v=0;
for (zuint i=0; i<commonLength_; i++)
v+=Mat1_(r,i)*Mat2_(i,c);
return v;
}
public:
const zMatrixBaseR<T,Major> &Mat1_, &Mat2_;
const zuint commonLength_;
};
template<typename T,class Major>
const zMatrixProductExpression<T,Major> operator*(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return zMatrixProductExpression<T,Major>(mat1,mat2);}
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zExpressionM.hpp
|
C++
|
gpl3
| 4,002
|
#pragma once
#include "zMatrixBase.hpp"
namespace zzz{
//func(v,mat)
#define CONSTANT_LEFT_EXPRESSIONC(name,func) \
template<typename T,class Major>\
class zFunctionLeft##name##ExpressionC : public zMatrixBaseR<T,Major>\
{\
public:\
explicit zFunctionLeft##name##ExpressionC(const T &v, const zMatrixBaseR<T,Major>& mat)\
:zMatrixBaseR<T,Major>(mat.rows_,mat.cols_),Mat_(mat),v_(v){}\
using zMatrixBaseR<T,Major>::operator(); \
const T operator()(zuint r, zuint c) const\
{\
CheckRange(r, c); \
return func(v_, Mat_(r,c)); \
}\
private:\
const T &v_; \
const zMatrixBaseR<T,Major> &Mat_; \
};
CONSTANT_LEFT_EXPRESSIONC(Pow,Pow<T>)
template<typename T,class Major>
const zFunctionLeftPowExpressionC<T,Major> operator^(const T &value, const zMatrixBaseR<T,Major> &mat)
{return zFunctionLeftPowExpressionC<T,Major>(value,mat);};
//func(mat,c)
#define CONSTANT_RIGHT_EXPRESSIONC(name,func) \
template<typename T,class Major>\
class zFunctionRight##name##ExpressionC : public zMatrixBaseR<T,Major>\
{\
public:\
explicit zFunctionRight##name##ExpressionC(const zMatrixBaseR<T,Major>& mat,const T &v)\
:zMatrixBaseR<T,Major>(mat.rows_,mat.cols_),Mat_(mat),v_(v){}\
using zMatrixBaseR<T,Major>::operator(); \
const T operator()(zuint r, zuint c) const\
{\
CheckRange(r, c); \
return func(Mat_(r,c),v_); \
}\
private:\
const T &v_; \
const zMatrixBaseR<T,Major> &Mat_; \
}; \
CONSTANT_RIGHT_EXPRESSIONC(Pow,Pow<T>)
template<typename T,class Major>
const zFunctionRightPowExpressionC<T,Major> operator^(const zMatrixBaseR<T,Major> &mat,const T &value)
{return zFunctionRightPowExpressionC<T,Major>(mat,value);};
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zExpressionFunctionC.hpp
|
C++
|
gpl3
| 1,712
|
#pragma once
#include <Math/Complex.hpp>
#include "zMatrixBase.hpp"
namespace zzz{
//specific for complex
#define COMPLEX_EXPRESSION(name,ope) \
template<typename T,class Major>\
class zComplex##name##Expression : public zMatrixBaseR<Complex<T>,Major>\
{\
public:\
explicit zComplex##name##Expression(const zMatrixBaseR<Complex<T>,Major>& mat)\
:zMatrixBaseR<Complex<T>,Major>(mat.rows_,mat.cols_),Mat_(mat){}\
using zMatrixBaseR<Complex<T>,Major>::operator(); \
const Complex<T> operator()(zuint r, zuint c) const\
{\
CheckRange(r, c); \
return ope(Mat_(r,c)); \
}\
private:\
const zMatrixBaseR<Complex<T>,Major> &Mat_; \
}; \
template<typename T,class Major>\
const zComplex##name##Expression<T,Major> name(const zMatrixBaseR<Complex<T>,Major> &mat)\
{\
return zComplex##name##Expression<T,Major>(mat); \
}
template<typename T>
inline Complex<T> conj(const Complex<T> &v)
{
return Complex<T>(v.Real(),-v.Imag());
}
COMPLEX_EXPRESSION(Conj,conj)
//complex to real
#define COMPLEX2_EXPRESSION(name,ope) \
template<typename T,class Major>\
class zComplex##name##Expression : public zMatrixBaseR<T,Major>\
{\
public:\
explicit zComplex##name##Expression(const zMatrixBaseR<Complex<T>,Major>& mat)\
:zMatrixBaseR<T,Major>(mat.rows_,mat.cols_),Mat_(mat){}\
using zMatrixBaseR<Complex<T>,Major>::operator(); \
const T operator()(zuint r, zuint c) const\
{\
CheckRange(r, c); \
return ope(Mat_(r,c)); \
}\
private:\
const zMatrixBaseR<Complex<T>,Major> &Mat_; \
}; \
template<typename T, class Major>\
const zComplex##name##Expression<T,Major> name(const zMatrixBaseR<Complex<T>,Major> &mat)\
{\
return zComplex##name##Expression<T,Major>(mat); \
}
template<typename T>
inline T real(const Complex<T> &v)
{
return v.Real();
}
template<typename T>
inline T imag(const Complex<T> &v)
{
return v.Imag();
}
COMPLEX_EXPRESSION(Real,real)
COMPLEX_EXPRESSION(Imag,imag)
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zExpressionComplex.hpp
|
C++
|
gpl3
| 1,998
|
#pragma once
#include "zMatrixBase.hpp"
namespace zzz{
//func(mat,mat)
#define CONSTANT_EXPRESSIONM(name,func) \
template<typename T,class Major>\
class zFunction##name##ExpressionM : public zMatrixBaseR<T,Major>\
{\
public:\
explicit zFunction##name##ExpressionM(const zMatrixBaseR<T,Major>& mat1, const zMatrixBaseR<T,Major>& mat2)\
:zMatrixBaseR<T,Major>(mat1.rows_,mat1.cols_),Mat1_(mat1),Mat2_(mat2){assert(Mat1_.rows_==Mat2_.rows_ && Mat1_.cols_==Mat2_.cols_);}\
using zMatrixBaseR<T,Major>::operator(); \
const T operator()(zuint r, zuint c) const\
{\
CheckRange(r, c); \
return func(Mat1_(r,c), Mat2_(r,c)); \
}\
private:\
const zMatrixBaseR<T,Major> &Mat1_, &Mat2_; \
}; \
CONSTANT_EXPRESSIONM(Pow,Pow<T>)
template<typename T,class Major>
const zFunctionPowExpressionM<T,Major> operator^(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return zFunctionPowExpressionM<T,Major>(mat1,mat2);};
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zExpressionFunctionM.hpp
|
C++
|
gpl3
| 977
|
#pragma once
#include <Utility/Log.hpp>
//for base class of all zMatrix classes
//can choose row major or column major, column major is default
//#include "zSubMatrix.hpp"
namespace zzz{
class EndlessArray;
template<typename T, class Major>
class zSubMatrixR;
template<typename T, class Major>
class zSubMatrixW;
class zColMajor
{
public:
static const zuint ToIndex(const zuint r,const zuint c, const zuint rows, const zuint cols)
{return c*rows+r;}
static void ToIndex(const zuint idx, const zuint rows, const zuint cols, zuint &r, zuint &c)
{r=idx%rows; c=zuint(idx/rows);}
static const int Dim_=1;
};
class zRowMajor
{
public:
static const zuint ToIndex(zuint r,zuint c,zuint rows, zuint cols)
{return r*cols+c;}
static void ToIndex(const zuint idx, const zuint rows, const zuint cols, zuint &r, zuint &c)
{c=idx%cols; r=zuint(idx/cols);}
static const int Dim_=0;
};
//Readable Matrix
template<typename T, class Major>
class zMatrixBaseR
{
public:
// constructor
zMatrixBaseR(zuint r, zuint c):rows_(r),cols_(c){}
// Check range
void CheckRange(zuint r, zuint c) const {
ZRCHECK_LT(r, rows_);
ZRCHECK_LT(c, cols_);
}
void CheckRange(zuint idx) const {
ZRCHECK_LT(idx, size());
}
// const operator() cannot be &, since may return some constant value calculated from input.
virtual const T operator()(zuint r, zuint c) const=0;
virtual const T operator[](zuint idx) const //might override to get faster
{
zuint r, c;
ToIndex(idx, r, c);
return (*this)(r,c);
}
// Submatrix
zSubMatrixR<T,Major> operator()(const EndlessArray &r, const EndlessArray &c) const
{
return zSubMatrixR<T,Major>(*this,r,c);
}
zSubMatrixR<T,Major> operator()(int r, const EndlessArray &c) const
{
return zSubMatrixR<T,Major>(*this,r,c);
}
zSubMatrixR<T,Major> operator()(const EndlessArray &r, int c) const
{
return zSubMatrixR<T,Major>(*this,r,c);
}
zSubMatrixR<T,Major> operator()(const zMatrixBaseR<int,Major> &r, const zMatrixBaseR<int,Major> &c) const
{
return zSubMatrixR<T,Major>(*this,r,c);
}
zSubMatrixR<T,Major> operator()(int r, const zMatrixBaseR<int,Major> &c) const
{
return zSubMatrixR<T,Major>(*this,r,c);
}
zSubMatrixR<T,Major> operator()(const zMatrixBaseR<int,Major> &r, int c) const
{
return zSubMatrixR<T,Major>(*this,r,c);
}
zSubMatrixR<T,Major> operator()(const EndlessArray &r, const zMatrixBaseR<int,Major> &c) const
{
return zSubMatrixR<T,Major>(*this,r,c);
}
zSubMatrixR<T,Major> operator()(const zMatrixBaseR<int,Major> &r, const EndlessArray &c) const
{
return zSubMatrixR<T,Major>(*this,r,c);
}
operator bool() const
{
for (zuint r=0; r<rows_; r++) for (zuint c=0; c<cols_; c++)
if (!((*this)(r,c))) return false;
return true;
}
// According to Matlab, == is itemwise ==
//operator==
// bool operator==(const zMatrixBaseR<T,Major> &other) const {
// if (rows_!=other.rows_ || cols_!=other.cols_) return false;
// for (zuint r=0; r<rows_; r++) for (zuint c=0; c<cols_; c++)
// if ((*this)(r,c) != other(r,c)) return false;
// return true;
// }
//get size
zuint Size(zuint i) const {
ZCHECK(i==0 || i==1)<<"Size() accept only 0 or 1";
if (i==0) return rows_;
else if (i==1) return cols_;
return -1;
}
zuint Rows() const {return rows_;}
zuint Cols() const {return cols_;}
zsize size() const {
return rows_ * cols_;
}
//IO
friend inline ostream& operator<<(ostream& os,const zMatrixBaseR<T,Major> &me) {
for (zuint r=0; r<me.rows_; r++) {
for (zuint c=0; c<me.cols_; c++)
os << me(r,c) << ' ';
if (r!=me.rows_-1) os << '\n';
}
return os;
}
//the only member variable
zuint rows_,cols_;
protected:
inline const zuint ToIndex(const zuint r, const zuint c) const {
return Major::ToIndex(r,c,zMatrixBaseR<T,Major>::rows_,zMatrixBaseR<T,Major>::cols_);
}
inline void ToIndex(const zuint idx, zuint &r, zuint &c) const {
Major::ToIndex(idx,zMatrixBaseR<T,Major>::rows_,zMatrixBaseR<T,Major>::cols_,r,c);
}
};
//Writable Matrix is also readable
template<typename T, class Major>
class zMatrixBaseW : public zMatrixBaseR<T,Major>
{
public:
zMatrixBaseW(zuint r,zuint c):zMatrixBaseR<T,Major>(r,c){}
// operator()
virtual T& operator()(zuint r, zuint c)=0;
// This function can be over ride to get faster performance
virtual T& operator[](zuint idx)
{
zuint r, c;
ToIndex(idx, r, c);
return (*this)(r,c);
}
virtual const zMatrixBaseW<T,Major>& operator=(const zMatrixBaseR<T,Major> &other) {
ZCHECK_EQ(rows_, other.rows_);
ZCHECK_EQ(cols_, other.cols_);
for (zuint i=0; i<rows_; i++) for (zuint j=0; j<cols_; j++)
(*this)(i,j)=other(i,j);
return *this;
}
// submatrix
zSubMatrixW<T,Major> operator()(const EndlessArray &r, const EndlessArray &c)
{
return zSubMatrixW<T,Major>(*this,r,c);
}
zSubMatrixW<T,Major> operator()(int r, const EndlessArray &c)
{
return zSubMatrixW<T,Major>(*this,r,c);
}
zSubMatrixW<T,Major> operator()(const EndlessArray &r, int c)
{
return zSubMatrixW<T,Major>(*this,r,c);
}
zSubMatrixW<T,Major> operator()(const zMatrixBaseR<int,Major> &r, const zMatrixBaseR<int,Major> &c)
{
return zSubMatrixW<T,Major>(*this,r,c);
}
zSubMatrixW<T,Major> operator()(int r, const zMatrixBaseR<int,Major> &c)
{
return zSubMatrixW<T,Major>(*this,r,c);
}
zSubMatrixW<T,Major> operator()(const zMatrixBaseR<int,Major> &r, int c)
{
return zSubMatrixW<T,Major>(*this,r,c);
}
zSubMatrixW<T,Major> operator()(const EndlessArray &r, const zMatrixBaseR<int,Major> &c)
{
return zSubMatrixW<T,Major>(*this,r,c);
}
zSubMatrixW<T,Major> operator()(const zMatrixBaseR<int,Major> &r, const EndlessArray &c)
{
return zSubMatrixW<T,Major>(*this,r,c);
}
//IO
friend inline istream& operator>>(istream& is,zMatrixBaseW<T,Major> &me) {
for (zuint r=0; r<me.rows_; r++) for (zuint c=0; c<me.cols_; c++)
is >> me(r,c);
return is;
}
using zMatrixBaseR<T,Major>::operator();
using zMatrixBaseR<T,Major>::ToIndex;
using zMatrixBaseR<T,Major>::CheckRange;
using zMatrixBaseR<T,Major>::rows_;
using zMatrixBaseR<T,Major>::cols_;
};
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMatrixBase.hpp
|
C++
|
gpl3
| 6,495
|
#pragma once
#include "zMatrix.hpp"
//just a special derivation of zmatrix(1,n) or zmatrix(n,1), column major is default
namespace zzz{
template<typename T, typename Major=zColMajor>
class zVector : public zMatrix<T,Major>
{
public:
//constructor
explicit zVector(){}
explicit zVector(zuint l):zMatrix<T,Major>(Major::Dim_==0?1:l, Major::Dim_==0?l:1){}
zVector(const zVector<T,Major> &other)
{
*this=other;
}
explicit zVector(const zMatrixBaseR<T,Major> &other)
{
*this=other;
}
//operator()
using zMatrix<T,Major>::operator();
const T operator()(zuint l) const
{
return zMatrix<T,Major>::operator()(Major::Dim_==0?0:l,Major::Dim_==0?l:0);
}
T& operator()(zuint l)
{
return zMatrix<T,Major>::operator()(Major::Dim_==0?0:l,Major::Dim_==0?l:0);
}
zSubMatrixW<T,Major> operator()(const zVConstantContinuousVector<int,Major> &r)
{
if (Major::Dim_==0)
return zMatrix<T,Major>::operator()(Colon(0,0),r);
else
return zMatrix<T,Major>::operator()(r,Colon(0,0));
}
zSubMatrixW<T,Major> operator()(const zMatrixBaseR<int,Major> &r)
{
if (Major::Dim_==0)
return zMatrix<T,Major>::operator()(Colon(0,0),r);
else
return zMatrix<T,Major>::operator()(r,Colon(0,0));
}
//operator=
const zMatrixBaseW<T,Major>& operator=(const zVector<T,Major>& other)
{
return zMatrix<T,Major>::operator =((const zMatrix<T,Major>&)other);
}
const zMatrixBaseW<T,Major>& operator=(const zMatrixBaseR<T,Major>& other)
{
return zMatrix<T,Major>::operator =(other);
}
};
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zVector.hpp
|
C++
|
gpl3
| 1,624
|
#pragma once
namespace zzz{
/////////////////////////////////////////////////
//GradientX
template<typename T,class Major>
class zSpecialGradxExpression : public zMatrixBaseR<T,Major>
{
using zMatrixBaseR<T,Major>::rows_;
using zMatrixBaseR<T,Major>::cols_;
public:
explicit zSpecialGradxExpression(const zMatrixBaseR<T,Major>& mat)
:zMatrixBaseR<T,Major>(mat.rows_,mat.cols_),Mat_(mat){ZCHECK_GE(cols_, 2);}
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
if (c==0) return Mat_(r,c+1)-Mat_(r,c);
if (c==cols_-1) return Mat_(r,c)-Mat_(r,c-1);
return (Mat_(r,c+1)-Mat_(r,c-1))/2;
}
private:
const zMatrixBaseR<T,Major> &Mat_;
};
template<typename T,class Major>
const zSpecialGradxExpression<T,Major> GradientX(const zMatrixBaseR<T,Major> &mat)
{
return zSpecialGradxExpression<T,Major>(mat);
}
/////////////////////////////////////////////////
//GradientY
template<typename T,class Major>
class zSpecialGradyExpression : public zMatrixBaseR<T,Major>
{
using zMatrixBaseR<T,Major>::rows_;
using zMatrixBaseR<T,Major>::cols_;
public:
explicit zSpecialGradyExpression(const zMatrixBaseR<T,Major>& mat)
:zMatrixBaseR<T,Major>(mat.rows_,mat.cols_),Mat_(mat){ZCHECK_GE(rows_, 2);}
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
if (r==0) return Mat_(r+1,c)-Mat_(r,c);
if (r==rows_-1) return Mat_(r,c)-Mat_(r-1,c);
return (Mat_(r+1,c)-Mat_(r-1,c))/2;
}
private:
const zMatrixBaseR<T,Major> &Mat_;
};
template<typename T,class Major>
const zSpecialGradyExpression<T,Major> GradientY(const zMatrixBaseR<T,Major> &mat)
{
return zSpecialGradyExpression<T,Major>(mat);
}
//////////////////////////////////////////////////
//Lower triangle
template<typename T,class Major>
class zSpecialTrilExpression : public zMatrixBaseR<T,Major>
{
using zMatrixBaseR<T,Major>::rows_;
using zMatrixBaseR<T,Major>::cols_;
public:
explicit zSpecialTrilExpression(const zMatrixBaseR<T,Major>& mat)
:zMatrixBaseR<T,Major>(mat.rows_,mat.cols_),Mat_(mat){ZCHECK_EQ(rows_, cols_);}
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
if (c > r) return 0;
return Mat_(r, c);
}
private:
const zMatrixBaseR<T,Major> &Mat_;
};
template<typename T,class Major>
const zSpecialTrilExpression<T,Major> Tril(const zMatrixBaseR<T,Major> &mat)
{
return zSpecialTrilExpression<T,Major>(mat);
}
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zExpressionSpecial.hpp
|
C++
|
gpl3
| 2,479
|
#pragma once
#include <LibraryConfig.hpp>
//use lapack to do high level math
#include "zMatrix.hpp"
namespace zzz{
bool LUFactorization(zMatrix<double,zColMajor> &mat, zMatrix<long,zColMajor> &IPIV, long *info=NULL);
bool CholeskyFactorization(zMatrix<double,zColMajor> &A, long *info=NULL);
// ATTENTION: original value will not be kept even if failed
bool Invert(zMatrix<double,zColMajor> &mat, long *info=NULL);
// Matlab style interface
inline zMatrix<double,zColMajor> Inv(const zMatrixBaseR<double,zColMajor> &mat, long *info=NULL) {
zMatrix<double,zColMajor> x(mat);
if (Invert(x, info))
return x;
else
return zMatrix<double,zColMajor>();
}
bool SVD(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &U, zMatrix<double,zColMajor> &S, zMatrix<double,zColMajor> &VT, long *info=NULL);
bool EigenSym(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &e, long *info=NULL);
double Det(zMatrix<double,zColMajor> &A);
// return eigen vector are in each column corresponding to eigen value order
bool EigRight(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &eigenVector, zMatrix<double,zColMajor> &eigenValueReal, zMatrix<double,zColMajor> &eigenValueImag, long *info=NULL);
bool SolveLinearLeastSquare(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &B_X, long *info=NULL);
bool SolveLinearLeastSquare2(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &B_X, long *info=NULL);
bool SolveLinear(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &B_X, long *info=NULL);
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMatrixLapack.hpp
|
C++
|
gpl3
| 1,577
|
#pragma once
#include "zMatrixBase.hpp"
namespace zzz{
template<typename T,class Major>
class HCombineMatrixR : public zMatrixBaseR<T,Major>
{
public:
explicit HCombineMatrixR(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
:mat1_(mat1),mat2_(mat2),zMatrixBaseR<T,Major>(mat1.rows_,mat1.cols_+mat2.cols_)
{ZCHECK_EQ(mat1.rows_, mat2.rows_);}
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
if (c<mat1_.cols_) return mat1_(r,c);
else return mat2_(r,c-mat1_.cols_);
}
private:
const zMatrixBaseR<T,Major> &mat1_, &mat2_;
};
template<typename T,class Major>
const HCombineMatrixR<T,Major> operator,(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return HCombineMatrixR<T,Major>(mat1,mat2);}
template<typename T,class Major>
class VCombineMatrixR : public zMatrixBaseR<T,Major>
{
public:
explicit VCombineMatrixR(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
:mat1_(mat1),mat2_(mat2),zMatrixBaseR<T,Major>(mat1.rows_+mat2.rows_,mat1.cols_)
{ZCHECK_EQ(mat1.cols_, mat2.cols_);}
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
if (r<mat1_.rows_) return mat1_(r,c);
else return mat2_(r-mat1_.rows_,c);
}
private:
const zMatrixBaseR<T,Major> &mat1_, &mat2_;
};
template<typename T,class Major>
const VCombineMatrixR<T,Major> operator%(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{return VCombineMatrixR<T,Major>(mat1,mat2);}
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMatrixCombine.hpp
|
C++
|
gpl3
| 1,553
|
#pragma once
#include "zMatrixBase.hpp"
//for mat+v or v+mat, one matrix and one scalar
namespace zzz{
///////////////////////////////////////////////////
//Left
#define CONSTANT_LEFT_EXPRESSION(name,ope) \
template<typename T, class Major>\
class zConstantLeft##name##Expression : public zMatrixBaseR<T,Major>\
{\
public:\
explicit zConstantLeft##name##Expression(const zMatrixBaseR<T,Major>& mat, T v)\
:zMatrixBaseR<T,Major>(mat.rows_,mat.cols_),Mat_(mat),V_(v){}\
const T operator()(zuint r, zuint c) const\
{\
CheckRange(r, c); \
return Mat_(r,c) ope V_; \
}\
public:\
const zMatrixBaseR<T,Major> &Mat_; \
const T V_; \
}; \
template<typename T, class Major>\
const zConstantLeft##name##Expression<T,Major> operator ope(const zMatrixBaseR<T,Major>& mat, T v)\
{return zConstantLeft##name##Expression<T,Major>(mat,v);}
CONSTANT_LEFT_EXPRESSION(Plus,+)
CONSTANT_LEFT_EXPRESSION(Minus,-)
CONSTANT_LEFT_EXPRESSION(Times,*)
CONSTANT_LEFT_EXPRESSION(DividedBy,/)
CONSTANT_LEFT_EXPRESSION(EQ,==)
CONSTANT_LEFT_EXPRESSION(NE,!=)
CONSTANT_LEFT_EXPRESSION(LT,<)
CONSTANT_LEFT_EXPRESSION(LE,<=)
CONSTANT_LEFT_EXPRESSION(GT,>)
CONSTANT_LEFT_EXPRESSION(GE,>=)
///////////////////////////////////////////////////
//Right
#define CONSTANT_RIGHT_EXPRESSION(name,ope) \
template<typename T,class Major>\
class zConstantRight##name##Expression : public zMatrixBaseR<T,Major>\
{\
public:\
explicit zConstantRight##name##Expression(const zMatrixBaseR<T,Major>& mat, T v)\
:zMatrixBaseR<T,Major>(mat.rows_,mat.cols_),Mat_(mat),V_(v){}\
using zMatrixBaseR<T,Major>::operator(); \
const T operator()(zuint r, zuint c) const\
{\
CheckRange(r, c); \
return V_ ope Mat_(r,c); \
}\
public:\
const zMatrixBaseR<T,Major> &Mat_; \
const T V_; \
}; \
template<typename T,class Major>\
const zConstantRight##name##Expression<T,Major> operator ope(T v, const zMatrixBaseR<T,Major>& mat)\
{return zConstantRight##name##Expression<T,Major>(mat,v);}
CONSTANT_RIGHT_EXPRESSION(Plus,+)
CONSTANT_RIGHT_EXPRESSION(Minus,-)
CONSTANT_RIGHT_EXPRESSION(Times,*)
CONSTANT_RIGHT_EXPRESSION(DividedBy,/)
CONSTANT_RIGHT_EXPRESSION(EQ,==)
CONSTANT_RIGHT_EXPRESSION(NE,!=)
CONSTANT_RIGHT_EXPRESSION(LT,<)
CONSTANT_RIGHT_EXPRESSION(LE,<=)
CONSTANT_RIGHT_EXPRESSION(GT,>)
CONSTANT_RIGHT_EXPRESSION(GE,>=)
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zExpressionC.hpp
|
C++
|
gpl3
| 2,390
|
#pragma once
#include "zMatrixBase.hpp"
// for Reshape(mat,row,col)
namespace zzz{
template<typename T,class Major>
class zFunctionReshapeR : public zMatrixBaseR<T,Major>
{
public:
explicit zFunctionReshapeR(const zMatrixBaseR<T,Major>& mat, zuint row, zuint col)
:zMatrixBaseR<T,Major>(row,col),Mat_(mat){ZCHECK_EQ(row * col, mat.rows_ * mat.cols_);}
const T operator()(zuint r, zuint c) const {
CheckRange(r, c);
return Mat_[ToIndex(r,c)];
}
using zMatrixBaseR<T,Major>::ToIndex;
private:
const zMatrixBaseR<T,Major> &Mat_;
};
template<typename T,class Major>
class zFunctionReshapeW : public zMatrixBaseW<T,Major>
{
public:
explicit zFunctionReshapeW(zMatrixBaseW<T,Major>& mat, zuint row, zuint col)
:zMatrixBaseW<T,Major>(row,col),Mat_(mat){assert(row*col==mat.rows_*mat.cols_);}
const T operator()(zuint r, zuint c) const {
CheckRange(r, c);
return Mat_[ToIndex(r,c)];
}
T& operator()(zuint r, zuint c) {
CheckRange(r, c);
return Mat_[ToIndex(r,c)];
}
// using zMatrixBaseW<T,Major>::operator=;
const zMatrixBaseW<T,Major>& operator=(const zMatrixBaseR<T,Major> &other)
{
return zMatrixBaseW<T,Major>::operator =(other);
}
using zMatrixBaseR<T,Major>::ToIndex;
private:
zMatrixBaseW<T,Major> &Mat_;
};
template<typename T,class Major>
const zFunctionReshapeR<T,Major> Reshape(const zMatrixBaseR<T,Major> &mat, zuint row, zuint col)
{
return zFunctionReshapeR<T,Major>(mat,row,col);
}
template<typename T,class Major>
zFunctionReshapeW<T,Major> Reshape(zMatrixBaseW<T,Major> &mat, zuint row, zuint col)
{
return zFunctionReshapeW<T,Major>(mat,row,col);
}
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMatrixReshape.hpp
|
C++
|
gpl3
| 1,695
|
#pragma once
#include "zMatrixBase.hpp"
//for f(mat)
namespace zzz{
#define CONSTANT_EXPRESSION(name,ope) \
template<typename T,class Major>\
class zFunction##name##Expression : public zMatrixBaseR<T,Major>\
{\
public:\
explicit zFunction##name##Expression(const zMatrixBaseR<T,Major>& mat)\
:zMatrixBaseR<T,Major>(mat.rows_,mat.cols_),Mat_(mat){}\
const T operator()(zuint r, zuint c) const\
{\
CheckRange(r, c); \
return ope(Mat_(r,c)); \
}\
private:\
const zMatrixBaseR<T,Major> &Mat_; \
}; \
template<typename T, class Major>\
const zFunction##name##Expression<T,Major> name(const zMatrixBaseR<T,Major> &mat)\
{\
return zFunction##name##Expression<T,Major>(mat); \
}
CONSTANT_EXPRESSION(Sin,sin)
CONSTANT_EXPRESSION(Cos,cos)
CONSTANT_EXPRESSION(Tan,tan)
CONSTANT_EXPRESSION(Pos,+)
CONSTANT_EXPRESSION(Neg,-)
template<typename T,class Major>
const zFunctionPosExpression<T,Major> operator+(const zMatrixBaseR<T,Major> &mat)
{
return zFunctionPosExpression<T,Major>(mat);
}
template<typename T,class Major>
const zFunctionNegExpression<T,Major> operator-(const zMatrixBaseR<T,Major> &mat)
{
return zFunctionNegExpression<T,Major>(mat);
}
template<typename T, class Major>
T Trace(const zMatrixBaseR<T,Major> &mat)
{
ZCHECK_EQ(mat.rows_, mat.cols_);
T t=0;
for (zuint i=0; i<mat.rows_; i++) t+=mat(i,i);
return t;
}
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zExpressionFunction.hpp
|
C++
|
gpl3
| 1,413
|
#pragma once
// Since there are many inter-reference inside these files,
// it is better to include this file when use zMatrix.
#include "zMatrixBase.hpp"
#include "zSubMatrix.hpp"
#include "zMatrix.hpp"
#include "zExpressionFunctionC.hpp"
#include "zExpressionFunctionM.hpp"
#include "zExpressionC.hpp"
#include "zExpressionFunction.hpp"
#include "zExpressionM.hpp"
#include "zExpressionComplex.hpp"
#include "zExpressionSpecial.hpp"
#include "zMatrixConstant.hpp"
#include "zMatrixOperation.hpp"
#include "zVector.hpp"
#include "zMatrixDress.hpp"
#include "zMatrixCombine.hpp"
#include "zMatrixCast.hpp"
#include "zMatrixReshape.hpp"
#include "zMatrixLapack.hpp"
#include "zMatrixFunction.hpp"
#include "zSparseMatrix.hpp"
#ifdef ZZZ_DYNAMIC
#ifdef _DEBUG
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"zMatrixdllD.lib")
#else
#pragma comment(lib,"zMatrixdllD_x64.lib")
#endif // ZZZ_OS_WIN64
#else
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"zMatrixdll.lib")
#else
#pragma comment(lib,"zMatrixdll_x64.lib")
#endif // ZZZ_OS_WIN64
#endif
#else
#ifdef _DEBUG
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"zMatrixD.lib")
#else
#pragma comment(lib,"zMatrixD_x64.lib")
#endif // ZZZ_OS_WIN64
#else
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"zMatrix.lib")
#else
#pragma comment(lib,"zMatrix_x64.lib")
#endif // ZZZ_OS_WIN64
#endif
#endif
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMat.hpp
|
C++
|
gpl3
| 1,489
|
#pragma once
#include "zMatrixBase.hpp"
//for constant matrix like ones and zeros
namespace zzz{
template<typename T,class Major>
class zConstantMatrix : public zMatrixBaseR<T,Major> //should not matter if rowmajor or colmajor
{
public:
//constructor
zConstantMatrix(zuint r, zuint c, T v):zMatrixBaseR<T,Major>(r,c),V_(v){}
//operator()
using zMatrixBaseR<T,Major>::operator();
const T operator()(zuint r, zuint c) const {
CheckRange(r, c);
return V_;
}
private:
const T V_;
};
template<typename T>
inline const zConstantMatrix<T,zColMajor> Ones(zuint r, zuint c, const T& v=1) {
return zConstantMatrix<T,zColMajor>(r,c,v);
}
inline const zConstantMatrix<double,zColMajor> Onesd(zuint r, zuint c, const double& v=1) {
return zConstantMatrix<double,zColMajor>(r,c,v);
}
inline const zConstantMatrix<float,zColMajor> Onesf(zuint r, zuint c, const float& v=1) {
return zConstantMatrix<float,zColMajor>(r,c,v);
}
template<typename T>
inline const zConstantMatrix<T,zColMajor> Zeros(zuint r, zuint c) {
return zConstantMatrix<T,zColMajor>(r,c,0);
}
inline const zConstantMatrix<double,zColMajor> Zerosd(zuint r, zuint c) {
return zConstantMatrix<double,zColMajor>(r,c,0);
}
inline const zConstantMatrix<float,zColMajor> Zerosf(zuint r, zuint c) {
return zConstantMatrix<float,zColMajor>(r,c,0);
}
template<typename T,class Major>
class zConstantDiagMatrix : public zMatrixBaseR<T,Major> //should not matter if rowmajor or colmajor
{
public:
//constructor
explicit zConstantDiagMatrix(const zMatrixBaseR<T,Major> &mat)
:zMatrixBaseR<T,Major>(mat.rows_,mat.rows_),Mat_(mat) {
ZCHECK_EQ(mat.cols_, 1);
}
//operator()
using zMatrixBaseR<T,Major>::operator();
const T operator()(zuint r, zuint c) const {
CheckRange(r, c);
if (r==c) return Mat_(r,0);
else return 0;
}
private:
const zMatrixBaseR<T,Major> &Mat_;
};
template<typename T,class Major>
const zConstantDiagMatrix<T,Major> Diag(const zMatrixBaseR<T,Major> &mat) {
return zConstantDiagMatrix<T,Major>(mat);
}
template<typename T>
const zConstantDiagMatrix<T,zColMajor> Eye(int n, const T &v=1) {
return zConstantDiagMatrix<T,zColMajor>(Ones<T>(n,1,v));
}
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMatrixConstant.hpp
|
C++
|
gpl3
| 2,281
|
#pragma once
//some tools for matrix
#include "zMatrix.hpp"
namespace zzz{
template<typename T,class Major>
const zMatrix<T,zColMajor> Temp(const zMatrixBaseR<T,Major> &mat)
{
zMatrix<T,zColMajor> v(mat);
return v;
}
template<typename T,class Major>
class zTransMatrix : public zMatrixBaseR<T,Major>
{
public:
explicit zTransMatrix(const zMatrixBaseR<T,Major>& mat)
:zMatrixBaseR<T,Major>(mat.cols_,mat.rows_),Mat_(mat){}
using zMatrixBaseR<T,Major>::operator();
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
return Mat_(c,r);
}
public:
const zMatrixBaseR<T,Major> &Mat_;
};
template<typename T,class Major>
const zTransMatrix<T,Major> Trans(const zMatrixBaseR<T,Major>& mat)
{return zTransMatrix<T,Major>(mat);}
template<typename T,class Major>
T Sum(const zMatrixBaseR<T,Major> &mat)
{
T sum=0;
for (zuint r=0; r<mat.rows_; r++) for (zuint c=0; c<mat.cols_; c++)
sum+=mat(r,c);
return sum;
}
template<typename T,class Major>
T Dot(const zMatrixBaseR<T,Major> &mat1, const zMatrixBaseR<T,Major> &mat2)
{
T sum=Sum(DotTimes(mat1,mat2));
return sum;
}
template<typename T,class Major>
T Norm(const zMatrixBaseR<T,Major> &mat)
{
T sqrsum=Dot(mat,mat);
return Sqrt<T>(sqrsum);
}
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMatrixOperation.hpp
|
C++
|
gpl3
| 1,302
|
#pragma once
#include "zMatrixBase.hpp"
#include "zMatrix.hpp"
#include <Math/Vector.hpp>
#include <Math/Matrix.hpp>
namespace zzz{
//////////////////////////////////////////////////////////////////////////
//Vector Dress
template<typename T, unsigned int N,typename Major>
class zMatrixVectorDressR : public zMatrixBaseR<T,Major>
{
public:
explicit zMatrixVectorDressR(const VectorBase<N,T> &vec)
:zMatrixBaseR<T,Major>(Major::Dim_==0?1:N,Major::Dim_==0?N:1),vec_(vec){}
const T operator()(zuint r, zuint c) const {
if (Major::Dim_==0) {
ZRCHECK_EQ(r, 0);
ZRCHECK_LT(c, N);
return vec_[c];
} else {
ZRCHECK_EQ(c, 0);
ZRCHECK_LT(r, N);
return vec_[r];
}
}
zSubMatrixR<T,Major> operator()(const int r) const {
if (Major::Dim_==0)
return zMatrixBaseR<T,Major>::operator()(0,r);
else
return zMatrixBaseR<T,Major>::operator()(r,0);
}
zSubMatrixR<T,Major> operator()(const EndlessArray &r) const {
if (Major::Dim_==0)
return zMatrixBaseR<T,Major>::operator()(0,r);
else
return zMatrixBaseR<T,Major>::operator()(r,0);
}
zSubMatrixR<T,Major> operator()(const zMatrixBaseR<int,Major> &r) const {
if (Major::Dim_==0)
return zMatrixBaseR<T,Major>::operator()(0,r);
else
return zMatrixBaseR<T,Major>::operator()(r,0);
}
private:
const VectorBase<N,T> &vec_;
};
template<typename T, unsigned int N,typename Major>
class zMatrixVectorDressW : public zMatrixBaseW<T,Major>
{
public:
explicit zMatrixVectorDressW(VectorBase<N,T> &vec)
:zMatrixBaseW<T,Major>(Major::Dim_==0?1:N,Major::Dim_==0?N:1),vec_(vec){}
const T operator()(zuint r, zuint c) const {
if (Major::Dim_==0) {
ZRCHECK_EQ(r, 0);
ZRCHECK_LT(c, N);
return vec_[c];
} else {
ZRCHECK_EQ(c, 0);
ZRCHECK_LT(r, N);
return vec_[r];
}
}
T &operator()(zuint r, zuint c) {
if (Major::Dim_==0) {
ZRCHECK_EQ(r, 0);
ZRCHECK_LT(c, N);
return vec_[c];
} else {
ZRCHECK_EQ(c, 0);
ZRCHECK_LT(r, N);
return vec_[r];
}
}
//don't know why this does not work
// using zMatrixBaseW<T,Major>::operator=;
const zMatrixBaseW<T,Major>& operator=(const zMatrixBaseR<T,Major> &other) {
return zMatrixBaseW<T,Major>::operator=(other);
}
zSubMatrixW<T,Major> operator()(const int r) {
if (Major::Dim_==0)
return zMatrix<T,Major>::operator()(0,r);
else
return zMatrix<T,Major>::operator()(r,0);
}
zSubMatrixW<T,Major> operator()(const EndlessArray &r) {
if (Major::Dim_==0)
return zMatrix<T,Major>::operator()(0,r);
else
return zMatrix<T,Major>::operator()(r,0);
}
zSubMatrixW<T,Major> operator()(const zMatrixBaseR<int,Major> &r) {
if (Major::Dim_==0)
return zMatrix<T,Major>::operator()(0,r);
else
return zMatrix<T,Major>::operator()(r,0);
}
private:
VectorBase<N,T> &vec_;
};
template<typename T, unsigned int N>
const zMatrixVectorDressR<T,N,zColMajor> Dress(const VectorBase<N,T> &v)
{return zMatrixVectorDressR<T,N,zColMajor>(v);}
template<typename T, unsigned int N>
zMatrixVectorDressW<T,N,zColMajor> Dress(VectorBase<N,T> &v)
{return zMatrixVectorDressW<T,N,zColMajor>(v);}
//////////////////////////////////////////////////////////////////////////
//Matrix Dress
template<typename T, unsigned int R, unsigned int C, class Major>
class zMatrixMatrixDressR : public zMatrixBaseR<T,Major>
{
public:
explicit zMatrixMatrixDressR(const MatrixBase<R,C,T> &mat):zMatrixBaseR<T,Major>(R,C),mat_(mat){}
const T operator()(zuint r, zuint c) const {
CheckRange(r, c);
return mat_.At(r,c);
}
using zMatrixBaseR<T,Major>::operator();
private:
const MatrixBase<R,C,T> &mat_;
};
template<typename T, unsigned int R, unsigned int C, class Major>
class zMatrixMatrixDressW : public zMatrixBaseW<T,Major>
{
public:
explicit zMatrixMatrixDressW(MatrixBase<R,C,T> &mat):zMatrixBaseW<T,Major>(R,C),mat_(mat){}
const T operator()(zuint r, zuint c) const {
CheckRange(r, c);
return mat_.At(r,c);
}
T &operator()(zuint r, zuint c) {
CheckRange(r, c);
return mat_.At(r,c);
}
//don't know why this does not work
// using zMatrixBaseW<T,Major>::operator =;
const zMatrixBaseW<T,Major>& operator=(const zMatrixBaseR<T,Major> &other) {
return zMatrixBaseW<T,Major>::operator =(other);
}
using zMatrixBaseW<T,Major>::operator();
private:
MatrixBase<R,C,T> &mat_;
};
template<typename T, unsigned int R, unsigned int C>
const zMatrixMatrixDressR<T,R,C,zColMajor> Dress(const MatrixBase<R,C,T> &v)
{return zMatrixMatrixDressR<T,R,C,zColMajor>(v);}
template<typename T, unsigned int R, unsigned int C>
zMatrixMatrixDressW<T,R,C,zColMajor> Dress(MatrixBase<R,C,T> &v)
{return zMatrixMatrixDressW<T,R,C,zColMajor>(v);}
////////////////////////////////////////////////////
// ArrayBase Dress
template<typename T,class Major>
class zMatrixArrayDressR : public zMatrixBaseR<T,Major>
{
using zMatrixBaseR<T,Major>::rows_;
using zMatrixBaseR<T,Major>::cols_;
public:
explicit zMatrixArrayDressR(const ArrayBase<2,T> &arr):zMatrixBaseR<T,Major>(arr.Size(0),arr.Size(1)),arr_(arr){}
const T operator()(zuint r, zuint c) const {
CheckRange(r, c);
return arr_.At(Vector2ui(r,c));
}
using zMatrixBaseR<T,Major>::operator();
private:
const ArrayBase<2,T> &arr_;
};
template<typename T,class Major>
class zMatrixArrayDressW : public zMatrixBaseW<T,Major>
{
using zMatrixBaseW<T,Major>::rows_;
using zMatrixBaseW<T,Major>::cols_;
public:
explicit zMatrixArrayDressW(ArrayBase<2,T> &arr):zMatrixBaseW<T,Major>(arr.Size(0),arr.Size(1)),arr_(arr){}
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
return arr_.At(Vector2ui(r,c));
}
T &operator()(zuint r, zuint c)
{
CheckRange(r, c);
return arr_.At(Vector2ui(r,c));
}
const zMatrixBaseW<T,Major> &operator=(const zMatrixBaseR<T,Major> &other)
{
arr_.SetSize(Vector2ui(other.rows_,other.cols_));
rows_=other.rows_;
cols_=other.cols_;
return zMatrixBaseW<T,Major>::operator=(other);
}
using zMatrixBaseW<T,Major>::operator();
private:
ArrayBase<2,T> &arr_;
};
template<typename T>
const zMatrixArrayDressR<T,zColMajor> Dress(const ArrayBase<2,T> &v)
{return zMatrixArrayDressR<T,zColMajor>(v);}
template<typename T>
zMatrixArrayDressW<T,zColMajor> Dress(ArrayBase<2,T> &v)
{return zMatrixArrayDressW<T,zColMajor>(v);}
////////////////////////////////////////////////////
// Raw C++ Array Dress
template<typename T,class Major>
class zMatrixRawArrayDressR : public zMatrixBaseR<T,Major>
{
using zMatrixBaseR<T,Major>::rows_;
using zMatrixBaseR<T,Major>::cols_;
public:
explicit zMatrixRawArrayDressR(const T *arr, zuint nrow, zuint ncol):zMatrixBaseR<T,Major>(nrow,ncol),arr_(arr){
ZCHECK_NOT_NULL(arr);
}
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
return arr_[Major::ToIndex(r,c,rows_,cols_)];
}
using zMatrixBaseR<T,Major>::operator();
private:
const T *arr_;
};
template<typename T,class Major>
class zMatrixRawArrayDressW : public zMatrixBaseW<T,Major>
{
using zMatrixBaseW<T,Major>::rows_;
using zMatrixBaseW<T,Major>::cols_;
public:
explicit zMatrixRawArrayDressW(T *arr, zuint nrow, zuint ncol):zMatrixBaseW<T,Major>(nrow,ncol),arr_(arr){
ZCHECK_NOT_NULL(arr);
}
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
return arr_[Major::ToIndex(r,c,rows_,cols_)];
}
T &operator()(zuint r, zuint c)
{
CheckRange(r, c);
return arr_[Major::ToIndex(r,c,rows_,cols_)];
}
const zMatrixBaseW<T,Major> &operator=(const zMatrixBaseR<T,Major> &other)
{
ZRCHECK_EQ(other.rows_, rows_);
ZRCHECK_EQ(other.cols_, cols_);
return zMatrixBaseW<T,Major>::operator=(other);
}
using zMatrixBaseW<T,Major>::operator();
private:
T *arr_;
};
template<typename T>
const zMatrixRawArrayDressR<T,zColMajor> Dress(const T *v, zuint nrow, zuint ncol)
{return zMatrixRawArrayDressR<T,zColMajor>(v,nrow,ncol);}
template<typename T>
zMatrixRawArrayDressW<T,zColMajor> Dress(T *v, zuint nrow, zuint ncol)
{return zMatrixRawArrayDressW<T,zColMajor>(v,nrow,ncol);}
////////////////////////////////////////////
//Dress for single value
template<typename T,class Major>
class zMatrixSingleDressR : public zMatrixBaseR<T,Major>
{
public:
explicit zMatrixSingleDressR(const T &v):zMatrixBaseR<T,Major>(1,1),v_(v){}
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
return v_;
}
using zMatrixBaseR<T,Major>::operator();
private:
const T &v_;
};
template<typename T,class Major>
class zMatrixSingleDressW : public zMatrixBaseW<T,Major>
{
public:
explicit zMatrixSingleDressW(T &v):zMatrixBaseW<T,Major>(1,1),v_(v){}
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
return v_;
}
T &operator()(zuint r, zuint c)
{
CheckRange(r, c);
return v_;
}
// don't know why this does not work
// using zMatrixBaseW<T,Major>::operator=;
const zMatrixBaseW<T,Major>& operator=(const zMatrixBaseR<T,Major> &other)
{
return zMatrixBaseW<T,Major>::operator =(other);
}
using zMatrixBaseW<T,Major>::operator();
private:
T &v_;
};
//////////////////////////////////////////////////////////////////////////
// std::vector Dress
template<typename T, typename Major>
class zMatrixStdVectorDressR : public zMatrixBaseR<T,Major>
{
public:
explicit zMatrixStdVectorDressR(const std::vector<T> &vec)
:zMatrixBaseR<T,Major>(Major::Dim_==0?1:vec.size(),Major::Dim_==0?vec.size():1),vec_(vec){}
const T operator()(zuint r, zuint c) const {
if (Major::Dim_==0) {
ZRCHECK_EQ(r, 0);
ZRCHECK_LT(c, vec_.size());
return vec_[c];
} else {
ZRCHECK_EQ(c, 0);
ZRCHECK_LT(r, vec_.size());
return vec_[r];
}
}
zSubMatrixR<T,Major> operator()(const int r) const {
if (Major::Dim_==0)
return zMatrixBaseR<T,Major>::operator()(0,r);
else
return zMatrixBaseR<T,Major>::operator()(r,0);
}
zSubMatrixR<T,Major> operator()(const EndlessArray &r) const {
if (Major::Dim_==0)
return zMatrixBaseR<T,Major>::operator()(0,r);
else
return zMatrixBaseR<T,Major>::operator()(r,0);
}
zSubMatrixR<T,Major> operator()(const zMatrixBaseR<int,Major> &r) const {
if (Major::Dim_==0)
return zMatrixBaseR<T,Major>::operator()(0,r);
else
return zMatrixBaseR<T,Major>::operator()(r,0);
}
private:
const std::vector<T> &vec_;
};
template<typename T, typename Major>
class zMatrixStdVectorDressW : public zMatrixBaseW<T,Major>
{
public:
explicit zMatrixStdVectorDressW(std::vector<T> &vec)
:zMatrixBaseW<T,Major>(Major::Dim_==0?1:vec.size(),Major::Dim_==0?vec.size():1),vec_(vec){}
const T operator()(zuint r, zuint c) const {
if (Major::Dim_==0) {
ZRCHECK_EQ(r, 0);
ZRCHECK_LT(c, vec_.size());
return vec_[c];
} else {
ZRCHECK_EQ(c, 0);
ZRCHECK_LT(r, vec_.size());
return vec_[r];
}
}
T &operator()(zuint r, zuint c) {
if (Major::Dim_==0) {
ZRCHECK_EQ(r, 0);
ZRCHECK_LT(c, vec_.size());
return vec_[c];
} else {
ZRCHECK_EQ(c, 0);
ZRCHECK_LT(r, vec_.size());
return vec_[r];
}
}
//don't know why this does not work
// using zMatrixBaseW<T,Major>::operator=;
const zMatrixBaseW<T,Major>& operator=(const zMatrixBaseR<T,Major> &other) {
if (Major::Dim_==0) {
ZRCHECK_EQ(other.rows_, 1);
vec_.resize(other.cols_);
cols_=other.cols_;
} else {
ZRCHECK_EQ(other.cols_, 1);
vec_.resize(other.rows_);
rows_=other.rows_;
}
return zMatrixBaseW<T,Major>::operator=(other);
}
zSubMatrixW<T,Major> operator()(const int r) {
if (Major::Dim_==0)
return zMatrix<T,Major>::operator()(0,r);
else
return zMatrix<T,Major>::operator()(r,0);
}
zSubMatrixW<T,Major> operator()(const EndlessArray &r) {
if (Major::Dim_==0)
return zMatrix<T,Major>::operator()(0,r);
else
return zMatrix<T,Major>::operator()(r,0);
}
zSubMatrixW<T,Major> operator()(const zMatrixBaseR<int,Major> &r) {
if (Major::Dim_==0)
return zMatrix<T,Major>::operator()(0,r);
else
return zMatrix<T,Major>::operator()(r,0);
}
private:
std::vector<T> &vec_;
};
template<typename T>
const zMatrixStdVectorDressR<T,zColMajor> Dress(const std::vector<T> &v)
{return zMatrixStdVectorDressR<T,zColMajor>(v);}
template<typename T>
zMatrixStdVectorDressW<T,zColMajor> Dress(std::vector<T> &v)
{return zMatrixStdVectorDressW<T,zColMajor>(v);}
//ATTENTION: cannot make a template Dress for single value
//since every object can be interpreted this way
#define SINGLEDRESS(T) \
inline const zMatrixSingleDressR<T,zColMajor> Dress(const T &v)\
{return zMatrixSingleDressR<T,zColMajor>(v);}\
inline zMatrixSingleDressW<T,zColMajor> Dress(T &v)\
{return zMatrixSingleDressW<T,zColMajor>(v);}
SINGLEDRESS(zint8);
SINGLEDRESS(zuint8);
SINGLEDRESS(zint16);
SINGLEDRESS(zuint16);
SINGLEDRESS(zint32);
SINGLEDRESS(zuint32);
SINGLEDRESS(float);
SINGLEDRESS(double);
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMatrixDress.hpp
|
C++
|
gpl3
| 13,554
|
#pragma once
#include "zMatrixBase.hpp"
#include <Math/Array2.hpp>
//matrix and operator + -
namespace zzz{
template<typename T, typename Major=zColMajor>
class zMatrix : public zMatrixBaseW<T,Major>
{
using zMatrixBaseW<T,Major>::ToIndex;
using zMatrixBaseW<T,Major>::rows_;
using zMatrixBaseW<T,Major>::cols_;
public:
//constructor
zMatrix():zMatrixBaseW<T,Major>(0,0){}
explicit zMatrix(zuint size):zMatrixBaseW<T,Major>(0,0) {
SetSize(size);
}
zMatrix(zuint r, zuint c)
:zMatrixBaseW<T,Major>(0,0) {
SetSize(r,c);
}
zMatrix(const zMatrix<T> &other)
:zMatrixBaseW<T,Major>(0,0) {
*this=other;
}
explicit zMatrix(const zMatrixBaseR<T,Major> &other)
:zMatrixBaseW<T,Major>(0,0) {
*this=other;
}
const T* Data() const { return V_.Data();}
T* Data() { return V_.Data();}
/////////////////////////////////////////////////////////
//operator()
const T operator()(zuint r, zuint c) const {
CheckRange(r, c);
return V_[ToIndex(r,c)];
}
T& operator()(zuint r, zuint c) {
CheckRange(r, c);
return V_[ToIndex(r,c)];
}
const T operator[](zuint i) const {
CheckRange(i);
return V_[i];
}
T& operator[](zuint i) {
CheckRange(i);
return V_[i];
}
using zMatrixBaseW<T,Major>::operator();
/////////////////////////////////////////////////////////
//operator=
template<typename T2>
const zMatrixBaseW<T,Major>& operator=(const zMatrixBaseR<T,Major>& other) {
SetSize(other.rows_,other.cols_);
for (zuint r=0; r<rows_; r++) for (zuint c=0; c<cols_; c++)
(*this)(r,c)=static_cast<T2>(other(r,c));
return *this;
}
const zMatrixBaseW<T,Major>& operator=(const zMatrixBaseR<T,Major>& other) {
SetSize(other.rows_,other.cols_);
return zMatrixBaseW<T,Major>::operator =(other);
}
// Special for matrix of the same major, will call memcpy if available
const zMatrixBaseW<T,Major>& operator=(const zMatrix<T,Major>& other) {
SetSize(other.rows_,other.cols_);
V_.SetData(other.V_.Data());
return *this;
}
/////////////////////////////////////////////////////////
//set size
void SetSize(zuint size) {
if (Major::Dim_==0) SetSize(1,size);
else SetSize(size,1);
}
void SetSize(zuint r, zuint c) {
V_.SetSize(Vector2ui(r,c));
rows_=r;
cols_=c;
}
//set zero
void Zero(zuchar x=0) {
V_.Zero(x);
}
void Fill(const T &a) {
for (zuint j=0; j<cols_; j++) for (zuint i=0; i<rows_; i++)
(*this)(i,j)=a;
}
void Fill(const zuint size, const T &a) {
SetSize(size);
Fill(a);
}
void Fill(const zuint r, zuint c, const T &a) {
SetSize(r, c);
Fill(a);
}
private:
Array<2,T> V_;
};
typedef zMatrix<double> zMatrixd;
typedef zMatrix<float> zMatrixf;
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMatrix.hpp
|
C++
|
gpl3
| 2,896
|
#pragma once
#include <Math/Random.hpp>
#include <zMatrix.hpp>
namespace zzz
{
zMatrix<double, zColMajor> Rand(zuint row, zuint col);
template<typename T, typename zMajor, typename T1>
T Interpolate(const zMatrixBaseR<T,zMajor> &mat, T1 r, T1 c) {
double row(r), col(c);
// do the interpolation
zuint r0=Clamp<int>(0, floor(row), mat.Size(0)-1);
zuint r1=Clamp<int>(0, ceil(row), mat.Size(0)-1);
zuint c0=Clamp<int>(0, floor(col), mat.Size(1)-1);
zuint c1=Clamp<int>(0, ceil(col), mat.Size(1)-1);
const double fractR = row - r0;
const double fractC = col - c0;
const T syx = mat(r0,c0);
const T syx1 = mat(r0,c1);
const T sy1x = mat(r1,c0);
const T sy1x1 = mat(r1,c1);
// normal interpolation within range
const T tmp1 = syx + (syx1-syx)*fractC;
const T tmp2 = sy1x + (sy1x1-sy1x)*fractC;
return T(tmp1 + (tmp2-tmp1)*fractR);
}
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMatrixFunction.hpp
|
C++
|
gpl3
| 893
|
#pragma once
#include "zMatrixBase.hpp"
#include "zMatrix.hpp"
#include <Math/Vector.hpp>
#include <Math/Matrix.hpp>
namespace zzz{
//////////////////////////////////////////////
//Dress to cast value
template<typename TO, typename FROM, class Major>
class zMatrixCastR : public zMatrixBaseR<TO,Major>
{
public:
explicit zMatrixCastR(const zMatrixBaseR<FROM,Major> &mat):Mat_(mat),zMatrixBaseR<TO,Major>(mat.rows_,mat.cols_){}
const TO operator()(zuint r, zuint c) const
{
CheckRange(r, c);
return static_cast<TO>(Mat_(r,c));
}
using zMatrixBaseR<TO,Major>::operator();
private:
const zMatrixBaseR<FROM,Major> &Mat_;
};
template<typename TO, typename FROM, class Major>
const zMatrixCastR<TO,FROM,Major> Cast(const zMatrixBaseR<FROM,Major> &mat)
{return zMatrixCastR<TO,FROM,Major>(mat);}
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMatrixCast.hpp
|
C++
|
gpl3
| 843
|
#include "zMatrixLapack.hpp"
#include "zMatrixConstant.hpp"
//use lapack to do high level math
#include <3rdParty/BlasLapack.hpp>
#include <Math/Math.hpp>
namespace zzz{
#ifdef ZZZ_LIB_LAPACK
bool LUFactorization(zMatrix<double,zColMajor> &mat, zMatrix<integer,zColMajor> &IPIV, integer *info)
{
/*
* M (input) INTEGER
* The number of rows of the matrix A. M >= 0.
*
* N (input) INTEGER
* The number of columns of the matrix A. N >= 0.
*
* A (input/output) DOUBLE PRECISION array, dimension (LDA,N)
* On entry, the M-by-N matrix to be factored.
* On exit, the factors L and U from the factorization
* A = P*L*U; the unit diagonal elements of L are not stored.
*
* LDA (input) INTEGER
* The leading dimension of the array A. LDA >= max(1,M).
*
* IPIV (output) INTEGER array, dimension (min(M,N))
* The pivot indices; for 1 <= i <= min(M,N), row i of the
* matrix was interchanged with row IPIV(i).
*
* INFO (output) INTEGER
* = 0: successful exit
* < 0: if INFO = -i, the i-th argument had an illegal value
* > 0: if INFO = i, U(i,i) is exactly zero. The factorization
* has been completed, but the factor U is exactly
* singular, and division by zero will occur if it is used
* to solve a system of equations.
*/
integer M=mat.Size(0),N=mat.Size(1),LDA=M,INFO;
IPIV.SetSize(Min<int>(M,N));
dgetrf_(&M,&N,mat.Data(),&LDA,IPIV.Data(),&INFO);
if (info!=NULL) *info=INFO;
return INFO==0;
}
//ATTENTION: original value will not be kept even if failed
bool Invert(zMatrix<double,zColMajor> &mat, integer *info)
{
zMatrix<integer,zColMajor> IPIV;
if (!LUFactorization(mat,IPIV,info)) return false;
/*
* N (input) INTEGER
* The order of the matrix A. N >= 0.
*
* A (input/output) DOUBLE PRECISION array, dimension (LDA,N)
* On entry, the factors L and U from the factorization
* A = P*L*U as computed by DGETRF.
* On exit, if INFO = 0, the inverse of the original matrix A.
*
* LDA (input) INTEGER
* The leading dimension of the array A. LDA >= max(1,N).
*
* IPIV (input) INTEGER array, dimension (N)
* The pivot indices from DGETRF; for 1<=i<=N, row i of the
* matrix was interchanged with row IPIV(i).
*
* WORK (workspace/output) DOUBLE PRECISION array, dimension (MAX(1,LWORK))
* On exit, if INFO=0, then WORK(1) returns the optimal LWORK.
*
* LWORK (input) INTEGER
* The dimension of the array WORK. LWORK >= max(1,N).
* For optimal performance LWORK >= N*NB, where NB is
* the optimal blocksize returned by ILAENV.
*
* If LWORK = -1, then a workspace query is assumed; the routine
* only calculates the optimal size of the WORK array, returns
* this value as the first entry of the WORK array, and no error
* message related to LWORK is issued by XERBLA.
*
* INFO (output) INTEGER
* = 0: successful exit
* < 0: if INFO = -i, the i-th argument had an illegal value
* > 0: if INFO = i, U(i,i) is exactly zero; the matrix is
* singular and its inverse could not be computed.
*/
ZCHECK_EQ(mat.Size(0), mat.Size(1));
integer N=mat.Size(0);
integer LDA=N;
//ilaenv is not compiled in my clapack lib
// integer ISPEC=1;
// integer N1=N;
// integer N2=-1;
// integer N3=-1;
// integer N4=-1;
// integer NB=ilaenv_(&ISPEC,"DGETRI","",&N1,&N2,&N3,&N4,6,0);
// printf("%d\n",NB);
// integer LWORK=N*NB;
integer LWORK=N;
zMatrix<double,zColMajor> WORK(LWORK);
integer INFO;
dgetri_(&N, mat.Data(), &LDA, IPIV.Data(), WORK.Data(), &LWORK, &INFO);
if (info!=NULL) *info=INFO;
return INFO==0;
}
bool SVD(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &U, zMatrix<double,zColMajor> &S, zMatrix<double,zColMajor> &VT, integer *info)
{
/*
* JOBU (input) CHARACTER*1
* Specifies options for computing all or part of the matrix U:
* = 'A': all M columns of U are returned in array U:
* = 'S': the first min(m,n) columns of U (the left singular
* vectors) are returned in the array U;
* = 'O': the first min(m,n) columns of U (the left singular
* vectors) are overwritten on the array A;
* = 'N': no columns of U (no left singular vectors) are
* computed.
*
* JOBVT (input) CHARACTER*1
* Specifies options for computing all or part of the matrix
* V**T:
* = 'A': all N rows of V**T are returned in the array VT;
* = 'S': the first min(m,n) rows of V**T (the right singular
* vectors) are returned in the array VT;
* = 'O': the first min(m,n) rows of V**T (the right singular
* vectors) are overwritten on the array A;
* = 'N': no rows of V**T (no right singular vectors) are
* computed.
*
* JOBVT and JOBU cannot both be 'O'.
*
* M (input) INTEGER
* The number of rows of the input matrix A. M >= 0.
*
* N (input) INTEGER
* The number of columns of the input matrix A. N >= 0.
*
* A (input/output) DOUBLE PRECISION array, dimension (LDA,N)
* On entry, the M-by-N matrix A.
* On exit,
* if JOBU = 'O', A is overwritten with the first min(m,n)
* columns of U (the left singular vectors,
* stored columnwise);
* if JOBVT = 'O', A is overwritten with the first min(m,n)
* rows of V**T (the right singular vectors,
* stored rowwise);
* if JOBU .ne. 'O' and JOBVT .ne. 'O', the contents of A
* are destroyed.
*
* LDA (input) INTEGER
* The leading dimension of the array A. LDA >= max(1,M).
*
* S (output) DOUBLE PRECISION array, dimension (min(M,N))
* The singular values of A, sorted so that S(i) >= S(i+1).
*
* U (output) DOUBLE PRECISION array, dimension (LDU,UCOL)
* (LDU,M) if JOBU = 'A' or (LDU,min(M,N)) if JOBU = 'S'.
* If JOBU = 'A', U contains the M-by-M orthogonal matrix U;
* if JOBU = 'S', U contains the first min(m,n) columns of U
* (the left singular vectors, stored columnwise);
* if JOBU = 'N' or 'O', U is not referenced.
*
* LDU (input) INTEGER
* The leading dimension of the array U. LDU >= 1; if
* JOBU = 'S' or 'A', LDU >= M.
*
* VT (output) DOUBLE PRECISION array, dimension (LDVT,N)
* If JOBVT = 'A', VT contains the N-by-N orthogonal matrix
* V**T;
* if JOBVT = 'S', VT contains the first min(m,n) rows of
* V**T (the right singular vectors, stored rowwise);
* if JOBVT = 'N' or 'O', VT is not referenced.
*
* LDVT (input) INTEGER
* The leading dimension of the array VT. LDVT >= 1; if
* JOBVT = 'A', LDVT >= N; if JOBVT = 'S', LDVT >= min(M,N).
*
* WORK (workspace/output) DOUBLE PRECISION array, dimension (MAX(1,LWORK))
* On exit, if INFO = 0, WORK(1) returns the optimal LWORK;
* if INFO > 0, WORK(2:MIN(M,N)) contains the unconverged
* superdiagonal elements of an upper bidiagonal matrix B
* whose diagonal is in S (not necessarily sorted). B
* satisfies A = U * B * VT, so it has the same singular values
* as A, and singular vectors related by U and VT.
*
* LWORK (input) INTEGER
* The dimension of the array WORK.
* LWORK >= MAX(1,3*MIN(M,N)+MAX(M,N),5*MIN(M,N)).
* For good performance, LWORK should generally be larger.
*
* If LWORK = -1, then a workspace query is assumed; the routine
* only calculates the optimal size of the WORK array, returns
* this value as the first entry of the WORK array, and no error
* message related to LWORK is issued by XERBLA.
*
* INFO (output) INTEGER
* = 0: successful exit.
* < 0: if INFO = -i, the i-th argument had an illegal value.
* > 0: if DBDSQR did not converge, INFO specifies how many
* superdiagonals of an intermediate bidiagonal form B
* did not converge to zero. See the description of WORK
* above for details.
*/
integer M = A.Size(0), N = A.Size(1), INFO;
integer LDA = M, LDU = M, LDVT = N;
integer minMN = Min<integer>(M,N);
integer LWORK = Max<integer>(3*minMN+Max<integer>(M,N), 5*minMN);
zMatrix<double> WORK(LWORK,1);
U.SetSize(LDU, M);
VT.SetSize(LDVT, N);
S.SetSize(minMN);
dgesvd_("A", "A", &M, &N, A.Data(), &LDA, S.Data(), U.Data(), &LDU,
VT.Data(), &LDVT, WORK.Data(), &LWORK, &INFO);
if (info!=NULL) *info=INFO;
return INFO==0;
}
double Det(zMatrix<double,zColMajor> &A)
{
ZCHECK_EQ(A.Size(0), A.Size(1));
zMatrix<integer> IPIV;
LUFactorization(A, IPIV);
double res = 1.0f;
for(zuint i=0; i<A.Size(0); i++)
res *= A(i,i);
for(zuint i=0; i<IPIV.size(); i++)
if (i!=IPIV[i]-1) res *= -1.0f;
return res;
};
bool EigenSym(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &e, integer *info)
{
/*
* JOBZ (input) CHARACTER*1
* = 'N': Compute eigenvalues only;
* = 'V': Compute eigenvalues and eigenvectors.
*
* UPLO (input) CHARACTER*1
* = 'U': Upper triangle of A is stored;
* = 'L': Lower triangle of A is stored.
*
* N (input) INTEGER
* The order of the matrix A. N >= 0.
*
* A (input/output) DOUBLE PRECISION array, dimension (LDA, N)
* On entry, the symmetric matrix A. If UPLO = 'U', the
* leading N-by-N upper triangular part of A contains the
* upper triangular part of the matrix A. If UPLO = 'L',
* the leading N-by-N lower triangular part of A contains
* the lower triangular part of the matrix A.
* On exit, if JOBZ = 'V', then if INFO = 0, A contains the
* orthonormal eigenvectors of the matrix A.
* If JOBZ = 'N', then on exit the lower triangle (if UPLO='L')
* or the upper triangle (if UPLO='U') of A, including the
* diagonal, is destroyed.
*
* LDA (input) INTEGER
* The leading dimension of the array A. LDA >= max(1,N).
*
* W (output) DOUBLE PRECISION array, dimension (N)
* If INFO = 0, the eigenvalues in ascending order.
*
* WORK (workspace/output) DOUBLE PRECISION array, dimension (MAX(1,LWORK))
* On exit, if INFO = 0, WORK(1) returns the optimal LWORK.
*
* LWORK (input) INTEGER
* The length of the array WORK. LWORK >= max(1,3*N-1).
* For optimal efficiency, LWORK >= (NB+2)*N,
* where NB is the blocksize for DSYTRD returned by ILAENV.
*
* If LWORK = -1, then a workspace query is assumed; the routine
* only calculates the optimal size of the WORK array, returns
* this value as the first entry of the WORK array, and no error
* message related to LWORK is issued by XERBLA.
*
* INFO (output) INTEGER
* = 0: successful exit
* < 0: if INFO = -i, the i-th argument had an illegal value
* > 0: if INFO = i, the algorithm failed to converge; i
* off-diagonal elements of an intermediate tridiagonal
* form did not converge to zero.
*/
ZCHECK_EQ(A.Size(0), A.Size(1));
integer N = A.Size(1), LWORK = -1, INFO;
e.SetSize(A.Size(0));
zMatrix<double> WORK(1);
dsyev_("V", "U", &N, A.Data(), &N, e.Data(), WORK.Data(), &LWORK, &INFO);
LWORK = (integer)(WORK[0]+0.5);
WORK.SetSize(LWORK);
dsyev_("V", "U", &N, A.Data(), &N, e.Data(), WORK.Data(), &LWORK, &INFO);
if (info!=NULL) *info=INFO;
return INFO==0;
}
bool EigRight(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &eigenVector, zMatrix<double,zColMajor> &eigenValueReal, zMatrix<double,zColMajor> &eigenValueImag, integer *info)
{
/*
* JOBVL (input) CHARACTER*1
* = 'N': left eigenvectors of A are not computed;
* = 'V': left eigenvectors of A are computed.
*
* JOBVR (input) CHARACTER*1
* = 'N': right eigenvectors of A are not computed;
* = 'V': right eigenvectors of A are computed.
*
* N (input) INTEGER
* The order of the matrix A. N >= 0.
*
* A (input/output) DOUBLE PRECISION array, dimension (LDA,N)
* On entry, the N-by-N matrix A.
* On exit, A has been overwritten.
*
* LDA (input) INTEGER
* The leading dimension of the array A. LDA >= max(1,N).
*
* WR (output) DOUBLE PRECISION array, dimension (N)
* WI (output) DOUBLE PRECISION array, dimension (N)
* WR and WI contain the real and imaginary parts,
* respectively, of the computed eigenvalues. Complex
* conjugate pairs of eigenvalues appear consecutively
* with the eigenvalue having the positive imaginary part
* first.
*
* VL (output) DOUBLE PRECISION array, dimension (LDVL,N)
* If JOBVL = 'V', the left eigenvectors u(j) are stored one
* after another in the columns of VL, in the same order
* as their eigenvalues.
* If JOBVL = 'N', VL is not referenced.
* If the j-th eigenvalue is real, then u(j) = VL(:,j),
* the j-th column of VL.
* If the j-th and (j+1)-st eigenvalues form a complex
* conjugate pair, then u(j) = VL(:,j) + i*VL(:,j+1) and
* u(j+1) = VL(:,j) - i*VL(:,j+1).
*
* LDVL (input) INTEGER
* The leading dimension of the array VL. LDVL >= 1; if
* JOBVL = 'V', LDVL >= N.
*
* VR (output) DOUBLE PRECISION array, dimension (LDVR,N)
* If JOBVR = 'V', the right eigenvectors v(j) are stored one
* after another in the columns of VR, in the same order
* as their eigenvalues.
* If JOBVR = 'N', VR is not referenced.
* If the j-th eigenvalue is real, then v(j) = VR(:,j),
* the j-th column of VR.
* If the j-th and (j+1)-st eigenvalues form a complex
* conjugate pair, then v(j) = VR(:,j) + i*VR(:,j+1) and
* v(j+1) = VR(:,j) - i*VR(:,j+1).
*
* LDVR (input) INTEGER
* The leading dimension of the array VR. LDVR >= 1; if
* JOBVR = 'V', LDVR >= N.
*
* WORK (workspace/output) DOUBLE PRECISION array, dimension (MAX(1,LWORK))
* On exit, if INFO = 0, WORK(1) returns the optimal LWORK.
*
* LWORK (input) INTEGER
* The dimension of the array WORK. LWORK >= max(1,3*N), and
* if JOBVL = 'V' or JOBVR = 'V', LWORK >= 4*N. For good
* performance, LWORK must generally be larger.
*
* If LWORK = -1, then a workspace query is assumed; the routine
* only calculates the optimal size of the WORK array, returns
* this value as the first entry of the WORK array, and no error
* message related to LWORK is issued by XERBLA.
*
* INFO (output) INTEGER
* = 0: successful exit
* < 0: if INFO = -i, the i-th argument had an illegal value.
* > 0: if INFO = i, the QR algorithm failed to compute all the
* eigenvalues, and no eigenvectors have been computed;
* elements i+1:N of WR and WI contain eigenvalues which
* have converged.
*/
ZCHECK_EQ(A.Size(0), A.Size(1));
char JOBVL = 'N'; /* Don't compute left eigenvectors */
char JOBVR = 'V'; /* Do compute right eigenvectors */
integer N = A.Size(1);
integer LDA = N;
eigenValueReal.SetSize(N,1);
eigenValueImag.SetSize(N,1);
double *VL = NULL;
integer LDVL = 1;
eigenVector.SetSize(N,N);
integer LDVR = N;
integer LWORK ; //query first
zMatrix<double,zColMajor> WORK(1,1);
integer INFO;
/* Query dgeev for the optimal value of lwork */
LWORK = -1;
dgeev_(&JOBVL, &JOBVR, &N, A.Data(), &LDA, eigenValueReal.Data(), eigenValueImag.Data(), VL, &LDVL, eigenVector.Data(), &LDVR, WORK.Data(), &LWORK, &INFO);
LWORK = (int) WORK(0,0);
WORK.SetSize(LWORK,1);
/* Make the call to dgeev */
dgeev_(&JOBVL, &JOBVR, &N, A.Data(), &LDA, eigenValueReal.Data(), eigenValueImag.Data(), VL, &LDVL, eigenVector.Data(), &LDVR, WORK.Data(), &LWORK, &INFO);
if (info!=NULL) *info=INFO;
return INFO==0;
}
bool SolveLinearLeastSquare(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &B_X, integer *info)
{
/*
* DGELSS computes the minimum norm solution to a real linear least
* squares problem:
*
* Minimize 2-norm(| b - A*x |).
*
* using the singular value decomposition (SVD) of A. A is an M-by-N
* matrix which may be rank-deficient.
*
* Several right hand side vectors b and solution vectors x can be
* handled in a single call; they are stored as the columns of the
* M-by-NRHS right hand side matrix B and the N-by-NRHS solution matrix
* X.
*
* The effective rank of A is determined by treating as zero those
* singular values which are less than RCOND times the largest singular
* value.
*
* Arguments
* =========
*
* M (input) INTEGER
* The number of rows of the matrix A. M >= 0.
*
* N (input) INTEGER
* The number of columns of the matrix A. N >= 0.
*
* NRHS (input) INTEGER
* The number of right hand sides, i.e., the number of columns
* of the matrices B and X. NRHS >= 0.
*
* A (input/output) DOUBLE PRECISION array, dimension (LDA,N)
* On entry, the M-by-N matrix A.
* On exit, the first min(m,n) rows of A are overwritten with
* its right singular vectors, stored rowwise.
*
* LDA (input) INTEGER
* The leading dimension of the array A. LDA >= max(1,M).
*
* B (input/output) DOUBLE PRECISION array, dimension (LDB,NRHS)
* On entry, the M-by-NRHS right hand side matrix B.
* On exit, B is overwritten by the N-by-NRHS solution
* matrix X. If m >= n and RANK = n, the residual
* sum-of-squares for the solution in the i-th column is given
* by the sum of squares of elements n+1:m in that column.
*
* LDB (input) INTEGER
* The leading dimension of the array B. LDB >= max(1,max(M,N)).
*
* S (output) DOUBLE PRECISION array, dimension (min(M,N))
* The singular values of A in decreasing order.
* The condition number of A in the 2-norm = S(1)/S(min(m,n)).
*
* RCOND (input) DOUBLE PRECISION
* RCOND is used to determine the effective rank of A.
* Singular values S(i) <= RCOND*S(1) are treated as zero.
* If RCOND < 0, machine precision is used instead.
*
* RANK (output) INTEGER
* The effective rank of A, i.e., the number of singular values
* which are greater than RCOND*S(1).
*
* WORK (workspace/output) DOUBLE PRECISION array, dimension (MAX(1,LWORK))
* On exit, if INFO = 0, WORK(1) returns the optimal LWORK.
*
* LWORK (input) INTEGER
* The dimension of the array WORK. LWORK >= 1, and also:
* LWORK >= 3*min(M,N) + max(2*min(M,N), max(M,N), NRHS)
* For good performance, LWORK should generally be larger.
*
* If LWORK = -1, then a workspace query is assumed; the routine
* only calculates the optimal size of the WORK array, returns
* this value as the first entry of the WORK array, and no error
* message related to LWORK is issued by XERBLA.
*
* INFO (output) INTEGER
* = 0: successful exit
* < 0: if INFO = -i, the i-th argument had an illegal value.
* > 0: the algorithm for computing the SVD failed to converge;
* if INFO = i, i off-diagonal elements of an intermediate
* bidiagonal form did not converge to zero.
*/
integer M = A.Size(0), N = A.Size(1);
integer NRHS = B_X.Size(1);
integer LDA = M, LDB = M;
zMatrix<double,zColMajor> S(N,1);
double RCOND = -1.0;
integer RANK; /* Output */
integer LWORK = 16 * (3 * min(M,N) + max(max(2 * min(M,N), max(M,N)), NRHS));
zMatrix<double,zColMajor> WORK(LWORK,1);
integer INFO;
/* Make the FORTRAN call */
dgelss_(&M, &N, &NRHS, A.Data(), &LDA, B_X.Data(), &LDB, S.Data(), &RCOND, &RANK, WORK.Data(), &LWORK, &INFO);
if (info!=NULL) *info=INFO;
return INFO==0;
}
bool SolveLinearLeastSquare2(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &B_X, integer *info)
{
/*
* DGELSY computes the minimum-norm solution to a real linear least
* squares problem:
* minimize || A * X - B ||
* using a complete orthogonal factorization of A. A is an M-by-N
* matrix which may be rank-deficient.
*
* Several right hand side vectors b and solution vectors x can be
* handled in a single call; they are stored as the columns of the
* M-by-NRHS right hand side matrix B and the N-by-NRHS solution
* matrix X.
*
* The routine first computes a QR factorization with column pivoting:
* A * P = Q * [ R11 R12 ]
* [ 0 R22 ]
* with R11 defined as the largest leading submatrix whose estimated
* condition number is less than 1/RCOND. The order of R11, RANK,
* is the effective rank of A.
*
* Then, R22 is considered to be negligible, and R12 is annihilated
* by orthogonal transformations from the right, arriving at the
* complete orthogonal factorization:
* A * P = Q * [ T11 0 ] * Z
* [ 0 0 ]
* The minimum-norm solution is then
* X = P * Z' [ inv(T11)*Q1'*B ]
* [ 0 ]
* where Q1 consists of the first RANK columns of Q.
*
* This routine is basically identical to the original xGELSX except
* three differences:
* o The call to the subroutine xGEQPF has been substituted by the
* the call to the subroutine xGEQP3. This subroutine is a Blas-3
* version of the QR factorization with column pivoting.
* o Matrix B (the right hand side) is updated with Blas-3.
* o The permutation of matrix B (the right hand side) is faster and
* more simple.
*
* Arguments
* =========
*
* M (input) INTEGER
* The number of rows of the matrix A. M >= 0.
*
* N (input) INTEGER
* The number of columns of the matrix A. N >= 0.
*
* NRHS (input) INTEGER
* The number of right hand sides, i.e., the number of
* columns of matrices B and X. NRHS >= 0.
*
* A (input/output) DOUBLE PRECISION array, dimension (LDA,N)
* On entry, the M-by-N matrix A.
* On exit, A has been overwritten by details of its
* complete orthogonal factorization.
*
* LDA (input) INTEGER
* The leading dimension of the array A. LDA >= max(1,M).
*
* B (input/output) DOUBLE PRECISION array, dimension (LDB,NRHS)
* On entry, the M-by-NRHS right hand side matrix B.
* On exit, the N-by-NRHS solution matrix X.
*
* LDB (input) INTEGER
* The leading dimension of the array B. LDB >= max(1,M,N).
*
* JPVT (input/output) INTEGER array, dimension (N)
* On entry, if JPVT(i) .ne. 0, the i-th column of A is permuted
* to the front of AP, otherwise column i is a free column.
* On exit, if JPVT(i) = k, then the i-th column of AP
* was the k-th column of A.
*
* RCOND (input) DOUBLE PRECISION
* RCOND is used to determine the effective rank of A, which
* is defined as the order of the largest leading triangular
* submatrix R11 in the QR factorization with pivoting of A,
* whose estimated condition number < 1/RCOND.
*
* RANK (output) INTEGER
* The effective rank of A, i.e., the order of the submatrix
* R11. This is the same as the order of the submatrix T11
* in the complete orthogonal factorization of A.
*
* WORK (workspace/output) DOUBLE PRECISION array, dimension (MAX(1,LWORK))
* On exit, if INFO = 0, WORK(1) returns the optimal LWORK.
*
* LWORK (input) INTEGER
* The dimension of the array WORK.
* The unblocked strategy requires that:
* LWORK >= MAX(MN+3*N+1, 2*MN+NRHS),
* where MN = min(M, N).
* The block algorithm requires that:
* LWORK >= MAX(MN+2*N+NB*(N+1), 2*MN+NB*NRHS),
* where NB is an upper bound on the blocksize returned
* by ILAENV for the routines DGEQP3, DTZRZF, STZRQF, DORMQR,
* and DORMRZ.
*
* If LWORK = -1, then a workspace query is assumed; the routine
* only calculates the optimal size of the WORK array, returns
* this value as the first entry of the WORK array, and no error
* message related to LWORK is issued by XERBLA.
*
* INFO (output) INTEGER
* = 0: successful exit
* < 0: If INFO = -i, the i-th argument had an illegal value.
*/
integer M = A.Size(0), N = A.Size(1);
integer NRHS = B_X.Size(1);
integer LDA = M, LDB = M;
zMatrix<integer,zColMajor> JPVT(Zeros<integer>(N,1));
double RCOND = -1.0;
integer RANK; /* Output */
integer LWORK;
zMatrix<double,zColMajor> WORK(1,1);
integer INFO;
//query first
LWORK = -1;
dgelsy_(&M, &N, &NRHS, A.Data(), &LDA, B_X.Data(), &LDB, JPVT.Data(), &RCOND, &RANK, WORK.Data(), &LWORK, &INFO);
//real call
LWORK = WORK(0,0);
WORK.SetSize(LWORK,1);
dgelsy_(&M, &N, &NRHS, A.Data(), &LDA, B_X.Data(), &LDB, JPVT.Data(), &RCOND, &RANK, WORK.Data(), &LWORK, &INFO);
if (info!=NULL) *info=INFO;
return INFO==0;
}
bool SolveLinear(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &B_X, long *info)
{
/*
* DGESV computes the solution to a real system of linear equations
* A * X = B,
* where A is an N-by-N matrix and X and B are N-by-NRHS matrices.
*
* The LU decomposition with partial pivoting and row interchanges is
* used to factor A as
* A = P * L * U,
* where P is a permutation matrix, L is unit lower triangular, and U is
* upper triangular. The factored form of A is then used to solve the
* system of equations A * X = B.
*
* Arguments
* =========
*
* N (input) INTEGER
* The number of linear equations, i.e., the order of the
* matrix A. N >= 0.
*
* NRHS (input) INTEGER
* The number of right hand sides, i.e., the number of columns
* of the matrix B. NRHS >= 0.
*
* A (input/output) DOUBLE PRECISION array, dimension (LDA,N)
* On entry, the N-by-N coefficient matrix A.
* On exit, the factors L and U from the factorization
* A = P*L*U; the unit diagonal elements of L are not stored.
*
* LDA (input) INTEGER
* The leading dimension of the array A. LDA >= max(1,N).
*
* IPIV (output) INTEGER array, dimension (N)
* The pivot indices that define the permutation matrix P;
* row i of the matrix was interchanged with row IPIV(i).
*
* B (input/output) DOUBLE PRECISION array, dimension (LDB,NRHS)
* On entry, the N-by-NRHS matrix of right hand side matrix B.
* On exit, if INFO = 0, the N-by-NRHS solution matrix X.
*
* LDB (input) INTEGER
* The leading dimension of the array B. LDB >= max(1,N).
*
* INFO (output) INTEGER
* = 0: successful exit
* < 0: if INFO = -i, the i-th argument had an illegal value
* > 0: if INFO = i, U(i,i) is exactly zero. The factorization
* has been completed, but the factor U is exactly
* singular, so the solution could not be computed.
*/
ZCHECK_EQ(A.Size(0), A.Size(1));
integer N=A.Size(0);
integer NRHS=B_X.Size(1);
integer LDA=N,LDB=N,INFO;
zMatrix<integer,zColMajor> IPIV(N,1);
dgesv_(&N, &NRHS, A.Data(), &LDA, IPIV.Data(), B_X.Data(), &LDB, &INFO);
if (info!=NULL) *info=INFO;
return INFO==0;
}
bool CholeskyFactorization(zMatrix<double,zColMajor> &A, long *info)
{
/*
* DPOTRF computes the Cholesky factorization of a real symmetric
* positive definite matrix A.
*
* The factorization has the form
* A = U**T * U, if UPLO = 'U', or
* A = L * L**T, if UPLO = 'L',
* where U is an upper triangular matrix and L is lower triangular.
*
* This is the block version of the algorithm, calling Level 3 BLAS.
*
* Arguments
* =========
*
* UPLO (input) CHARACTER*1
* = 'U': Upper triangle of A is stored;
* = 'L': Lower triangle of A is stored.
*
* N (input) INTEGER
* The order of the matrix A. N >= 0.
*
* A (input/output) DOUBLE PRECISION array, dimension (LDA,N)
* On entry, the symmetric matrix A. If UPLO = 'U', the leading
* N-by-N upper triangular part of A contains the upper
* triangular part of the matrix A, and the strictly lower
* triangular part of A is not referenced. If UPLO = 'L', the
* leading N-by-N lower triangular part of A contains the lower
* triangular part of the matrix A, and the strictly upper
* triangular part of A is not referenced.
*
* On exit, if INFO = 0, the factor U or L from the Cholesky
* factorization A = U**T*U or A = L*L**T.
*
* LDA (input) INTEGER
* The leading dimension of the array A. LDA >= max(1,N).
*
* INFO (output) INTEGER
* = 0: successful exit
* < 0: if INFO = -i, the i-th argument had an illegal value
* > 0: if INFO = i, the leading minor of order i is not
* positive definite, and the factorization could not be
* completed.
*
*/
ZCHECK_EQ(A.Size(0), A.Size(1));
integer N=A.Size(0), LDA=N, INFO;
char UPLO = 'U';
/* Call lapack routine */
dpotrf_(&UPLO, &N, A.Data(), &LDA, &INFO);
if (info!=NULL) *info=INFO;
return INFO==0;
}
#else
bool LUFactorization(zMatrix<double,zColMajor> &mat, zMatrix<long,zColMajor> &IPIV, long *info) {
ZLOGE<<"Not implemented due to the lack of the Lapack\n";
return false;
}
bool CholeskyFactorization(zMatrix<double,zColMajor> &A, long *info){
ZLOGE<<"Not implemented due to the lack of the Lapack\n";
return false;
}
bool Invert(zMatrix<double,zColMajor> &mat, long *info){
ZLOGE<<"Not implemented due to the lack of the Lapack\n";
return false;
}
bool SVD(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &U, zMatrix<double,zColMajor> &S, zMatrix<double,zColMajor> &VT, long *info){
ZLOGE<<"Not implemented due to the lack of the Lapack\n";
return false;
}
bool EigenSym(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &e, long *info){
ZLOGE<<"Not implemented due to the lack of the Lapack\n";
return false;
}
double Det(zMatrix<double,zColMajor> &A){
ZLOGE<<"Not implemented due to the lack of the Lapack\n";
return false;
}
bool EigRight(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &eigenVector, zMatrix<double,zColMajor> &eigenValueReal, zMatrix<double,zColMajor> &eigenValueImag, long *info){
ZLOGE<<"Not implemented due to the lack of the Lapack\n";
return false;
}
bool SolveLinearLeastSquare(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &B_X, long *info){
ZLOGE<<"Not implemented due to the lack of the Lapack\n";
return false;
}
bool SolveLinearLeastSquare2(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &B_X, long *info){
ZLOGE<<"Not implemented due to the lack of the Lapack\n";
return false;
}
bool SolveLinear(zMatrix<double,zColMajor> &A, zMatrix<double,zColMajor> &B_X, long *info){
ZLOGE<<"Not implemented due to the lack of the Lapack\n";
return false;
}
#endif
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMatrixLapack.cpp
|
C++
|
gpl3
| 33,496
|
#pragma once
#include <Math\Vector2.hpp>
//sub matrix support, works like matlab
namespace zzz{
template<typename T,class Major>
class zMatrixBaseR;
class EndlessArray
{
public:
explicit EndlessArray(int begin):begin_(begin){}
int begin_;
};
inline const EndlessArray Colon(int begin=0)
{
return EndlessArray(begin);
}
//continuous column vector
template<typename T,class Major>
class zVConstantContinuousVector : public zMatrixBaseR<T,Major>
{
using zMatrixBaseR<T,Major>::rows_;
using zMatrixBaseR<T,Major>::cols_;
public:
// constructor
explicit zVConstantContinuousVector(T v0, T v1, T step=1)
:zMatrixBaseR<T,Major>(zuint((v1-v0)/step+1),1),V0_(v0),V1_(v1),Step_(step){}
// operator()
using zMatrixBaseR<T,Major>::operator();
const T operator()(zuint r, zuint c) const {
CheckRange(r, c);
return V0_+r*Step_;
}
public:
T V0_,V1_,Step_;
};
template<typename T,class Major>
inline zVConstantContinuousVector<T,Major> Colon(T begin, T end, T step=1)
{
return zVConstantContinuousVector<T,Major>(begin,end,step);
}
inline zVConstantContinuousVector<double,zColMajor> Colond(double begin, double end, double step=1)
{
return zVConstantContinuousVector<double,zColMajor>(begin,end,step);
}
inline zVConstantContinuousVector<float,zColMajor> Colonf(float begin, float end, float step=1)
{
return zVConstantContinuousVector<float,zColMajor>(begin,end,step);
}
inline zVConstantContinuousVector<int,zColMajor> Colon(int begin, int end, int step=1)
{
return zVConstantContinuousVector<int,zColMajor>(begin,end,step);
}
inline zVConstantContinuousVector<int,zColMajor> Colon(const Vector2i &range, int step=1)
{
return zVConstantContinuousVector<int,zColMajor>(range[0],range[1],step);
}
template<typename T,class Major>
class zHConstantContinuousVector : public zMatrixBaseR<T,Major> //should not matter if rowmajor or colmajor
{
using zMatrixBaseR<T,Major>::rows_;
using zMatrixBaseR<T,Major>::cols_;
public:
//constructor
explicit zHConstantContinuousVector(T v0, T v1, T step=1)
:zMatrixBaseR<T,Major>(1,zuint((v1-v0)/step+1)),V0_(v0),V1_(v1),Step_(step){}
//operator()
using zMatrixBaseR<T,Major>::operator();
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
return V0_ + c * Step_;
}
public:
T V0_, V1_, Step_;
};
template<typename T,class Major>
inline zHConstantContinuousVector<T,Major> HColon(T begin, T end, T step=1)
{
return zHConstantContinuousVector<T,Major>(begin,end,step);
}
template<typename T,class Major>
class zSubMatrixR : public zMatrixBaseR<T,Major>
{
using zMatrixBaseR<T,Major>::rows_;
using zMatrixBaseR<T,Major>::cols_;
public:
zSubMatrixR(const zMatrixBaseR<T,Major> &mat, const int r, const int c):Mat_(mat),rtype_(ZMAT_IDX_CONST),ctype_(ZMAT_IDX_CONST),
zMatrixBaseR<T,Major>(1,1),ri_(r),ci_(c) {
ZCHECK_GE(ri_, 0);
ZCHECK_LT(ri_, (int)mat.rows_);
ZCHECK_GE(ci_, 0);
ZCHECK_LT(ci_, (int)mat.cols_);
}
zSubMatrixR(const zMatrixBaseR<T,Major> &mat, const int r, const EndlessArray &c):Mat_(mat),rtype_(ZMAT_IDX_CONST),ctype_(ZMAT_IDX_ENDLESS),
zMatrixBaseR<T,Major>(1,mat.cols_-c.begin_),ri_(r),ci_(c.begin_) {
ZCHECK_GE(ri_, 0);
ZCHECK_LT(ri_, (int)mat.rows_);
ZCHECK_GE(ci_, 0);
ZCHECK_LT(ci_, (int)mat.cols_);
}
zSubMatrixR(const zMatrixBaseR<T,Major> &mat, const int r, const zMatrixBaseR<int,Major> &c):Mat_(mat),rtype_(ZMAT_IDX_CONST),ctype_(ZMAT_IDX_ARRAY),
zMatrixBaseR<T,Major>(1,c.rows_),ri_(r),c_(&c) {
ZCHECK_GE(ri_, 0);
ZCHECK_LT(ri_, (int)mat.rows_);
ZCHECK_EQ(c.cols_, 1);
}
zSubMatrixR(const zMatrixBaseR<T,Major> &mat, const EndlessArray &r, const EndlessArray &c):Mat_(mat),rtype_(ZMAT_IDX_ENDLESS),ctype_(ZMAT_IDX_ENDLESS),
zMatrixBaseR<T,Major>(mat.rows_-r.begin_,mat.cols_-c.begin_),ri_(r.begin_),ci_(c.begin_) {
ZCHECK_GE(ri_, 0);
ZCHECK_LT(ri_, (int)mat.rows_);
ZCHECK_GE(ci_, 0);
ZCHECK_LT(ci_, (int)mat.cols_);
}
zSubMatrixR(const zMatrixBaseR<T,Major> &mat, const EndlessArray &r, const int c):Mat_(mat),rtype_(ZMAT_IDX_ENDLESS),ctype_(ZMAT_IDX_CONST),
zMatrixBaseR<T,Major>(mat.rows_-r.begin_,1),ri_(r.begin_),ci_(c) {
ZCHECK_GE(ri_, 0);
ZCHECK_LT(ri_, (int)mat.rows_);
ZCHECK_GE(ci_, 0);
ZCHECK_LT(ci_, (int)mat.cols_);
}
zSubMatrixR(const zMatrixBaseR<T,Major> &mat, const EndlessArray &r, const zMatrixBaseR<int,Major> &c):Mat_(mat),rtype_(ZMAT_IDX_ENDLESS),ctype_(ZMAT_IDX_ARRAY),
zMatrixBaseR<T,Major>(mat.rows_-r.begin_,c.rows_),ri_(r.begin_),c_(&c) {
ZCHECK_GE(ri_, 0);
ZCHECK_LT(ri_, (int)mat.rows_);
ZCHECK_EQ(c.cols_, 1);
}
zSubMatrixR(const zMatrixBaseR<T,Major> &mat, const zMatrixBaseR<int,Major> &r, const zMatrixBaseR<int,Major> &c):Mat_(mat),rtype_(ZMAT_IDX_ARRAY),ctype_(ZMAT_IDX_ARRAY),
zMatrixBaseR<T,Major>(r.rows_,c.rows_),r_(&r),c_(&c) {
ZCHECK_EQ(r.cols_, 1);
ZCHECK_EQ(c.cols_, 1);
}
zSubMatrixR(const zMatrixBaseR<T,Major> &mat, const zMatrixBaseR<int,Major> &r, const int c):Mat_(mat),rtype_(ZMAT_IDX_ARRAY),ctype_(ZMAT_IDX_CONST),
zMatrixBaseR<T,Major>(r.rows_,1),r_(&r),ci_(c) {
ZCHECK_EQ(r.cols_, 1);
ZCHECK_GE(ci_, 0);
ZCHECK_LT(ci_, (int)mat.cols_);
}
zSubMatrixR(const zMatrixBaseR<T,Major> &mat, const zMatrixBaseR<int,Major> &r, const EndlessArray &c):Mat_(mat),rtype_(ZMAT_IDX_ARRAY),ctype_(ZMAT_IDX_ENDLESS),
zMatrixBaseR<T,Major>(r.rows_,mat.cols_-c.begin_),r_(&r),ci_(c.begin_) {
ZCHECK_EQ(r.cols_, 1);
ZCHECK_GE(ci_, 0);
ZCHECK_LT(ci_, (int)mat.cols_);
}
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
int r2,c2;
switch(rtype_) {
case ZMAT_IDX_ARRAY: r2=(*r_)(r,0); break;
case ZMAT_IDX_CONST: r2=ri_; break;
case ZMAT_IDX_ENDLESS: r2=ri_+r; break;
}
switch(ctype_) {
case ZMAT_IDX_ARRAY: c2=(*c_)(c,0); break;
case ZMAT_IDX_CONST: c2=ci_; break;
case ZMAT_IDX_ENDLESS: c2=ci_+c; break;
}
ZCHECK_GE(r2, 0);
ZCHECK_LT(r2, (int)Mat_.rows_);
ZCHECK_GE(c2, 0);
ZCHECK_LT(c2, (int)Mat_.cols_);
return Mat_(zuint(r2),zuint(c2));
}
private:
const zMatrixBaseR<T,Major> &Mat_;
enum {ZMAT_IDX_ARRAY,ZMAT_IDX_CONST,ZMAT_IDX_ENDLESS} rtype_,ctype_;
int ri_, ci_;
const zMatrixBaseR<int,Major> *r_,*c_;
};
template<typename T,class Major>
class zSubMatrixW : public zMatrixBaseW<T,Major>
{
using zMatrixBaseR<T,Major>::rows_;
using zMatrixBaseR<T,Major>::cols_;
public:
zSubMatrixW(zMatrixBaseW<T,Major> &mat, const int r, const int c):Mat_(mat),rtype_(ZMAT_IDX_CONST),ctype_(ZMAT_IDX_CONST),
zMatrixBaseW<T,Major>(1,1),ri_(r),ci_(c) {
ZCHECK_GE(ri_, 0);
ZCHECK_LT(ri_, (int)mat.rows_);
ZCHECK_GE(ci_, 0);
ZCHECK_LT(ci_, (int)mat.cols_);
}
zSubMatrixW(zMatrixBaseW<T,Major> &mat, const int r, const EndlessArray &c):Mat_(mat),rtype_(ZMAT_IDX_CONST),ctype_(ZMAT_IDX_ENDLESS),
zMatrixBaseW<T,Major>(1,mat.cols_-c.begin_),ri_(r),ci_(c.begin_) {
ZCHECK_GE(ri_, 0);
ZCHECK_LT(ri_, (int)mat.rows_);
ZCHECK_GE(ci_, 0);
ZCHECK_LT(ci_, (int)mat.cols_);
}
zSubMatrixW(zMatrixBaseW<T,Major> &mat, const int r, const zMatrixBaseR<int,Major> &c):Mat_(mat),rtype_(ZMAT_IDX_CONST),ctype_(ZMAT_IDX_ARRAY),
zMatrixBaseW<T,Major>(1,c.rows_),ri_(r),c_(&c) {
ZCHECK_GE(ri_, 0);
ZCHECK_LT(ri_, (int)mat.rows_);
ZCHECK_EQ(c.cols_, 1);
}
zSubMatrixW(zMatrixBaseW<T,Major> &mat, const EndlessArray &r, const EndlessArray &c):Mat_(mat),rtype_(ZMAT_IDX_ENDLESS),ctype_(ZMAT_IDX_ENDLESS),
zMatrixBaseW<T,Major>(mat.rows_-r.begin_,mat.cols_-c.begin_),ri_(r.begin_),ci_(c.begin_) {
ZCHECK_GE(ri_, 0);
ZCHECK_LT(ri_, (int)mat.rows_);
ZCHECK_GE(ci_, 0);
ZCHECK_LT(ci_, (int)mat.cols_);
}
zSubMatrixW(zMatrixBaseW<T,Major> &mat, const EndlessArray &r, const int c):Mat_(mat),rtype_(ZMAT_IDX_ENDLESS),ctype_(ZMAT_IDX_CONST),
zMatrixBaseW<T,Major>(mat.rows_-r.begin_,1),ri_(r.begin_),ci_(c) {
ZCHECK_GE(ri_, 0);
ZCHECK_LT(ri_, (int)mat.rows_);
ZCHECK_GE(ci_, 0);
ZCHECK_LT(ci_, (int)mat.cols_);
}
zSubMatrixW(zMatrixBaseW<T,Major> &mat, const EndlessArray &r, const zMatrixBaseR<int,Major> &c):Mat_(mat),rtype_(ZMAT_IDX_ENDLESS),ctype_(ZMAT_IDX_ARRAY),
zMatrixBaseW<T,Major>(mat.rows_ - r.begin_, c.rows_),ri_(r.begin_),c_(&c) {
ZCHECK_GE(ri_, 0);
ZCHECK_LT(ri_, (int)mat.rows_);
ZCHECK_EQ(c.cols_, 1);
}
zSubMatrixW(zMatrixBaseW<T,Major> &mat, const zMatrixBaseR<int,Major> &r, const zMatrixBaseR<int,Major> &c):Mat_(mat),rtype_(ZMAT_IDX_ARRAY),ctype_(ZMAT_IDX_ARRAY),
zMatrixBaseW<T,Major>(r.rows_,c.rows_),r_(&r),c_(&c) {
ZCHECK_EQ(r.cols_, 1);
ZCHECK_EQ(c.cols_, 1);
}
zSubMatrixW(zMatrixBaseW<T,Major> &mat, const zMatrixBaseR<int,Major> &r, const int c):Mat_(mat),rtype_(ZMAT_IDX_ARRAY),ctype_(ZMAT_IDX_CONST),
zMatrixBaseW<T,Major>(r.rows_,1),r_(&r),ci_(c) {
ZCHECK_EQ(r.cols_, 1);
ZCHECK_GE(ci_, 0);
ZCHECK_LT(ci_, (int)mat.cols_);
}
zSubMatrixW(zMatrixBaseW<T,Major> &mat, const zMatrixBaseR<int,Major> &r, const EndlessArray &c):Mat_(mat),rtype_(ZMAT_IDX_ARRAY),ctype_(ZMAT_IDX_ENDLESS),
zMatrixBaseW<T,Major>(r.rows_,mat.cols_-c.begin_),r_(&r),ci_(c.begin_) {
ZCHECK_EQ(r.cols_, 1);
ZCHECK_GE(ci_, 0);
ZCHECK_LT(ci_, (int)mat.cols_);
}
const T operator()(zuint r, zuint c) const
{
CheckRange(r, c);
int r2,c2;
switch(rtype_)
{
case ZMAT_IDX_ARRAY: r2=(*r_)(r,0); break;
case ZMAT_IDX_CONST: r2=ri_; break;
case ZMAT_IDX_ENDLESS: r2=ri_+r; break;
}
switch(ctype_)
{
case ZMAT_IDX_ARRAY: c2=(*c_)(c,0); break;
case ZMAT_IDX_CONST: c2=ci_; break;
case ZMAT_IDX_ENDLESS: c2=ci_+c; break;
}
assert(r2>=0 && r2<(int)Mat_.rows_ && c2>=0 && c2<(int)Mat_.cols_);
return Mat_(zuint(r2),zuint(c2));
}
T& operator()(zuint r, zuint c)
{
CheckRange(r, c);
int r2,c2;
switch(rtype_) {
case ZMAT_IDX_ARRAY: r2=(*r_)(r,0); break;
case ZMAT_IDX_CONST: r2=ri_; break;
case ZMAT_IDX_ENDLESS: r2=ri_+r; break;
}
switch(ctype_) {
case ZMAT_IDX_ARRAY: c2=(*c_)(c,0); break;
case ZMAT_IDX_CONST: c2=ci_; break;
case ZMAT_IDX_ENDLESS: c2=ci_+c; break;
}
assert(r2>=0 && r2<(int)Mat_.rows_ && c2>=0 && c2<(int)Mat_.cols_);
return Mat_(zuint(r2),zuint(c2));
}
// using zMatrixBaseW<T,Major>::operator=;
const zMatrixBaseW<T,Major>& operator=(const zSubMatrixW<T,Major>& other)
{
return zMatrixBaseW<T,Major>::operator=(static_cast<const zMatrixBaseR<T,Major>&>(other));
}
const zMatrixBaseW<T,Major>& operator=(const zMatrixBaseR<T,Major>& other)
{
return zMatrixBaseW<T,Major>::operator=(other);
}
private:
zMatrixBaseW<T,Major> &Mat_;
enum {ZMAT_IDX_ARRAY,ZMAT_IDX_CONST,ZMAT_IDX_ENDLESS} rtype_,ctype_;
int ri_, ci_;
const zMatrixBaseR<int,Major> *r_,*c_;
};
}
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zSubMatrix.hpp
|
C++
|
gpl3
| 11,301
|
#pragma once
#include <vector>
#include "zMatrixBase.hpp"
// Sparse Matrix, still lack of operation
namespace zzz {
// It should no be derived from zMatrixBaseW,
// since we don't want it to be writable as general zMatrixBaseW.
// Although it can, any operation will destroy the sparsity.
template<typename T, class Major=zColMajor>
class zSparseMatrix : public zMatrixBaseW<T,Major>
{
public:
struct zSparseMatrixNode {
public:
zSparseMatrixNode(zuint row, zuint col, const T& v):row_(row), col_(col), v_(v) {}
zuint row_, col_;
T v_;
};
zSparseMatrix():zMatrixBaseW<T,Major>(0, 0), sorted_(SORT_NONE){}
zSparseMatrix(zuint row, zuint col):zMatrixBaseW<T,Major>(row, col), sorted_(SORT_NONE){}
zSparseMatrix(const zSparseMatrix<T,Major> &other)
:zMatrixBaseW<T,Major>(other), sorted_(other.sorted_), v_(other.v_){}
explicit zSparseMatrix(const zMatrixBaseR<T,Major> &other)
:zMatrixBaseW<T,Major>(other.rows_, other.cols_), sorted_(SORT_COL) {
for (zuint c=0; c<cols_; c++) for (zuint r=0; r<rows_; r++) {
T v=other(r,c);
if (v!=0) v_.push_back(zSparseMatrixNode(r, c, v));
}
}
void SetSize(zuint row, zuint col) {
Clear();
rows_=row;
cols_=col;
}
// Clear data only, do not change size
void ClearData() {
v_.clear();
}
// Get number of non-zero data cell
zuint DataSize() const {
return v_.size();
}
// Check if exist
bool CheckExist(zuint row, zuint col) const {
return GetConstNode(row, col)!=NULL;
}
// This is slow, O(N) time
bool Remove(zuint row, zuint col) {
zSparseMatrixNode* node = GetNode(row, col);
if (!node) return false;
v_.erase(node-v_.data()+v_.begin());
return true;
}
const T operator()(zuint row, zuint col) const {
return Get(row, col);
}
T& operator()(zuint row, zuint col) {
return MustGet(row, col);
}
const zSparseMatrix<T,Major>& operator=(const zMatrixBaseR<T,Major> &other) {
ZCHECK_EQ(rows_, other.rows_);
ZCHECK_EQ(cols_, other.cols_);
for (zuint i=0; i<rows_; i++) for (zuint j=0; j<cols_; j++) {
T v=other(i,j);
if (v!=0) AddData(i, j, v);
}
return *this;
}
const T Get(zuint row, zuint col) const {
const zSparseMatrixNode* node = GetConstNode(row, col);
if (node)
return node->v_;
else
return ZERO_VALUE;
}
T& MustGet(zuint row, zuint col) {
zSparseMatrixNode* node = GetNode(row, col);
if (node)
return node->v_;
else {
zSparseMatrixNode newnode(row, col, 0);
if (sorted_==SORT_ROW && !v_.empty() && !RowMajorLess()(v_.back(), newnode)) sorted_=SORT_NONE;
else if (sorted_==SORT_COL && !v_.empty() && !ColMajorLess()(v_.back(), newnode)) sorted_=SORT_NONE;
v_.push_back(newnode);
return v_.back().v_;
}
}
void AddData(int row, int col, const T& number) {
if (number!=0)
MustGet(row, col) = number;
}
zSparseMatrixNode& GetNode(zuint i) {
return v_[i];
}
const zSparseMatrixNode& GetNode(zuint i) const {
return v_[i];
}
void ColMajorSort() {
if (sorted_ == SORT_COL) return;
sort(v_.begin(), v_.end(), ColMajorLess());
sorted_ = SORT_COL;
}
void RowMajorSort() {
if (sorted_ == SORT_ROW) return;
sort(v_.begin(), v_.end(), RowMajorLess());
sorted_ = SORT_ROW;
}
private:
struct RowMajorLess {
bool operator()(const zSparseMatrixNode &a, const zSparseMatrixNode &b) {
if (a.row_ < b.row_ || (a.row_==b.row_ && a.col_<b.col_))
return true;
return false;
}
};
struct ColMajorLess {
bool operator()(const zSparseMatrixNode &a, const zSparseMatrixNode &b) {
if (a.col_ < b.col_ || (a.col_==b.col_ && a.row_<b.row_))
return true;
return false;
}
};
struct RowColEqual {
RowColEqual(zuint row, zuint col):row_(row), col_(col){}
bool operator()(const zSparseMatrixNode &n) {
return n.row_ == row_ && n.col_ == col_;
}
zuint row_, col_;
};
zSparseMatrixNode* GetNode(zuint row, zuint col) {
vector<zSparseMatrixNode>::iterator vi;
switch (sorted_) {
case SORT_ROW:
vi = std::lower_bound(v_.begin(), v_.end(), zSparseMatrixNode(row, col, 0), RowMajorLess());
if (vi!=v_.end() && RowColEqual(row, col)(*vi)) return vi-v_.begin()+v_.data();
return NULL;
case SORT_COL:
vi = std::lower_bound(v_.begin(), v_.end(), zSparseMatrixNode(row, col, 0), ColMajorLess());
if (vi!=v_.end() && RowColEqual(row, col)(*vi)) return vi-v_.begin()+v_.data();
return NULL;
case SORT_NONE:
vi = std::find_if(v_.begin(), v_.end(), RowColEqual(row, col));
if (vi == v_.end()) return NULL;
else return vi-v_.begin()+v_.data();
default:
ZCHECK(false)<<"Unknown sort type, this should not happen!";
}
return NULL;
}
const zSparseMatrixNode* GetConstNode(zuint row, zuint col) const {
vector<zSparseMatrixNode>::const_iterator vi;
switch (sorted_) {
case SORT_ROW:
vi = std::lower_bound(v_.begin(), v_.end(), zSparseMatrixNode(row, col, 0), RowMajorLess());
if (vi!=v_.end() && RowColEqual(row, col)(*vi)) return vi-v_.begin()+v_.data();
return NULL;
case SORT_COL:
vi = std::lower_bound(v_.begin(), v_.end(), zSparseMatrixNode(row, col, 0), ColMajorLess());
if (vi!=v_.end() && RowColEqual(row, col)(*vi)) return vi-v_.begin()+v_.data();
return NULL;
case SORT_NONE:
vi = std::find_if(v_.begin(), v_.end(), RowColEqual(row, col));
if (vi == v_.end()) return NULL;
else return vi-v_.begin()+v_.data();
default:
ZCHECK(false)<<"Unknown sort type, this should not happen!";
}
return NULL;
}
static T ZERO_VALUE;
enum SortType {SORT_NONE, SORT_ROW, SORT_COL} sorted_;
std::vector<zSparseMatrixNode> v_;
};
template<typename T, class Major>
T zSparseMatrix<T, Major>::ZERO_VALUE=T(0);
template<typename T, class Major>
zSparseMatrix<T, Major> ATA(zSparseMatrix<T, Major> &A)
{
zSparseMatrix<T, Major> ret(A.Size(1), A.Size(1));
ret.RowMajorSort();
A.ColMajorSort();
vector<pair<int,int> > col_start;
int last_col = -1;
for (zuint i=0; i<A.DataSize(); i++) {
int this_col = A.GetNode(i).col_;
if (this_col > last_col) {
col_start.push_back(make_pair(i,this_col));
last_col=this_col;
}
}
col_start.push_back(make_pair(int(A.DataSize()),int(-1)));
for (zuint line1=0;line1<col_start.size()-1;line1++) {
for (zuint line2=0;line2<col_start.size()-1;line2++) {
int pos1=col_start[line1].first, pos2=col_start[line2].first;
int r=col_start[line1].second, c=col_start[line2].second;
T v=0;
while(pos1<col_start[line1+1].first && pos2<col_start[line2+1].first) {
const zSparseMatrix<T, Major>::zSparseMatrixNode &node1=A.GetNode(pos1), &node2=A.GetNode(pos2);
if (node1.row_ == node2.row_) {
v += node1.v_ * node2.v_;
pos1++; pos2++;
} else if (node1.row_ > node2.row_)
pos2++;
else
pos1++;
}
if (v!=0)
ret.AddData(r, c, v);
}
}
return ret;
}
}; // namespace zzz
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zSparseMatrix.hpp
|
C++
|
gpl3
| 7,383
|
#include <zMatrixFunction.hpp>
#include <zCoreAutoLink.hpp>
namespace zzz {
zMatrix<double, zColMajor> Rand(zuint row, zuint col)
{
RandomReal<double> r(0.0, 1.0);
zMatrix<double, zColMajor> mat(row, col);
for (zuint i=0; i<mat.size(); i++)
mat[i]=r.Rand();
return mat;
}
}; // namespace zzz
|
zzz-engine
|
zzzEngine/zMatrix/zMatrix/zMatrixFunction.cpp
|
C++
|
gpl3
| 317
|
SET(THISLIB zGraphics)
FILE(GLOB_RECURSE LibSrc *.cpp)
FILE(GLOB_RECURSE RemoveSrc zScriptRenderer.cpp)
FILE(GLOB_RECURSE RemoveSrc1 z*.cpp)
FILE(GLOB_RECURSE RemoveSrc2 *Script.cpp)
LIST(REMOVE_ITEM LibSrc ${RemoveSrc})
LIST(REMOVE_ITEM LibSrc ${RemoveSrc1})
LIST(REMOVE_ITEM LibSrc ${RemoveSrc2})
#MESSAGE(STATUS "files ${RemoveSrc2}")
IF( "${DEBUG_MODE}" EQUAL "1")
SET(THISLIB ${THISLIB}D)
ENDIF()
IF( "${BIT_MODE}" EQUAL "64" )
SET(THISLIB ${THISLIB}_X64)
ENDIF()
ADD_LIBRARY(${THISLIB} STATIC ${LibSrc})
|
zzz-engine
|
zzzEngine/zGraphics/CMakeLists.txt
|
CMake
|
gpl3
| 528
|
#pragma once
#include <EnvDetect.hpp>
#include <LibraryConfig.hpp>
#ifdef ZZZ_LIB_MINIMAL
#include "zGraphicsConfig.hpp.minimal"
#else
#ifdef ZZZ_OS_WIN32
#include "zGraphicsConfig.hpp.win32"
#endif
#ifdef ZZZ_OS_WIN64
#include "zGraphicsConfig.hpp.win64"
#endif
#ifdef ZZZ_OS_MINGW
#include "zGraphicsConfig.hpp.MinGW"
#endif
#ifdef ZZZ_OS_LINUX
#include "zGraphicsConfig.hpp.linux"
#endif
#endif // ZZZ_LIB_MINIMAL
#ifdef ZZZ_DYNAMIC
#ifdef ZGRAPHICS_SOURCE
#define ZGRAPHICS_FUNC __declspec(dllexport)
#define ZGRAPHICS_CLASS __declspec(dllexport)
#else
#define ZGRAPHICS_FUNC __declspec(dllimport)
#define ZGRAPHICS_CLASS __declspec(dllimport)
#endif
#else
#define ZGRAPHICS_FUNC
#define ZGRAPHICS_CLASS
#endif
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/zGraphicsConfig.hpp
|
C++
|
gpl3
| 790
|
#pragma once
// Separate link so when change a lib, only link needs redo.
#include "zGraphicsConfig.hpp"
#include "zGraphicsAutoLink3rdParty.hpp"
#ifndef ZZZ_NO_PRAGMA_LIB
#ifdef ZZZ_COMPILER_MSVC
#ifdef ZZZ_DYNAMIC
#ifdef ZZZ_DEBUG
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"zGraphicsdllD.lib")
#else
#pragma comment(lib,"zGraphicsdllD_x64.lib")
#endif // ZZZ_OS_WIN64
#else
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"zGraphicsdll.lib")
#else
#pragma comment(lib,"zGraphicsdll_x64.lib")
#endif // ZZZ_OS_WIN64
#endif
#else
#ifdef ZZZ_DEBUG
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"zGraphicsD.lib")
#else
#pragma comment(lib,"zGraphicsD_x64.lib")
#endif // ZZZ_OS_WIN64
#else
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"zGraphics.lib")
#else
#pragma comment(lib,"zGraphics_x64.lib")
#endif // ZZZ_OS_WIN64
#endif
#endif
#endif // ZZZ_COMPILER_MSVC
#endif // ZZZ_NO_PRAGMA_LIB
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/zGraphicsAutoLink.hpp
|
C++
|
gpl3
| 1,031
|
#pragma once
// Separate link so when change a lib, only link needs redo.
#include "zGraphicsConfig.hpp"
#ifndef ZZZ_NO_PRAGMA_LIB
#ifdef ZZZ_COMPILER_MSVC
// GLEW will be built along with the engine
#ifdef ZZZ_DEBUG
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"GlewD.lib")
#else
#pragma comment(lib,"GlewD_X64.lib")
#endif // ZZZ_OS_WIN64
#else
#ifndef ZZZ_OS_WIN64
#pragma comment(lib,"Glew.lib")
#else
#pragma comment(lib,"Glew_X64.lib")
#endif // ZZZ_OS_WIN64
#endif // ZZZ_DEBUG
#ifdef ZZZ_LIB_OPENGL
#pragma comment(lib,"opengl32.lib")
#pragma comment(lib,"glu32.lib")
#endif // ZZZ_LIB_OPENGL
#ifdef ZZZ_LIB_ANTTWEAKBAR
#ifndef ZZZ_OS_WIN64
#pragma comment(lib, "AntTweakBar.lib")
#else
#pragma comment(lib, "AntTweakBar64.lib")
#endif // ZZZ_OS_WIN64
#endif // ZZZ_LIB_ANTTWEAKBAR
#ifdef ZZZ_LIB_GLFW
#ifdef ZZZ_DEBUG
#pragma comment(lib, "GLFWD.lib")
#else
#pragma comment(lib, "GLFW.lib")
#endif /// ZZZ_DEBUG
#endif // ZZZ_LIB_GLFW
// Freeglut is included in zzzEngine
#ifndef ZZZ_OS_WIN64
#ifdef ZZZ_DEBUG
#pragma comment(lib,"freeglutD.lib")
#else
#pragma comment(lib,"freeglut.lib")
#endif
#else
#ifdef ZZZ_DEBUG
#pragma comment(lib,"freeglutD_X64.lib")
#else
#pragma comment(lib,"freeglut_X64.lib")
#endif
#endif // ZZZ_OS_WIN64
#ifdef ZZZ_LIB_GLUI
#pragma comment(lib,"glui32.lib")
#endif // ZZZ_LIB_GLUI
#ifdef ZZZ_LIB_QT4
#if !defined(ZZZ_OS_WIN64)
#ifdef ZZZ_DEBUG
#pragma comment(lib,"QtGuid4.lib")
#pragma comment(lib,"QtCored4.lib")
#pragma comment(lib,"QtOpenGLd4.lib")
#else
#pragma comment(lib,"QtGui4.lib")
#pragma comment(lib,"QtCore4.lib")
#pragma comment(lib,"QtOpenGL4.lib")
#endif
#else
#ifdef ZZZ_DEBUG
#pragma comment(lib,"QtGui_X64d4.lib")
#pragma comment(lib,"QtCore_X64d4.lib")
#pragma comment(lib,"QtOpenGL_X64d4.lib")
#else
#pragma comment(lib,"QtGui_X644.lib")
#pragma comment(lib,"QtCore_X644.lib")
#pragma comment(lib,"QtOpenGL_X644.lib")
#endif
#endif // ZZZ_OS_WIN64
#endif // ZZZ_LIB_QT4
#ifdef ZZZ_OS_WIN
#pragma comment(lib, "WINMM.LIB")
#endif
#endif // ZZZ_COMPILER_MSVC
#endif // ZZZ_NO_PRAGMA_LIB
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/zGraphicsAutoLink3rdParty.hpp
|
C++
|
gpl3
| 2,271
|
#include "ArcBallRenderer.hpp"
namespace zzz {
ArcBallRenderer::ArcBallRenderer()
{
pCurObjArcBall_=NULL;
pCurEnvArcBall_=NULL;
lockArcBall_=false;
}
ArcBallRenderer::~ArcBallRenderer()
{
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/ArcBallRenderer.cpp
|
C++
|
gpl3
| 216
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "ArcBallRenderer.hpp"
#include "../Graphics/ArcBall.hpp"
namespace zzz {
class ZGRAPHICS_CLASS OneObjRenderer : public ArcBallRenderer
{
public:
OneObjRenderer();
void ResetArcball();
ArcBallGUI objArcBall_;
protected:
void CreateMsg();
void AfterOnSize(unsigned int nType, int cx, int cy);
void DrawObj();
void SetupCamera();
bool InitData();
public:
void OnMouseMove(unsigned int nFlags,int x,int y);
void OnLButtonDown(unsigned int nFlags,int x,int y);
void OnLButtonUp(unsigned int nFlags,int x,int y);
void OnSize(unsigned int nType, int cx, int cy);
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/OneObjRenderer.hpp
|
C++
|
gpl3
| 643
|
#include "OneObjEnvRenderer.hpp"
namespace zzz {
void OneObjEnvRenderer::AfterOnSize(unsigned int nType, int cx, int cy)
{
camera_.OnSize(nType, cx, cy);
objArcBall_.OnSize(nType, cx, cy);
envArcBall_.OnSize(nType, cx, cy);
}
void OneObjEnvRenderer::DrawObj()
{
glColor3f(1.0,1.0,1.0);
glBegin(GL_QUADS);
glVertex3d(-1,-1,0);
glVertex3d(1,-1,0);
glVertex3d(1,1,0);
glVertex3d(-1,1,0);
glEnd();
}
void OneObjEnvRenderer::SetupCamera()
{
camera_.ApplyGL();
objArcBall_.ApplyGL();
}
OneObjEnvRenderer::OneObjEnvRenderer()
{
pCurObjArcBall_=&objArcBall_;
pCurEnvArcBall_=&envArcBall_;
}
void OneObjEnvRenderer::OnLButtonDown(unsigned int nFlags,int x,int y)
{
if (!lockArcBall_) {
objArcBall_.OnLButtonDown(nFlags, x, y);
envArcBall_.OnLButtonDown(nFlags, x, y);
}
}
void OneObjEnvRenderer::OnLButtonUp(unsigned int nFlags,int x,int y)
{
objArcBall_.OnLButtonUp(nFlags, x, y);
envArcBall_.OnLButtonUp(nFlags, x, y);
}
void OneObjEnvRenderer::OnRButtonDown(unsigned int nFlags,int x,int y)
{
if (!lockArcBall_) {
envArcBall_.OnLButtonDown(nFlags, x, y);
}
}
void OneObjEnvRenderer::OnRButtonUp(unsigned int nFlags,int x,int y)
{
envArcBall_.OnLButtonUp(nFlags, x, y);
}
void OneObjEnvRenderer::OnMButtonDown(unsigned int nFlags,int x,int y)
{
if (!lockArcBall_) {
objArcBall_.OnLButtonDown(nFlags, x, y);
}
}
void OneObjEnvRenderer::OnMButtonUp(unsigned int nFlags,int x,int y)
{
objArcBall_.OnLButtonUp(nFlags, x, y);
}
void OneObjEnvRenderer::OnMouseMove(unsigned int nFlags,int x,int y)
{
if (!lockArcBall_) {
objArcBall_.OnMouseMove(nFlags, x, y);
envArcBall_.OnMouseMove(nFlags, x, y);
Redraw();
}
}
void OneObjEnvRenderer::ResetArcball()
{
objArcBall_.Reset();
envArcBall_.Reset();
}
bool OneObjEnvRenderer::InitData()
{
envArcBall_.Init(this);
objArcBall_.Init(this);
return ArcBallRenderer::InitData();
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/OneObjEnvRenderer.cpp
|
C++
|
gpl3
| 2,006
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "Renderer.hpp"
#include "../Graphics/Camera.hpp"
#include <Math/Vector2.hpp>
#include "../GraphicsGUI/MovingCameraGUI.hpp"
namespace zzz{
class ZGRAPHICS_CLASS CameraRenderer : public Renderer
{
public:
CameraRenderer();
void DrawObj();
void SetupCamera();
void AfterOnSize(unsigned int nType, int cx, int cy);
bool InitData();
void OnMouseMove(unsigned int nFlags,int x,int y);
void OnLButtonDown(unsigned int nFlags,int x,int y);
void OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y);
void OnChar(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags);
MovingCameraGUI camera_;
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/CameraRenderer.hpp
|
C++
|
gpl3
| 704
|
#pragma once
#include "Vis2DRenderer.hpp"
#include <Image/Image.hpp>
#include <Math/Vector2.hpp>
namespace zzz{
/// To manipulate A SINGLE image
/// some functions are overriden to satisfy the relative to image originate
template<typename T>
class OneImageRenderer : public Vis2DRenderer, public GraphicsHelper
{
public:
OneImageRenderer():image_(NULL){}
Vector2d GetHoverPixel(int mouse_x, int mouse_y) const
{
if (image_==NULL) return Vector2d(-1,-1);
Vector2d p=Vis2DRenderer::GetHoverPixel(mouse_x, mouse_y);
p[0]-=image_->orir_;
p[1]-=image_->oric_;
return p;
}
/// ATTENTION this cannot be inside glBegin~glEnd
Vector3d UnProjectRelative(double winx,double winy) const
{
if (image_==NULL) return Vector3d(0);
return Vis2DRenderer::UnProjectRelative(winx+image_->oric_, winy+image_->orir_);
}
void DrawObj()
{
if (image_!=NULL) DrawImage(*image_);
}
Image<T> *image_;
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/OneImageRenderer.hpp
|
C++
|
gpl3
| 973
|
#pragma once
#include <zGraphicsConfig.hpp>
#include <Math/Vector2.hpp>
#include "../Graphics/Coordinate.hpp"
#include "../Resource/Mesh/Mesh.hpp"
#include "../Resource/Texture/TextureSpecify.hpp"
#include "../Resource/Shader/ShaderSpecify.hpp"
#include "../FBO/FBO.hpp"
#include "../FBO/RenderBuffer.hpp"
#include "OneObjRenderer.hpp"
namespace zzz
{
class ZGRAPHICS_CLASS ControlRenderer : public OneObjRenderer
{
public:
ControlRenderer();
virtual bool Draw();
virtual bool InitData();
virtual void OnMouseMove(unsigned int nFlags,int x,int y);
virtual void OnLButtonDown(unsigned int nFlags,int x,int y);
virtual void OnLButtonUp(unsigned int nFlags,int x,int y);
virtual void OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags);
virtual void OnKeyUp(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags);
virtual void OnSize(unsigned int nType, int cx, int cy);
bool LoadObj(const string & filename);
protected:
vector<Cartesian3DCoordf> ControlPoints_;
vector<Cartesian3DCoordf> selected_;
int FindNearest(int x,int y);
int FindNearestSelected(int x,int y);
void RenderIdMap();
vector<zuint> mesh_group_end_;
TriMesh *mesh_;
FBO *fbo_;
Texture2D3ub *target_;
Renderbuffer *depth_;
GLdouble modelMatrix_[16], projMatrix_[16];
GLint viewport_[4];
zuint keyDown_;
int overpoint_,selectedpoint_;
double selectedx_,selectedy_,selectedz_;
double selectedwx_,selectedwy_;
GLUquadricObj* quadric;
bool showObj_,showCpt_;
bool leftButton_, middleButton_;
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/ControlRenderer.hpp
|
C++
|
gpl3
| 1,612
|
#include "Vis2DRenderer.hpp"
namespace zzz{
zzz::Vis2DRenderer::Vis2DRenderer()
{
posx_=0;posy_=0;
zoomratio_=1;
showMsg_=false;
allowmove_=true;
allowzoom_=true;
middleButton_ = false;
}
void Vis2DRenderer::OnMouseMove(unsigned int nFlags,int x,int y)
{
if(allowmove_ && middleButton_)
{
posx_+=x-lastx_;
posy_-=y-lasty_;
lastx_=x;
lasty_=y;
Redraw();
}
}
void Vis2DRenderer::OnMButtonDown(unsigned int nFlags,int x,int y)
{
middleButton_=true;
lastx_=x;
lasty_=y;
}
void Vis2DRenderer::OnMButtonUp(unsigned int nFlags,int x,int y)
{
middleButton_=false;
if (middletimer_.Elapsed()<0.3)
{
zoomratio_=1;
posx_=0;
posy_=0;
Redraw();
}
middletimer_.Restart();
}
bool Vis2DRenderer::InitState()
{
Renderer::InitState();
glDisable(GL_DEPTH_TEST);
return true;
}
void Vis2DRenderer::SetCenter(int width,int height)
{
posx_=(width_-width)/2;
posy_=(height_-height)/2;
}
void Vis2DRenderer::OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y)
{
if (!allowzoom_) return;
double newratio;
if (zDelta>0) newratio=zoomratio_*1.1;
else newratio=zoomratio_/1.1;
posx_=x-(x-posx_)*newratio/zoomratio_;
posy_=height_-y-(height_-y-posy_)*newratio/zoomratio_;
zoomratio_=newratio;
Redraw();
}
void Vis2DRenderer::SetRasterPosRelative(double x, double y) const
{
SetRasterPos(posx_+x*zoomratio_, posy_+y*zoomratio_);
}
Vector3d Vis2DRenderer::UnProjectRelative(double winx,double winy) const
{
return UnProject(posx_+winx*zoomratio_, posy_+winy*zoomratio_, 0);
}
Vector2d Vis2DRenderer::GetHoverPixel(int mouse_x, int mouse_y, int img_x, int img_y) const
{
double glx=mouse_x,gly=height_-mouse_y; //to opengl coordinate
glx-=posx_+img_x;gly-=posy_+img_y; //to image coordinate
glx/=zoomratio_;gly/=zoomratio_; //unzoom
return Vector2d(gly,glx); //to row,column coordinate
}
void Vis2DRenderer::DrawObj()
{
return;
}
void Vis2DRenderer::Draw2DPoint(double x, double y, const Colorf& color, float size)
{
color.ApplyGL();
GLPointSize::Set(size);
Vector3d p=UnProjectRelative(x,y);
glBegin(GL_POINTS);
glVertex3dv(p.Data());
glEnd();
GLPointSize::Restore();
}
void Vis2DRenderer::Draw2DLine(double x0, double y0, double x1, double y1, const zzz::Colorf& color, float size)
{
color.ApplyGL();
GLLineWidth::Set(size);
Vector3d p0=UnProjectRelative(x0,y0);
Vector3d p1=UnProjectRelative(x1,y1);
glBegin(GL_LINES);
glVertex3dv(p0.Data());
glVertex3dv(p1.Data());
glEnd();
GLLineWidth::Restore();
}
void Vis2DRenderer::SetupCamera()
{
Renderer::SetupCamera();
glPixelZoom(zoomratio_,zoomratio_);
glPixelStorei(GL_UNPACK_ALIGNMENT,1);
SetRasterPos(posx_, posy_);
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/Vis2DRenderer.cpp
|
C++
|
gpl3
| 2,846
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "../FBO/FBO.hpp"
#include "../FBO/RenderBuffer.hpp"
#include <common.hpp>
#include "../Resource/Texture/TextureSpecify.hpp"
#include "../Resource/Mesh/Mesh.hpp"
#include "../Resource/Shader/Shader.hpp"
#include <Utility/Singleton.hpp>
#ifdef ZZZ_LIB_BOOST
#include <boost/function.hpp>
namespace zzz{
class ZGRAPHICS_CLASS RendererHelper : public Singleton<RendererHelper>
{
public:
RendererHelper();
~RendererHelper();
void RenderCubemap(TextureCube &t, TriMesh &o,Cartesian3DCoordf &c,Shader &s);
void RenderCubemap(TextureCube &t, Cartesian3DCoordf &c, boost::function<void (void)> drawfunc);
void RenderCubemap(Texture2D *t, Cartesian3DCoordf &c, boost::function<void (void)> drawfunc);
void RenderCubemap(Texture2D *t, Texture2D *depth, Cartesian3DCoordf &c, boost::function<void (void)> drawfunc);
void RenderToTexture(Texture2D &tex, boost::function<void (void)> setupcamera, boost::function<void (void)> drawfunc);
FBO fbo;
Texture2D depthbuffer;
double zNear, zFar;
static Colorui8 ZuintToColor(zuint32 x);
static zuint32 ColorToZuint(const Vector3ui8 &c);
static zuint32 ColorToZuint(const Vector4ui8 &c);
};
}
#endif // ZZZ_LIB_BOOST
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/RendererHelper.hpp
|
C++
|
gpl3
| 1,261
|
#include "OneObjRenderer.hpp"
#include <Utility\StringPrintf.hpp>
namespace zzz {
OneObjRenderer::OneObjRenderer()
{
pCurObjArcBall_=&objArcBall_;
pCurEnvArcBall_=NULL;
}
void OneObjRenderer::AfterOnSize(unsigned int nType, int cx, int cy)
{
camera_.OnSize(nType, cx, cy);
objArcBall_.OnSize(nType, cx, cy);
}
void OneObjRenderer::SetupCamera()
{
camera_.ApplyGL();
objArcBall_.ApplyGL();
}
void OneObjRenderer::OnLButtonDown(unsigned int nFlags,int x,int y)
{
if (!lockArcBall_) {
objArcBall_.OnLButtonDown(nFlags, x, y);
}
}
void OneObjRenderer::OnLButtonUp(unsigned int nFlags,int x,int y)
{
objArcBall_.OnLButtonUp(nFlags, x, y);
}
void OneObjRenderer::OnMouseMove(unsigned int nFlags,int x,int y)
{
if (!lockArcBall_) {
objArcBall_.OnMouseMove(nFlags, x, y);
Redraw();
}
ArcBallRenderer::OnMouseMove(nFlags, x, y);
}
void OneObjRenderer::OnSize(unsigned int nType, int cx, int cy)
{
if (cy > 0) {
objArcBall_.OnSize(nType, cx,cy);
}
ArcBallRenderer::OnSize(nType,cx,cy);
}
void OneObjRenderer::ResetArcball()
{
objArcBall_.Reset();
}
void OneObjRenderer::CreateMsg()
{
SStringPrintf(msg_,"Res: %d x %d, SPF: %lf = FPS: %lf",width_,height_,SPF_,FPS_);
}
void OneObjRenderer::DrawObj()
{
glColor3f(1.0,1.0,1.0);
glBegin(GL_QUADS);
glVertex3d(-1,-1,0);
glVertex3d(1,-1,0);
glVertex3d(1,1,0);
glVertex3d(-1,1,0);
glEnd();
}
bool OneObjRenderer::InitData()
{
objArcBall_.Init(this);
return ArcBallRenderer::InitData();
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/OneObjRenderer.cpp
|
C++
|
gpl3
| 1,581
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "ArcBallRenderer.hpp"
namespace zzz {
class ZGRAPHICS_CLASS MultiObjEnvRenderer : public ArcBallRenderer
{
public:
MultiObjEnvRenderer();
void ResetArcball();
int curObjArcBall_;
bool allArcBall_;
ArcBallGUI objArcBall_[10]; //arcball for object rotation
ArcBallGUI envArcBall_; //arcball for environment rotation
protected:
void CreateMsg();
void DrawObj();
void SetupCamera();
void AfterOnSize(unsigned int nType, int cx, int cy);
bool InitData();
public:
void OnMouseMove(unsigned int nFlags,int x,int y);
void OnLButtonDown(unsigned int nFlags,int x,int y);
void OnLButtonUp(unsigned int nFlags,int x,int y);
void OnRButtonDown(unsigned int nFlags,int x,int y);
void OnRButtonUp(unsigned int nFlags,int x,int y);
void OnMButtonDown(unsigned int nFlags,int x,int y);
void OnMButtonUp(unsigned int nFlags,int x,int y);
void OnChar(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags);
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/MultiObjEnvRenderer.hpp
|
C++
|
gpl3
| 1,014
|
#pragma once
#include <zGraphicsConfig.hpp>
#include <common.hpp>
#include "../GraphicsGUI/ArcBallGUI.hpp"
#include "Renderer.hpp"
namespace zzz {
class ZGRAPHICS_CLASS ArcBallRenderer : public Renderer
{
public:
ArcBallRenderer();
virtual ~ArcBallRenderer();
ArcBallGUI *pCurObjArcBall_,*pCurEnvArcBall_;
bool lockArcBall_;
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/ArcBallRenderer.hpp
|
C++
|
gpl3
| 361
|
#include "RendererHelper.hpp"
#include "../Graphics/OpenGLTools.hpp"
#include <Utility/Timer.hpp>
#ifdef ZZZ_LIB_BOOST
namespace zzz{
RendererHelper::RendererHelper()
:zNear(0.1), zFar(1000), depthbuffer(GL_DEPTH_COMPONENT)
{
}
RendererHelper::~RendererHelper()
{
}
void RendererHelper::RenderCubemap(TextureCube &t, TriMesh &o,Cartesian3DCoordf &c,Shader &s)
{
fbo.Bind();
fbo.AttachTexture(depthbuffer, GL_DEPTH_ATTACHMENT);
GLViewport::Set(0,0,t.width_,t.height_);
depthbuffer.Create(t.width_,t.width_);
CHECK_GL_ERROR();
s.Begin();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPerspective(90,1,zNear,zFar);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
CHECK_GL_ERROR();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(GL_TEXTURE_CUBE_MAP_POSITIVE_X,t.GetID());
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0]+1,c.v[1],c.v[2],0,-1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
o.DrawElement(MESH_POS|MESH_NOR);
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(GL_TEXTURE_CUBE_MAP_NEGATIVE_X,t.GetID());
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0]-1,c.v[1],c.v[2],0,-1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
o.DrawElement(MESH_POS|MESH_NOR);
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(GL_TEXTURE_CUBE_MAP_POSITIVE_Y,t.GetID());
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1]+1,c.v[2],0,0,1);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
o.DrawElement(MESH_POS|MESH_NOR);
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,t.GetID());
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1]-1,c.v[2],0,0,-1);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
o.DrawElement(MESH_POS|MESH_NOR);
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(GL_TEXTURE_CUBE_MAP_POSITIVE_Z,t.GetID());
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1],c.v[2]+1,0,-1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
o.DrawElement(MESH_POS|MESH_NOR);
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,t.GetID());
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1],c.v[2]-1,0,-1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
o.DrawElement(MESH_POS|MESH_NOR);
fbo.Unattach(GL_COLOR_ATTACHMENT0);
CHECK_GL_ERROR();
glMatrixMode(GL_MODELVIEW);
CHECK_GL_ERROR();
glPopMatrix();
CHECK_GL_ERROR();
glMatrixMode(GL_PROJECTION);
CHECK_GL_ERROR();
glPopMatrix();
CHECK_GL_ERROR();
s.End();
CHECK_GL_ERROR();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.Unattach(GL_DEPTH_ATTACHMENT);
fbo.Disable();
CHECK_GL_ERROR();
GLViewport::Restore();
CHECK_GL_ERROR();
}
void RendererHelper::RenderCubemap(TextureCube &t, Cartesian3DCoordf &c, boost::function<void (void)> drawfunc)
{
GLViewport::Set(0,0,t.width_,t.height_);
fbo.Bind();
fbo.AttachTexture(depthbuffer, GL_DEPTH_ATTACHMENT);
depthbuffer.Create(t.width_,t.width_);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPerspective(90,1,zNear,zFar);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
GLuint tex=t.GetID();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(GL_TEXTURE_CUBE_MAP_POSITIVE_X,tex,GL_COLOR_ATTACHMENT0_EXT);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0]+1,c.v[1],c.v[2],0,-1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(GL_TEXTURE_CUBE_MAP_NEGATIVE_X,tex,GL_COLOR_ATTACHMENT0_EXT);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0]-1,c.v[1],c.v[2],0,-1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(GL_TEXTURE_CUBE_MAP_POSITIVE_Y,tex,GL_COLOR_ATTACHMENT0_EXT);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1]+1,c.v[2],0,0,1);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,tex,GL_COLOR_ATTACHMENT0_EXT);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1]-1,c.v[2],0,0,-1);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(GL_TEXTURE_CUBE_MAP_POSITIVE_Z,tex,GL_COLOR_ATTACHMENT0_EXT);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1],c.v[2]+1,0,-1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,tex,GL_COLOR_ATTACHMENT0_EXT);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1],c.v[2]-1,0,-1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.Unattach(GL_DEPTH_ATTACHMENT);
fbo.Disable();
GLViewport::Restore();
}
void RendererHelper::RenderCubemap(Texture2D *t, Cartesian3DCoordf &c, boost::function<void (void)> drawfunc)
{
GLViewport::Set(0,0,t[0].GetWidth(),t[0].GetHeight());
depthbuffer.Create(t[0].GetWidth(),t[0].GetHeight());
fbo.Bind();
fbo.AttachTexture(depthbuffer, GL_DEPTH_ATTACHMENT);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPerspective(90,1,zNear,zFar);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(t[0],GL_COLOR_ATTACHMENT0);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0]+1,c.v[1],c.v[2],0,+1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(t[1],GL_COLOR_ATTACHMENT0);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0]-1,c.v[1],c.v[2],0,+1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(t[2],GL_COLOR_ATTACHMENT0);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1]+1,c.v[2],0,0,+1);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(t[3],GL_COLOR_ATTACHMENT0);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1]-1,c.v[2],0,0,-1);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(t[4],GL_COLOR_ATTACHMENT0);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1],c.v[2]+1,0,+1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(t[5],GL_COLOR_ATTACHMENT0);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1],c.v[2]-1,0,+1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
CHECK_GL_ERROR();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.Unattach(GL_DEPTH_ATTACHMENT);
fbo.Disable();
GLViewport::Restore();
}
void RendererHelper::RenderCubemap(Texture2D *t, Texture2D *depth, Cartesian3DCoordf &c, boost::function<void (void)> drawfunc)
{
GLViewport::Set(0,0,t[0].GetWidth(),t[0].GetHeight());
for (zuint i=0; i<6; i++) {
depth[i].ChangeInternalFormat(GL_DEPTH_COMPONENT);
depth[i].Create(t[i].GetWidth(),t[i].GetHeight());
}
fbo.Bind();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPerspective(90,1,zNear,zFar);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(t[0],GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(depth[0], GL_DEPTH_ATTACHMENT);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0]+1,c.v[1],c.v[2],0,+1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(t[1],GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(depth[1], GL_DEPTH_ATTACHMENT);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0]-1,c.v[1],c.v[2],0,+1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(t[2],GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(depth[2], GL_DEPTH_ATTACHMENT);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1]+1,c.v[2],0,0,+1);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(t[3],GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(depth[3], GL_DEPTH_ATTACHMENT);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1]-1,c.v[2],0,0,-1);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(t[4],GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(depth[4], GL_DEPTH_ATTACHMENT);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1],c.v[2]+1,0,+1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(t[5],GL_COLOR_ATTACHMENT0);
fbo.AttachTexture(depth[5], GL_DEPTH_ATTACHMENT);
glLoadIdentity();
gluLookAt(c.v[0],c.v[1],c.v[2],c.v[0],c.v[1],c.v[2]-1,0,+1,0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawfunc();
CHECK_GL_ERROR();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
fbo.Unattach(GL_DEPTH_ATTACHMENT);
fbo.Disable();
GLViewport::Restore();
}
void RendererHelper::RenderToTexture(Texture2D &t, boost::function<void (void)> setupcamera, boost::function<void (void)> drawfunc)
{
fbo.Bind();
CHECK_GL_ERROR();
GLViewport::Set(0,0,t.GetWidth(),t.GetHeight());
CHECK_GL_ERROR();
depthbuffer.Create(t.GetWidth(),t.GetHeight());
CHECK_GL_ERROR();
fbo.AttachTexture(depthbuffer, GL_DEPTH_ATTACHMENT);
CHECK_GL_ERROR();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
setupcamera();
CHECK_GL_ERROR();
fbo.AttachTexture(t, GL_COLOR_ATTACHMENT0);
CHECK_GL_ERROR();
fbo.CheckStatus();
CHECK_GL_ERROR();
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
CHECK_GL_ERROR();
drawfunc();
CHECK_GL_ERROR();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
CHECK_GL_ERROR();
fbo.Unattach(GL_COLOR_ATTACHMENT0);
CHECK_GL_ERROR();
fbo.Unattach(GL_DEPTH_ATTACHMENT);
CHECK_GL_ERROR();
fbo.Disable();
CHECK_GL_ERROR();
GLViewport::Restore();
}
Colorui8 RendererHelper::ZuintToColor(zuint32 x)
{
return Colorui8(x & 0xFF, (x >> 8) & 0xFF, (x >> 16) & 0xFF);
}
zuint32 RendererHelper::ColorToZuint(const Vector3ui8 &c)
{
return c.r() + (c.g() << 8) + (c.b() << 16);
}
zuint32 RendererHelper::ColorToZuint(const Vector4ui8 &c)
{
return c.r() + (c.g() << 8) + (c.b() << 16) + (c.a() << 24);
}
}
#endif // ZZZ_LIB_BOOST
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/RendererHelper.cpp
|
C++
|
gpl3
| 11,406
|
#include "MultiObjEnvRenderer.hpp"
#include "../Graphics\ColorDefine.hpp"
#include <Utility/StringPrintf.hpp>
namespace zzz {
void MultiObjEnvRenderer::DrawObj()
{
ColorDefine::white.ApplyGL();
glBegin(GL_QUADS);
glVertex3d(-1,-1,0);
glVertex3d(1,-1,0);
glVertex3d(1,1,0);
glVertex3d(-1,1,0);
glEnd();
}
void MultiObjEnvRenderer::SetupCamera()
{
camera_.ApplyGL();
objArcBall_[curObjArcBall_].ApplyGL();
}
MultiObjEnvRenderer::MultiObjEnvRenderer()
{
allArcBall_=false;
lockArcBall_=false;
curObjArcBall_=0;
pCurObjArcBall_=&objArcBall_[0];
pCurEnvArcBall_=&envArcBall_;
}
void MultiObjEnvRenderer::OnLButtonDown(unsigned int nFlags,int x,int y)
{
if (!lockArcBall_) {
if (allArcBall_) {
for (int i=0; i<10; i++) {
objArcBall_[i].OnLButtonDown(nFlags, x, y);
}
} else {
objArcBall_[curObjArcBall_].OnLButtonDown(nFlags, x, y);
}
envArcBall_.OnLButtonDown(nFlags, x, y);
}
}
void MultiObjEnvRenderer::OnLButtonUp(unsigned int nFlags,int x,int y)
{
for (int i=0; i<10; i++)
objArcBall_[i].OnLButtonUp(nFlags, x, y);
envArcBall_.OnLButtonUp(nFlags, x, y);
}
void MultiObjEnvRenderer::OnRButtonDown(unsigned int nFlags,int x,int y)
{
if (!lockArcBall_) {
envArcBall_.OnLButtonDown(nFlags, x, y);
}
}
void MultiObjEnvRenderer::OnRButtonUp(unsigned int nFlags,int x,int y)
{
envArcBall_.OnLButtonUp(nFlags, x, y);
}
void MultiObjEnvRenderer::OnMButtonDown(unsigned int nFlags,int x,int y)
{
if (!lockArcBall_) {
if (allArcBall_) {
for (int i=0; i<10; i++) {
objArcBall_[i].OnLButtonDown(nFlags, x, y);
}
} else {
objArcBall_[curObjArcBall_].OnLButtonDown(nFlags, x, y);
}
}
}
void MultiObjEnvRenderer::OnMButtonUp(unsigned int nFlags,int x,int y)
{
for (int i=0; i<10; i++)
objArcBall_[i].OnLButtonUp(nFlags, x, y);
}
void MultiObjEnvRenderer::OnMouseMove(unsigned int nFlags,int x,int y)
{
if (!lockArcBall_) {
if (allArcBall_) {
for (int i=0; i<10; i++)
objArcBall_[i].OnMouseMove(nFlags, x, y);
} else
objArcBall_[curObjArcBall_].OnMouseMove(nFlags, x, y);
envArcBall_.OnMouseMove(nFlags, x, y);
}
Redraw();
}
void MultiObjEnvRenderer::OnChar(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags)
{
switch(nChar) {
case ZZZKEY_NUM_DOT: //'numpad .'
allArcBall_=true;
printf("All the ArcBalls are controled\n");
Redraw();
break;
case ZZZKEY_NUM_0:
curObjArcBall_=0;allArcBall_=false;pCurObjArcBall_=&(objArcBall_[curObjArcBall_]);
printf("Current ArcBall: %d\n",curObjArcBall_);
Redraw();
break;
case ZZZKEY_NUM_1:
curObjArcBall_=1;allArcBall_=false;pCurObjArcBall_=&(objArcBall_[curObjArcBall_]);
printf("Current ArcBall: %d\n",curObjArcBall_);
Redraw();
break;
case ZZZKEY_NUM_2:
curObjArcBall_=2;allArcBall_=false;pCurObjArcBall_=&(objArcBall_[curObjArcBall_]);
printf("Current ArcBall: %d\n",curObjArcBall_);
Redraw();
break;
case ZZZKEY_NUM_3:
curObjArcBall_=3;allArcBall_=false;pCurObjArcBall_=&(objArcBall_[curObjArcBall_]);
printf("Current ArcBall: %d\n",curObjArcBall_);
Redraw();
break;
case ZZZKEY_NUM_4:
curObjArcBall_=4;allArcBall_=false;pCurObjArcBall_=&(objArcBall_[curObjArcBall_]);
printf("Current ArcBall: %d\n",curObjArcBall_);
Redraw();
break;
case ZZZKEY_NUM_5:
curObjArcBall_=5;allArcBall_=false;pCurObjArcBall_=&(objArcBall_[curObjArcBall_]);
printf("Current ArcBall: %d\n",curObjArcBall_);
Redraw();
break;
case ZZZKEY_NUM_6:
curObjArcBall_=6;allArcBall_=false;pCurObjArcBall_=&(objArcBall_[curObjArcBall_]);
printf("Current ArcBall: %d\n",curObjArcBall_);
Redraw();
break;
case ZZZKEY_NUM_7:
curObjArcBall_=7;allArcBall_=false;pCurObjArcBall_=&(objArcBall_[curObjArcBall_]);
printf("Current ArcBall: %d\n",curObjArcBall_);
Redraw();
break;
case ZZZKEY_NUM_8:
curObjArcBall_=8;allArcBall_=false;pCurObjArcBall_=&(objArcBall_[curObjArcBall_]);
printf("Current ArcBall: %d\n",curObjArcBall_);
Redraw();
break;
case ZZZKEY_NUM_9:
curObjArcBall_=9;allArcBall_=false;pCurObjArcBall_=&(objArcBall_[curObjArcBall_]);
printf("Current ArcBall: %d\n",curObjArcBall_);
Redraw();
}
}
void MultiObjEnvRenderer::AfterOnSize(unsigned int nType, int cx, int cy)
{
for (int i=0; i<10; i++)
objArcBall_[i].OnSize(nType, cx, cy);
envArcBall_.OnSize(nType, cx, cy);
}
void MultiObjEnvRenderer::ResetArcball()
{
envArcBall_.Reset();
for (zuint i=0; i<10; i++)
objArcBall_[i].Reset();
}
void MultiObjEnvRenderer::CreateMsg()
{
SStringPrintf(msg_,"Current ArcBall: %d, Res: %d x %d, SPF: %lf = FPS: %lf",allArcBall_?123:curObjArcBall_,width_,height_,SPF_,FPS_);
}
bool MultiObjEnvRenderer::InitData()
{
envArcBall_.Init(this);
for (zuint i=0; i<10; i++)
objArcBall_[i].Init(this);
return ArcBallRenderer::InitData();
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/MultiObjEnvRenderer.cpp
|
C++
|
gpl3
| 5,134
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "Renderer.hpp"
namespace zzz{
class ZGRAPHICS_CLASS SwitchRenderer : public Renderer
{
public:
SwitchRenderer(void);
~SwitchRenderer(void);
bool AddRenderer(Renderer *, const int idx);
bool SwitchTo(const int idx);
virtual void SetContext(Context *context);
virtual bool RenderScene();
virtual bool InitData();
virtual bool InitState();
virtual void OnMouseMove(unsigned int nFlags,int x,int y);
virtual void OnLButtonDown(unsigned int nFlags,int x,int y);
virtual void OnLButtonUp(unsigned int nFlags,int x,int y);
virtual void OnRButtonDown(unsigned int nFlags,int x,int y);
virtual void OnRButtonUp(unsigned int nFlags,int x,int y);
virtual void OnMButtonDown(unsigned int nFlags,int x,int y);
virtual void OnMButtonUp(unsigned int nFlags,int x,int y);
virtual void OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y);
virtual void OnSize(unsigned int nType, int cx, int cy);
virtual void OnChar(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags);
virtual void OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags);
virtual void OnKeyUp(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags);
virtual void OnIdle();
protected:
vector<pair<int, Renderer*> > renderers_;
vector<int> statuses_;
Renderer *currenderer_;
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/SwitchRenderer.hpp
|
C++
|
gpl3
| 1,415
|
#include "zScriptRenderer.hpp"
namespace zzz{
zScriptRenderer::zScriptRenderer()
:loaded(false)
{
}
void zScriptRenderer::LoadRenderScript( const char *filename )
{
loaded=m_zRS.LoadScript(filename);
m_zRS.SetVariable("i_width",width_);
m_zRS.SetVariable("i_height",height_);
m_zRS.SetVariable("i_zdist",camera_.m_Position[2]);
if (loaded) m_zRS.DoFunction("<ONCE>");
Redraw();
}
bool zScriptRenderer::InitData()
{
ArcBallRenderer::InitData();
m_zRS.Init(this);
return true;
}
bool zScriptRenderer::Draw()
{
if (loaded)
{
m_zRS.DoFunction("<REPEAT>");
}
else
MultiObjEnvRenderer::Draw();
return true;
}
void zScriptRenderer::OnChar( unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags )
{
MultiObjEnvRenderer::OnChar(nChar,nRepCnt,nFlags);
m_zRS.OnChar(nChar,nRepCnt,nFlags);
}
void zScriptRenderer::SingleCommand( const string &str )
{
m_zRS.SingleCommand(str);
}
void zScriptRenderer::OnMouseWheel( unsigned int nFlags, int zDelta, int x,int y )
{
MultiObjEnvRenderer::OnMouseWheel(nFlags,zDelta,x,y);
m_zRS.SetVariable("zDist",camera_.m_Position[2]);
}
void zScriptRenderer::OnSize( unsigned int nType, int cx, int cy )
{
MultiObjEnvRenderer::OnSize(nType,cx,cy);
m_zRS.SetVariable("i_width",cx);
m_zRS.SetVariable("i_height",cy);
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/zScriptRenderer.cpp
|
C++
|
gpl3
| 1,366
|
#include "CameraRenderer.hpp"
#include "../Context/Context.hpp"
#include "../Graphics/ColorDefine.hpp"
namespace zzz{
CameraRenderer::CameraRenderer()
{
}
void CameraRenderer::AfterOnSize(unsigned int nType, int cx, int cy)
{
camera_.OnSize(nType, cx, cy);
}
void CameraRenderer::SetupCamera()
{
camera_.ApplyGL();
}
void CameraRenderer::OnMouseMove(unsigned int nFlags,int x,int y)
{
if (camera_.OnMouseMove(nFlags, x, y))
Redraw();
}
void CameraRenderer::OnLButtonDown(unsigned int nFlags,int x,int y)
{
if (camera_.OnLButtonDown(nFlags, x, y))
Redraw();
}
void CameraRenderer::OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y)
{
if (camera_.OnMouseWheel(nFlags, zDelta, x, y))
Redraw();
}
void CameraRenderer::OnChar(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags)
{
if (camera_.OnChar(nChar, nRepCnt, nFlags))
Redraw();
}
void CameraRenderer::DrawObj()
{
glBegin(GL_QUADS);
//wall
ColorDefine::cyan.ApplyGL();
glVertex3d(-1,-1,1);
glVertex3d(1,-1,1);
glVertex3d(1,1,1);
glVertex3d(-1,1,1);
ColorDefine::magenta.ApplyGL();
glColor3f(1.0,0.0,1.0);
glVertex3d(-1,-1,-1);
glVertex3d(1,-1,-1);
glVertex3d(1,1,-1);
glVertex3d(-1,1,-1);
ColorDefine::yellow.ApplyGL();
glVertex3d(-1,-1,-1);
glVertex3d(-1,1,-1);
glVertex3d(-1,1,1);
glVertex3d(-1,-1,1);
ColorDefine::blue.ApplyGL();
glVertex3d(1,-1,-1);
glVertex3d(1,1,-1);
glVertex3d(1,1,1);
glVertex3d(1,-1,1);
//ceiling
ColorDefine::black.ApplyGL();
glVertex3d(1,1,-1);
glVertex3d(1,1,1);
glVertex3d(-1,1,1);
glVertex3d(-1,1,-1);
//floor
ColorDefine::white.ApplyGL();
glVertex3d(1,-1,-1);
glVertex3d(1,-1,1);
glVertex3d(-1,-1,1);
glVertex3d(-1,-1,-1);
glEnd();
}
bool CameraRenderer::InitData()
{
return camera_.Init(this) && Renderer::InitData();
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/CameraRenderer.cpp
|
C++
|
gpl3
| 1,935
|
#include "ControlRenderer.hpp"
#include "../Resource/Mesh/MeshIO/MeshIO.hpp"
namespace zzz
{
bool ControlRenderer::Draw()
{
if (mesh_)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
camera_.ApplyGL();
objArcBall_.ApplyGL();
if (showObj_)
{
glEnable(GL_LIGHTING);
glColor3f(0.26,0.73,0.5);
mesh_->Draw();
glDisable(GL_LIGHTING);
}
if (showCpt_)
{
ZRM->Get<Shader*>("ColorShader")->Begin();
for (zuint i=0; i<ControlPoints_.size(); i++)
{
glPushMatrix();
glTranslatef(ControlPoints_[i].v[0],ControlPoints_[i].v[1],ControlPoints_[i].v[2]);
glColor3f(0,0,1);
gluSphere(quadric,0.02*mesh_->AABB_.Diff().Max(),6,5);
glPopMatrix();
}
if (overpoint_!=-1)
{
if (keyDown_==ZZZKEY_S)
{
glPushMatrix();
glTranslatef(mesh_->pos_[overpoint_][0],mesh_->pos_[overpoint_][1],mesh_->pos_[overpoint_][2]);
if (find(ControlPoints_.begin(),ControlPoints_.end(),mesh_->pos_[overpoint_])==ControlPoints_.end())
glColor3f(1,0,0);
else
glColor3f(0,1,0);
gluSphere(quadric,0.021*mesh_->AABB_.Diff().Max(),6,5);
glPopMatrix();
}
else
{
glPushMatrix();
glTranslatef(ControlPoints_[overpoint_].v[0],ControlPoints_[overpoint_].v[1],ControlPoints_[overpoint_].v[2]);
glColor3f(0,1,0);
gluSphere(quadric,0.021*mesh_->AABB_.Diff().Max(),6,5);
glPopMatrix();
}
}
Shader::End();
}
glPopMatrix();
return true;
}
else
return OneObjRenderer::Draw();
}
void ControlRenderer::OnLButtonDown(unsigned int nFlags,int x,int y)
{
switch (keyDown_)
{
case ZZZKEY_F:
overpoint_=FindNearestSelected(x,y);
if (overpoint_!=-1)
{
selectedpoint_=overpoint_;
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
camera_.ApplyGL();
objArcBall_.ApplyGL();
Cartesian3DCoordf point=ControlPoints_[selectedpoint_];
GLdouble modelMatrix[16], projMatrix[16];
GLint viewport[4];
glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
glGetIntegerv(GL_VIEWPORT,viewport);
double winx,winy,winz;
gluProject(point.v[0],point.v[1],point.v[2],modelMatrix,projMatrix,viewport,&winx,&winy,&winz);
selectedx_=winx-x;
selectedy_=winy-(height_-y);
selectedz_=winz;
glPopMatrix();
}
leftButton_=true;
break;
case ZZZKEY_NOKEY:
OneObjRenderer::OnLButtonDown(nFlags,x,y);
}
}
void ControlRenderer::OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags)
{
if (keyDown_==ZZZKEY_NOKEY)
{
keyDown_=nChar;
if (nChar==ZZZKEY_SPACE) showCpt_=!showCpt_;
Redraw();
}
}
ControlRenderer::ControlRenderer()
{
keyDown_=ZZZKEY_NOKEY;
fbo_=NULL;
target_=NULL;
depth_=NULL;
overpoint_=-1;
quadric=gluNewQuadric();
showCpt_=true;
showObj_=true;
mesh_=NULL;
leftButton_ = false;
middleButton_ = false;
}
void ControlRenderer::OnLButtonUp(unsigned int nFlags,int x,int y)
{
switch (keyDown_)
{
case ZZZKEY_S:
if (overpoint_!=-1)
{
vector<Cartesian3DCoordf>::iterator vui=find(ControlPoints_.begin(),ControlPoints_.end(),mesh_->pos_[overpoint_]);
if (vui==ControlPoints_.end())
{
ControlPoints_.push_back(mesh_->pos_[overpoint_]);
}
else
{
ControlPoints_.erase(vui);
}
Redraw();
}
leftButton_=false;
break;
case ZZZKEY_D:
if (overpoint_!=-1)
{
ControlPoints_.erase(ControlPoints_.begin()+overpoint_);
overpoint_=-1;
Redraw();
}
leftButton_=false;
break;
case ZZZKEY_F:
selectedpoint_=-1;
leftButton_=false;
break;
case ZZZKEY_NOKEY:
OneObjRenderer::OnLButtonUp(nFlags,x,y);
}
}
void ControlRenderer::OnKeyUp(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags)
{
keyDown_=ZZZKEY_NOKEY;
overpoint_=-1;
Redraw();
}
void ControlRenderer::OnSize(unsigned int nType, int cx, int cy)
{
if (cx!=0 && cy!=0)
{
if (target_) target_->ChangeSize(cx,cy);
if (depth_) depth_->Create(GL_DEPTH_COMPONENT32,cx,cy);
}
OneObjRenderer::OnSize(nType,cx,cy);
}
int ControlRenderer::FindNearest(int x,int y)
{
Image3uc img;
target_->TextureToImage(img);
GLubyte *data=(GLubyte*)&(img.At(height_-y,x));
if (data[0]!=255)
{
zuint id=data[0]*256*256+data[1]*256+data[2];
zuint idx;
for (idx=0;idx<mesh_group_end_.size();idx++)
if (id<mesh_group_end_[idx]) break;
if (idx>0) id-=mesh_group_end_[idx-1];
Cartesian3DCoordf point[3];
point[0]=mesh_->pos_[mesh_->groups_[idx]->facep_[id][0]];
point[1]=mesh_->pos_[mesh_->groups_[idx]->facep_[id][1]];
point[2]=mesh_->pos_[mesh_->groups_[idx]->facep_[id][2]];
float mindist=1000;
int minp=-1;
double winx,winy,winz;
gluProject(point[0][0],point[0][1],point[0][2],modelMatrix_,projMatrix_,viewport_,&winx,&winy,&winz);
float dist=(Vector2f(x,height_-y)-Vector2f(winx,winy)).Len();
if (mindist>dist) {mindist=dist;minp=0;}
gluProject(point[1][0],point[1][1],point[1][2],modelMatrix_,projMatrix_,viewport_,&winx,&winy,&winz);
dist=(Vector2f(x,height_-y)-Vector2f(winx,winy)).Len();
if (mindist>dist) {mindist=dist;minp=1;}
gluProject(point[2][0],point[2][1],point[2][2],modelMatrix_,projMatrix_,viewport_,&winx,&winy,&winz);
dist=(Vector2f(x,height_-y)-Vector2f(winx,winy)).Len();
if (mindist>dist) {mindist=dist;minp=0;}
minp=mesh_->groups_[idx]->facep_[id][minp];
return minp;
}
else
{
return -1;
}
}
int ControlRenderer::FindNearestSelected(int x,int y)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
camera_.ApplyGL();
objArcBall_.ApplyGL();
GLdouble modelMatrix[16], projMatrix[16];
GLint viewport[4];
glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
glGetIntegerv(GL_VIEWPORT,viewport);
glPopMatrix();
float mindist=1000;
int minp=-1;
for (zuint i=0; i<ControlPoints_.size(); i++)
{
Cartesian3DCoordf point;
point=ControlPoints_[i];
double winx,winy,winz;
gluProject(point.v[0],point.v[1],point.v[2],modelMatrix_,projMatrix_,viewport_,&winx,&winy,&winz);
float dist=(Vector2f(x,height_-y)-Vector2f(winx,winy)).Len();
if (mindist>dist) {mindist=dist;minp=i;}
}
if (mindist<50)
{
return minp;
}
else
{
return -1;
}
}
bool ControlRenderer::LoadObj(const string & filename)
{
if (mesh_) delete mesh_;
mesh_=new TriMesh;
if (!ObjIO::Load(filename,*mesh_))
{
printf("Cannot open file.");
delete mesh_;
mesh_=NULL;
return false;
}
//prepare id color
mesh_group_end_.clear();
mesh_group_end_.push_back(mesh_->groups_[0]->facep_.size());
for (zuint i=1; i<mesh_->groups_.size(); i++)
mesh_group_end_.push_back(mesh_group_end_[i-1]+mesh_->groups_[i]->facep_.size());
int cur=0;
for (zuint idx=0;idx<mesh_->groups_.size();idx++)
{
GLubyte *color=new GLubyte[mesh_group_end_[idx]*9];
for (zuint i=0; i<mesh_->groups_[idx]->facep_.size(); i++)
{
zuint id=cur;
GLubyte r,g,b;
b=id%256;
id-=b;
id/=256;
g=id%256;
id-=g;
id/=256;
r=id;
color[cur*9+0]=r;color[cur*9+1]=g;color[cur*9+2]=b;
color[cur*9+3]=r;color[cur*9+4]=g;color[cur*9+5]=b;
color[cur*9+6]=r;color[cur*9+7]=g;color[cur*9+8]=b;
cur++;
}
mesh_->groups_[idx]->VBOColor_.Create(color,mesh_group_end_[idx]*3,VBODescript::Color3ub);
delete[] color;
}
mesh_->CreateVBO(MESH_POS);
mesh_->CalPosNormal();
GLfloat lpos[4]={0,0,10,1};
GLfloat lamb[4]={0.5,0.5,0.5,1};
GLfloat ldif[4]={1,1,1,1};
GLfloat lspe[4]={1,1,1,1};
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0,GL_POSITION,lpos);
glLightfv(GL_LIGHT0,GL_AMBIENT,lamb);
glLightfv(GL_LIGHT0,GL_DIFFUSE,ldif);
glLightfv(GL_LIGHT0,GL_SPECULAR,lspe);
glDisable(GL_LIGHTING);
return true;
}
bool ControlRenderer::InitData()
{
fbo_=new FBO;
target_=new Texture2D3ub(1,1);
depth_=new Renderbuffer(GL_DEPTH_COMPONENT32,1,1);
fbo_->AttachRenderBuffer(depth_->GetID(),GL_DEPTH_ATTACHMENT_EXT);
fbo_->AttachTexture(GL_TEXTURE_2D,target_->GetID(),GL_COLOR_ATTACHMENT0_EXT);
fbo_->Disable();
showMsg_=false;
return OneObjRenderer::InitData();
}
void ControlRenderer::OnMouseMove(unsigned int nFlags,int x,int y)
{
switch (keyDown_)
{
case ZZZKEY_S:
overpoint_=FindNearest(x,y);
Redraw();
break;
case ZZZKEY_D:
if (!leftButton_)
{
overpoint_=FindNearestSelected(x,y);
Redraw();
}
break;
case ZZZKEY_F:
if (!leftButton_)
{
overpoint_=FindNearestSelected(x,y);
Redraw();
}
else
{
if (selectedpoint_!=-1)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
camera_.ApplyGL();
objArcBall_.ApplyGL();
Cartesian3DCoordf point=ControlPoints_[selectedpoint_];
GLdouble modelMatrix[16], projMatrix[16];
GLint viewport[4];
glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
glGetIntegerv(GL_VIEWPORT,viewport);
double objx,objy,objz;
gluUnProject(selectedx_+x,selectedy_+height_-y,selectedz_,modelMatrix,projMatrix,viewport,&objx,&objy,&objz);
ControlPoints_[selectedpoint_].v[0]=objx;
ControlPoints_[selectedpoint_].v[1]=objy;
ControlPoints_[selectedpoint_].v[2]=objz;
glPopMatrix();
Redraw();
}
}
break;
case ZZZKEY_NOKEY:
OneObjRenderer::OnMouseMove(nFlags,x,y);
}
}
void ControlRenderer::RenderIdMap()
{
fbo_->Bind();
glClearColor(1.0f,0.0f,0.0f,1.0f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
camera_.ApplyGL();
objArcBall_.ApplyGL();
ZRM->Get<Shader*>("ColorShader")->Begin();
mesh_->DrawVBO(MESH_POS|MESH_COLOR);
Shader::End();
glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix_);
glGetDoublev(GL_PROJECTION_MATRIX,projMatrix_);
glGetIntegerv(GL_VIEWPORT,viewport_);
glPopMatrix();
fbo_->Disable();
glClearColor(0.1f,0.1f,0.1f,1.0f);
// target_->TextureToImage();
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/ControlRenderer.cpp
|
C++
|
gpl3
| 10,971
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "ArcBallRenderer.hpp"
namespace zzz {
class ZGRAPHICS_CLASS OneObjEnvRenderer : public ArcBallRenderer
{
public:
OneObjEnvRenderer();
void ResetArcball();
int curObjArcBall_;
bool allArcBall_;
ArcBallGUI objArcBall_; //arcball for object rotation
ArcBallGUI envArcBall_; //arcball for environment rotation
protected:
void CreateMsg();
void AfterOnSize(unsigned int nType, int cx, int cy);
void DrawObj();
void SetupCamera();
bool InitData();
public:
void OnMouseMove(unsigned int nFlags,int x,int y);
void OnLButtonDown(unsigned int nFlags,int x,int y);
void OnLButtonUp(unsigned int nFlags,int x,int y);
void OnRButtonDown(unsigned int nFlags,int x,int y);
void OnRButtonUp(unsigned int nFlags,int x,int y);
void OnMButtonDown(unsigned int nFlags,int x,int y);
void OnMButtonUp(unsigned int nFlags,int x,int y);
void OnSize(unsigned int nType, int cx, int cy);
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/OneObjEnvRenderer.hpp
|
C++
|
gpl3
| 981
|
#pragma once
#include "MultiObjEnvRenderer.hpp"
#include "../zRenderScript/zRenderScript.hpp"
namespace zzz{
class zScriptRenderer : public MultiObjEnvRenderer
{
public:
zScriptRenderer();
void LoadRenderScript(const char *filename);
void SingleCommand(const string &str);
virtual void OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y);
virtual void OnSize(unsigned int nType, int cx, int cy);
virtual void OnChar(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags);
protected:
virtual bool InitData();
virtual bool Draw();
protected:
zRenderScript m_zRS;
bool loaded;
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/zScriptRenderer.hpp
|
C++
|
gpl3
| 639
|
#include "Renderer.hpp"
#include "../Context/Context.hpp"
#include "../Resource/Shader/ShaderSpecify.hpp"
#include "../Resource/Texture/Texture.hpp"
#include <Utility/Timer.hpp>
#include <common.hpp>
#include <Math/Vector4.hpp>
#include "../Graphics/BMPFont.hpp"
#include "../Graphics/ColorDefine.hpp"
#include <Utility/StringPrintf.hpp>
#include <Utility/CmdParser.hpp>
ZFLAGS_STRING(renderer_clear_color, "0.1 0.1 0.1 1", "Default clear color for zzz::Renderer");
ZFLAGS_DOUBLE(renderer_clear_depth, 1, "Default clear depth for zzz::Renderer");
ZFLAGS_DOUBLE(renderer_camera_near, 0.01, "Near z plane of camera");
ZFLAGS_DOUBLE(renderer_camera_far, 1000, "Far z plane of camera");
ZFLAGS_DOUBLE(renderer_camera_fovy, 60, "Camera Near z plane of camera");
ZFLAGS_BOOL(renderer_show_msg, true, "Show renderer message");
namespace zzz{
Renderer::Renderer()
:showMsg_(ZFLAG_renderer_show_msg),SPF_(0),FPS_(0),context_(NULL),gui_(NULL)
{
camera_.SetPerspective(width_, height_, ZFLAG_renderer_camera_near, ZFLAG_renderer_camera_far, ZFLAG_renderer_camera_fovy);
}
bool Renderer::InitState()
{
glShadeModel(GL_SMOOTH);
GLClearColor::Set(Colorf(FromString<Vector4f>(ZFLAG_renderer_clear_color)));
GLClearDepth::Set(ZFLAG_renderer_clear_depth);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
ColorDefine::white.ApplyGL();
CHECK_GL_ERROR()
return true;
}
bool Renderer::InitData()
{
camera_.Init(this);
return true;
}
void Renderer::SetupCamera()
{
camera_.ApplyGL();
}
bool Renderer::RenderScene()
{
Timer mytimer;
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
CHECK_GL_ERROR()
Draw();
CHECK_GL_ERROR()
if (showMsg_)
{
CreateMsg();
RenderText(msg_.c_str());
}
SPF_=mytimer.Elapsed();
FPS_=1.0/SPF_;
CHECK_GL_ERROR()
return true;
}
void Renderer::RenderText(const string &msg)
{
CHECK_GL_ERROR()
SetRasterPos(0,height_ - BMPFont::Instance().FontHeight() - 1);
CHECK_GL_ERROR()
Texture::DisableAll();
glPixelZoom(1,1);
BMPFont::Instance().Draw(msg);
CHECK_GL_ERROR()
}
bool Renderer::Draw()
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
CHECK_GL_ERROR()
SetupCamera();
CHECK_GL_ERROR()
DrawObj();
CHECK_GL_ERROR()
glPopMatrix();
return true;
}
void Renderer::DrawObj()
{
glColor3f(1.0,1.0,1.0);
glBegin(GL_QUADS);
glVertex3d(-1,-1,0);
glVertex3d(1,-1,0);
glVertex3d(1,1,0);
glVertex3d(-1,1,0);
glEnd();
}
/////////////////////////////////////////////////////////
// User Event
void Renderer::OnLButtonDown(unsigned int nFlags,int x,int y)
{
}
void Renderer::OnLButtonUp(unsigned int nFlags,int x,int y)
{
}
void Renderer::OnRButtonDown(unsigned int nFlags,int x,int y)
{
if (camera_.OnRButtonDown(nFlags, x, y))
Redraw();
}
void Renderer::OnRButtonUp(unsigned int nFlags,int x,int y)
{
if (camera_.OnRButtonUp(nFlags, x, y))
Redraw();
}
void Renderer::OnMButtonDown(unsigned int nFlags,int x,int y)
{
if (camera_.OnMButtonDown(nFlags, x, y))
Redraw();
}
void Renderer::OnMButtonUp(unsigned int nFlags,int x,int y)
{
if (camera_.OnMButtonUp(nFlags, x, y))
Redraw();
}
void Renderer::OnMouseMove(unsigned int nFlags,int x,int y)
{
if (camera_.OnMouseMove(nFlags, x, y))
Redraw();
}
void Renderer::OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y)
{
if (camera_.OnMouseWheel(nFlags, zDelta, x, y))
Redraw();
}
void Renderer::OnChar(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags)
{
}
void Renderer::OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags)
{
}
void Renderer::OnKeyUp(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags)
{
}
void Renderer::OnSize(unsigned int nType, int cx, int cy)
{
if (cy <= 0) return;
width_ = cx;
height_ = cy;
GLViewport::Set(0, 0, width_, height_);
AfterOnSize(nType, cx, cy);
glMatrixMode(GL_MODELVIEW);
Redraw();
}
void Renderer::AfterOnSize(unsigned int nType, int cx, int cy)
{
camera_.OnSize(nType, cx, cy);
}
Renderer::~Renderer()
{
}
void Renderer::Redraw()
{
if (context_) context_->Redraw();
}
void Renderer::InstantRedraw()
{
if (context_) context_->RenderScene();
}
void Renderer::MakeCurrent()
{
if (context_) context_->MakeCurrent();
}
void Renderer::CreateMsg()
{
SStringPrintf(msg_,"Res: %d x %d, SPF: %lf = FPS: %lf",width_,height_,SPF_,FPS_);
}
void Renderer::SetContext(Context *context)
{
context_=context;
}
void Renderer::OnIdle()
{
return;
}
zzz::Vector3d Renderer::UnProject(double winx, double winy, double winz) const
{
OpenGLProjector proj;
return proj.UnProject(winx, winy, winz);
}
void Renderer::SetRasterPos(double winx, double winy) const
{
// it is a trick to set raster pos and make it available even across left or bottom edge
// very useful when need to move image around
// in glBitmap winx winy are relative movement, so need to set to 0 first
glWindowPos2d(0, 0);
glBitmap(0, 0, 0, 0, winx, winy, NULL);
//the following code also works, only that opengl will draw nothing when raster pos is across left or bottom edge
//you can also set a larger viewport(larger than screen) to make it work,,, ugly hack,,
// winy = height_ - winy - 1;
// glWindowPos2d(winx, winy);
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/Renderer.cpp
|
C++
|
gpl3
| 5,556
|
#include "SwitchRenderer.hpp"
#include <Utility/Tools.hpp>
namespace zzz{
#define STATUS_NEED_RESIZE (1)
SwitchRenderer::SwitchRenderer(void)
:currenderer_(NULL)
{
}
SwitchRenderer::~SwitchRenderer(void)
{
}
bool SwitchRenderer::AddRenderer(Renderer *renderer, const int idx)
{
for (zuint i=0; i<renderers_.size(); i++)
if (renderers_[i].first==idx)
return false;
renderers_.push_back(make_pair(idx,renderer));
statuses_.push_back(0);
return true;
}
bool SwitchRenderer::SwitchTo(const int idx)
{
for (zuint i=0; i<renderers_.size(); i++)
if (renderers_[i].first==idx)
{
currenderer_=renderers_[i].second;
if (CheckBit(statuses_[i],STATUS_NEED_RESIZE))
{
currenderer_->OnSize(0,width_,height_);
ClearBit(statuses_[i],STATUS_NEED_RESIZE);
}
return true;
}
return false;
}
void SwitchRenderer::SetContext(Context *context)
{
for (zuint i=0; i<renderers_.size(); i++)
renderers_[i].second->SetContext(context);
context_=context;
}
bool SwitchRenderer::RenderScene()
{
if (currenderer_==NULL) return true;
return currenderer_->RenderScene();
}
bool SwitchRenderer::InitData()
{
for (zuint i=0; i<renderers_.size(); i++)
renderers_[i].second->InitData();
return true;
}
bool SwitchRenderer::InitState()
{
for (zuint i=0; i<renderers_.size(); i++)
renderers_[i].second->InitState();
return true;
}
void SwitchRenderer::OnMouseMove(unsigned int nFlags,int x,int y)
{
if (currenderer_==NULL) return;
currenderer_->OnMouseMove( nFlags, x, y);
}
void SwitchRenderer::OnLButtonDown(unsigned int nFlags,int x,int y)
{
if (currenderer_==NULL) return;
currenderer_->OnLButtonDown( nFlags, x, y);
}
void SwitchRenderer::OnLButtonUp(unsigned int nFlags,int x,int y)
{
if (currenderer_==NULL) return;
currenderer_->OnLButtonUp( nFlags, x, y);
}
void SwitchRenderer::OnRButtonDown(unsigned int nFlags,int x,int y)
{
if (currenderer_==NULL) return;
currenderer_->OnRButtonDown( nFlags, x, y);
}
void SwitchRenderer::OnRButtonUp(unsigned int nFlags,int x,int y)
{
if (currenderer_==NULL) return;
currenderer_->OnRButtonUp( nFlags, x, y);
}
void SwitchRenderer::OnMButtonDown(unsigned int nFlags,int x,int y)
{
if (currenderer_==NULL) return;
currenderer_->OnMButtonDown( nFlags, x, y);
}
void SwitchRenderer::OnMButtonUp(unsigned int nFlags,int x,int y)
{
if (currenderer_==NULL) return;
currenderer_->OnMButtonUp( nFlags, x, y);
}
void SwitchRenderer::OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y)
{
if (currenderer_==NULL) return;
currenderer_->OnMouseWheel( nFlags, zDelta, x, y);
}
void SwitchRenderer::OnSize(unsigned int nType, int cx, int cy)
{
Renderer::OnSize(nType,cx,cy);
for (zuint i=0; i<renderers_.size(); i++)
if (renderers_[i].second==currenderer_)
currenderer_->OnSize(nType,cx,cy);
else
SetBit(statuses_[i],STATUS_NEED_RESIZE);
}
void SwitchRenderer::OnChar(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags)
{
if (currenderer_==NULL) return;
currenderer_->OnChar(nChar, nRepCnt, nFlags);
}
void SwitchRenderer::OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags)
{
if (currenderer_==NULL) return;
currenderer_->OnKeyDown(nChar, nRepCnt, nFlags);
}
void SwitchRenderer::OnKeyUp(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags)
{
if (currenderer_==NULL) return;
currenderer_->OnKeyUp(nChar, nRepCnt, nFlags);
}
void SwitchRenderer::OnIdle()
{
if (currenderer_==NULL) return;
currenderer_->OnIdle();
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/SwitchRenderer.cpp
|
C++
|
gpl3
| 3,716
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "../Graphics/OpenGLTools.hpp"
#include "../GraphicsGUI/CameraGUI.hpp"
#include "../Context/Context.hpp"
#include "../Graphics/Color.hpp"
#include "../Resource/ResourceManager.hpp"
namespace zzz
{
class Context;
class ZGRAPHICS_CLASS Renderer : public Uncopyable
{
public:
Renderer();
virtual ~Renderer();
// Called by context, before OpenGL is inited.
virtual void SetContext(Context *context);
Context* GetContext(){return context_;}
// Will set context dirty.
void Redraw();
// Redraw instantly, do not call this in draw! A recurrsive draw will happen!
void InstantRedraw();
// Make attached context current.
void MakeCurrent();
// Top level draw function, called by context.
// Should clear background, and call Draw() then call RenderText();
virtual bool RenderScene();
// Called after OpenGL inited, be overriden to generate data.
virtual bool InitData();
// Called after OpenGL inited, be overriden to set OpenGL status.
virtual bool InitState();
int width_,height_;
CameraGUI camera_;
GraphicsGUI<Renderer> *gui_;
protected:
// It is called by RenderScene()
// Need to set camera etc. and call DrawObj().
// Usually only need to override SetupCamera() and DrawObj().
virtual bool Draw();
// It will be called every frame, to ganerate msg inside msg_.
virtual void CreateMsg();
// Setup ModelView matrix. Matrix mode will be set to ModelView before it is called.
// Just do the work but do not PushMatrix or set MatrixMode
virtual void SetupCamera();
// Called by Draw(), do the real drawing.
virtual void DrawObj();
// Will be called by RenderScene(), to render msg_ to screen.
virtual void RenderText(const string &t);
// Will be called by OnSize, should setup those objects who need windows size
virtual void AfterOnSize(unsigned int nType, int cx, int cy);
protected:
bool showMsg_;
string msg_;
double SPF_,FPS_;
Context *context_;
public:
//for mouse position
//all context should convert into that;
//topleft is 0,0
//x increases along left to right
//y increases along top to bottom
virtual void OnMouseMove(unsigned int nFlags,int x,int y);
virtual void OnLButtonDown(unsigned int nFlags,int x,int y);
virtual void OnLButtonUp(unsigned int nFlags,int x,int y);
virtual void OnRButtonDown(unsigned int nFlags,int x,int y);
virtual void OnRButtonUp(unsigned int nFlags,int x,int y);
virtual void OnMButtonDown(unsigned int nFlags,int x,int y);
virtual void OnMButtonUp(unsigned int nFlags,int x,int y);
virtual void OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y);
virtual void OnSize(unsigned int nType, int cx, int cy);
virtual void OnChar(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags);
virtual void OnKeyDown(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags);
virtual void OnKeyUp(unsigned int nChar, unsigned int nRepCnt, unsigned int nFlags);
virtual void OnIdle();
public:
//ATTENTION this cannot be inside glBegin~glEnd
Vector3d UnProject(double winx,double winy,double winz=0) const;
void SetRasterPos(double winx,double winy) const;
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/Renderer.hpp
|
C++
|
gpl3
| 3,276
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "Renderer.hpp"
#include "../Graphics/GraphicsHelper.hpp"
#include <Utility/Timer.hpp>
//For showing images
//no projective matrix
//no zooming
//middle mouse button to move around
namespace zzz
{
class ZGRAPHICS_CLASS Vis2DRenderer : public Renderer
{
public:
Vis2DRenderer();
virtual bool InitState();
virtual void OnMouseMove(unsigned int nFlags,int x,int y);
virtual void OnMButtonDown(unsigned int nFlags,int x,int y);
virtual void OnMButtonUp(unsigned int nFlags,int x,int y);
virtual void OnMouseWheel(unsigned int nFlags, int zDelta, int x,int y);
virtual void SetupCamera();
virtual void DrawObj();
void SetCenter(int width,int height);
//set raster position relative to original screen coordinate
//zoom will be considered
//left bottom corner of original screen is zero, right x, up y
//it will move as origin moves
void SetRasterPosRelative(double x, double y) const;
//ATTENTION this cannot be inside glBegin~glEnd
Vector3d UnProjectRelative(double winx,double winy) const;
//return row and column of the pixel which mouse is hovering on
//the image should drawpixels at (x,y)
Vector2d GetHoverPixel(int mouse_x, int mouse_y, int img_x=0, int img_y=0) const;
//to draw 3d stuff according to 2d position
void Draw2DPoint(double x, double y, const Colorf& color, float size);
void Draw2DLine(double x0, double y0, double x1, double y1, const zzz::Colorf& color, float size);
protected:
bool allowmove_,allowzoom_;
double zoomratio_;
int posx_,posy_;
private:
Timer middletimer_;
int lastx_,lasty_;
bool middleButton_;
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Renderer/Vis2DRenderer.hpp
|
C++
|
gpl3
| 1,706
|
#include "ResourceManager.hpp"
#include "Texture/Texture2D.hpp"
#include "Shader/Shader.hpp"
#include "Mesh/Material.hpp"
#include <Utility/StringTools.hpp>
#include <Utility/FileTools.hpp>
namespace zzz{
ResourceManager __default_RM;
bool ResourceManager::Add(Texture2D *tex, const string &name, bool cover)
{
return AnyHolder::Add(tex,name,cover);
}
bool ResourceManager::Add(Shader *shader, const string &name, bool cover)
{
return AnyHolder::Add(shader,name,cover);
}
bool ResourceManager::Add(Material *mat, const string &name, bool cover)
{
return AnyHolder::Add(mat,name,cover);
}
void ResourceManager::Destroy(Any &v)
{
if (v.IsType<Texture2D*>())
delete any_cast<Texture2D*>(v);
else if (v.IsType<Shader*>())
delete any_cast<Shader*>(v);
else if (v.IsType<Material*>())
delete any_cast<Material*>(v);
else
ZLOG(ZFATAL)<<"Unknown type stored! This should not happen!\n";
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/ResourceManager.cpp
|
C++
|
gpl3
| 953
|
#pragma once
#include <zGraphicsConfig.hpp>
#include <Image/Image.hpp>
#include "Texture.hpp"
#include <Utility/Tools.hpp>
#include "../../Graphics/Coordinate.hpp"
namespace zzz{
class ZGRAPHICS_CLASS TextureCube : public Texture
{
public:
TextureCube(int newiformat=GL_RGB);
TextureCube(zuint32 size, int newiformat);
TextureCube(zuint32 width, zuint32 height, int newiformat);
TextureCube(const string &filename, int newiformat);
TextureCube(const string &PosX, const string &NegX, const string &PosY,
const string &NegY, const string &PosZ, const string &NegZ,
int newiformat);
void Create(zuint32 size);
void Create(zuint width, zuint height);
void Create(const string &filename);
void Create(const string &PosX, const string &NegX, const string &PosY,
const string &NegY, const string &PosZ, const string &NegZ);
template<typename T> bool ImageToTexture(const Image<T> &PosX,const Image<T> &NegX,const Image<T> &PosY,
const Image<T> &NegY,const Image<T> &PosZ,const Image<T> &NegZ);
template<typename T> bool TextureToImage(Image<T> &PosX,Image<T> &NegX,Image<T> &PosY,
Image<T> &NegY,Image<T> &PosZ,Image<T> &NegZ);
bool Bind(GLenum bindto=GL_TEXTURE0);
void ChangeInternalFormat(int newiformat);
void ChangeSize(zuint32 width,zuint32 height);
void ChangeSize(zuint32 size);
void ChangeParameter(GLenum filter,GLenum wrap);
bool DrawCubemap(float size=1);
zuint width_,height_;
private:
bool ReadPfm(const string &filename);
bool SavePfm(const string &filename);
};
template<typename T>
bool TextureCube::ImageToTexture(const Image<T> &PosX,const Image<T> &NegX,const Image<T> &PosY,
const Image<T> &NegY,const Image<T> &PosZ,const Image<T> &NegZ)
{
glBindTexture(GL_TEXTURE_CUBE_MAP,GetID());
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, filter_para_);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, filter_para_);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, wrap_para_);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, wrap_para_);
width_=PosX.Cols();
height_=PosX.Rows();
int format=PosX.Format_;
int type=PosY.Type_;
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X,0,internal_format_,width_,height_,0,format,type,(const GLvoid *)PosX.Data());
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X,0,internal_format_,width_,height_,0,format,type,(const GLvoid *)NegX.Data());
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y,0,internal_format_,width_,height_,0,format,type,(const GLvoid *)PosY.Data());
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,0,internal_format_,width_,height_,0,format,type,(const GLvoid *)NegY.Data());
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z,0,internal_format_,width_,height_,0,format,type,(const GLvoid *)PosZ.Data());
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,0,internal_format_,width_,height_,0,format,type,(const GLvoid *)NegZ.Data());
CHECK_GL_ERROR()
return true;
}
template<typename T>
bool TextureCube::TextureToImage(Image<T> &PosX,Image<T> &NegX,Image<T> &PosY,
Image<T> &NegY,Image<T> &PosZ,Image<T> &NegZ)
{
GLint lastTex;
glGetIntegerv(GL_TEXTURE_BINDING_CUBE_MAP,&lastTex);
int format=PosX.Format_;
int type=PosY.Type_;
PosX.SetSize(height_,width_);
NegX.SetSize(height_,width_);
PosY.SetSize(height_,width_);
NegY.SetSize(height_,width_);
PosZ.SetSize(height_,width_);
NegZ.SetSize(height_,width_);
glBindTexture(GL_TEXTURE_CUBE_MAP,GetID());
glGetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_X,0,format,type,(GLvoid *)PosX.Data());
glGetTexImage(GL_TEXTURE_CUBE_MAP_NEGATIVE_X,0,format,type,(GLvoid *)NegX.Data());
glGetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_Y,0,format,type,(GLvoid *)PosY.Data());
glGetTexImage(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,0,format,type,(GLvoid *)NegY.Data());
glGetTexImage(GL_TEXTURE_CUBE_MAP_POSITIVE_Z,0,format,type,(GLvoid *)PosZ.Data());
glGetTexImage(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,0,format,type,(GLvoid *)NegZ.Data());
glBindTexture(GL_TEXTURE_CUBE_MAP,lastTex);
CHECK_GL_ERROR()
return true;
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Texture/TextureCube.hpp
|
C++
|
gpl3
| 4,236
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "Texture.hpp"
namespace zzz {
class ZGRAPHICS_CLASS Texture1D : public Texture
{
public:
Texture1D(int newiformat=GL_RGB);
Texture1D(zuint width, int newiformat);
void Create(zuint width);
bool Bind(GLenum bindto=GL_TEXTURE0);
template<typename T>
void DataToTexture(const T *v, zsize size);
template<typename T>
void TextureToData(T *v);
void ChangeInternalFormat(int newiformat);
void ChangeSize(zuint width,zuint useless);
void ChangeSize(zuint width);
void ChangeParameter(GLenum filter,GLenum wrap);
zuint width_;
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Texture/Texture1D.hpp
|
C++
|
gpl3
| 633
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "Texture.hpp"
#include "../../Graphics/OpenGLTools.hpp"
#include <Image/Image.hpp>
#include <Utility/IOObject.hpp>
namespace zzz {
class ZGRAPHICS_CLASS Texture2D : public Texture
{
public:
Texture2D(int iformat=GL_RGB);
Texture2D(zuint width, zuint height, int iformat=GL_RGB);
Texture2D(const string &filename, int iformat=GL_RGB);
void Create(zuint width, zuint height);
void Create(int internal_format);
void Create(const string &filename);
bool Bind(GLenum bindto=GL_TEXTURE0);
void Unbind();
template<typename T> bool ImageToTexture(const Image<T> &img);
template<typename T> bool TextureToImage(Image<T> &img) const;
template<typename T> bool FileToTexture(const string &filename);
template<typename T> bool TextureToFile(const string &filename) const;
void ChangeInternalFormat(int newiformat);
void ChangeSize(zuint width,zuint height);
void ChangeParameter(GLenum filter,GLenum wrap);
zuint GetWidth(){return width_;}
zuint GetHeight(){return height_;}
static bool CopyTexture(Texture2D &from, Texture2D &to);
private:
zuint width_, height_;
void Create();
};
template<typename T>
bool Texture2D::ImageToTexture(const Image<T> &img)
{
GLvoid *data=(GLvoid *)img.Data();
width_=img.Cols();
height_=img.Rows();
CHECK_GL_ERROR()
Bind();
CHECK_GL_ERROR()
if (internal_format_==GL_DEPTH_COMPONENT)
glTexImage2D(GL_TEXTURE_2D,0,internal_format_,width_,height_,0,GL_DEPTH_COMPONENT,img.Type_,data);
else
glTexImage2D(GL_TEXTURE_2D,0,internal_format_,width_,height_,0,img.Format_,img.Type_,data);
CHECK_GL_ERROR()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter_para_);
CHECK_GL_ERROR()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter_para_);
CHECK_GL_ERROR()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_para_);
CHECK_GL_ERROR()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_para_);
CHECK_GL_ERROR()
return true;
}
template<typename T>
bool Texture2D::TextureToImage(Image<T> &img) const
{
CHECK_GL_ERROR()
if (!IsValid()) {
ZLOGE<<"Calling TextureToImage on a invalid texture!\n";
return false;
}
CHECK_GL_ERROR()
glBindTexture(GL_TEXTURE_2D,tex_);
CHECK_GL_ERROR()
img.SetSize(height_,width_);
GLvoid *data=(GLvoid *)img.Data();
if (internal_format_==GL_DEPTH_COMPONENT && img.Format_==ZZZ_LUMINANCE)
glGetTexImage(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT,img.Type_, data);
else
glGetTexImage(GL_TEXTURE_2D,0,img.Format_,img.Type_,data);
CHECK_GL_ERROR()
return true;
}
template<typename T>
bool Texture2D::FileToTexture(const string &filename)
{
Image<T> img(filename);
return ImageToTexture(img);
}
template<typename T>
bool Texture2D::TextureToFile(const string &filename) const
{
Image<T> img;
return TextureToImage(img) && img.SaveFile(filename);
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Texture/Texture2D.hpp
|
C++
|
gpl3
| 2,995
|
#include "TextureCube.hpp"
#include <Math/Math.hpp>
#include <Utility/StringTools.hpp>
#include <Utility/FileTools.hpp>
namespace zzz{
TextureCube::TextureCube(int newiformat)
:Texture(GL_TEXTURE_CUBE_MAP, newiformat)
{}
TextureCube::TextureCube(zuint32 size, int newiformat)
:Texture(GL_TEXTURE_CUBE_MAP, newiformat)
{
TextureCube(size,size,newiformat);
}
TextureCube::TextureCube(zuint32 width, zuint32 height, int newiformat)
:Texture(GL_TEXTURE_CUBE_MAP, newiformat)
{
Create(width,height);
}
TextureCube::TextureCube(const string &filename, int newiformat)
:Texture(GL_TEXTURE_CUBE_MAP, newiformat)
{
Create(filename);
}
TextureCube::TextureCube(const string &PosX, const string &NegX, const string &PoxY, const string &NegY, const string &PosZ, const string &NegZ, int newiformat)
:Texture(GL_TEXTURE_CUBE_MAP, newiformat)
{
Create(PosX,NegX,PoxY,NegY,PosZ,NegZ);
}
bool TextureCube::Bind(GLenum bindto/*=GL_TEXTURE0*/)
{
int lastLevel;
glGetIntegerv(GL_ACTIVE_TEXTURE,&lastLevel);
glActiveTexture(bindto);
Disable(bindto);
glEnable(GL_TEXTURE_CUBE_MAP);
GLBindTextureCube::Set(GetID());
glActiveTexture(lastLevel);
CHECK_GL_ERROR()
return true;
}
void TextureCube::Create(zuint32 size)
{
Create(size,size);
}
void TextureCube::Create(zuint width, zuint height)
{
width_=width;
height_=height;
glBindTexture(GL_TEXTURE_CUBE_MAP,GetID());
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, filter_para_);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, filter_para_);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, wrap_para_);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, wrap_para_);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X,0,internal_format_,width,height,0,0,0,NULL);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X,0,internal_format_,width,height,0,0,0,NULL);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y,0,internal_format_,width,height,0,0,0,NULL);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,0,internal_format_,width,height,0,0,0,NULL);
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z,0,internal_format_,width,height,0,0,0,NULL);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,0,internal_format_,width,height,0,0,0,NULL);
CHECK_GL_ERROR()
}
void TextureCube::Create(const string &filename)
{
string ext=filename;
ext=GetExt(ext);
ToLow(ext);
if (ext==".pfm")
if (!ReadPfm(filename))
{
printf("ERROR: ReadPfm: %s\n",filename);
}
CHECK_GL_ERROR()
}
void TextureCube::Create(const string &PosX, const string &NegX, const string &PosY, const string &NegY, const string &PosZ, const string &NegZ)
{
Image4f img[6];
img[POSX].LoadFile(PosX);
img[NEGX].LoadFile(NegX);
img[POSY].LoadFile(PosY);
img[NEGY].LoadFile(NegY);
img[POSZ].LoadFile(PosZ);
img[NEGZ].LoadFile(NegZ);
ImageToTexture(img[POSX],img[NEGX],img[POSY],img[NEGY],img[POSZ],img[NEGZ]);
CHECK_GL_ERROR()
}
void TextureCube::ChangeInternalFormat(int newiformat)
{
if (internal_format_==newiformat) return;
Image4f img[6];
TextureToImage(img[POSX],img[NEGX],img[POSY],img[NEGY],img[POSZ],img[NEGZ]);
internal_format_=newiformat;
ImageToTexture(img[POSX],img[NEGX],img[POSY],img[NEGY],img[POSZ],img[NEGZ]);
CHECK_GL_ERROR()
}
void TextureCube::ChangeSize(zuint32 width,zuint32 height)
{
if (width_==width && height_==height) return;
Image4f img[6];
TextureToImage(img[POSX],img[NEGX],img[POSY],img[NEGY],img[POSZ],img[NEGZ]);
for (zuint i=0; i<6; i++)
img[i].Resize(height,width);
ImageToTexture(img[POSX],img[NEGX],img[POSY],img[NEGY],img[POSZ],img[NEGZ]);
CHECK_GL_ERROR()
}
void TextureCube::ChangeSize(zuint32 size)
{
ChangeSize(size,size);
}
bool TextureCube::ReadPfm(const string &filename)
{
FILE *fp;
fp=fopen(filename.c_str(),"r");
if (fp==NULL)
return false;
char s[1000];
s[0]=0;
int width,height;
int headerlen=0;
if (fscanf(fp,"%[^\x0a]\x0a",s)!=1) {
fclose(fp);
return false;
}
if ((strlen(s)<2)||(s[0]!='P')||(s[1]!='f'&&s[1]!='F')) {
fclose(fp);
return false;
}
headerlen+=(int)strlen(s)+1;
if (fscanf(fp,"%[^\x0a]\x0a",s)!=1) {
fclose(fp);
return false;
}
if (sscanf(s,"%d %d",&width,&height)!=2) {
fclose(fp);
return false;
}
if (width%3!=0||height%4!=0||(((width/3)&(width/3-1))!=0)||(((height/4)&(height/4-1))!=0)||width/3!=height/4) {
fclose(fp);
return false;
}
headerlen+=(int)strlen(s)+1;
if (fscanf(fp,"%[^\x0a]\x0a",s)!=1) {
fclose(fp);
return false;
}
headerlen+=(int)strlen(s)+1;
fclose(fp);
fp=fopen(filename.c_str(),"rb");
float *data;
data=new float[width*height*3];
if (fseek(fp,headerlen,SEEK_SET)!=0) return false;
int ii=(int)fread((void *)data,1,width*height*3*(int)sizeof(float),fp);
if (ii!=width*height*3*(int)sizeof(float))
{
delete[] data;
data=0;
fclose(fp);
return false;
}
fclose(fp);
width_=width/3;
height_=height/4;
Image3f image[6];
for (zuint i=0; i<6; i++)
image[i].SetSize(height_,width_);
float *imagedata;
imagedata=(float *)image[POSX].Data();
for (zuint i=0; i<height_; i++) for (zuint j=0; j<width_; j++)
memcpy(imagedata+(width_*i+j)*3,data+((height_*3-1-i)*width+width_*3-1-j)*3,sizeof(float)*3);
imagedata=(float *)image[NEGX].Data();
for (zuint i=0; i<height_; i++) for (zuint j=0; j<width_; j++)
memcpy(imagedata+(width_*i+j)*3,data+((height_*3-1-i)*width+width_-1-j)*3,sizeof(float)*3);
imagedata=(float *)image[POSY].Data();
for (zuint i=0; i<height_; i++)
memcpy(imagedata+width_*i*3,data+((height_*3+i)*width+width_)*3,sizeof(float)*3*width_);
imagedata=(float *)image[NEGY].Data();
for (zuint i=0; i<height_; i++)
memcpy(imagedata+width_*3*i,data+((height_*1+i)*width+width_)*3,sizeof(float)*3*width_);
imagedata=(float *)image[POSZ].Data();
for (zuint i=0; i<height_; i++)
memcpy(imagedata+width_*3*i,data+((height_*0+i)*width+width_)*3,sizeof(float)*3*width_);
imagedata=(float *)image[NEGZ].Data();
for (zuint i=0; i<height_; i++) for (zuint j=0; j<width_; j++)
memcpy(imagedata+(width_*i+j)*3,data+((height_*3-1-i)*width+width_*2-1-j)*3,sizeof(float)*3);
delete[] data;
CHECK_GL_ERROR()
return true;
}
bool TextureCube::SavePfm(const string &filename)
{
char s1[1000];
FILE *fp=fopen(filename.c_str(),"wb");
if (fp==NULL) return false;
sprintf(s1,"PF\x0a%d %d\x0a-1.000000\x0a",width_*3,width_*4);
fwrite(s1,1,strlen(s1),fp);
int width=width_*3;
int height=height_*4;
float *data;
data=new float[width*height*3];
memset(data,0,sizeof(float)*width*height*3);
Image3f image[6];
TextureToImage(image[POSX],image[NEGX],image[POSY],image[NEGY],image[POSZ],image[NEGZ]);
float *imagedata;
imagedata=(float *)image[POSX].Data();
for (zuint i=0; i<height_; i++) for (zuint j=0; j<width_; j++)
memcpy(data+((height_*3-1-i)*width+width_*3-1-j)*3,imagedata+(width_*i+j)*3,sizeof(float)*3);
imagedata=(float *)image[NEGX].Data();
for (zuint i=0; i<height_; i++) for (zuint j=0; j<width_; j++)
memcpy(data+((height_*3-1-i)*width+width_-1-j)*3,imagedata+(width_*i+j)*3,sizeof(float)*3);
imagedata=(float *)image[POSY].Data();
for (zuint i=0; i<height_; i++)
memcpy(data+((height_*3+i)*width+width_)*3,imagedata+width_*i*3,sizeof(float)*3*width_);
imagedata=(float *)image[NEGY].Data();
for (zuint i=0; i<height_; i++)
memcpy(data+((height_*1+i)*width+width_)*3,imagedata+width_*3*i,sizeof(float)*3*width_);
imagedata=(float *)image[POSZ].Data();
for (zuint i=0; i<height_; i++)
memcpy(data+((height_*0+i)*width+width_)*3,imagedata+width_*3*i,sizeof(float)*3*width_);
imagedata=(float *)image[NEGZ].Data();
for (zuint i=0; i<height_; i++) for (zuint j=0; j<width_; j++)
memcpy(data+((height_*3-1-i)*width+width_*2-1-j)*3,imagedata+(width_*i+j)*3,sizeof(float)*3);
fwrite(data,1,width*height*3*sizeof(float),fp);
fclose(fp);
delete[] data;
CHECK_GL_ERROR()
return true;
}
bool TextureCube::DrawCubemap(float size /*=1*/)
{
if (!IsValid())
return false;
Bind(GL_TEXTURE0);
int lastEnv;
glGetTexEnviv(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,&lastEnv);
glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_DECAL);
glDepthMask(0);
int s=width_;
double t=(s-1)/(double)s;
glColor3f(0.5,0.5,0.5);
//front face
glBegin(GL_QUADS);
glTexCoord3d(-t,-t,1); glVertex3d(-size,-size,size);
glTexCoord3d(t,-t,1); glVertex3d(size,-size,size);
glTexCoord3d(t,t,1); glVertex3d(size,size,size);
glTexCoord3d(-t,t,1); glVertex3d(-size,size,size);
//left face
glTexCoord3d(-1,-t,-t); glVertex3d(-size,-size,-size);
glTexCoord3d(-1,-t,t); glVertex3d(-size,-size,size);
glTexCoord3d(-1,t,t); glVertex3d(-size,size,size);
glTexCoord3d(-1,t,-t); glVertex3d(-size,size,-size);
//right face
glTexCoord3d(1,-t,t); glVertex3d(size,-size,size);
glTexCoord3d(1,-t,-t); glVertex3d(size,-size,-size);
glTexCoord3d(1,t,-t); glVertex3d(size,size,-size);
glTexCoord3d(1,t,t); glVertex3d(size,size,size);
//back face
glTexCoord3d(t,-t,-1); glVertex3d(size,-size,-size);
glTexCoord3d(-t,-t,-1); glVertex3d(-size,-size,-size);
glTexCoord3d(-t,t,-1); glVertex3d(-size,size,-size);
glTexCoord3d(t,t,-1); glVertex3d(size,size,-size);
//top face
glTexCoord3d(-t,1,t); glVertex3d(-size,size,size);
glTexCoord3d(t,1,t); glVertex3d(size,size,size);
glTexCoord3d(t,1,-t); glVertex3d(size,size,-size);
glTexCoord3d(-t,1,-t); glVertex3d(-size,size,-size);
//bottom face
glTexCoord3d(-t,-1,-t); glVertex3d(-size,-size,-size);
glTexCoord3d(t,-1,-t); glVertex3d(size,-size,-size);
glTexCoord3d(t,-1,t); glVertex3d(size,-size,size);
glTexCoord3d(-t,-1,t); glVertex3d(-size,-size,size);
glEnd();
glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,lastEnv);
glDepthMask(1);
CHECK_GL_ERROR()
return true;
}
void TextureCube::ChangeParameter(GLenum filter,GLenum wrap)
{
Bind();
if (filter!=0)
{
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, filter);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, filter);
}
if (wrap!=0)
{
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, wrap);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, wrap);
}
filter_para_=filter;
wrap_para_=filter;
CHECK_GL_ERROR()
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Texture/TextureCube.cpp
|
C++
|
gpl3
| 10,703
|
#include "Texture2D.hpp"
#include <Utility/Tools.hpp>
#include "../../FBO/FBO.hpp"
namespace zzz{
//you cannot gen texture in constructor
//since it might construct before opengl is initialized
Texture2D::Texture2D(int newiformat)
:Texture(GL_TEXTURE_2D, newiformat), width_(0), height_(0)
{}
Texture2D::Texture2D(zuint width, zuint height, int newiformat)
:Texture(GL_TEXTURE_2D, newiformat)
{
Create(width,height);
}
Texture2D::Texture2D(const string &filename, int newiformat)
:Texture(GL_TEXTURE_2D, newiformat)
{
Create(filename);
}
bool Texture2D::Bind(GLenum bindto/*=GL_TEXTURE0*/)
{
CHECK_GL_ERROR()
GLActiveTexture::Set(bindto);
CHECK_GL_ERROR()
// Disable(bindto);
CHECK_GL_ERROR()
glEnable(GL_TEXTURE_2D);
CHECK_GL_ERROR()
GLBindTexture2D::Set(GetID());
CHECK_GL_ERROR()
GLActiveTexture::Restore();
CHECK_GL_ERROR()
return true;
}
void Texture2D::Create(int newiformat)
{
if (internal_format_==newiformat)
return;
internal_format_=newiformat;
Create();
CHECK_GL_ERROR()
}
void Texture2D::Create(zuint width, zuint height)
{
if (width_==width || height == height_)
return;
static const int max_size = GetMaxSize();
if (int(width) > max_size || int(height) > max_size) {
ZLOGV<<"Cannot create texture, too large size: "
<<width<<"x"<<height<<", max size is "<< max_size<<endl;
return;
}
width_=width;
height_=height;
Create();
CHECK_GL_ERROR()
}
void Texture2D::Unbind()
{
GLBindTexture2D::Restore();
}
void Texture2D::Create(const string &filename)
{
Image4uc img;
img.LoadFile(filename);
ImageToTexture(img);
CHECK_GL_ERROR()
}
void Texture2D::Create()
{
CHECK_GL_ERROR()
Bind();
CHECK_GL_ERROR()
if (internal_format_==GL_DEPTH_COMPONENT)
glTexImage2D(GL_TEXTURE_2D,0,internal_format_,width_,height_,0,GL_DEPTH_COMPONENT,GL_UNSIGNED_BYTE,NULL);
else
glTexImage2D(GL_TEXTURE_2D,0,internal_format_,width_,height_,0,GL_RGB,GL_UNSIGNED_BYTE,NULL);
CHECK_GL_ERROR()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter_para_);
CHECK_GL_ERROR()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter_para_);
CHECK_GL_ERROR()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap_para_);
CHECK_GL_ERROR()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap_para_);
CHECK_GL_ERROR()
}
void Texture2D::ChangeInternalFormat(int newiformat)
{
if (internal_format_==newiformat) return;
Image4f img;
TextureToImage(img);
internal_format_=newiformat;
ImageToTexture(img);
CHECK_GL_ERROR()
}
void Texture2D::ChangeSize(zuint width,zuint height)
{
if (width==width_ && height==height_) return;
width_=width;
height_=height;
Image4f img;
TextureToImage(img);
img.Resize(height_,width_);
ImageToTexture(img);
CHECK_GL_ERROR()
}
void Texture2D::ChangeParameter(GLenum filter,GLenum wrap)
{
CHECK_GL_ERROR()
Bind();
CHECK_GL_ERROR()
if (filter!=0)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
CHECK_GL_ERROR()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
CHECK_GL_ERROR()
}
if (wrap!=0)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap);
CHECK_GL_ERROR()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap);
CHECK_GL_ERROR()
}
filter_para_=filter;
wrap_para_=wrap;
CHECK_GL_ERROR()
}
bool Texture2D::CopyTexture(Texture2D &from, Texture2D &to)
{
CHECK_GL_ERROR()
to.internal_format_=from.internal_format_;
to.filter_para_=from.filter_para_;
to.wrap_para_=from.wrap_para_;
to.Create(from.width_,from.height_);
FBO fbo;
CHECK_GL_ERROR()
fbo.AttachTexture(GL_TEXTURE_2D,to.GetID());
CHECK_GL_ERROR()
fbo.Bind();
CHECK_GL_ERROR()
from.Bind();
CHECK_GL_ERROR()
glCopyTexSubImage2D(GL_TEXTURE_2D,0,0,0,0,0,from.width_,from.height_);
CHECK_GL_ERROR()
from.DisableAll();
CHECK_GL_ERROR()
fbo.Disable();
CHECK_GL_ERROR()
fbo.UnattachAll();
CHECK_GL_ERROR()
return true;
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Texture/Texture2D.cpp
|
C++
|
gpl3
| 4,169
|
#include "Texture1D.hpp"
#include <Utility/Tools.hpp>
#include <Math/Vector4.hpp>
#include <Math/Vector3.hpp>
namespace zzz{
Texture1D::Texture1D(int newiformat)
:Texture(GL_TEXTURE_1D, newiformat), width_(0)
{}
Texture1D::Texture1D(zuint width, int newiformat)
:Texture(GL_TEXTURE_1D, newiformat)
{}
bool Texture1D::Bind(GLenum bindto/*=GL_TEXTURE0*/)
{
int lastLevel;
glGetIntegerv(GL_ACTIVE_TEXTURE,&lastLevel);
glActiveTexture(bindto);
Disable(bindto);
glEnable(GL_TEXTURE_1D);
GLBindTexture1D::Set(GetID());
glActiveTexture(lastLevel);
CHECK_GL_ERROR()
return true;
}
void Texture1D::Create(zuint width)
{
if (width_==width)
return;
width_=width;
Bind();
glTexImage1D(GL_TEXTURE_1D,0,internal_format_,width_,0,0,0,NULL);
CHECK_GL_ERROR()
}
void Texture1D::ChangeInternalFormat(int newiformat)
{
if (internal_format_==newiformat) return;
Vector4f *data=new Vector4f[width_];
TextureToData(data);
internal_format_=newiformat;
DataToTexture(data,width_);
delete[] data;
CHECK_GL_ERROR()
}
void Texture1D::ChangeSize(zuint width)
{
if (width==width_) return;
Vector4f *data=new Vector4f[width_];
TextureToData(data);
width_=width;
DataToTexture(data,width);
delete[] data;
CHECK_GL_ERROR()
}
void Texture1D::ChangeSize(zuint width,zuint useless)
{
ChangeSize(width);
}
void Texture1D::ChangeParameter(GLenum filter,GLenum wrap)
{
Bind();
if (filter!=0)
{
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, filter);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, filter);
}
if (wrap!=0)
{
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, wrap);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, wrap);
}
filter_para_=filter;
wrap_para_=wrap;
CHECK_GL_ERROR()
}
template<>
void Texture1D::DataToTexture(const Vector3f *v, zsize size)
{
Bind();
glTexImage1D(GL_TEXTURE_1D,0,internal_format_,size,0,GL_RGB,GL_FLOAT,v);
width_=size;
CHECK_GL_ERROR()
}
template<>
void Texture1D::TextureToData(Vector3f *v)
{
Bind();
glGetTexImage(GL_TEXTURE_2D,0,GL_RGB,GL_FLOAT,v);
CHECK_GL_ERROR()
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Texture/Texture1D.cpp
|
C++
|
gpl3
| 2,223
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "Texture2D.hpp"
#include <ImageIO\ILImage.hpp>
namespace zzz {
template<>
class IOObject<Texture2D>
{
public:
static void WriteFileB(FILE *fp, const Texture2D &src) {
IOObj::WriteFileB(fp, src.GetInternalFormat());
IOObj::WriteFileB(fp, src.GetFilterParam());
IOObj::WriteFileB(fp, src.GetWrapParam());
switch(src.GetInternalFormat()) {
case GL_RGB: {
Image3uc img;
src.TextureToImage(img);
IOObject<Image3uc>::WriteFileB(fp, img);
break;
}
case GL_RGBA: {
Image4uc img;
src.TextureToImage(img);
IOObj::WriteFileB(fp, img);
break;
}
default:
ZLOGE<<"IOObject<Texture2D>::WriteFileB is not defined for internal format "<<src.GetInternalFormat();
break;
}
}
static void ReadFileB(FILE *fp, Texture2D& dst) {
zint32 iformat, fparam, wparam;
IOObj::ReadFileB(fp, iformat);
dst.Create(iformat);
IOObj::ReadFileB(fp, fparam);
IOObj::ReadFileB(fp, wparam);
dst.ChangeParameter(fparam, wparam);
switch(iformat) {
case GL_RGB: {
Image3uc img;
IOObject<Image3uc>::ReadFileB(fp, img);
dst.ImageToTexture(img);
break;
}
case GL_RGBA: {
Image4uc img;
IOObject<Image4uc>::ReadFileB(fp, img);
dst.ImageToTexture(img);
break;
}
default:
ZLOGE<<"IOObject<Texture2D>::ReadFileB is not defined for internal format "<<dst.GetInternalFormat();
break;
}
}
static const zint32 RF_IFORMAT=1;
static const zint32 RF_FPARAM=2;
static const zint32 RF_WPARAM=3;
static const zint32 RF_IMG=4;
static void WriteFileR(RecordFile &fp, const zint32 label, const Texture2D& src) {
fp.WriteChildBegin(label);
IOObj::WriteFileR(fp, RF_IFORMAT, src.GetInternalFormat());
IOObj::WriteFileR(fp, RF_FPARAM, src.GetFilterParam());
IOObj::WriteFileR(fp, RF_WPARAM, src.GetWrapParam());
switch(src.GetInternalFormat()) {
case GL_RGB: {
Image3uc img;
src.TextureToImage(img);
IOObj::WriteFileR(fp, RF_IMG, img);
break;
}
case GL_RGBA: {
Image4uc img;
src.TextureToImage(img);
IOObj::WriteFileR(fp, RF_IMG, img);
break;
}
default:
ZLOGE<<"IOObject<Texture2D>::WriteFileR is not defined for internal format "<<src.GetInternalFormat();
break;
}
fp.WriteChildEnd();
}
static void ReadFileR(RecordFile &fp, const zint32 label, Texture2D& dst) {
fp.ReadChildBegin(label);
int iformat, fparam, wparam;
IOObj::ReadFileR(fp, RF_IFORMAT, iformat);
dst.Create(iformat);
IOObj::ReadFileR(fp, RF_FPARAM, fparam);
IOObj::ReadFileR(fp, RF_WPARAM, wparam);
dst.ChangeParameter(fparam, wparam);
switch(iformat) {
case GL_RGB: {
Image3uc img;
IOObj::ReadFileR(fp, RF_IMG, img);
// ILImage image; // Add this line to avoid crash for unknown reason, it actually does nothing
dst.ImageToTexture(img);
break;
}
case GL_RGBA: {
Image4uc img;
IOObj::ReadFileR(fp, RF_IMG, img);
dst.ImageToTexture(img);
break;
}
default:
ZLOGE<<"IOObject<Texture2D>::ReadFileR is not defined for internal format "<<dst.GetInternalFormat();
break;
}
fp.ReadChildEnd();
}
};
}; // namespace zzz
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Texture/Texture2DIOObject.hpp
|
C++
|
gpl3
| 3,488
|
#include "Texture.hpp"
namespace zzz{
bool zzz::Texture::Disable(GLenum level)
{
int lastLevel;
CHECK_GL_ERROR()
glGetIntegerv(GL_ACTIVE_TEXTURE,&lastLevel);
CHECK_GL_ERROR()
glActiveTexture(level);
CHECK_GL_ERROR()
glDisable(GL_TEXTURE_1D);
CHECK_GL_ERROR()
glDisable(GL_TEXTURE_2D);
CHECK_GL_ERROR()
glDisable(GL_TEXTURE_3D);
CHECK_GL_ERROR()
glDisable(GL_TEXTURE_CUBE_MAP);
CHECK_GL_ERROR()
glActiveTexture(lastLevel);
CHECK_GL_ERROR()
return true;
}
void Texture::DisableAll()
{
Disable(GL_TEXTURE0);
Disable(GL_TEXTURE1);
Disable(GL_TEXTURE2);
Disable(GL_TEXTURE3);
Disable(GL_TEXTURE4);
Disable(GL_TEXTURE5);
Disable(GL_TEXTURE6);
Disable(GL_TEXTURE7);
// Disable(GL_TEXTURE8);
// Disable(GL_TEXTURE9);
// Disable(GL_TEXTURE10);
// Disable(GL_TEXTURE11);
// Disable(GL_TEXTURE12);
// Disable(GL_TEXTURE13);
// Disable(GL_TEXTURE14);
// Disable(GL_TEXTURE15);
// Disable(GL_TEXTURE16);
// Disable(GL_TEXTURE17);
// Disable(GL_TEXTURE18);
// Disable(GL_TEXTURE19);
// Disable(GL_TEXTURE20);
// Disable(GL_TEXTURE21);
// Disable(GL_TEXTURE22);
// Disable(GL_TEXTURE23);
// Disable(GL_TEXTURE24);
// Disable(GL_TEXTURE25);
// Disable(GL_TEXTURE26);
// Disable(GL_TEXTURE27);
// Disable(GL_TEXTURE28);
// Disable(GL_TEXTURE29);
// Disable(GL_TEXTURE30);
// Disable(GL_TEXTURE31);
CHECK_GL_ERROR()
}
Texture::Texture(GLenum tex_target, GLenum internalFormat)
:tex_(0), tex_target_(tex_target),
internal_format_(internalFormat),filter_para_(GL_LINEAR),wrap_para_(GL_CLAMP_TO_EDGE)
{
}
Texture::~Texture()
{
if (IsValid())
glDeleteTextures(1,&tex_);
CHECK_GL_ERROR()
}
bool Texture::IsValid() const
{
bool valid=(glIsTexture(tex_)==GL_TRUE);
CHECK_GL_ERROR()
return valid;
}
GLuint Texture::GetID()
{
if (!IsValid()) {
glGenTextures(1,&tex_);
CHECK_GL_ERROR()
ZCHECK_NOT_ZERO(tex_);
}
return tex_;
}
int Texture::GetMaxSize()
{
GLint max_size = 0;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_size);
return max_size;
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Texture/Texture.cpp
|
C++
|
gpl3
| 2,159
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "Texture2D.hpp"
#include "TextureCube.hpp"
namespace zzz{
#define TEXTURE2D_SPECIFY(classname,iformat) \
class classname : public Texture2D\
{\
public:\
classname():Texture2D(iformat){;}\
classname(const string & filename):Texture2D(filename,iformat){;}\
classname(int width, int height):Texture2D(width,height,iformat){;}\
};
TEXTURE2D_SPECIFY(Texture2D4f,GL_RGBA16F_ARB)
TEXTURE2D_SPECIFY(Texture2D3f,GL_RGB16F_ARB)
TEXTURE2D_SPECIFY(Texture2D4ub,GL_RGBA)
TEXTURE2D_SPECIFY(Texture2D3ub,GL_RGB)
#define TEXTURECUBE_SPECIFY(classname,iformat) \
class classname : public TextureCube\
{\
public:\
classname():TextureCube(iformat){;}\
classname(const string & filename):TextureCube(filename,iformat){;}\
classname(int width, int height):TextureCube(width,height,iformat){;}\
classname(const string & f1,const string & f2,const string & f3,const string & f4,const string & f5,const string & f6):TextureCube(f1,f2,f3,f4,f5,f6,iformat){;}\
};
TEXTURECUBE_SPECIFY(TextureCube4f,GL_RGBA16F_ARB)
TEXTURECUBE_SPECIFY(TextureCube3f,GL_RGB16F_ARB)
TEXTURECUBE_SPECIFY(TextureCube4ub,GL_RGBA)
TEXTURECUBE_SPECIFY(TextureCube3ub,GL_RGB)
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Texture/TextureSpecify.hpp
|
C++
|
gpl3
| 1,232
|
#pragma once
#include <zGraphicsConfig.hpp>
#include <common.hpp>
#include "../../Graphics/Graphics.hpp"
#include "../../Graphics/OpenGLTools.hpp"
#include <Utility/Uncopyable.hpp>
namespace zzz{
class ZGRAPHICS_CLASS Texture : public Uncopyable
{
public:
Texture(GLenum tex_target, GLenum internalFormat);
virtual ~Texture();
static bool Disable(GLenum level);
static void DisableAll();
virtual bool Bind(GLenum bindto=GL_TEXTURE0)=0;
virtual void ChangeInternalFormat(zint32 newiformat)=0;
virtual void ChangeSize(zuint32 width,zuint32 height)=0;
virtual void ChangeParameter(GLenum filter,GLenum wrap)=0;
bool IsValid() const;
GLuint GetID();
static int GetMaxSize();
zint32 GetInternalFormat() const {return internal_format_;}
zint32 GetFilterParam() const {return filter_para_;}
zint32 GetWrapParam() const {return wrap_para_;}
GLenum tex_target_;
protected:
zint32 internal_format_;
zint32 filter_para_,wrap_para_;
protected:
GLuint tex_;
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Texture/Texture.hpp
|
C++
|
gpl3
| 1,025
|
#pragma once
#include <zGraphicsConfig.hpp>
#include "../../Graphics/Graphics.hpp"
namespace zzz{
class ZGRAPHICS_CLASS Light {
public:
Light();
void Enable(GLenum l=0);
void Disable();
void DrawLine();
void Rotate(const GLfloat *rotmat);
static void Disable(GLenum l);
static void DisableAll();
GLenum mylight_;
GLfloat oripos_[4],pos_[4],amb_[4],dif_[4],spe_[4];
bool inited_;
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Light/Light.hpp
|
C++
|
gpl3
| 405
|
#include "Light.hpp"
#include <Utility/Tools.hpp>
namespace zzz{
Light::Light()
{
mylight_=0;
pos_[0]=0; pos_[1]=0; pos_[2]=0; pos_[3]=0;
amb_[0]=0; amb_[1]=0; amb_[2]=0; amb_[3]=0;
dif_[0]=0; dif_[1]=0; dif_[2]=0; dif_[3]=0;
spe_[0]=0; spe_[1]=0; spe_[2]=0; spe_[3]=0;
inited_=false;
}
void Light::Enable(GLenum l/*=0*/)
{
if (inited_==false) return;
if (l==0)
{
if (mylight_==0) mylight_=GL_LIGHT0;
}
else
mylight_=l;
glEnable(GL_LIGHTING);
glEnable(mylight_);
glLightfv(mylight_,GL_POSITION,pos_);
glLightfv(mylight_,GL_AMBIENT,amb_);
glLightfv(mylight_,GL_DIFFUSE,dif_);
glLightfv(mylight_,GL_SPECULAR,spe_);
}
void Light::Disable()
{
if (inited_==false) return;
if (mylight_==0) return;
glDisable(mylight_);
}
void Light::Disable(GLenum l)
{
glDisable(l);
}
void Light::DisableAll()
{
glDisable(GL_LIGHTING);
}
void Light::DrawLine()
{
glBegin(GL_LINES);
glColor4fv(dif_);
glVertex3f(0,0,0);
glVertex4fv(pos_);
glEnd();
}
void Light::Rotate(const GLfloat *rotmat)
{
pos_[0]=rotmat[0]*oripos_[0]+rotmat[4]*oripos_[1]+rotmat[8]*oripos_[2]+rotmat[12]*oripos_[3];
pos_[1]=rotmat[1]*oripos_[0]+rotmat[5]*oripos_[1]+rotmat[9]*oripos_[2]+rotmat[13]*oripos_[3];
pos_[2]=rotmat[2]*oripos_[0]+rotmat[6]*oripos_[1]+rotmat[10]*oripos_[2]+rotmat[14]*oripos_[3];
pos_[3]=rotmat[3]*oripos_[0]+rotmat[7]*oripos_[1]+rotmat[11]*oripos_[2]+rotmat[15]*oripos_[3];
glLightfv(mylight_,GL_POSITION,pos_);
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Light/Light.cpp
|
C++
|
gpl3
| 1,473
|
#include "SimpleMesh.hpp"
#include "../../Graphics/Graphics.hpp"
namespace zzz{
SimpleMesh::SimpleMesh()
{}
void SimpleMesh::Clear()
{
faces_.clear();
vertices_.clear();
triangles_.clear();
normals_.clear();
texcoords_.clear();
ClrAllFlags();
}
void SimpleMesh::DrawTriangles()
{
if (HasNoFlag(SMESH_TRI))
return;
glBegin(GL_TRIANGLES);
for (zuint i=0; i<triangles_.size(); i++)
{
const Triangle &t = triangles_[i];
glVertex3fv(t[0].Data());
glVertex3fv(t[1].Data());
glVertex3fv(t[2].Data());
}
glEnd();
}
void SimpleMesh::DrawTriangle(zuint i)
{
if (HasNoFlag(SMESH_TRI))
return;
glBegin(GL_TRIANGLES);
glVertex3fv(triangles_[i][0].Data());
glVertex3fv(triangles_[i][1].Data());
glVertex3fv(triangles_[i][2].Data());
glEnd();
}
void SimpleMesh::DrawFaces()
{
if (HasNoFlag(SMESH_POS))
return;
glBegin(GL_TRIANGLES);
for (zuint i=0; i<faces_.size(); i++)
{
const Vector3i &f = faces_[i];
glVertex3fv(vertices_[f[0]].Data());
glVertex3fv(vertices_[f[1]].Data());
glVertex3fv(vertices_[f[2]].Data());
}
glEnd();
}
void SimpleMesh::DrawFace(zuint i)
{
if (HasNoFlag(SMESH_POS))
return;
glBegin(GL_TRIANGLES);
glVertex3fv(vertices_[faces_[i][0]].Data());
glVertex3fv(vertices_[faces_[i][1]].Data());
glVertex3fv(vertices_[faces_[i][2]].Data());
glEnd();
}
void SimpleMesh::DrawPoint(zuint i)
{
if (HasNoFlag(SMESH_POS))
return;
glBegin(GL_POINTS);
glVertex3fv(vertices_[i].Data());
glEnd();
}
void SimpleMesh::FromTriangles()
{
vertices_.clear();
faces_.clear();
map<Vector3f, zuint> m;
map<Vector3f, zuint>::iterator mi;
for (zuint n = 0; n<triangles_.size(); n++)
{
const Triangle &t = triangles_[n];
Vector3i f;
for (zuint i=0; i<3; i++)
{
mi=m.find(t[i]);
if (mi==m.end())
{
f[i]=vertices_.size();
vertices_.push_back(t[i]);
m[t[i]]=f[i];
}
else
f[i]=mi->second;
}
faces_.push_back(f);
}
SetFlag(SMESH_POS);
}
void SimpleMesh::ToTriangles()
{
triangles_.clear();
for (zuint i=0; i<faces_.size(); i++) {
const Vector3i &f = faces_[i];
triangles_.push_back(Triangle(vertices_[f[0]],vertices_[f[1]],vertices_[f[2]]));
}
SetFlag(SMESH_TRI);
}
void SimpleMesh::SetDataFlags()
{
if (!vertices_.empty()) SetFlag(SMESH_POS);
if (!normals_.empty()) SetFlag(SMESH_NOR);
if (!texcoords_.empty()) SetFlag(SMESH_TEX);
if (!triangles_.empty()) SetFlag(SMESH_TRI);
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Mesh/SimpleMesh.cpp
|
C++
|
gpl3
| 2,648
|
#include "Mesh.hpp"
//#include "ObjMesh.hpp"
namespace zzz{
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Mesh/Mesh.cpp
|
C++
|
gpl3
| 72
|
#pragma once
#include <zGraphicsConfig.hpp>
#include <Math/Vector3.hpp>
#include <Utility/HasFlag.hpp>
#include <Utility/STLVector.hpp>
//hold only vertex
//2 ways, face indexes vertex
//or redundant triangle
//can convert from one to another
namespace zzz{
const int SMESH_POS =0x00000001;
const int SMESH_NOR =0x00000002;
const int SMESH_TEX =0x00000004;
const int SMESH_TRI =0x00000008;
class ZGRAPHICS_CLASS SimpleMesh : public HasFlags
{
public:
SimpleMesh();
void SetDataFlags();
void Clear();
typedef Vector<3,Vector3f> Triangle;
STLVector<Triangle> triangles_;
STLVector<Vector3f> vertices_;
STLVector<Vector3i> faces_;
void DrawTriangles();
void DrawTriangle(zuint i);
void DrawFaces();
void DrawFace(zuint i);
void DrawPoint(zuint i);
void FromTriangles();
void ToTriangles();
STLVector<Vector3f> normals_;
STLVector<Vector3f> texcoords_;
};
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Mesh/SimpleMesh.hpp
|
C++
|
gpl3
| 957
|
#include "Material.hpp"
#include "../../Graphics/Graphics.hpp"
#include <Utility/Tools.hpp>
#include <Resource/Texture/Texture2DIOObject.hpp>
namespace zzz{
Material::Material()
:diffuse_(0.8f,0.8f,0.8f,1.0f),
ambient_(0.7f,0.7f,0.7f,1.0f),
specular_(1.0f,1.0f,1.0f,1.0f),
emission_(0.0f,0.0f,0.0f,1.0f),
shininess_(100.0f)
{}
Material::~Material()
{}
void Material::ApplyMaterial()
{
if (HasFlag(MAT_AMB))
glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT,ambient_.Data());
if (HasFlag(MAT_DIF))
glMaterialfv(GL_FRONT_AND_BACK,GL_DIFFUSE,diffuse_.Data());
if (HasFlag(MAT_SPE))
{
glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,specular_.Data());
glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,shininess_);
}
if (HasFlag(MAT_EMI))
glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,emission_.Data());
}
void Material::BindDiffuseTexture(GLenum bindto /*= GL_TEXTURE0*/)
{
if (HasFlag(MAT_DIFTEX))
diffuseTex_.Bind(bindto);
}
void Material::UnbindDiffuseTexture()
{
if (HasFlag(MAT_DIFTEX))
diffuseTex_.Unbind();
}
void Material::BindAmbientTexture(GLenum bindto /*= GL_TEXTURE0*/)
{
if (HasFlag(MAT_AMBTEX))
ambientTex_.Bind(bindto);
}
void Material::UnbindAmbientTexture()
{
if (HasFlag(MAT_AMBTEX))
ambientTex_.Unbind();
}
}
|
zzz-engine
|
zzzEngine/zGraphics/zGraphics/Resource/Mesh/Material.cpp
|
C++
|
gpl3
| 1,332
|