Merge branch 'main' into ly-as-sdk/LYN-2948

This commit is contained in:
phistere
2021-05-13 11:25:03 -05:00
1224 changed files with 18773 additions and 126359 deletions
@@ -190,9 +190,8 @@ Please note that only those seed files will get updated that are active for your
void SourceFileRelocator::HandleMetaDataFiles(QStringList pathMatches, QHash<QString, int>& sourceIndexMap, const ScanFolderInfo* scanFolderInfo, SourceFileRelocationContainer& metadataFiles, bool excludeMetaDataFiles) const
{
QSet<QString> metaDataFileEntries;
for (QStringList::Iterator fileIter = pathMatches.begin(); fileIter != pathMatches.end();)
for (QString file : pathMatches)
{
QString file = *fileIter;
for (int idx = 0; idx < m_platformConfig->MetaDataFileTypesCount(); idx++)
{
QPair<QString, QString> metaInfo = m_platformConfig->GetMetaDataFileTypeAt(idx);
@@ -203,8 +202,7 @@ Please note that only those seed files will get updated that are active for your
{
AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Metadata file %s will be ignored because --excludeMetadataFiles was specified in the command line.\n",
file.toUtf8().constData());
fileIter = pathMatches.erase(fileIter);
continue;
break; // don't check it against other metafile entries, we've already ascertained its a metafile.
}
else
{
@@ -263,8 +261,6 @@ Please note that only those seed files will get updated that are active for your
}
}
}
fileIter++;
}
}
-1
View File
@@ -15,7 +15,6 @@ add_subdirectory(AWSNativeSDKInit)
add_subdirectory(AzTestRunner)
add_subdirectory(CrashHandler)
add_subdirectory(CryCommonTools)
add_subdirectory(CryXML)
add_subdirectory(News)
add_subdirectory(PythonBindingsExample)
add_subdirectory(RemoteConsole)
-26
View File
@@ -13,44 +13,18 @@ if (NOT PAL_TRAIT_BUILD_HOST_TOOLS)
return()
endif()
ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME})
ly_add_target(
NAME CryCommonTools STATIC
NAMESPACE Legacy
FILES_CMAKE
crycommontools_files.cmake
${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake
INCLUDE_DIRECTORIES
PUBLIC
.
${pal_dir}
BUILD_DEPENDENCIES
PRIVATE
3rdParty::lz4
3rdParty::zlib
3rdParty::zstd
AZ::AzCore
PUBLIC
Legacy::CryCommon
AZ::AzFramework
)
if(PAL_TRAIT_BUILD_TESTS_SUPPORTED)
ly_add_target(
NAME CryCommonTools.Tests ${PAL_TRAIT_TEST_TARGET_TYPE}
NAMESPACE Legacy
FILES_CMAKE
crycommontools_tests_files.cmake
INCLUDE_DIRECTORIES
PUBLIC
UnitTests
BUILD_DEPENDENCIES
PRIVATE
Legacy::CryCommonTools
AZ::AzTest
)
ly_add_googletest(
NAME Legacy::CryCommonTools.Tests
)
endif()
-514
View File
@@ -1,514 +0,0 @@
// Modifications copyright Amazon.com, Inc. or its affiliates.
#include <platform.h>
// Taken from http://tog.acm.org/GraphicsGems/gemsiv/polar_decomp/Decompose.c
/**** Decompose.c ****/
/* Ken Shoemake, 1993 */
#include <math.h>
#include "Decompose.h"
#pragma warning(disable:4244) // conversion from 'double' to 'float', possible loss of data
#pragma warning(disable:4305) // 'initializing' : truncation from 'double' to 'float'
namespace decomp {
/******* Matrix Preliminaries *******/
/** Fill out 3x3 matrix to 4x4 **/
#define mat_pad(A) (A[W][X]=A[X][W]=A[W][Y]=A[Y][W]=A[W][Z]=A[Z][W]=0,A[W][W]=1)
/** Copy nxn matrix A to C using "gets" for assignment **/
#define mat_copy(C,gets,A,n) {int i,j; for(i=0;i<n;i++) for(j=0;j<n;j++)\
C[i][j] gets (A[i][j]);}
/** Copy transpose of nxn matrix A to C using "gets" for assignment **/
#define mat_tpose(AT,gets,A,n) {int i,j; for(i=0;i<n;i++) for(j=0;j<n;j++)\
AT[i][j] gets (A[j][i]);}
/** Assign nxn matrix C the element-wise combination of A and B using "op" **/
#define mat_binop(C,gets,A,op,B,n) {int i,j; for(i=0;i<n;i++) for(j=0;j<n;j++)\
C[i][j] gets (A[i][j]) op (B[i][j]);}
/** Multiply the upper left 3x3 parts of A and B to get AB **/
void mat_mult(HMatrix A, HMatrix B, HMatrix AB)
{
int i, j;
for (i = 0; i < 3; i++) for (j = 0; j < 3; j++)
AB[i][j] = A[i][0] * B[0][j] + A[i][1] * B[1][j] + A[i][2] * B[2][j];
}
/** Return dot product of length 3 vectors va and vb **/
float vdot(float* va, float* vb)
{
return (va[0] * vb[0] + va[1] * vb[1] + va[2] * vb[2]);
}
/** Set v to cross product of length 3 vectors va and vb **/
void vcross(float* va, float* vb, float* v)
{
v[0] = va[1] * vb[2] - va[2] * vb[1];
v[1] = va[2] * vb[0] - va[0] * vb[2];
v[2] = va[0] * vb[1] - va[1] * vb[0];
}
/** Set MadjT to transpose of inverse of M times determinant of M **/
void adjoint_transpose(HMatrix M, HMatrix MadjT)
{
vcross(M[1], M[2], MadjT[0]);
vcross(M[2], M[0], MadjT[1]);
vcross(M[0], M[1], MadjT[2]);
}
/******* Quaternion Preliminaries *******/
/* Construct a (possibly non-unit) quaternion from real components. */
Quat Qt_(float x, float y, float z, float w)
{
Quat qq;
qq.x = x; qq.y = y; qq.z = z; qq.w = w;
return (qq);
}
/* Return conjugate of quaternion. */
Quat Qt_Conj(Quat q)
{
Quat qq;
qq.x = -q.x; qq.y = -q.y; qq.z = -q.z; qq.w = q.w;
return (qq);
}
/* Return quaternion product qL * qR. Note: order is important!
* To combine rotations, use the product Mul(qSecond, qFirst),
* which gives the effect of rotating by qFirst then qSecond. */
Quat Qt_Mul(Quat qL, Quat qR)
{
Quat qq;
qq.w = qL.w * qR.w - qL.x * qR.x - qL.y * qR.y - qL.z * qR.z;
qq.x = qL.w * qR.x + qL.x * qR.w + qL.y * qR.z - qL.z * qR.y;
qq.y = qL.w * qR.y + qL.y * qR.w + qL.z * qR.x - qL.x * qR.z;
qq.z = qL.w * qR.z + qL.z * qR.w + qL.x * qR.y - qL.y * qR.x;
return (qq);
}
/* Return product of quaternion q by scalar w. */
Quat Qt_Scale(Quat q, float w)
{
Quat qq;
qq.w = q.w * w; qq.x = q.x * w; qq.y = q.y * w; qq.z = q.z * w;
return (qq);
}
/* Construct a unit quaternion from rotation matrix. Assumes matrix is
* used to multiply column vector on the left: vnew = mat vold. Works
* correctly for right-handed coordinate system and right-handed rotations.
* Translation and perspective components ignored. */
Quat Qt_FromMatrix(HMatrix mat)
{
/* This algorithm avoids near-zero divides by looking for a large component
* - first w, then x, y, or z. When the trace is greater than zero,
* |w| is greater than 1/2, which is as small as a largest component can be.
* Otherwise, the largest diagonal entry corresponds to the largest of |x|,
* |y|, or |z|, one of which must be larger than |w|, and at least 1/2. */
Quat qu;
double tr, s;
tr = mat[X][X] + mat[Y][Y] + mat[Z][Z];
if (tr >= 0.0) {
s = sqrt(tr + mat[W][W]);
qu.w = s * 0.5;
s = 0.5 / s;
qu.x = (mat[Z][Y] - mat[Y][Z]) * s;
qu.y = (mat[X][Z] - mat[Z][X]) * s;
qu.z = (mat[Y][X] - mat[X][Y]) * s;
} else {
int h = X;
if (mat[Y][Y] > mat[X][X]) h = Y;
if (mat[Z][Z] > mat[h][h]) h = Z;
switch (h) {
#define caseMacro(i,j,k,I,J,K) \
case I:\
s = sqrt( (mat[I][I] - (mat[J][J]+mat[K][K])) + mat[W][W] );\
qu.i = s*0.5;\
s = 0.5 / s;\
qu.j = (mat[I][J] + mat[J][I]) * s;\
qu.k = (mat[K][I] + mat[I][K]) * s;\
qu.w = (mat[K][J] - mat[J][K]) * s;\
break
caseMacro(x, y, z, X, Y, Z);
caseMacro(y, z, x, Y, Z, X);
caseMacro(z, x, y, Z, X, Y);
}
}
if (mat[W][W] != 1.0) qu = Qt_Scale(qu, 1 / sqrt(mat[W][W]));
return (qu);
}
/******* Decomp Auxiliaries *******/
static HMatrix mat_id = { {1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1} };
/** Compute either the 1 or infinity norm of M, depending on tpose **/
float mat_norm(HMatrix M, int tpose)
{
int i;
float sum, max;
max = 0.0;
for (i = 0; i < 3; i++) {
if (tpose) sum = fabs(M[0][i]) + fabs(M[1][i]) + fabs(M[2][i]);
else sum = fabs(M[i][0]) + fabs(M[i][1]) + fabs(M[i][2]);
if (max < sum) max = sum;
}
return max;
}
float norm_inf(HMatrix M) { return mat_norm(M, 0); }
float norm_one(HMatrix M) { return mat_norm(M, 1); }
/** Return index of column of M containing maximum abs entry, or -1 if M=0 **/
int find_max_col(HMatrix M)
{
float abs, max;
int i, j, col;
max = 0.0; col = -1;
for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) {
abs = M[i][j]; if (abs < 0.0) abs = -abs;
if (abs > max) { max = abs; col = j; }
}
return col;
}
/** Setup u for Household reflection to zero all v components but first **/
void make_reflector(float* v, float* u)
{
float s = sqrt(vdot(v, v));
u[0] = v[0]; u[1] = v[1];
u[2] = v[2] + ((v[2] < 0.0) ? -s : s);
s = sqrt(2.0 / vdot(u, u));
u[0] = u[0] * s; u[1] = u[1] * s; u[2] = u[2] * s;
}
/** Apply Householder reflection represented by u to column vectors of M **/
void reflect_cols(HMatrix M, float* u)
{
int i, j;
for (i = 0; i < 3; i++) {
float s = u[0] * M[0][i] + u[1] * M[1][i] + u[2] * M[2][i];
for (j = 0; j < 3; j++) M[j][i] -= u[j] * s;
}
}
/** Apply Householder reflection represented by u to row vectors of M **/
void reflect_rows(HMatrix M, float* u)
{
int i, j;
for (i = 0; i < 3; i++) {
float s = vdot(u, M[i]);
for (j = 0; j < 3; j++) M[i][j] -= u[j] * s;
}
}
/** Find orthogonal factor Q of rank 1 (or less) M **/
void do_rank1(HMatrix M, HMatrix Q)
{
float v1[3], v2[3], s;
int col;
mat_copy(Q, =, mat_id, 4);
/* If rank(M) is 1, we should find a non-zero column in M */
col = find_max_col(M);
if (col < 0) return; /* Rank is 0 */
v1[0] = M[0][col]; v1[1] = M[1][col]; v1[2] = M[2][col];
make_reflector(v1, v1); reflect_cols(M, v1);
v2[0] = M[2][0]; v2[1] = M[2][1]; v2[2] = M[2][2];
make_reflector(v2, v2); reflect_rows(M, v2);
s = M[2][2];
if (s < 0.0) Q[2][2] = -1.0;
reflect_cols(Q, v1); reflect_rows(Q, v2);
}
/** Find orthogonal factor Q of rank 2 (or less) M using adjoint transpose **/
void do_rank2(HMatrix M, HMatrix MadjT, HMatrix Q)
{
float v1[3], v2[3];
float w, x, y, z, c, s, d;
int col;
/* If rank(M) is 2, we should find a non-zero column in MadjT */
col = find_max_col(MadjT);
if (col < 0) { do_rank1(M, Q); return; } /* Rank<2 */
v1[0] = MadjT[0][col]; v1[1] = MadjT[1][col]; v1[2] = MadjT[2][col];
make_reflector(v1, v1); reflect_cols(M, v1);
vcross(M[0], M[1], v2);
make_reflector(v2, v2); reflect_rows(M, v2);
w = M[0][0]; x = M[0][1]; y = M[1][0]; z = M[1][1];
if (w * z > x* y) {
c = z + w; s = y - x; d = sqrt(c * c + s * s); c = c / d; s = s / d;
Q[0][0] = Q[1][1] = c; Q[0][1] = -(Q[1][0] = s);
} else {
c = z - w; s = y + x; d = sqrt(c * c + s * s); c = c / d; s = s / d;
Q[0][0] = -(Q[1][1] = c); Q[0][1] = Q[1][0] = s;
}
Q[0][2] = Q[2][0] = Q[1][2] = Q[2][1] = 0.0; Q[2][2] = 1.0;
reflect_cols(Q, v1); reflect_rows(Q, v2);
}
/******* Polar Decomposition *******/
/* Polar Decomposition of 3x3 matrix in 4x4,
* M = QS. See Nicholas Higham and Robert S. Schreiber,
* Fast Polar Decomposition of An Arbitrary Matrix,
* Technical Report 88-942, October 1988,
* Department of Computer Science, Cornell University.
*/
float polar_decomp(HMatrix M, HMatrix Q, HMatrix S)
{
#define TOL 1.0e-6
HMatrix Mk, MadjTk, Ek;
float det, M_one, M_inf, MadjT_one, MadjT_inf, E_one, gamma, g1, g2;
int i, j;
mat_tpose(Mk, =, M, 3);
M_one = norm_one(Mk); M_inf = norm_inf(Mk);
do {
adjoint_transpose(Mk, MadjTk);
det = vdot(Mk[0], MadjTk[0]);
if (det == 0.0) { do_rank2(Mk, MadjTk, Mk); break; }
MadjT_one = norm_one(MadjTk); MadjT_inf = norm_inf(MadjTk);
gamma = sqrt(sqrt((MadjT_one * MadjT_inf) / (M_one * M_inf)) / fabs(det));
g1 = gamma * 0.5;
g2 = 0.5 / (gamma * det);
mat_copy(Ek, =, Mk, 3);
mat_binop(Mk, =, g1 * Mk, +, g2 * MadjTk, 3);
mat_copy(Ek, -=, Mk, 3);
E_one = norm_one(Ek);
M_one = norm_one(Mk); M_inf = norm_inf(Mk);
} while (E_one > (M_one * TOL));
mat_tpose(Q, =, Mk, 3); mat_pad(Q);
mat_mult(Mk, M, S); mat_pad(S);
for (i = 0; i < 3; i++) for (j = i; j < 3; j++)
S[i][j] = S[j][i] = 0.5 * (S[i][j] + S[j][i]);
return (det);
}
/******* Spectral Decomposition *******/
/* Compute the spectral decomposition of symmetric positive semi-definite S.
* Returns rotation in U and scale factors in result, so that if K is a diagonal
* matrix of the scale factors, then S = U K (U transpose). Uses Jacobi method.
* See Gene H. Golub and Charles F. Van Loan. Matrix Computations. Hopkins 1983.
*/
HVect spect_decomp(HMatrix S, HMatrix U)
{
HVect kv;
double Diag[3], OffD[3]; /* OffD is off-diag (by omitted index) */
double g, h, fabsh, fabsOffDi, t, theta, c, s, tau, ta, OffDq, a, b;
static char nxt[] = { Y,Z,X };
int sweep, i, j;
mat_copy(U, =, mat_id, 4);
Diag[X] = S[X][X]; Diag[Y] = S[Y][Y]; Diag[Z] = S[Z][Z];
OffD[X] = S[Y][Z]; OffD[Y] = S[Z][X]; OffD[Z] = S[X][Y];
for (sweep = 20; sweep > 0; sweep--) {
float sm = fabs(OffD[X]) + fabs(OffD[Y]) + fabs(OffD[Z]);
if (sm == 0.0) break;
for (i = Z; i >= X; i--) {
int p = nxt[i]; int q = nxt[p];
fabsOffDi = fabs(OffD[i]);
g = 100.0 * fabsOffDi;
if (fabsOffDi > 0.0) {
h = Diag[q] - Diag[p];
fabsh = fabs(h);
if (fabsh + g == fabsh) {
t = OffD[i] / h;
} else {
theta = 0.5 * h / OffD[i];
t = 1.0 / (fabs(theta) + sqrt(theta * theta + 1.0));
if (theta < 0.0) t = -t;
}
c = 1.0 / sqrt(t * t + 1.0); s = t * c;
tau = s / (c + 1.0);
ta = t * OffD[i]; OffD[i] = 0.0;
Diag[p] -= ta; Diag[q] += ta;
OffDq = OffD[q];
OffD[q] -= s * (OffD[p] + tau * OffD[q]);
OffD[p] += s * (OffDq - tau * OffD[p]);
for (j = Z; j >= X; j--) {
a = U[j][p]; b = U[j][q];
U[j][p] -= s * (b + tau * a);
U[j][q] += s * (a - tau * b);
}
}
}
}
kv.x = Diag[X]; kv.y = Diag[Y]; kv.z = Diag[Z]; kv.w = 1.0;
return (kv);
}
/******* Spectral Axis Adjustment *******/
/* Given a unit quaternion, q, and a scale vector, k, find a unit quaternion, p,
* which permutes the axes and turns freely in the plane of duplicate scale
* factors, such that q p has the largest possible w component, i.e. the
* smallest possible angle. Permutes k's components to go with q p instead of q.
* See Ken Shoemake and Tom Duff. Matrix Animation and Polar Decomposition.
* Proceedings of Graphics Interface 1992. Details on p. 262-263.
*/
Quat snuggle(Quat q, HVect* k)
{
#define SQRTHALF (0.7071067811865475244f)
#define sgn(n,v) ((n)?-(v):(v))
#define swap(a,i,j) {a[3]=a[i]; a[i]=a[j]; a[j]=a[3];}
#define cycle(a,p) if (p) {a[3]=a[0]; a[0]=a[1]; a[1]=a[2]; a[2]=a[3];}\
else {a[3]=a[2]; a[2]=a[1]; a[1]=a[0]; a[0]=a[3];}
Quat p;
float ka[4];
int i, turn = -1;
ka[X] = k->x; ka[Y] = k->y; ka[Z] = k->z;
if (ka[X] == ka[Y]) { if (ka[X] == ka[Z]) turn = W; else turn = Z; }
else { if (ka[X] == ka[Z]) turn = Y; else if (ka[Y] == ka[Z]) turn = X; }
if (turn >= 0) {
Quat qtoz, qp;
unsigned neg[3], win;
double mag[3], t;
static Quat qxtoz = { 0,SQRTHALF,0,SQRTHALF };
static Quat qytoz = { SQRTHALF,0,0,SQRTHALF };
static Quat qppmm = { 0.5, 0.5,-0.5,-0.5 };
static Quat qpppp = { 0.5, 0.5, 0.5, 0.5 };
static Quat qmpmm = { -0.5, 0.5,-0.5,-0.5 };
static Quat qpppm = { 0.5, 0.5, 0.5,-0.5 };
static Quat q0001 = { 0.0, 0.0, 0.0, 1.0 };
static Quat q1000 = { 1.0, 0.0, 0.0, 0.0 };
switch (turn) {
default: return (Qt_Conj(q));
case X: q = Qt_Mul(q, qtoz = qxtoz); swap(ka, X, Z) break;
case Y: q = Qt_Mul(q, qtoz = qytoz); swap(ka, Y, Z) break;
case Z: qtoz = q0001; break;
}
q = Qt_Conj(q);
mag[0] = (double)q.z * q.z + (double)q.w * q.w - 0.5;
mag[1] = (double)q.x * q.z - (double)q.y * q.w;
mag[2] = (double)q.y * q.z + (double)q.x * q.w;
for (i = 0; i < 3; i++) if (neg[i] = (mag[i] < 0.0)) mag[i] = -mag[i];
if (mag[0] > mag[1]) { if (mag[0] > mag[2]) win = 0; else win = 2; }
else { if (mag[1] > mag[2]) win = 1; else win = 2; }
switch (win) {
case 0: if (neg[0]) p = q1000; else p = q0001; break;
case 1: if (neg[1]) p = qppmm; else p = qpppp; cycle(ka, 0) break;
case 2: if (neg[2]) p = qmpmm; else p = qpppm; cycle(ka, 1) break;
}
qp = Qt_Mul(q, p);
t = sqrt(mag[win] + 0.5);
p = Qt_Mul(p, Qt_(0.0, 0.0, -qp.z / t, qp.w / t));
p = Qt_Mul(qtoz, Qt_Conj(p));
} else {
float qa[4], pa[4];
unsigned lo, hi, neg[4], par = 0;
double all, big, two;
qa[0] = q.x; qa[1] = q.y; qa[2] = q.z; qa[3] = q.w;
for (i = 0; i < 4; i++) {
pa[i] = 0.0;
if (neg[i] = (qa[i] < 0.0)) qa[i] = -qa[i];
par ^= neg[i];
}
/* Find two largest components, indices in hi and lo */
if (qa[0] > qa[1]) lo = 0; else lo = 1;
if (qa[2] > qa[3]) hi = 2; else hi = 3;
if (qa[lo] > qa[hi]) {
if (qa[lo ^ 1] > qa[hi]) { hi = lo; lo ^= 1; }
else { hi ^= lo; lo ^= hi; hi ^= lo; }
} else {if (qa[hi^1]>qa[lo]) lo = hi^1;}
all = (qa[0] + qa[1] + qa[2] + qa[3]) * 0.5;
two = (qa[hi] + qa[lo]) * SQRTHALF;
big = qa[hi];
if (all > two) {
if (all > big) {/*all*/
{int i; for (i = 0; i < 4; i++) pa[i] = sgn(neg[i], 0.5); }
cycle(ka, par)
} else {/*big*/ pa[hi] = sgn(neg[hi],1.0);}
} else {
if (two > big) {/*two*/
pa[hi] = sgn(neg[hi], SQRTHALF); pa[lo] = sgn(neg[lo], SQRTHALF);
if (lo > hi) { hi ^= lo; lo ^= hi; hi ^= lo; }
if (hi == W) { hi = "\001\002\000"[lo]; lo = 3 - hi - lo; }
swap(ka, hi, lo)
} else {/*big*/ pa[hi] = sgn(neg[hi],1.0);}
}
p.x = -pa[0]; p.y = -pa[1]; p.z = -pa[2]; p.w = pa[3];
}
k->x = ka[X]; k->y = ka[Y]; k->z = ka[Z];
return (p);
}
/******* Decompose Affine Matrix *******/
/* Decompose 4x4 affine matrix A as TFRUK(U transpose), where t contains the
* translation components, q contains the rotation R, u contains U, k contains
* scale factors, and f contains the sign of the determinant.
* Assumes A transforms column vectors in right-handed coordinates.
* See Ken Shoemake and Tom Duff. Matrix Animation and Polar Decomposition.
* Proceedings of Graphics Interface 1992.
*/
void decomp_affine(HMatrix A, AffineParts* parts)
{
HMatrix Q, S, U;
Quat p;
float det;
parts->t = Qt_(A[X][W], A[Y][W], A[Z][W], 0);
det = polar_decomp(A, Q, S);
if (det < 0.0) {
mat_copy(Q, =, -Q, 3);
parts->f = -1;
} else parts->f = 1;
parts->q = Qt_FromMatrix(Q);
parts->k = spect_decomp(S, U);
parts->u = Qt_FromMatrix(U);
p = snuggle(parts->u, &parts->k);
parts->u = Qt_Mul(parts->u, p);
}
/******* Invert Affine Decomposition *******/
/* Compute inverse of affine decomposition.
*/
void invert_affine(AffineParts* parts, AffineParts* inverse)
{
Quat t, p;
inverse->f = parts->f;
inverse->q = Qt_Conj(parts->q);
inverse->u = Qt_Mul(parts->q, parts->u);
inverse->k.x = (parts->k.x == 0.0) ? 0.0 : 1.0 / parts->k.x;
inverse->k.y = (parts->k.y == 0.0) ? 0.0 : 1.0 / parts->k.y;
inverse->k.z = (parts->k.z == 0.0) ? 0.0 : 1.0 / parts->k.z;
inverse->k.w = parts->k.w;
t = Qt_(-parts->t.x, -parts->t.y, -parts->t.z, 0);
t = Qt_Mul(Qt_Conj(inverse->u), Qt_Mul(t, inverse->u));
t = Qt_(inverse->k.x * t.x, inverse->k.y * t.y, inverse->k.z * t.z, 0);
p = Qt_Mul(inverse->q, inverse->u);
t = Qt_Mul(p, Qt_Mul(t, Qt_Conj(p)));
inverse->t = (inverse->f > 0.0) ? t : Qt_(-t.x, -t.y, -t.z, 0);
}
}
-30
View File
@@ -1,30 +0,0 @@
// Modifications copyright Amazon.com, Inc. or its affiliates.
namespace decomp {
// Taken from http://tog.acm.org/GraphicsGems/gemsiv/polar_decomp/Decompose.h
/**** Decompose.h - Basic declarations ****/
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_DECOMPOSE_H
#define CRYINCLUDE_CRYCOMMONTOOLS_DECOMPOSE_H
#pragma once
typedef struct {float x, y, z, w;} Quat; /* Quaternion */
enum QuatPart {X, Y, Z, W};
typedef Quat HVect; /* Homogeneous 3D vector */
typedef float HMatrix[4][4]; /* Right-handed, for column vectors */
typedef struct {
HVect t; /* Translation components */
Quat q; /* Essential rotation */
Quat u; /* Stretch rotation */
HVect k; /* Stretch factors */
float f; /* Sign of determinant */
} AffineParts;
float polar_decomp(HMatrix M, HMatrix Q, HMatrix S);
HVect spect_decomp(HMatrix S, HMatrix U);
Quat snuggle(Quat q, HVect *k);
void decomp_affine(HMatrix A, AffineParts *parts);
void invert_affine(AffineParts *parts, AffineParts *inverse);
#endif // CRYINCLUDE_CRYCOMMONTOOLS_DECOMPOSE_H
}
-43
View File
@@ -1,43 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXCEPTIONS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXCEPTIONS_H
#pragma once
#include <stdexcept>
#include <string>
class BaseException
: public std::exception
{
public:
BaseException(const string& msg)
: msg(msg) {}
virtual const char* what() const throw () {return msg.c_str(); }
private:
string msg;
};
template <typename Tag>
class Exception
: public BaseException
{
public:
Exception(const string& msg)
: BaseException(msg) {}
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXCEPTIONS_H
@@ -1,297 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "AnimationData.h"
AnimationData::AnimationData(int modelCount, float fps, float startTime)
: m_entries(modelCount)
, m_frameCount(0)
, m_startTime(startTime)
, m_fps(fps)
{
}
void AnimationData::SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3])
{
State& state = m_entries[modelIndex].samples[frameIndex];
state.translation[0] = translation[0];
state.translation[1] = translation[1];
state.translation[2] = translation[2];
state.rotation[0] = rotation[0];
state.rotation[1] = rotation[1];
state.rotation[2] = rotation[2];
state.scale[0] = scale[0];
state.scale[1] = scale[1];
state.scale[2] = scale[2];
}
void AnimationData::SetFrameCount(int frameCount)
{
m_frameCount = frameCount;
for (int modelIndex = 0, modelCount = int(m_entries.size()); modelIndex < modelCount; ++modelIndex)
{
m_entries[modelIndex].samples.resize(frameCount);
}
}
void AnimationData::SetModelFlags(int modelIndex, unsigned modelFlags)
{
m_entries[modelIndex].flags = modelFlags;
}
void AnimationData::GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const
{
translation = m_entries[modelIndex].samples[frameIndex].translation;
rotation = m_entries[modelIndex].samples[frameIndex].rotation;
scale = m_entries[modelIndex].samples[frameIndex].scale;
}
void AnimationData::GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const
{
translation = m_entries[modelIndex].samples[frameIndex].translation;
}
void AnimationData::GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const
{
rotation = m_entries[modelIndex].samples[frameIndex].rotation;
}
void AnimationData::GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const
{
scale = m_entries[modelIndex].samples[frameIndex].scale;
}
int AnimationData::GetFrameCount() const
{
return m_frameCount;
}
unsigned AnimationData::GetModelFlags(int modelIndex) const
{
return m_entries[modelIndex].flags;
}
AnimationData::State::State()
{
translation[0] = translation[1] = translation[2] = 0.0f;
rotation[0] = rotation[1] = rotation[2] = 0.0f;
scale[0] = scale[1] = scale[2] = 1.0f;
}
AnimationData::ModelEntry::ModelEntry()
: flags(0)
{
}
///////////////////////////////////////////////////////////////////////////
NonSkeletalAnimationData::NonSkeletalAnimationData(int modelCount)
: m_entries(modelCount)
{
}
void NonSkeletalAnimationData::SetModelFlags(int modelIndex, unsigned modelFlags)
{
m_entries[modelIndex].flags = modelFlags;
}
unsigned NonSkeletalAnimationData::GetModelFlags(int modelIndex) const
{
return m_entries[modelIndex].flags;
}
void NonSkeletalAnimationData::SetFrameTimePos(int modelIndex, int frameIndex, float time)
{
State& state = m_entries[modelIndex].samplesPos[frameIndex];
state.time = time;
}
void NonSkeletalAnimationData::SetFrameDataPos(int modelIndex, int frameIndex, float translation[3])
{
State& state = m_entries[modelIndex].samplesPos[frameIndex];
state.data[0] = translation[0];
state.data[1] = translation[1];
state.data[2] = translation[2];
}
void NonSkeletalAnimationData::SetFrameCountPos(int modelIndex, int frameCount)
{
m_entries[modelIndex].samplesPos.resize(frameCount);
}
void NonSkeletalAnimationData::SetFrameTimeRot(int modelIndex, int frameIndex, float time)
{
State& state = m_entries[modelIndex].samplesRot[frameIndex];
state.time = time;
}
void NonSkeletalAnimationData::SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3])
{
State& state = m_entries[modelIndex].samplesRot[frameIndex];
state.data[0] = rotation[0];
state.data[1] = rotation[1];
state.data[2] = rotation[2];
}
void NonSkeletalAnimationData::SetFrameCountRot(int modelIndex, int frameCount)
{
m_entries[modelIndex].samplesRot.resize(frameCount);
}
void NonSkeletalAnimationData::SetFrameTimeScl(int modelIndex, int frameIndex, float time)
{
State& state = m_entries[modelIndex].samplesScl[frameIndex];
state.time = time;
}
void NonSkeletalAnimationData::SetFrameDataScl(int modelIndex, int frameIndex, float scale[3])
{
State& state = m_entries[modelIndex].samplesScl[frameIndex];
state.data[0] = scale[0];
state.data[1] = scale[1];
state.data[2] = scale[2];
}
void NonSkeletalAnimationData::SetFrameCountScl(int modelIndex, int frameCount)
{
m_entries[modelIndex].samplesScl.resize(frameCount);
}
float NonSkeletalAnimationData::GetFrameTimePos(int modelIndex, int frameIndex) const
{
return m_entries[modelIndex].samplesPos[frameIndex].time;
}
void NonSkeletalAnimationData::GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const
{
translation = m_entries[modelIndex].samplesPos[frameIndex].data;
}
int NonSkeletalAnimationData::GetFrameCountPos(int modelIndex) const
{
return int(m_entries[modelIndex].samplesPos.size());
}
float NonSkeletalAnimationData::GetFrameTimeRot(int modelIndex, int frameIndex) const
{
return m_entries[modelIndex].samplesRot[frameIndex].time;
}
void NonSkeletalAnimationData::GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const
{
rotation = m_entries[modelIndex].samplesRot[frameIndex].data;
}
int NonSkeletalAnimationData::GetFrameCountRot(int modelIndex) const
{
return int(m_entries[modelIndex].samplesRot.size());
}
float NonSkeletalAnimationData::GetFrameTimeScl(int modelIndex, int frameIndex) const
{
return m_entries[modelIndex].samplesScl[frameIndex].time;
}
void NonSkeletalAnimationData::GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const
{
scale = m_entries[modelIndex].samplesScl[frameIndex].data;
}
int NonSkeletalAnimationData::GetFrameCountScl(int modelIndex) const
{
return int(m_entries[modelIndex].samplesScl.size());
}
void NonSkeletalAnimationData::SetFrameTCBPos(int modelIndex, int frameIndex, IAnimationData::TCB tcb)
{
State& state = m_entries[modelIndex].samplesPos[frameIndex];
state.tcb = tcb;
}
void NonSkeletalAnimationData::SetFrameTCBRot(int modelIndex, int frameIndex, IAnimationData::TCB tcb)
{
State& state = m_entries[modelIndex].samplesRot[frameIndex];
state.tcb = tcb;
}
void NonSkeletalAnimationData::SetFrameTCBScl(int modelIndex, int frameIndex, IAnimationData::TCB tcb)
{
State& state = m_entries[modelIndex].samplesScl[frameIndex];
state.tcb = tcb;
}
void NonSkeletalAnimationData::SetFrameEaseInOutPos(int modelIndex, int frameIndex, IAnimationData::Ease ease)
{
State& state = m_entries[modelIndex].samplesPos[frameIndex];
state.ease = ease;
}
void NonSkeletalAnimationData::SetFrameEaseInOutRot(int modelIndex, int frameIndex, IAnimationData::Ease ease)
{
State& state = m_entries[modelIndex].samplesRot[frameIndex];
state.ease = ease;
}
void NonSkeletalAnimationData::SetFrameEaseInOutScl(int modelIndex, int frameIndex, IAnimationData::Ease ease)
{
State& state = m_entries[modelIndex].samplesScl[frameIndex];
state.ease = ease;
}
void NonSkeletalAnimationData::GetFrameTCBPos(int modelIndex, int frameIndex, IAnimationData::TCB& tcb) const
{
const State& state = m_entries[modelIndex].samplesPos[frameIndex];
tcb = state.tcb;
}
void NonSkeletalAnimationData::GetFrameTCBRot(int modelIndex, int frameIndex, IAnimationData::TCB& tcb) const
{
const State& state = m_entries[modelIndex].samplesRot[frameIndex];
tcb = state.tcb;
}
void NonSkeletalAnimationData::GetFrameTCBScl(int modelIndex, int frameIndex, IAnimationData::TCB& tcb) const
{
const State& state = m_entries[modelIndex].samplesScl[frameIndex];
tcb = state.tcb;
}
void NonSkeletalAnimationData::GetFrameEaseInOutPos(int modelIndex, int frameIndex, IAnimationData::Ease& ease) const
{
const State& state = m_entries[modelIndex].samplesPos[frameIndex];
ease = state.ease;
}
void NonSkeletalAnimationData::GetFrameEaseInOutRot(int modelIndex, int frameIndex, IAnimationData::Ease& ease) const
{
const State& state = m_entries[modelIndex].samplesRot[frameIndex];
ease = state.ease;
}
void NonSkeletalAnimationData::GetFrameEaseInOutScl(int modelIndex, int frameIndex, IAnimationData::Ease& ease) const
{
const State& state = m_entries[modelIndex].samplesScl[frameIndex];
ease = state.ease;
}
NonSkeletalAnimationData::State::State()
{
time = 0.0f;
data[0] = data[1] = data[2] = 0.0f;
}
NonSkeletalAnimationData::ModelEntry::ModelEntry()
: flags(0)
{
}
@@ -1,211 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ANIMATIONDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ANIMATIONDATA_H
#pragma once
#include "IAnimationData.h"
#include <vector>
// Animation data class for skeletal animations
// It has a same count of samples for all models(bones)
// and always has translation/rotation/scaling data together as a set.
class AnimationData
: public IAnimationData
{
public:
AnimationData(int modelCount, float fps, float startTime);
virtual ~AnimationData() {}
// IAnimationData
virtual void SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]);
virtual void SetFrameCount(int frameCount);
virtual void SetModelFlags(int modelIndex, unsigned modelFlags);
virtual void SetFrameTimePos(int modelIndex, int frameIndex, float time)
{ assert(0); }
virtual void SetFrameDataPos(int modelIndex, int frameIndex, float translation[3])
{ assert(0); }
virtual void SetFrameCountPos(int modelIndex, int frameCount)
{ assert(0); }
virtual void SetFrameTimeRot(int modelIndex, int frameIndex, float time)
{ assert(0); }
virtual void SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3])
{ assert(0); }
virtual void SetFrameCountRot(int modelIndex, int frameCount)
{ assert(0); }
virtual void SetFrameTimeScl(int modelIndex, int frameIndex, float time)
{ assert(0); }
virtual void SetFrameDataScl(int modelIndex, int frameIndex, float scale[3])
{ assert(0); }
virtual void SetFrameCountScl(int modelIndex, int frameCount)
{ assert(0); }
virtual void GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const;
virtual int GetFrameCount() const;
virtual unsigned GetModelFlags(int modelIndex) const;
virtual float GetFrameTimePos(int modelIndex, int frameIndex) const
{ return m_startTime + frameIndex / m_fps; }
virtual void GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const;
virtual int GetFrameCountPos(int) const
{ return GetFrameCount(); }
virtual float GetFrameTimeRot(int modelIndex, int frameIndex) const
{ return m_startTime + frameIndex / m_fps; }
virtual void GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const;
virtual int GetFrameCountRot(int) const
{ return GetFrameCount(); }
virtual float GetFrameTimeScl(int modelIndex, int frameIndex) const
{ return m_startTime + frameIndex / m_fps; }
virtual void GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const;
virtual int GetFrameCountScl(int) const
{ return GetFrameCount(); }
// TCB & Ease-In/-Out not supported for the skeletal animation.
virtual void SetFrameTCBPos(int modelIndex, int frameIndex, TCB tcb)
{ assert(0); }
virtual void SetFrameTCBRot(int modelIndex, int frameIndex, TCB tcb)
{ assert(0); }
virtual void SetFrameTCBScl(int modelIndex, int frameIndex, TCB tcb)
{ assert(0); }
virtual void SetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease ease)
{ assert(0); }
virtual void SetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease ease)
{ assert(0); }
virtual void SetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease ease)
{ assert(0); }
virtual void GetFrameTCBPos(int modelIndex, int frameIndex, TCB& tcb) const
{ assert(0); }
virtual void GetFrameTCBRot(int modelIndex, int frameIndex, TCB& tcb) const
{ assert(0); }
virtual void GetFrameTCBScl(int modelIndex, int frameIndex, TCB& tcb) const
{ assert(0); }
virtual void GetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease& ease) const
{ assert(0); }
virtual void GetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease& ease) const
{ assert(0); }
virtual void GetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease& ease) const
{ assert(0); }
private:
struct State
{
public:
State();
float translation[3];
float rotation[3];
float scale[3];
};
struct ModelEntry
{
ModelEntry();
unsigned flags;
std::vector<State> samples;
};
std::vector<ModelEntry> m_entries;
int m_frameCount;
float m_startTime;
float m_fps;
};
// Animation data class for non-skeletal animations
// It can have different counts of samples for each model
// and each channel of transformation data.
class NonSkeletalAnimationData
: public IAnimationData
{
public:
NonSkeletalAnimationData(int modelCount);
virtual ~NonSkeletalAnimationData() {}
// IAnimationData
virtual void SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3])
{ assert(0); }
virtual void SetFrameCount(int frameCount)
{ assert(0); }
virtual void SetModelFlags(int modelIndex, unsigned modelFlags);
virtual void SetFrameTimePos(int modelIndex, int frameIndex, float time);
virtual void SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]);
virtual void SetFrameCountPos(int modelIndex, int frameCount);
virtual void SetFrameTimeRot(int modelIndex, int frameIndex, float time);
virtual void SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]);
virtual void SetFrameCountRot(int modelIndex, int frameCount);
virtual void SetFrameTimeScl(int modelIndex, int frameIndex, float time);
virtual void SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]);
virtual void SetFrameCountScl(int modelIndex, int frameCount);
virtual void GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const
{ assert(0); }
virtual int GetFrameCount() const
{
assert(0);
return 0;
}
virtual unsigned GetModelFlags(int modelIndex) const;
virtual float GetFrameTimePos(int modelIndex, int frameIndex) const;
virtual void GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const;
virtual int GetFrameCountPos(int) const;
virtual float GetFrameTimeRot(int modelIndex, int frameIndex) const;
virtual void GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const;
virtual int GetFrameCountRot(int) const;
virtual float GetFrameTimeScl(int modelIndex, int frameIndex) const;
virtual void GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const;
virtual int GetFrameCountScl(int) const;
virtual void SetFrameTCBPos(int modelIndex, int frameIndex, TCB tcb);
virtual void SetFrameTCBRot(int modelIndex, int frameIndex, TCB tcb);
virtual void SetFrameTCBScl(int modelIndex, int frameIndex, TCB tcb);
virtual void SetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease ease);
virtual void SetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease ease);
virtual void SetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease ease);
virtual void GetFrameTCBPos(int modelIndex, int frameIndex, TCB& tcb) const;
virtual void GetFrameTCBRot(int modelIndex, int frameIndex, TCB& tcb) const;
virtual void GetFrameTCBScl(int modelIndex, int frameIndex, TCB& tcb) const;
virtual void GetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease& ease) const;
virtual void GetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease& ease) const;
virtual void GetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease& ease) const;
private:
struct State
{
public:
State();
float time;
float data[3];
TCB tcb;
Ease ease;
};
struct ModelEntry
{
ModelEntry();
unsigned flags;
std::vector<State> samplesPos;
std::vector<State> samplesRot;
std::vector<State> samplesScl;
};
std::vector<ModelEntry> m_entries;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ANIMATIONDATA_H
@@ -1,57 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "CBAHelpers.h"
#include "../PathHelpers.h"
#include "StringHelpers.h"
static string FindRootContainingFileGoingUpwards(const char* filePath, const char* filePathToLookFor, IPakSystem* pakSystem)
{
// Here we just search upwards from the current directory, looking for a directory that
// contains a file at the relative path "Animations/Animations.cba". This is designed to
// handle root Game paths that differ from the default "Game".
string rootDirCandidate = PathHelpers::GetDirectory(filePath);
string rootDir;
while (!rootDirCandidate.empty())
{
string cbaCandidatePath = PathHelpers::Join(rootDirCandidate, filePathToLookFor);
if (PakSystemFile* file = pakSystem->Open(cbaCandidatePath.c_str(), "r"))
{
// File exists, we have found the correct root path.
pakSystem->Close(file);
rootDir = rootDirCandidate;
break;
}
string previousCandidate = rootDirCandidate;
rootDirCandidate = PathHelpers::GetDirectory(rootDirCandidate);
if (rootDirCandidate == previousCandidate)
{
break;
}
}
return (rootDir.empty() ? rootDir : PathHelpers::Join(rootDir, filePathToLookFor));
}
string CBAHelpers::FindCBAFileForFile(const char* filePath, IPakSystem* pakSystem)
{
return FindRootContainingFileGoingUpwards(filePath, "Animations/Animations.cba", pakSystem);
}
string CBAHelpers::FindSkeletonListForFile(const char* filePath, IPakSystem* pakSystem)
{
return FindRootContainingFileGoingUpwards(filePath, "Animations/SkeletonList.xml", pakSystem);
}
@@ -1,27 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_CBAHELPERS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_CBAHELPERS_H
#pragma once
#include "IPakSystem.h"
namespace CBAHelpers
{
string FindCBAFileForFile(const char* filePath, IPakSystem* pakSystem);
string FindSkeletonListForFile(const char* filePath, IPakSystem* pakSystem);
}
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_CBAHELPERS_H
@@ -1,556 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "ColladaExportWriter.h"
#include "ColladaWriter.h"
#include "IExportSource.h"
#include "PathHelpers.h"
#include "ResourceCompilerHelper.h"
#include "SettingsManagerHelpers.h"
#include "IExportContext.h"
#include "ProgressRange.h"
#include "XMLWriter.h"
#include "XMLPakFileSink.h"
#include "ISettings.h"
#include "SingleAnimationExportSourceAdapter.h"
#include "GeometryExportSourceAdapter.h"
#include "ModelData.h"
#include "MaterialData.h"
#include "GeometryFileData.h"
#include "FileUtil.h"
#include "CBAHelpers.h"
#include "ModuleHelpers.h"
#include "PropertyHelpers.h"
#include "StringHelpers.h"
#include <ctime>
#include <list>
namespace
{
class ResourceCompilerLogListener
: public IResourceCompilerListener
{
public:
ResourceCompilerLogListener(IExportContext* context)
: m_context(context)
{
}
virtual void OnRCMessage(IResourceCompilerListener::MessageSeverity severity, const char* text)
{
ILogger::ESeverity outSeverity;
switch (severity)
{
case IResourceCompilerListener::MessageSeverity_Debug:
case IResourceCompilerListener::MessageSeverity_Info: // normal RC text should just be debug
outSeverity = ILogger::eSeverity_Debug;
break;
case IResourceCompilerListener::MessageSeverity_Warning:
outSeverity = ILogger::eSeverity_Warning;
break;
case IResourceCompilerListener::MessageSeverity_Error:
outSeverity = ILogger::eSeverity_Error;
break;
default:
outSeverity = ILogger::eSeverity_Error;
break;
}
m_context->Log(outSeverity, "%s", text);
}
private:
IExportContext* m_context;
};
}
void ColladaExportWriter::Export(IExportSource* source, IExportContext* context)
{
// Create an object to report on our progress to the export context.
ProgressRange progressRange(context, &IExportContext::SetProgress);
CResourceCompilerHelper compiler; // we need a real instance of this specific implementation.
// Log build information.
context->Log(ILogger::eSeverity_Info, "Exporter build created on " __DATE__);
#ifdef STLPORT
context->Log(ILogger::eSeverity_Info, "Using STLport C++ Standard Library implementation");
#else //STLPORT
context->Log(ILogger::eSeverity_Info, "Using Microsoft (tm) C++ Standard Library implementation");
#endif //STLPORT
#if defined(_DEBUG)
context->Log(ILogger::eSeverity_Info, "******DEBUG BUILD******");
#else //_DEBUG
context->Log(ILogger::eSeverity_Info, "Release build.");
#endif //_DEBUG
context->Log(ILogger::eSeverity_Debug, "Bit count == %d.", (sizeof(void*) * 8));
std::string exePath = StringHelpers::ConvertString<string>(ModuleHelpers::GetCurrentModulePath(ModuleHelpers::CurrentModuleSpecifier_Executable));
context->Log(ILogger::eSeverity_Debug, "Application path: %s", exePath.c_str());
std::string exporterPath = StringHelpers::ConvertString<string>(ModuleHelpers::GetCurrentModulePath(ModuleHelpers::CurrentModuleSpecifier_Library));
context->Log(ILogger::eSeverity_Debug, "Exporter path: %s", exporterPath.c_str());
bool const bExportCompressed = (GetSetting<int>(context->GetSettings(), "ExportCompressedCOLLADA", 1)) != 0;
context->Log(ILogger::eSeverity_Debug, "ExportCompressedCOLLADA key: %d", (bExportCompressed ? 1 : 0));
std::string const exportExtension = bExportCompressed ? ".dae.zip" : ".dae";
// Log the start time.
{
char buf[1024];
std::time_t t = std::time(0);
std::strftime(buf, sizeof(buf) / sizeof(buf[0]), "%H:%M:%S on %a, %d/%m/%Y", std::localtime(&t));
context->Log(ILogger::eSeverity_Info, "Export begun at %s", buf);
}
// Select the name of the directory to export to.
std::string const originalExportDirectory = source->GetExportDirectory();
if (originalExportDirectory.empty())
{
throw IExportContext::NeedSaveError("Scene must be saved before exporting.");
}
GeometryFileData geometryFileData;
std::vector<std::string> colladaGeometryFileNameList;
std::vector<std::string> assetGeometryFileNameList;
typedef std::vector<std::pair<std::pair<int, int>, std::string> > AnimationFileNameList;
AnimationFileNameList animationFileNameList;
AnimationFileNameList animationCompileFileNameList;
{
CurrentTaskScope currentTask(context, "dae");
// Choose the files to which to export all the animations.
std::list<SingleAnimationExportSourceAdapter> animationExportSources;
std::list<GeometryExportSourceAdapter> geometryExportSources;
typedef std::vector<std::pair<std::string, IExportSource*> > ExportList;
ExportList exportList;
std::vector<int> geometryFileIndices;
{
ProgressRange readProgressRange(progressRange, 0.2f);
source->ReadGeometryFiles(context, &geometryFileData);
for (int geometryFileIndex = 0; geometryFileIndex < geometryFileData.GetGeometryFileCount(); ++geometryFileIndex)
{
const std::string geometryFileName = geometryFileData.GetGeometryFileName(geometryFileIndex);
IGeometryFileData::SProperties properties = geometryFileData.GetProperties(geometryFileIndex);
if (properties.filetypeInt == CRY_FILE_TYPE_CAF)
{
// LDS: This is a temporary fix for some old hacky code that would activate a deprecated compression path during export
// It needs a proper fix by tearing out the old compression code and moving the system to the new i_caf system by default.
// See for http://docs.cryengine.com/display/SDKDOC3/Transition+from+CBA+to+AnimSettings details.
properties.filetypeInt = CRY_FILE_TYPE_INTERMEDIATE_CAF;
geometryFileData.SetProperties(geometryFileIndex, properties);
}
bool const hasGeometry = (properties.filetypeInt != CRY_FILE_TYPE_CAF &&
properties.filetypeInt != CRY_FILE_TYPE_INTERMEDIATE_CAF);
if (hasGeometry && !geometryFileName.empty())
{
geometryFileIndices.push_back(geometryFileIndex);
}
}
if (!geometryFileIndices.empty())
{
std::string name = PathHelpers::RemoveExtension(PathHelpers::GetFilename(source->GetDCCFileName()));
std::replace(name.begin(), name.end(), ' ', '_');
std::string const colladaPath = PathHelpers::Join(originalExportDirectory, name + exportExtension);
colladaGeometryFileNameList.push_back(colladaPath);
geometryExportSources.push_back(GeometryExportSourceAdapter(source, &geometryFileData, geometryFileIndices));
exportList.push_back(std::make_pair(colladaPath, &geometryExportSources.back()));
}
for (int geometryFileIndex = 0; geometryFileIndex < geometryFileData.GetGeometryFileCount(); ++geometryFileIndex)
{
std::string const geometryFileName = geometryFileData.GetGeometryFileName(geometryFileIndex);
int const fileTypeInt = geometryFileData.GetProperties(geometryFileIndex).filetypeInt;
std::string customExportPath = geometryFileData.GetProperties(geometryFileIndex).customExportPath;
bool const hasGeometry = (fileTypeInt != CRY_FILE_TYPE_CAF &&
fileTypeInt != CRY_FILE_TYPE_INTERMEDIATE_CAF);
if (hasGeometry && !geometryFileName.empty())
{
std::string extension = "missingextension";
if (fileTypeInt == CRY_FILE_TYPE_CGF)
{
extension = "cgf";
}
else if ((fileTypeInt == CRY_FILE_TYPE_CGA) || (fileTypeInt == (CRY_FILE_TYPE_CGA | CRY_FILE_TYPE_ANM)))
{
extension = "cga";
}
else if (fileTypeInt == CRY_FILE_TYPE_ANM)
{
extension = "anm";
}
else if (fileTypeInt == CRY_FILE_TYPE_CHR ||
(fileTypeInt == (CRY_FILE_TYPE_CHR | CRY_FILE_TYPE_CAF)) ||
(fileTypeInt == (CRY_FILE_TYPE_CHR | CRY_FILE_TYPE_INTERMEDIATE_CAF)))
{
extension = "chr";
}
else if (fileTypeInt == CRY_FILE_TYPE_SKIN)
{
extension = "skin";
}
std::string safeGeometryFileName = geometryFileName;
std::replace(safeGeometryFileName.begin(), safeGeometryFileName.end(), ' ', '_');
std::string finalFileName;
if (customExportPath.size() > 0)
{
if (PathHelpers::IsRelative(customExportPath))
{
std::string const assetRelativePath = PathHelpers::Join(originalExportDirectory, customExportPath);
finalFileName = PathHelpers::Join(assetRelativePath, safeGeometryFileName + "." + extension);
}
else
{
context->Log(ILogger::eSeverity_Warning, "An absolute path was specified for export of node %s (%s) - This is unlikely to be correct", geometryFileName.c_str(), customExportPath.c_str());
finalFileName = PathHelpers::Join(customExportPath, safeGeometryFileName + "." + extension);
}
}
else
{
// no relative path, just export it in the original directory.
finalFileName = PathHelpers::Join(originalExportDirectory, safeGeometryFileName + "." + extension);
}
if (finalFileName.size() > 0)
{
assetGeometryFileNameList.push_back(finalFileName);
if (!FileUtil::EnsureDirectoryExists(PathHelpers::GetDirectory(finalFileName).c_str()))
{
context->Log(ILogger::eSeverity_Error, "Unable to create directory for %s", finalFileName.c_str());
return;
}
}
}
if ((fileTypeInt & (CRY_FILE_TYPE_CAF | CRY_FILE_TYPE_INTERMEDIATE_CAF)) != 0)
{
for (int animationIndex = 0; animationIndex < source->GetAnimationCount(); ++animationIndex)
{
std::string const animationName = source->GetAnimationName(&geometryFileData, geometryFileIndex, animationIndex);
// Animations beginning with an underscore should be ignored.
bool const ignoreAnimation = animationName.empty() || (animationName[0] == '_');
if (!ignoreAnimation)
{
std::string safeAnimationName = animationName;
std::replace(safeAnimationName.begin(), safeAnimationName.end(), ' ', '_');
std::string exportPath = PathHelpers::Join(originalExportDirectory, safeAnimationName + exportExtension);
animationFileNameList.push_back(std::make_pair(std::make_pair(animationIndex, geometryFileIndex), exportPath));
if (fileTypeInt & CRY_FILE_TYPE_CAF)
{
animationCompileFileNameList.push_back(std::make_pair(std::make_pair(animationIndex, geometryFileIndex), exportPath));
}
animationExportSources.push_back(SingleAnimationExportSourceAdapter(source, &geometryFileData, geometryFileIndex, animationIndex));
exportList.push_back(std::make_pair(exportPath, &animationExportSources.back()));
}
}
}
}
}
// Export the COLLADA file to the chosen file.
{
ProgressRange exportProgressRange(progressRange, 0.6f);
size_t const daeCount = exportList.size();
float const daeProgressRangeSlice = 1.0f / (daeCount > 0 ? daeCount : 1);
for (ExportList::iterator itFile = exportList.begin(); itFile != exportList.end(); ++itFile)
{
const std::string& colladaFileName = (*itFile).first;
IExportSource* fileExportSource = (*itFile).second;
ProgressRange animationExportProgressRange(exportProgressRange, daeProgressRangeSlice);
try
{
context->Log(ILogger::eSeverity_Info, "Exporting to file '%s'", colladaFileName.c_str());
// Try to create the directory for the file.
if (!FileUtil::EnsureDirectoryExists(PathHelpers::GetDirectory(colladaFileName).c_str()))
{
context->Log(ILogger::eSeverity_Error, "Unable to create directory for %s", colladaFileName.c_str());
return;
}
bool ok;
if (bExportCompressed)
{
IPakSystem* pakSystem = (context ? context->GetPakSystem() : 0);
if (!pakSystem)
{
throw IExportContext::PakSystemError("No pak system provided.");
}
std::string const archivePath = colladaFileName;
std::string archiveRelativePath = colladaFileName.substr(0, colladaFileName.length() - exportExtension.length()) + ".dae";
archiveRelativePath = PathHelpers::GetFilename(archiveRelativePath);
XMLPakFileSink sink(pakSystem, archivePath, archiveRelativePath);
ok = ColladaWriter::Write(fileExportSource, context, &sink, animationExportProgressRange);
}
else
{
XMLFileSink fileSink(colladaFileName);
ok = ColladaWriter::Write(fileExportSource, context, &fileSink, animationExportProgressRange);
}
if (!ok)
{
// FIXME: erase the resulting file somehow
context->Log(ILogger::eSeverity_Error, "Failed to export '%s'", colladaFileName.c_str());
return;
}
}
catch (IXMLSink::OpenFailedError e)
{
context->Log(ILogger::eSeverity_Error, "Unable to open output file: %s", e.what());
return;
}
catch (...)
{
context->Log(ILogger::eSeverity_Error, "Unexpected crash in COLLADA exporter");
return;
}
}
}
}
// Get the RC path. If a custom one isn't specified then fall back to the registry method as per the default.
wchar_t resourceCompilerPath[512];
{
const std::string resourceCompilerPathString = source->GetResourceCompilerPath();
if (!resourceCompilerPathString.empty())
{
SettingsManagerHelpers::ConvertUtf8ToUtf16(resourceCompilerPathString.c_str(), SettingsManagerHelpers::CWCharBuffer(resourceCompilerPath, sizeof(resourceCompilerPath)));
}
}
// Run the resource compiler on the COLLADA file to generate uncompressed CAFs.
{
ProgressRange compilerProgressRange(progressRange, 0.075f);
CurrentTaskScope currentTask(context, "rc");
size_t const daeCount = animationFileNameList.size();
float const animationProgressRangeSlice = 1.0f / (daeCount > 0 ? daeCount : 1);
for (AnimationFileNameList::iterator itFile = animationFileNameList.begin(); itFile != animationFileNameList.end(); ++itFile)
{
std::string colladaFileName = (*itFile).second;
int geometryFileIndex = itFile->first.second;
std::string expectedCAFPath;
{
bool isIntermediateCAF = (geometryFileData.GetProperties(geometryFileIndex).filetypeInt & CRY_FILE_TYPE_INTERMEDIATE_CAF) != 0;
string nameWithoutExtension = colladaFileName.substr(0, colladaFileName.length() - exportExtension.length());
expectedCAFPath = nameWithoutExtension + (isIntermediateCAF ? ".i_caf" : ".caf");
}
if (FileUtil::FileExists(expectedCAFPath.c_str()))
{
if (!DeleteFileA(expectedCAFPath.c_str()))
{
context->Log(ILogger::eSeverity_Error, "Failed to remove existing animation file: %s", expectedCAFPath.c_str());
continue;
}
}
string arguments = "/refresh";
ProgressRange animationCompileProgressRange(compilerProgressRange, animationProgressRangeSlice);
ResourceCompilerLogListener listener(context);
context->Log(ILogger::eSeverity_Info, "Calling RC to generate uncompressed CAF file: %s", colladaFileName.c_str());
CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler( // actual instance of compiler used
colladaFileName.c_str(),
arguments.c_str(),
&listener,
true, false, false, 0, resourceCompilerPath);
if (result != CResourceCompilerHelper::eRcCallResult_success)
{
context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result));
continue;
}
context->Log(ILogger::eSeverity_Debug, "RC finished: %s", colladaFileName.c_str());
if (!FileUtil::FileExists(expectedCAFPath.c_str()))
{
context->Log(ILogger::eSeverity_Error, "Following Animation file is expected to be created by RC: %s", expectedCAFPath.c_str());
context->Log(ILogger::eSeverity_Error, "Do you have an old RC version?");
}
#if !defined(_DEBUG)
// Delete the Collada file.
DeleteFileA(colladaFileName.c_str());
#endif
}
}
// Run the resource compiler on the COLLADA file to generate the geometry assets.
{
ProgressRange compilerProgressRange(progressRange, 0.075f);
CurrentTaskScope currentTask(context, "rc");
size_t const daeCount = colladaGeometryFileNameList.size();
float const assetProgressRangeSlice = 1.0f / (daeCount > 0 ? daeCount : 1);
for (size_t i = 0; i < daeCount; ++i)
{
const std::string& colladaFileName = colladaGeometryFileNameList[i];
ProgressRange assetCompileProgressRange(compilerProgressRange, assetProgressRangeSlice);
ResourceCompilerLogListener listener(context);
context->Log(ILogger::eSeverity_Info, "Calling RC to generate raw asset file: %s", colladaFileName.c_str());
CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler(
colladaFileName.c_str(),
"/refresh",
&listener,
true, false, false, 0, resourceCompilerPath);
#if !defined(_DEBUG)
// Delete the Collada file.
DeleteFileA(colladaFileName.c_str());
#endif
if (result == CResourceCompilerHelper::eRcCallResult_success)
{
context->Log(ILogger::eSeverity_Debug, "RC finished: %s", colladaFileName.c_str());
}
else
{
context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result));
return;
}
}
}
{
// Create an RC helper - do it outside the loop, since it queries the registry on construction.
ResourceCompilerLogListener listener(context);
// Check the registry to see whether we should compress the animations or not.
int processAnimations = GetSetting<int>(context->GetSettings(), "CompressCAFs", 1);
if (!processAnimations)
{
context->Log(ILogger::eSeverity_Warning, "CompressCAFs registry key set to 0 - not compressing CAFs");
}
else
{
// Run the resource compiler again on the generated CAF files to compress/process them.
context->Log(ILogger::eSeverity_Debug, "CompressCAFs not set or set to 1 - compressing CAFs");
CurrentTaskScope currentTask(context, "compress");
ProgressRange compressRange(progressRange, 0.025f);
size_t const cafCount = animationCompileFileNameList.size();
float const animationProgressRangeSlice = 1.0f / (cafCount > 0 ? cafCount : 1);
for (AnimationFileNameList::iterator itFile = animationCompileFileNameList.begin(); itFile != animationCompileFileNameList.end(); ++itFile)
{
std::string colladaFileName = (*itFile).second;
ProgressRange animationProgressRange(compressRange, animationProgressRangeSlice);
// Assume the RC generated the CAF file using the take name and adding .CAF.
std::string cafPath = colladaFileName.substr(0, colladaFileName.length() - exportExtension.length()) + ".caf";
std::string cbaPath = StringHelpers::ConvertString<string>(CBAHelpers::FindCBAFileForFile(cafPath.c_str(), context->GetPakSystem()));
if (cbaPath.empty())
{
context->Log(ILogger::eSeverity_Error, "Unable to find CBA file for file \"%s\" (looked for a root game directory that contains a relative path of \"Animations/Animations.cba\"", cafPath.c_str());
}
else
{
char buffer[2048];
sprintf(buffer, "/file=\"%s\" /refresh /SkipDba", cafPath.c_str());
context->Log(ILogger::eSeverity_Info, "Calling RC to compress CAF file: (CBA file = %s) %s", cbaPath.c_str(), buffer);
CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler(cbaPath.c_str(), buffer, &listener, true, resourceCompilerPathType, false, false, 0, resourceCompilerPath);
if (result == CResourceCompilerHelper::eRcCallResult_success)
{
context->Log(ILogger::eSeverity_Debug, "RC finished: %s %s", cbaPath.c_str(), buffer);
}
else
{
context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result));
return;
}
}
}
}
// Check the registry to see whether we should optimize the geometry files or not.
int optimizeGeometry = GetSetting<int>(context->GetSettings(), "OptimizeAssets", 1);
// Run the resource compiler again on the generated geometry files to compress/process them.
// TODO: This should not be necessary, the RC should be modified so that assets are automatically
// compressed when exported from COLLADA.
if (!optimizeGeometry)
{
context->Log(ILogger::eSeverity_Warning, "OptimizeAssets registry key set to 0 - not compressing CAFs");
}
else
{
context->Log(ILogger::eSeverity_Debug, "OptimizeAssets not set or set to 1 - optimizing geometry");
CurrentTaskScope currentTask(context, "compress");
ProgressRange compressRange(progressRange, 0.025f);
size_t const assetCount = assetGeometryFileNameList.size();
float const assetProgressRangeSlice = 1.0f / (assetCount > 0 ? assetCount : 1);
for (size_t i = 0; i < assetCount; ++i)
{
const std::string& assetFileName = assetGeometryFileNameList[i];
ProgressRange animationProgressRange(compressRange, assetProgressRangeSlice);
// note: we skip some asset types because we know that they are "optimized" already
if (StringHelpers::EndsWithIgnoreCase(assetFileName, ".anm") || StringHelpers::EndsWithIgnoreCase(assetFileName, ".chr") || StringHelpers::EndsWithIgnoreCase(assetFileName, ".skin"))
{
context->Log(ILogger::eSeverity_Info, "Calling RC to optimize asset \"%s\"", assetFileName.c_str());
CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler(assetFileName.c_str(), "/refresh", &listener, true, resourceCompilerPathType, false, false, 0, resourceCompilerPath);
if (result == CResourceCompilerHelper::eRcCallResult_success)
{
context->Log(ILogger::eSeverity_Debug, "RC finished: %s", assetFileName.c_str());
}
else
{
context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result));
return;
}
}
}
}
}
// Log the end time.
{
char buf[1024];
std::time_t t = std::time(0);
std::strftime(buf, sizeof(buf) / sizeof(buf[0]), "%H:%M:%S on %a, %d/%m/%Y", std::localtime(&t));
context->Log(ILogger::eSeverity_Info, "Export finished at %s", buf);
}
}
@@ -1,29 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAEXPORTWRITER_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAEXPORTWRITER_H
#pragma once
#include "IExportWriter.h"
class ColladaExportWriter
: public IExportWriter
{
public:
// IExportWriter
virtual void Export(IExportSource* source, IExportContext* context);
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAEXPORTWRITER_H
File diff suppressed because it is too large Load Diff
@@ -1,32 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAWRITER_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAWRITER_H
#pragma once
#include <string>
class IExportSource;
class IExportContext;
class ProgressRange;
class IXMLSink;
class ColladaWriter
{
public:
static bool Write(IExportSource* source, IExportContext* context, IXMLSink* sink, ProgressRange& progressRange);
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAWRITER_H
@@ -1,66 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "ExportFileType.h"
#include "StringHelpers.h"
struct SFileTypeInfo
{
int type;
const char* name;
};
SFileTypeInfo s_fileTypes[] =
{
{ CRY_FILE_TYPE_CGF, "cgf" },
{ CRY_FILE_TYPE_CGA, "cga" },
{ CRY_FILE_TYPE_CHR, "chr" },
{ CRY_FILE_TYPE_CAF, "caf" },
{ CRY_FILE_TYPE_ANM, "anm" },
{ CRY_FILE_TYPE_CHR | CRY_FILE_TYPE_CAF, "chrcaf" },
{ CRY_FILE_TYPE_CGA | CRY_FILE_TYPE_ANM, "cgaanm" },
{ CRY_FILE_TYPE_SKIN, "skin" },
{ CRY_FILE_TYPE_INTERMEDIATE_CAF, "i_caf" },
};
static const int s_fileTypeCount = (sizeof(s_fileTypes) / sizeof(s_fileTypes[0]));
const char* ExportFileTypeHelpers::CryFileTypeToString(int const cryFileType)
{
for (int i = 0; i < s_fileTypeCount; ++i)
{
if (s_fileTypes[i].type == cryFileType)
{
return s_fileTypes[i].name;
}
}
return "unknown";
}
int ExportFileTypeHelpers::StringToCryFileType(const char* str)
{
if (str)
{
for (int i = 0; i < s_fileTypeCount; ++i)
{
if (_stricmp(str, s_fileTypes[i].name) == 0)
{
return s_fileTypes[i].type;
}
}
}
return CRY_FILE_TYPE_NONE;
}
@@ -1,42 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTFILETYPE_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTFILETYPE_H
#pragma once
enum CryFileType
{
CRY_FILE_TYPE_NONE = 0x0000,
CRY_FILE_TYPE_CGF = 0x0001,
CRY_FILE_TYPE_CGA = 0x0002,
CRY_FILE_TYPE_CHR = 0x0004,
CRY_FILE_TYPE_CAF = 0x0008,
CRY_FILE_TYPE_ANM = 0x0010,
CRY_FILE_TYPE_SKIN = 0x0020,
CRY_FILE_TYPE_INTERMEDIATE_CAF = 0x0040,
//START: Add Skinned Geometry (.CGF) export type (for touch bending vegetation)
CRY_FILE_TYPE_SKIN_CGF = 0x0080,
//END: Add Skinned Geometry (.CGF) export type (for touch bending vegetation)
};
namespace ExportFileTypeHelpers
{
const char* CryFileTypeToString(int cryFileType);
int StringToCryFileType(const char* str);
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTFILETYPE_H
@@ -1,83 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTHELPERS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTHELPERS_H
#pragma once
#include <cmath>
namespace ExportHelpers
{
inline void GenerateTextureCoordinates(float* const res_s, float* const res_t, const float x, const float y, const float z)
{
const float ax = ::fabs(x);
const float ay = ::fabs(y);
const float az = ::fabs(z);
float s = 0.0f;
float t = 0.0f;
if (ax > 1e-3f || ay > 1e-3f || az > 1e-3f)
{
if (ax > ay)
{
if (ax > az)
{
// X rules
s = y / ax;
t = z / ax;
}
else
{
// Z rules
s = x / az;
t = y / az;
}
}
else
{
// ax <= ay
if (ay > az)
{
// Y rules
s = x / ay;
t = z / ay;
}
else
{
// Z rules
s = x / az;
t = y / az;
}
}
}
// Now the texture coordinates are in the range [-1,1].
// We want normalized [0,1] texture coordinates.
s = (s + 1) * 0.5f;
t = (t + 1) * 0.5f;
if (res_s)
{
*res_s = s;
}
if (res_t)
{
*res_t = t;
}
}
}
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTHELPERS_H
@@ -1,130 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "ExportSourceDecoratorBase.h"
ExportSourceDecoratorBase::ExportSourceDecoratorBase(IExportSource* source)
: source(source)
{
}
void ExportSourceDecoratorBase::GetMetaData(SExportMetaData& metaData) const
{
this->source->GetMetaData(metaData);
}
std::string ExportSourceDecoratorBase::GetDCCFileName() const
{
return this->source->GetDCCFileName();
}
std::string ExportSourceDecoratorBase::GetExportDirectory() const
{
return this->source->GetExportDirectory();
}
void ExportSourceDecoratorBase::ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData)
{
this->source->ReadGeometryFiles(context, geometryFileData);
}
bool ExportSourceDecoratorBase::ReadMaterials(IExportContext* context, const IGeometryFileData* const geometryFileData, IMaterialData* materialData)
{
return this->source->ReadMaterials(context, geometryFileData, materialData);
}
void ExportSourceDecoratorBase::ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData)
{
this->source->ReadModels(geometryFileData, geometryFileIndex, modelData);
}
void ExportSourceDecoratorBase::ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* const modelData, int modelIndex, ISkeletonData* skeletonData)
{
this->source->ReadSkinning(context, skinningData, modelData, modelIndex, skeletonData);
}
bool ExportSourceDecoratorBase::ReadSkeleton(const IGeometryFileData* const geometryFileData, int geometryFileIndex, const IModelData* const modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData)
{
return this->source->ReadSkeleton(geometryFileData, geometryFileIndex, modelData, modelIndex, materialData, skeletonData);
}
int ExportSourceDecoratorBase::GetAnimationCount() const
{
return this->source->GetAnimationCount();
}
std::string ExportSourceDecoratorBase::GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const
{
return this->source->GetAnimationName(geometryFileData, geometryFileIndex, animationIndex);
}
void ExportSourceDecoratorBase::GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const
{
this->source->GetAnimationTimeSpan(start, stop, animationIndex);
}
void ExportSourceDecoratorBase::ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const
{
this->source->ReadAnimationFlags(context, animationData, geometryFileData, modelData, modelIndex, skeletonData, animationIndex);
}
IAnimationData* ExportSourceDecoratorBase::ReadAnimation(IExportContext* context, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const
{
return this->source->ReadAnimation(context, geometryFileData, modelData, modelIndex, skeletonData, animationIndex, fps);
}
bool ExportSourceDecoratorBase::ReadGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* const modelData, const IMaterialData* const materialData, int modelIndex)
{
return this->source->ReadGeometry(context, geometry, modelData, materialData, modelIndex);
}
bool ExportSourceDecoratorBase::ReadGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, const IModelData* const modelData, const IMaterialData* const materialData, int modelIndex) const
{
return this->source->ReadGeometryMaterialData(context, geometryMaterialData, modelData, materialData, modelIndex);
}
bool ExportSourceDecoratorBase::ReadBoneGeometry(IExportContext* context, IGeometryData* geometry, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* const materialData)
{
return this->source->ReadBoneGeometry(context, geometry, skeletonData, boneIndex, materialData);
}
bool ExportSourceDecoratorBase::ReadBoneGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* const materialData) const
{
return this->source->ReadBoneGeometryMaterialData(context, geometryMaterialData, skeletonData, boneIndex, materialData);
}
void ExportSourceDecoratorBase::ReadMorphs(IExportContext* context, IMorphData* morphData, const IModelData* const modelData, int modelIndex)
{
this->source->ReadMorphs(context, morphData, modelData, modelIndex);
}
bool ExportSourceDecoratorBase::ReadMorphGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* const modelData, int modelIndex, const IMorphData* const morphData, int morphIndex, const IMaterialData* materialData)
{
return this->source->ReadMorphGeometry(context, geometry, modelData, modelIndex, morphData, morphIndex, materialData);
}
bool ExportSourceDecoratorBase::HasValidPosController(const IModelData* modelData, int modelIndex) const
{
return this->source->HasValidPosController(modelData, modelIndex);
}
bool ExportSourceDecoratorBase::HasValidRotController(const IModelData* modelData, int modelIndex) const
{
return this->source->HasValidRotController(modelData, modelIndex);
}
bool ExportSourceDecoratorBase::HasValidSclController(const IModelData* modelData, int modelIndex) const
{
return this->source->HasValidSclController(modelData, modelIndex);
}
@@ -1,54 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSOURCEDECORATORBASE_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSOURCEDECORATORBASE_H
#pragma once
#include "IExportSource.h"
class ExportSourceDecoratorBase
: public IExportSource
{
public:
ExportSourceDecoratorBase(IExportSource* source);
virtual std::string GetResourceCompilerPath() const { return std::string(""); };
virtual void GetMetaData(SExportMetaData& metaData) const;
virtual std::string GetDCCFileName() const;
virtual std::string GetExportDirectory() const;
virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData);
virtual bool ReadMaterials(IExportContext* context, const IGeometryFileData* geometryFileData, IMaterialData* materialData);
virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData);
virtual void ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* modelData, int modelIndex, ISkeletonData* skeletonData);
virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData);
virtual int GetAnimationCount() const;
virtual std::string GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const;
virtual void GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const;
virtual void ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const;
virtual IAnimationData* ReadAnimation(IExportContext* context, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const;
virtual bool ReadGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, const IMaterialData* materialData, int modelIndex);
virtual bool ReadGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, const IModelData* modelData, const IMaterialData* materialData, int modelIndex) const;
virtual bool ReadBoneGeometry(IExportContext* context, IGeometryData* geometry, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData);
virtual bool ReadBoneGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData) const;
virtual void ReadMorphs(IExportContext* context, IMorphData* morphData, const IModelData* modelData, int modelIndex);
virtual bool ReadMorphGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, int modelIndex, const IMorphData* morphData, int morphIndex, const IMaterialData* materialData);
virtual bool HasValidPosController(const IModelData* modelData, int modelIndex) const;
virtual bool HasValidRotController(const IModelData* modelData, int modelIndex) const;
virtual bool HasValidSclController(const IModelData* modelData, int modelIndex) const;
protected:
IExportSource* source;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSOURCEDECORATORBASE_H
@@ -1,215 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "ExportStatusWindow.h"
#include "UI/Win32GUI.h"
#include "StringHelpers.h"
#include <process.h>
#include <Windows.h>
enum
{
WM_USER_TASK_FINISHED = WM_USER + 53,
WM_USER_ACCEPTED
};
struct ThreadData
{
ExportStatusWindow* statusWindow;
void (ExportStatusWindow::* initialize)(int width, int height, const std::vector<std::pair<std::string, std::string> >& tasks);
void (ExportStatusWindow::* run)();
int width;
int height;
const std::vector<std::pair<std::string, std::string> >* tasks;
HANDLE initializedSemaphore;
};
unsigned int __stdcall ThreadFunc(void* threadDataMemory)
{
ThreadData* data = static_cast<ThreadData*>(threadDataMemory);
ExportStatusWindow* statusWindow = data->statusWindow;
void (ExportStatusWindow::* initialize)(int width, int height, const std::vector<std::pair<std::string, std::string> >& tasks) = data->initialize;
void (ExportStatusWindow::* run)() = data->run;
int width = data->width;
int height = data->height;
const std::vector<std::pair<std::string, std::string> >& tasks = *data->tasks;
HANDLE initializedSemaphore = data->initializedSemaphore;
// Initialize the data.
(statusWindow->*initialize)(width, height, tasks);
// Let the creating thread know that we have read the data - it is
// now safe for it to clear it.
ReleaseSemaphore(initializedSemaphore, 1, 0);
// Perform the main thread processing.
(statusWindow->*run)();
return 0;
}
#pragma warning(push)
#pragma warning(disable: 4355) // 'this' : used in base member initializer list
ExportStatusWindow::ExportStatusWindow(int width, int height, const std::vector<std::pair<std::string, std::string> >& tasks)
: m_threadHandle(0)
, m_warningsEncountered(false)
, m_errorsEncountered(false)
, m_waitState(WaitState_WarningsAndErrors)
, m_okButtonSpacer(0, 0, 2000, 0)
, m_okButton(_T("OK"), this, &ExportStatusWindow::OkPressed)
, m_okButtonLayout(Layout::DirectionHorizontal)
{
OutputDebugString(_T("Showing status window.\n"));
Win32GUI::Initialize();
HANDLE initializedSemaphore = CreateSemaphore(0, 0, 1, 0);
// Create a thread to handle the message pump for the window.
ThreadData threadData;
threadData.statusWindow = this;
threadData.initialize = &ExportStatusWindow::Initialize;
threadData.run = &ExportStatusWindow::Run;
threadData.width = width;
threadData.height = height;
threadData.tasks = &tasks;
threadData.initializedSemaphore = initializedSemaphore;
m_threadHandle = (HANDLE)_beginthreadex(
0, //void *security,
0, //unsigned stack_size,
ThreadFunc, //unsigned ( *start_address )( void * ),
&threadData, //void *arglist,
0, //unsigned initflag,
0); //unsigned *thrdaddr
// Wait until the thread has read the data, since once we return the data will be lost.
WaitForSingleObject(initializedSemaphore, INFINITE);
CloseHandle(initializedSemaphore);
}
#pragma warning(pop)
ExportStatusWindow::~ExportStatusWindow()
{
OutputDebugString(_T("Hiding status window.\n"));
// Tell the thread to exit and then wait for it to do so.
if (HWND hwnd = (HWND)m_frameWindow.GetHWND())
{
PostMessage(hwnd, WM_USER_TASK_FINISHED, 0, 0);
m_okButton.Enable(true);
WaitForSingleObject((HANDLE)m_threadHandle, INFINITE);
}
}
void ExportStatusWindow::Initialize(int width, int height, const std::vector<std::pair<std::string, std::string> >& tasks)
{
OutputDebugString(_T("Beginning status window thread.\n"));
for (int taskIndex = 0, taskCount = int(tasks.size()); taskIndex < taskCount; ++taskIndex)
{
m_taskList.AddTask(tasks[taskIndex].first, tasks[taskIndex].second);
}
m_okButtonLayout.AddComponent(&m_okButtonSpacer);
m_okButtonLayout.AddComponent(&m_okButton);
m_okButton.Enable(false);
m_frameWindow.AddComponent(&m_taskList);
m_frameWindow.AddComponent(&m_progressBar);
m_frameWindow.AddComponent(&m_logWindow);
m_frameWindow.AddComponent(&m_okButtonLayout);
m_frameWindow.Show(true, width, height);
}
void ExportStatusWindow::Run()
{
MSG msg;
BOOL status;
bool waitingAcceptance = false;
while ((status = GetMessage(&msg, HWND(0), UINT(0), UINT(0))) != 0)
{
if (status == -1)
{
break;
}
else if (msg.message == WM_USER_TASK_FINISHED)
{
if (m_waitState == WaitState_Always ||
(m_waitState == WaitState_WarningsAndErrors && m_warningsEncountered || m_errorsEncountered) ||
(m_waitState == WaitState_ErrorsOnly && m_errorsEncountered))
{
waitingAcceptance = true;
}
else
{
break;
}
}
else if (waitingAcceptance && msg.message == WM_USER_ACCEPTED)
{
break;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
m_frameWindow.Show(false, 0, 0);
OutputDebugString(_T("Ending status window thread.\n"));
}
void ExportStatusWindow::OkPressed()
{
if (HWND hwnd = (HWND)m_frameWindow.GetHWND())
{
PostMessage(hwnd, WM_USER_ACCEPTED, 0, 0);
}
}
void ExportStatusWindow::SetWaitState(WaitState state)
{
m_waitState = state;
}
void ExportStatusWindow::AddTask(const std::string& id, const std::string& description)
{
m_taskList.AddTask(id, description);
}
void ExportStatusWindow::SetCurrentTask(const std::string& id)
{
m_taskList.SetCurrentTask(id);
}
void ExportStatusWindow::SetProgress(float progress)
{
TCHAR buffer[2048];
_sntprintf_s(buffer, sizeof(buffer), _TRUNCATE, _T("%.1f%% complete - exporting scene."), progress * 100);
m_frameWindow.SetCaption(buffer);
m_progressBar.SetProgress(progress);
}
void ExportStatusWindow::Log(ILogger::ESeverity eSeverity, const char* message)
{
if (eSeverity == ILogger::eSeverity_Error)
{
m_errorsEncountered = true;
}
else if (eSeverity == ILogger::eSeverity_Warning)
{
m_warningsEncountered = true;
}
m_logWindow.Log(eSeverity, StringHelpers::ConvertString<tstring>(message).c_str());
}
@@ -1,67 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSTATUSWINDOW_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSTATUSWINDOW_H
#pragma once
#include "UI/FrameWindow.h"
#include "UI/ProgressBar.h"
#include "UI/TaskList.h"
#include "UI/LogWindow.h"
#include "UI/Spacer.h"
#include "UI/Layout.h"
#include "UI/PushButton.h"
#include "ILogger.h"
class ExportStatusWindow
{
public:
enum WaitState
{
WaitState_WarningsAndErrors,
WaitState_ErrorsOnly,
WaitState_Always,
WaitState_Never,
};
ExportStatusWindow(int width, int height, const std::vector<std::pair<std::string, std::string> >& tasks);
~ExportStatusWindow();
void SetWaitState(WaitState state);
void AddTask(const std::string& id, const std::string& description);
void SetCurrentTask(const std::string& id);
void SetProgress(float progress);
void Log(ILogger::ESeverity eSeverity, const char* message);
private:
void Initialize(int width, int height, const std::vector<std::pair<std::string, std::string> >& tasks);
void Run();
void OkPressed();
FrameWindow m_frameWindow;
TaskList m_taskList;
ProgressBar m_progressBar;
Spacer m_okButtonSpacer;
PushButton m_okButton;
Layout m_okButtonLayout;
LogWindow m_logWindow;
void* m_threadHandle;
bool m_warningsEncountered;
bool m_errorsEncountered;
WaitState m_waitState;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSTATUSWINDOW_H
@@ -1,82 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "GeometryData.h"
GeometryData::GeometryData()
{
}
int GeometryData::AddPosition(float x, float y, float z)
{
int positionIndex = int(this->positions.size());
this->positions.push_back(Vector(x, y, z));
return positionIndex;
}
int GeometryData::AddNormal(float x, float y, float z)
{
int normalIndex = int(this->normals.size());
this->normals.push_back(Vector(x, y, z));
return normalIndex;
}
int GeometryData::AddTextureCoordinate(float u, float v)
{
int textureCoordinateIndex = int(this->textureCoordinates.size());
this->textureCoordinates.push_back(TextureCoordinate(u, v));
return textureCoordinateIndex;
}
int GeometryData::AddVertexColor(float r, float g, float b, float a)
{
int vertexColorIndex = int(this->vertexColors.size());
this->vertexColors.push_back(VertexColor(r, g, b, a));
return vertexColorIndex;
}
int GeometryData::AddPolygon(const int* indices, int mtlID)
{
int polygonIndex = int(this->polygons.size());
this->polygons.push_back(Polygon(mtlID,
Polygon::Vertex(indices[0], indices[1], indices[2], indices[3]),
Polygon::Vertex(indices[4], indices[5], indices[6], indices[7]),
Polygon::Vertex(indices[8], indices[9], indices[10], indices[11])));
return polygonIndex;
}
int GeometryData::GetNumberOfPositions() const
{
return (int)this->positions.size();
}
int GeometryData::GetNumberOfNormals() const
{
return (int)this->normals.size();
}
int GeometryData::GetNumberOfTextureCoordinates() const
{
return (int)this->textureCoordinates.size();
}
int GeometryData::GetNumberOfVertexColors() const
{
return (int)this->vertexColors.size();
}
int GeometryData::GetNumberOfPolygons() const
{
return (int)this->polygons.size();
}
@@ -1,102 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYDATA_H
#pragma once
#include "IGeometryData.h"
#include <vector>
class GeometryData
: public IGeometryData
{
public:
GeometryData();
// IGeometryData
virtual int AddPosition(float x, float y, float z);
virtual int AddNormal(float x, float y, float z);
virtual int AddTextureCoordinate(float u, float v);
virtual int AddVertexColor(float r, float g, float b, float a);
virtual int AddPolygon(const int* indices, int mtlID);
virtual int GetNumberOfPositions() const;
virtual int GetNumberOfNormals() const;
virtual int GetNumberOfTextureCoordinates() const;
virtual int GetNumberOfVertexColors() const;
virtual int GetNumberOfPolygons() const;
struct Vector
{
Vector(float x, float y, float z)
: x(x)
, y(y)
, z(z) {}
float x, y, z;
};
struct TextureCoordinate
{
TextureCoordinate(float u, float v)
: u(u)
, v(v) {}
float u, v;
};
struct VertexColor
{
VertexColor(float r, float g, float b, float a)
: r(r)
, g(g)
, b(b)
, a(a) {}
float r, g, b, a;
};
struct Polygon
{
struct Vertex
{
Vertex() {}
Vertex(int positionIndex, int normalIndex, int textureCoordinateIndex, int vertexColorIndex)
: positionIndex(positionIndex)
, normalIndex(normalIndex)
, textureCoordinateIndex(textureCoordinateIndex)
, vertexColorIndex(vertexColorIndex) {}
int positionIndex, normalIndex, textureCoordinateIndex, vertexColorIndex;
};
Polygon(int mtlID, const Vertex& v0, const Vertex& v1, const Vertex& v2)
: mtlID(mtlID)
{
v[0] = v0;
v[1] = v1;
v[2] = v2;
}
int mtlID;
Vertex v[3];
};
std::vector<Vector> positions;
std::vector<Vector> normals;
std::vector<TextureCoordinate> textureCoordinates;
std::vector<VertexColor> vertexColors;
std::vector<Polygon> polygons;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYDATA_H
@@ -1,54 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "GeometryExportSourceAdapter.h"
#include "IGeometryFileData.h"
#include <cassert>
GeometryExportSourceAdapter::GeometryExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryFileData, const std::vector<int>& geometryFileIndices)
: ExportSourceDecoratorBase(source)
, m_geometryFileData(geometryFileData)
, m_geometryFileIndices(geometryFileIndices)
{
assert(m_geometryFileIndices.size() <= m_geometryFileData->GetGeometryFileCount());
for (size_t i = 0; i < m_geometryFileIndices.size(); ++i)
{
int const geometryFileIndex = m_geometryFileIndices[i];
assert(geometryFileIndex >= 0 && geometryFileIndex < m_geometryFileData->GetGeometryFileCount());
}
}
void GeometryExportSourceAdapter::ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData)
{
for (size_t i = 0; i < m_geometryFileIndices.size(); ++i)
{
int const geometryFileIndex = m_geometryFileIndices[i];
int const newGeometryFileIndex = geometryFileData->AddGeometryFile(
m_geometryFileData->GetGeometryFileHandle(geometryFileIndex),
m_geometryFileData->GetGeometryFileName(geometryFileIndex),
m_geometryFileData->GetProperties(geometryFileIndex));
}
}
void GeometryExportSourceAdapter::ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData)
{
assert(geometryFileIndex >= 0 && geometryFileIndex < m_geometryFileIndices.size());
this->source->ReadModels(m_geometryFileData, m_geometryFileIndices[geometryFileIndex], modelData);
}
bool GeometryExportSourceAdapter::ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData)
{
assert(geometryFileIndex >= 0 && geometryFileIndex < m_geometryFileIndices.size());
return this->source->ReadSkeleton(m_geometryFileData, m_geometryFileIndices[geometryFileIndex], modelData, modelIndex, materialData, skeletonData);
}
@@ -1,36 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYEXPORTSOURCEADAPTER_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYEXPORTSOURCEADAPTER_H
#pragma once
#include "ExportSourceDecoratorBase.h"
class GeometryExportSourceAdapter
: public ExportSourceDecoratorBase
{
public:
GeometryExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryFileData, const std::vector<int>& geometryFileIndices);
virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData);
virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData);
virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData);
private:
IGeometryFileData* m_geometryFileData;
std::vector<int> m_geometryFileIndices;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYEXPORTSOURCEADAPTER_H
@@ -1,59 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "GeometryFileData.h"
int GeometryFileData::AddGeometryFile(const void* handle, const char* name, const SProperties& properties)
{
const int geometryFileIndex = int(m_geometryFiles.size());
m_geometryFiles.push_back(GeometryFileEntry(handle, name, properties));
return geometryFileIndex;
}
int GeometryFileData::GetGeometryFileCount() const
{
return int(m_geometryFiles.size());
}
const void* GeometryFileData::GetGeometryFileHandle(int geometryFileIndex) const
{
return m_geometryFiles[geometryFileIndex].handle;
}
const char* GeometryFileData::GetGeometryFileName(int geometryFileIndex) const
{
return m_geometryFiles[geometryFileIndex].name.c_str();
}
//////////////////////////////////////////////////////////////////////////
const IGeometryFileData::SProperties& GeometryFileData::GetProperties(int geometryFileIndex) const
{
if (size_t(geometryFileIndex) >= m_geometryFiles.size())
{
assert(0);
static SProperties badValue;
return badValue;
}
return m_geometryFiles[geometryFileIndex].properties;
}
void GeometryFileData::SetProperties(int geometryFileIndex, const IGeometryFileData::SProperties& properties)
{
if (size_t(geometryFileIndex) >= m_geometryFiles.size())
{
assert(0);
return;
}
m_geometryFiles[geometryFileIndex].properties = properties;
}
@@ -1,52 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYFILEDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYFILEDATA_H
#pragma once
#include "IGeometryFileData.h"
#include "STLHelpers.h"
class GeometryFileData
: public IGeometryFileData
{
public:
// IGeometryFileData
virtual int AddGeometryFile(const void* handle, const char* name, const SProperties& properties);
virtual const SProperties& GetProperties(int geometryFileIndex) const;
virtual void SetProperties(int geometryFileIndex, const SProperties& properties);
virtual int GetGeometryFileCount() const;
virtual const void* GetGeometryFileHandle(int geometryFileIndex) const;
virtual const char* GetGeometryFileName(int geometryFileIndex) const;
private:
struct GeometryFileEntry
{
GeometryFileEntry(const void* a_handle, const char* a_name, const SProperties& a_properties)
: handle(a_handle)
, name(a_name)
, properties(a_properties)
{
}
const void* handle;
std::string name;
SProperties properties;
};
std::vector<GeometryFileEntry> m_geometryFiles;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYFILEDATA_H
@@ -1,36 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "GeometryMaterialData.h"
void GeometryMaterialData::AddUsedMaterialIndex(int materialIndex)
{
std::map<int, int>::iterator usedMaterialPos = m_usedMaterialIndexIndexMap.find(materialIndex);
if (usedMaterialPos == m_usedMaterialIndexIndexMap.end())
{
int materialIndexIndex = int(m_usedMaterialIndices.size());
m_usedMaterialIndices.push_back(materialIndex);
m_usedMaterialIndexIndexMap.insert(std::make_pair(materialIndex, materialIndexIndex));
}
}
int GeometryMaterialData::GetUsedMaterialCount() const
{
return int(m_usedMaterialIndices.size());
}
int GeometryMaterialData::GetUsedMaterialIndex(int usedMaterialIndex) const
{
return m_usedMaterialIndices[usedMaterialIndex];
}
@@ -1,35 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYMATERIALDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYMATERIALDATA_H
#pragma once
#include "IGeometryMaterialData.h"
class GeometryMaterialData
: public IGeometryMaterialData
{
public:
// IGeometryMaterialData
virtual void AddUsedMaterialIndex(int materialIndex);
virtual int GetUsedMaterialCount() const;
virtual int GetUsedMaterialIndex(int usedMaterialIndex) const;
private:
std::vector<int> m_usedMaterialIndices;
std::map<int, int> m_usedMaterialIndexIndexMap;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYMATERIALDATA_H
@@ -1,41 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_HELPERDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_HELPERDATA_H
#pragma once
struct SHelperData
{
public:
enum EHelperType
{
eHelperType_UNKNOWN,
eHelperType_Point,
eHelperType_Dummy
};
public:
SHelperData()
: m_eHelperType(eHelperType_UNKNOWN)
{
}
public:
EHelperType m_eHelperType;
float m_boundBoxMin[3]; // used for eHelperType_Dummy only
float m_boundBoxMax[3]; // used for eHelperType_Dummy only
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_HELPERDATA_H
@@ -1,96 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IANIMATIONDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IANIMATIONDATA_H
#pragma once
class IAnimationData
{
public:
virtual ~IAnimationData() {}
virtual void SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]) = 0;
virtual void SetFrameCount(int frameCount) = 0;
virtual void SetFrameTimePos(int modelIndex, int frameIndex, float time) = 0;
virtual void SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]) = 0;
virtual void SetFrameCountPos(int modelIndex, int frameCount) = 0;
virtual void SetFrameTimeRot(int modelIndex, int frameIndex, float time) = 0;
virtual void SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]) = 0;
virtual void SetFrameCountRot(int modelIndex, int frameCount) = 0;
virtual void SetFrameTimeScl(int modelIndex, int frameIndex, float time) = 0;
virtual void SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]) = 0;
virtual void SetFrameCountScl(int modelIndex, int frameCount) = 0;
// For TCB & Ease-In/-Out support
struct TCB
{
float tension;
float continuity;
float bias;
TCB()
: tension(0)
, continuity(0)
, bias(0) {}
};
struct Ease
{
float in;
float out;
Ease()
: in(0)
, out(0) {}
};
virtual void SetFrameTCBPos(int modelIndex, int frameIndex, TCB tcb) = 0;
virtual void SetFrameTCBRot(int modelIndex, int frameIndex, TCB tcb) = 0;
virtual void SetFrameTCBScl(int modelIndex, int frameIndex, TCB tcb) = 0;
virtual void SetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease ease) = 0;
virtual void SetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease ease) = 0;
virtual void SetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease ease) = 0;
enum ModelFlags
{
ModelFlags_NoExport = 1 << 0
};
virtual void SetModelFlags(int modelIndex, unsigned modelFlags) = 0;
virtual void GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const = 0;
virtual int GetFrameCount() const = 0;
virtual float GetFrameTimePos(int modelIndex, int frameIndex) const = 0;
virtual void GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const = 0;
virtual int GetFrameCountPos(int modelIndex) const = 0;
virtual float GetFrameTimeRot(int modelIndex, int frameIndex) const = 0;
virtual void GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const = 0;
virtual int GetFrameCountRot(int modelIndex) const = 0;
virtual float GetFrameTimeScl(int modelIndex, int frameIndex) const = 0;
virtual void GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const = 0;
virtual int GetFrameCountScl(int modelIndex) const = 0;
// For TCB & Ease-In/-Out support
virtual void GetFrameTCBPos(int modelIndex, int frameIndex, TCB& tcb) const = 0;
virtual void GetFrameTCBRot(int modelIndex, int frameIndex, TCB& tcb) const = 0;
virtual void GetFrameTCBScl(int modelIndex, int frameIndex, TCB& tcb) const = 0;
virtual void GetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease& ease) const = 0;
virtual void GetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease& ease) const = 0;
virtual void GetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease& ease) const = 0;
virtual unsigned GetModelFlags(int modelIndex) const = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IANIMATIONDATA_H
@@ -1,55 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTCONTEXT_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTCONTEXT_H
#pragma once
#include <cstdarg>
#include "Exceptions.h"
#include "ILogger.h"
struct IPakSystem;
class ISettings;
class IExportContext
: public ILogger
{
public:
// Declare an exception type to report the case where the scene must be saved before exporting.
struct NeedSaveErrorTag {};
typedef Exception<NeedSaveErrorTag> NeedSaveError;
struct PakSystemErrorTag {};
typedef Exception<PakSystemErrorTag> PakSystemError;
virtual void SetProgress(float progress) = 0;
virtual void SetCurrentTask(const std::string& id) = 0;
virtual IPakSystem* GetPakSystem() = 0;
virtual ISettings* GetSettings() = 0;
virtual void GetRootPath(char* buffer, int bufferSizeInBytes) = 0;
protected:
// ILogger
virtual void LogImpl(ILogger::ESeverity eSeverity, const char* message) = 0;
};
struct CurrentTaskScope
{
CurrentTaskScope(IExportContext* context, const std::string& id)
: context(context) {context->SetCurrentTask(id); }
~CurrentTaskScope() {context->SetCurrentTask(""); }
IExportContext* context;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTCONTEXT_H
@@ -1,98 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTSOURCE_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTSOURCE_H
#pragma once
#include "Exceptions.h"
class ISkeletonData;
class IAnimationData;
class IExportContext;
class IModelData;
class IGeometryFileData;
class IGeometryData;
class IMaterialData;
class ISkinningData;
class IMorphData;
class IGeometryMaterialData;
namespace ExportGlobal
{
const float g_defaultFrameRate = 30.f;
};
struct SExportMetaData
{
enum EAxisUp
{
X_UP,
Y_UP,
Z_UP
};
char authoring_tool[128];
char source_data[1024]; // Filename of the source.
char author[128]; // Name of the author.
char revision[64];
EAxisUp up_axis;
float fMeterUnit;
float fFramesPerSecond;
SExportMetaData()
{
fMeterUnit = 1.0f;
up_axis = Z_UP;
fFramesPerSecond = ExportGlobal::g_defaultFrameRate;
strcpy(authoring_tool, "CryENGINE Collada Exporter");
strcpy(source_data, "");
strcpy(author, "");
strcpy(revision, "1.4.1");
}
};
class IExportSource
{
public:
virtual ~IExportSource()
{
}
virtual std::string GetResourceCompilerPath() const = 0;
virtual void GetMetaData(SExportMetaData& metaData) const = 0;
virtual std::string GetDCCFileName() const = 0;
virtual float GetDCCFrameRate() const{ return ExportGlobal::g_defaultFrameRate; }
virtual std::string GetExportDirectory() const = 0;
virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) = 0;
virtual bool ReadMaterials(IExportContext* context, const IGeometryFileData* geometryFileData, IMaterialData* materialData) = 0;
virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) = 0;
virtual void ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* modelData, int modelIndex, ISkeletonData* skeletonData) = 0;
virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) = 0;
virtual int GetAnimationCount() const = 0;
virtual std::string GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const = 0;
virtual void GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const = 0;
virtual void ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const = 0;
virtual IAnimationData* ReadAnimation(IExportContext* context, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const = 0;
virtual bool ReadGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, const IMaterialData* materialData, int modelIndex) = 0;
virtual bool ReadGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, const IModelData* modelData, const IMaterialData* materialData, int modelIndex) const = 0;
virtual bool ReadBoneGeometry(IExportContext* context, IGeometryData* geometry, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData) = 0;
virtual bool ReadBoneGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData) const = 0;
virtual void ReadMorphs(IExportContext* context, IMorphData* morphData, const IModelData* modelData, int modelIndex) = 0;
virtual bool ReadMorphGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, int modelIndex, const IMorphData* morphData, int morphIndex, const IMaterialData* materialData) = 0;
virtual bool HasValidPosController(const IModelData* modelData, int modelIndex) const = 0;
virtual bool HasValidRotController(const IModelData* modelData, int modelIndex) const = 0;
virtual bool HasValidSclController(const IModelData* modelData, int modelIndex) const = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTSOURCE_H
@@ -1,28 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTWRITER_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTWRITER_H
#pragma once
class IExportSource;
class IExportContext;
class IExportWriter
{
public:
virtual void Export(IExportSource* source, IExportContext* context) = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTWRITER_H
@@ -1,35 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYDATA_H
#pragma once
class IGeometryData
{
public:
virtual int AddPosition(float x, float y, float z) = 0;
virtual int AddNormal(float x, float y, float z) = 0;
virtual int AddTextureCoordinate(float u, float v) = 0;
virtual int AddVertexColor(float r, float g, float b, float a) = 0;
virtual int AddPolygon(const int* indices, int mtlID) = 0;
virtual int GetNumberOfPositions() const = 0;
virtual int GetNumberOfNormals() const = 0;
virtual int GetNumberOfTextureCoordinates() const = 0;
virtual int GetNumberOfVertexColors() const = 0;
virtual int GetNumberOfPolygons() const = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYDATA_H
@@ -1,54 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYFILEDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYFILEDATA_H
#pragma once
#include "ExportFileType.h"
#include <string>
class IGeometryFileData
{
public:
struct SProperties
{
int filetypeInt; // combination of flags from CryFileType
bool bDoNotMerge;
bool bUseCustomNormals;
bool bUseF32VertexFormat;
bool b8WeightsPerVertex;
std::string customExportPath;
SProperties()
: filetypeInt(CRY_FILE_TYPE_NONE)
, bDoNotMerge(false)
, bUseCustomNormals(false)
, bUseF32VertexFormat(false)
, b8WeightsPerVertex(false)
{
}
};
public:
virtual int AddGeometryFile(const void* handle, const char* name, const SProperties& properties) = 0;
virtual const SProperties& GetProperties(int geometryFileIndex) const = 0;
virtual int GetGeometryFileCount() const = 0;
// return an implementation-specific handle (for example a maya Dag Path string, or a MAX node name or whatever)
// its opaque to the exporter, but you can cast it yourself.
virtual const void* GetGeometryFileHandle(int geometryFileIndex) const = 0;
virtual const char* GetGeometryFileName(int geometryFileIndex) const = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYFILEDATA_H
@@ -1,27 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYMATERIALDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYMATERIALDATA_H
#pragma once
class IGeometryMaterialData
{
public:
virtual void AddUsedMaterialIndex(int materialIndex) = 0;
virtual int GetUsedMaterialCount() const = 0;
virtual int GetUsedMaterialIndex(int usedMaterialIndex) const = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYMATERIALDATA_H
@@ -1,33 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMATERIALDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMATERIALDATA_H
#pragma once
class IMaterialData
{
public:
// the handle represents an implementation specific underlying handle (like a maya pointer to a string dag name).
virtual int AddMaterial(const char* name, int id, const void* handle, const char* properties) = 0;
virtual int AddMaterial(const char* name, int id, const char* subMatName, const void* handle, const char* properties) = 0;
virtual int GetMaterialCount() const = 0;
virtual const char* GetName(int materialIndex) const = 0;
virtual int GetID(int materialIndex) const = 0;
virtual const char* GetSubMatName(int materialIndex) const = 0;
virtual const void* GetHandle(int materialIndex) const = 0;
virtual const char* GetProperties(int materialIndex) const = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMATERIALDATA_H
@@ -1,36 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMODELDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMODELDATA_H
#pragma once
#include "HelperData.h"
#include <string>
class IModelData
{
public:
virtual int AddModel(const void* handle, const char* modelName, int parentModelIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString) = 0;
virtual int GetModelCount() const = 0;
virtual const void* GetModelHandle(int modelIndex) const = 0;
virtual const char* GetModelName(int modelIndex) const = 0;
virtual void SetTranslationRotationScale(int modelIndex, const float* translation, const float* rotation, const float* scale) = 0;
virtual void GetTranslationRotationScale(int modelIndex, float* translation, float* rotation, float* scale) const = 0;
virtual const SHelperData& GetHelperData(int modelIndex) const = 0;
virtual const std::string& GetProperties(int modelIndex) const = 0;
virtual bool IsRoot(int modelIndex) const = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMODELDATA_H
@@ -1,29 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMORPHDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMORPHDATA_H
#pragma once
class IMorphData
{
public:
virtual void SetHandle(const void* handle) = 0;
virtual void AddMorph(const void* handle, const char* name, const char* fullName = NULL) = 0;
virtual const void* GetHandle() const = 0;
virtual int GetMorphCount() const = 0;
virtual const void* GetMorphHandle(int morphIndex) const = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMORPHDATA_H
@@ -1,56 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKELETONDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKELETONDATA_H
#pragma once
class ISkeletonData
{
public:
enum Axis
{
AxisX,
AxisY,
AxisZ
};
enum Limit
{
LimitMin,
LimitMax
};
virtual int AddBone(const void* handle, const char* name, int parentIndex) = 0;
virtual int FindBone(const char* name) const = 0;
virtual const void* GetBoneHandle(int boneIndex) const = 0;
virtual int GetBoneParentIndex(int boneIndex) const = 0;
virtual int GetBoneCount() const = 0;
virtual void SetTranslation(int boneIndex, const float* vec) = 0;
virtual void SetRotation(int boneIndex, const float* vec) = 0;
virtual void SetScale(int boneIndex, const float* vec) = 0;
virtual void SetParentFrameTranslation(int boneIndex, const float* vec) = 0;
virtual void SetParentFrameRotation(int boneIndex, const float* vec) = 0;
virtual void SetParentFrameScale(int boneIndex, const float* vec) = 0;
virtual void SetPhysicalized(int boneIndex, bool physicalized) = 0;
virtual void SetHasGeometry(int boneIndex, bool hasGeometry) = 0;
virtual void SetBoneProperties(int boneIndex, const char* propertiesString) = 0;
virtual void SetBoneGeomProperties(int boneIndex, const char* propertiesString) = 0;
virtual void SetLimit(int boneIndex, Axis axis, Limit extreme, float limit) = 0;
virtual void SetSpringTension(int boneIndex, Axis axis, float springTension) = 0;
virtual void SetSpringAngle(int boneIndex, Axis axis, float springAngle) = 0;
virtual void SetAxisDamping(int boneIndex, Axis axis, float damping) = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKELETONDATA_H
@@ -1,26 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKINNINGDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKINNINGDATA_H
#pragma once
class ISkinningData
{
public:
virtual void SetVertexCount(int vertexCount) = 0;
virtual void AddWeight(int vertexIndex, int boneIndex, float weight) = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKINNINGDATA_H
@@ -1,69 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "MaterialData.h"
int MaterialData::AddMaterial(const char* name, int id, const void* handle, const char* properties)
{
const int materialIndex = int(m_materials.size());
m_materials.push_back(MaterialEntry(name, id, "submat", handle, properties));
return materialIndex;
}
int MaterialData::AddMaterial(const char* name, int id, const char* subMatName, const void* handle, const char* properties)
{
const int materialIndex = int(m_materials.size());
m_materials.push_back(MaterialEntry(name, id, subMatName, handle, properties));
return materialIndex;
}
int MaterialData::GetMaterialCount() const
{
return int(m_materials.size());
}
const char* MaterialData::GetName(int materialIndex) const
{
assert(materialIndex >= 0);
assert(materialIndex < int(m_materials.size()));
return m_materials[materialIndex].name.c_str();
}
int MaterialData::GetID(int materialIndex) const
{
assert(materialIndex >= 0);
assert(materialIndex < int(m_materials.size()));
return m_materials[materialIndex].id;
}
const char* MaterialData::GetSubMatName(int materialIndex) const
{
assert(materialIndex >= 0);
assert(materialIndex < int(m_materials.size()));
return m_materials[materialIndex].subMatName.c_str();
}
const void* MaterialData::GetHandle(int materialIndex) const
{
assert(materialIndex >= 0);
assert(materialIndex < int(m_materials.size()));
return m_materials[materialIndex].handle;
}
const char* MaterialData::GetProperties(int materialIndex) const
{
assert(materialIndex >= 0);
assert(materialIndex < int(m_materials.size()));
return m_materials[materialIndex].properties.c_str();
}
@@ -1,56 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALDATA_H
#pragma once
#include "IMaterialData.h"
class MaterialData
: public IMaterialData
{
public:
virtual int AddMaterial(const char* name, int id, const void* handle, const char* properties);
virtual int AddMaterial(const char* name, int id, const char* subMatName, const void* handle, const char* properties);
virtual int GetMaterialCount() const;
virtual const char* GetName(int materialIndex) const;
virtual int GetID(int materialIndex) const;
virtual const char* GetSubMatName(int materialIndex) const;
virtual const void* GetHandle(int materialIndex) const;
virtual const char* GetProperties(int materialIndex) const;
private:
struct MaterialEntry
{
MaterialEntry(const char* a_name, int a_id, const char* a_subMatName, const void* a_handle, const char* a_properties)
: name(a_name)
, id(a_id)
, subMatName(a_subMatName)
, handle(a_handle)
, properties(a_properties ? a_properties : "")
{
}
string name;
int id;
string subMatName;
const void* handle;
string properties;
};
std::vector<MaterialEntry> m_materials;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALDATA_H
@@ -1,107 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "MaterialHelpers.h"
#include "StringHelpers.h"
#include "PathHelpers.h"
#include "properties.h"
MaterialHelpers::MaterialInfo::MaterialInfo()
{
this->id = -1;
this->name = "";
this->physicalize = "None";
this->diffuseTexture = "";
this->diffuseColor[0] = this->diffuseColor[1] = this->diffuseColor[2] = 1.0f;
this->specularColor[0] = this->specularColor[1] = this->specularColor[2] = 1.0f;
this->emissiveColor[0] = this->emissiveColor[1] = this->emissiveColor[2] = 0.0f;
}
std::string MaterialHelpers::PhysicsIDToString(const int physicsID)
{
switch (physicsID)
{
case 1:
return "Default";
break;
case 2:
return "ProxyNoDraw";
break;
case 3:
return "NoCollide";
break;
case 4:
return "Obstruct";
break;
default:
return "None";
break;
}
}
bool MaterialHelpers::WriteMaterials(const std::string& filename, const std::vector<MaterialInfo>& materialList)
{
FILE* materialFile = fopen(filename.c_str(), "w");
if (materialFile)
{
fprintf(materialFile, "<Material MtlFlags=\"524544\" >\n");
fprintf(materialFile, " <SubMaterials>\n");
for (int i = 0; i < materialList.size(); i++)
{
const MaterialInfo& material = materialList[i];
fprintf(materialFile, " <Material Name=\"%s\" ", material.name.c_str());
if (strcmp(material.physicalize.c_str(), "ProxyNoDraw") == 0)
{
fprintf(materialFile, "MtlFlags=\"1152\" Shader=\"Nodraw\" GenMask=\"0\" ");
}
else
{
fprintf(materialFile, "MtlFlags=\"524416\" Shader=\"Illum\" GenMask=\"100000000\" ");
}
fprintf(materialFile, "SurfaceType=\"\" MatTemplate=\"\" ");
fprintf(materialFile, "Diffuse=\"%f,%f,%f\" ", material.diffuseColor[0], material.diffuseColor[1], material.diffuseColor[2]);
fprintf(materialFile, "Specular=\"%f,%f,%f\" ", material.specularColor[0], material.specularColor[1], material.specularColor[2]);
fprintf(materialFile, "Emissive=\"%f,%f,%f\" ", material.emissiveColor[0], material.emissiveColor[1], material.emissiveColor[2]);
fprintf(materialFile, "Shininess=\"10\" ");
fprintf(materialFile, "Opacity=\"1\" ");
fprintf(materialFile, ">\n");
fprintf(materialFile, " <Textures>\n");
// Write out diffuse texture.
if (material.diffuseTexture.length() > 0)
{
//fprintf( materialFile, " <Texture Map=\"Diffuse\" File=\"%s\" >\n", ProcessTexturePath( material.diffuseTexture ).c_str() );
fprintf(materialFile, " <Texture Map=\"Diffuse\" File=\"%s\" >\n", material.diffuseTexture.c_str());
fprintf(materialFile, " <TexMod />\n");
fprintf(materialFile, " </Texture>\n");
}
fprintf(materialFile, " </Textures>\n");
fprintf(materialFile, " </Material>\n");
}
fprintf(materialFile, " </SubMaterials>\n");
fprintf(materialFile, "</Material>\n");
fclose(materialFile);
return true;
}
else
{
return false;
}
}
@@ -1,39 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALHELPERS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALHELPERS_H
#pragma once
namespace MaterialHelpers
{
struct MaterialInfo
{
MaterialInfo();// : id(-1) { }
std::string name;
std::string physicalize;
int id;
float diffuseColor[3];
float specularColor[3];
float emissiveColor[3];
std::string diffuseTexture;
};
std::string PhysicsIDToString(const int physicsID);
bool WriteMaterials(const std::string& filename, const std::vector<MaterialHelpers::MaterialInfo>& materialList);
}
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALHELPERS_H
@@ -1,138 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXHELPERS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXHELPERS_H
#pragma once
#include "CompileTimeAssert.h"
#include "PathHelpers.h"
#include "StringHelpers.h"
namespace MaxHelpers
{
enum
{
kBadChar = '_'
};
#if !defined(MAX_PRODUCT_VERSION_MAJOR)
#error MAX_PRODUCT_VERSION_MAJOR is undefined
#elif (MAX_PRODUCT_VERSION_MAJOR >= 15)
COMPILE_TIME_ASSERT(sizeof(MCHAR) == 2);
#define MAX_MCHAR_SIZE 2
typedef wstring MaxCompatibleString;
#elif (MAX_PRODUCT_VERSION_MAJOR >= 12)
COMPILE_TIME_ASSERT(sizeof(MCHAR) == 1);
#define MAX_MCHAR_SIZE 1
typedef string MaxCompatibleString;
#else
#error 3dsMax 2009 and older are not supported anymore
#endif
inline string CreateAsciiString(const char* s_ansi)
{
return StringHelpers::ConvertAnsiToAscii(s_ansi, kBadChar);
}
inline string CreateAsciiString(const wchar_t* s_utf16)
{
const string s_ansi = StringHelpers::ConvertUtf16ToAnsi(s_utf16, kBadChar);
return CreateAsciiString(s_ansi.c_str());
}
inline string CreateUtf8String(const char* s_ansi)
{
return StringHelpers::ConvertAnsiToUtf8(s_ansi);
}
inline string CreateUtf8String(const wchar_t* s_utf16)
{
return StringHelpers::ConvertUtf16ToUtf8(s_utf16);
}
inline string CreateTidyAsciiNodeName(const char* s_ansi)
{
const size_t len = strlen(s_ansi);
string res;
res.reserve(len);
for (size_t i = 0; i < len; ++i)
{
char c = s_ansi[i];
if (c < ' ' || c >= 127)
{
c = kBadChar;
}
res.append(1, c);
}
return res;
}
inline string CreateTidyAsciiNodeName(const wchar_t* s_utf16)
{
const string s_ansi = StringHelpers::ConvertUtf16ToAnsi(s_utf16, kBadChar);
return CreateTidyAsciiNodeName(s_ansi.c_str());
;
}
inline MSTR CreateMaxStringFromAscii(const char* s_ascii)
{
#if (MAX_MCHAR_SIZE == 2)
return MSTR(StringHelpers::ConvertAsciiToUtf16(s_ascii).c_str());
#else
return MSTR(s_ascii);
#endif
}
inline MaxCompatibleString CreateMaxCompatibleStringFromAscii(const char* s_ascii)
{
#if (MAX_MCHAR_SIZE == 2)
return StringHelpers::ConvertAsciiToUtf16(s_ascii);
#else
return MaxCompatibleString(s_ascii);
#endif
}
inline string GetAbsoluteAsciiPath(const char* s_ansi)
{
if (!s_ansi || !s_ansi[0])
{
return string();
}
return PathHelpers::GetAbsoluteAsciiPath(StringHelpers::ConvertAnsiToUtf16(s_ansi).c_str());
}
inline string GetAbsoluteAsciiPath(const wchar_t* s_utf16)
{
if (!s_utf16 || !s_utf16[0])
{
return string();
}
return PathHelpers::GetAbsoluteAsciiPath(s_utf16);
}
}
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXHELPERS_H
@@ -1,99 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "MaxUserPropertyHelpers.h"
#include "StringHelpers.h"
#include "MaxHelpers.h"
std::string MaxUserPropertyHelpers::GetNodeProperties(INode* node)
{
if (node == 0)
{
return std::string();
}
MSTR buf;
node->GetUserPropBuffer(buf);
return MaxHelpers::CreateAsciiString(buf);
}
std::string MaxUserPropertyHelpers::GetStringNodeProperty(INode* node, const char* name, const char* defaultValue)
{
if (node == 0)
{
return defaultValue;
}
MSTR val;
if (!node->GetUserPropString(MaxHelpers::CreateMaxStringFromAscii(name), val))
{
return defaultValue;
}
return MaxHelpers::CreateAsciiString(val);
}
float MaxUserPropertyHelpers::GetFloatNodeProperty(INode* node, const char* name, float defaultValue)
{
if (node == 0)
{
return defaultValue;
}
float val;
if (!node->GetUserPropFloat(MaxHelpers::CreateMaxStringFromAscii(name), val))
{
return defaultValue;
}
return val;
}
int MaxUserPropertyHelpers::GetIntNodeProperty(INode* node, const char* name, int defaultValue)
{
if (node == 0)
{
return defaultValue;
}
int val;
if (!node->GetUserPropInt(MaxHelpers::CreateMaxStringFromAscii(name), val))
{
return defaultValue;
}
return val;
}
bool MaxUserPropertyHelpers::GetBoolNodeProperty(INode* node, const char* name, bool defaultValue)
{
if (node == 0)
{
return defaultValue;
}
BOOL val;
if (!node->GetUserPropBool(MaxHelpers::CreateMaxStringFromAscii(name), val))
{
return defaultValue;
}
return (val != 0);
}
@@ -1,32 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXUSERPROPERTYHELPERS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXUSERPROPERTYHELPERS_H
#pragma once
#include <string>
class INode;
namespace MaxUserPropertyHelpers
{
std::string GetNodeProperties(INode* node);
std::string GetStringNodeProperty(INode* node, const char* name, const char* defaultValue);
float GetFloatNodeProperty(INode* node, const char* name, float defaultValue);
int GetIntNodeProperty(INode* node, const char* name, int defaultValue);
bool GetBoolNodeProperty(INode* node, const char* name, bool defaultValue);
}
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXUSERPROPERTYHELPERS_H
@@ -1,914 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MESHUTILS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MESHUTILS_H
#pragma once
#include "BaseTypes.h" // uint8
#include "Cry_Vector3.h" // Vec3
#include "IIndexedMesh.h" // CMesh
namespace MeshUtils
{
struct Face
{
int vertexIndex[3];
};
struct Color
{
uint8 r;
uint8 g;
uint8 b;
};
// Stores linking of a vertex to bone(s)
class VertexLinks
{
public:
struct Link
{
int boneId;
float weight;
Vec3 offset;
Link()
: boneId(-1)
, weight(-1.0f)
, offset(0.0f, 0.0f, 0.0f)
{
}
};
enum ESort
{
eSort_ByWeight,
eSort_ByBoneId,
};
public:
std::vector<Link> links;
public:
// minWeightToDelete: links with weights <= minWeightToDelete will be deleted
const char* Normalize(ESort eSort, const float minWeightToDelete, const int maxLinkCount)
{
if (minWeightToDelete < 0 || minWeightToDelete >= 1)
{
return "Bad minWeightToDelete passed";
}
if (maxLinkCount <= 0)
{
return "Bad maxLinkCount passed";
}
// Merging links with matching bone ids
{
DeleteByWeight(0.0f);
if (links.empty())
{
return "All bone links of a vertex have zero weight";
}
std::sort(links.begin(), links.end(), CompareLinksByBoneId);
size_t dst = 0;
for (size_t i = 1; i < links.size(); ++i)
{
if (links[i].boneId == links[dst].boneId)
{
const float w0 = links[dst].weight;
const float w1 = links[i].weight;
const float a = w0 / (w0 + w1);
links[dst].offset = links[dst].offset * a + links[i].offset * (1 - a);
links[dst].weight = w0 + w1;
}
else
{
links[++dst] = links[i];
}
}
links.resize(dst + 1);
}
// Deleting links, normalizing link weights.
//
// Note: we produce meaningful results even in cases like this:
// input weights are { 0.03, 0.01 }, minWeightTodelete is 0.2.
// Output weights produced are { 0.75, 0.25 }.
{
std::sort(links.begin(), links.end(), CompareLinksByWeight);
if (links.size() > maxLinkCount)
{
links.resize(maxLinkCount);
}
NormalizeWeights();
const size_t oldSize = links.size();
DeleteByWeight(minWeightToDelete);
if (links.empty())
{
return "All bone links of a vertex are deleted (minWeightToDelete is too big)";
}
if (links.size() != oldSize)
{
NormalizeWeights();
}
}
switch (eSort)
{
case eSort_ByWeight:
// Do nothing because we already sorted links by weight (see above)
break;
case eSort_ByBoneId:
std::sort(links.begin(), links.end(), CompareLinksByBoneId);
break;
default:
assert(0);
break;
}
return 0;
}
private:
void DeleteByWeight(float minWeightToDelete)
{
for (size_t i = 0; i < links.size(); ++i)
{
if (links[i].weight <= minWeightToDelete)
{
if (i < links.size() - 1)
{
links[i] = links[links.size() - 1];
}
links.resize(links.size() - 1);
--i;
}
}
}
void NormalizeWeights()
{
assert(!links.empty() && links[0].weight > 0);
float w = 0;
for (size_t i = 0; i < links.size(); ++i)
{
w += links[i].weight;
}
w = 1 / w;
for (size_t i = 0; i < links.size(); ++i)
{
links[i].weight *= w;
}
}
static bool CompareLinksByBoneId(const Link& left, const Link& right)
{
if (left.boneId != right.boneId)
{
return left.boneId < right.boneId;
}
if (left.weight != right.weight)
{
return left.weight < right.weight;
}
return memcmp(&left.offset, &right.offset, sizeof(left.offset)) < 0;
}
static bool CompareLinksByWeight(const Link& left, const Link& right)
{
if (left.weight != right.weight)
{
return left.weight > right.weight;
}
if (left.boneId != right.boneId)
{
return left.boneId < right.boneId;
}
return memcmp(&left.offset, &right.offset, sizeof(left.offset)) < 0;
}
};
class Mesh
{
public:
// Vertex data
std::vector<Vec3> m_positions;
std::vector<int> m_topologyIds;
std::vector<Vec3> m_normals;
std::vector<std::vector<Vec2>> m_texCoords;
std::vector<Color> m_colors;
std::vector<uint8> m_alphas;
std::vector<VertexLinks> m_links;
std::vector<int> m_vertexMatIds;
size_t m_auxSizeof;
std::vector<uint8> m_aux;
// Face data
std::vector<Face> m_faces;
std::vector<int> m_faceMatIds;
// Mappings computed and filled by ComputeVertexRemapping()
std::vector<int> m_vertexOldToNew;
std::vector<int> m_vertexNewToOld;
public:
Mesh()
: m_auxSizeof(0)
{
}
int GetVertexCount() const
{
return m_positions.size();
}
int GetFaceCount() const
{
return m_faces.size();
}
//////////////////////////////////////////////////////////////////////////
// Setters
void Clear()
{
m_positions.clear();
m_topologyIds.clear();
m_normals.clear();
m_texCoords.clear();
m_colors.clear();
m_alphas.clear();
m_links.clear();
m_vertexMatIds.clear();
m_aux.clear();
m_faces.clear();
m_faceMatIds.clear();
m_vertexOldToNew.clear();
m_vertexNewToOld.clear();
}
const char* SetPositions(const float* pVec3, int count, int stride, const float scale)
{
if (count <= 0)
{
return "bad position count";
}
if (stride < 0 || (stride > 0 && stride < sizeof(Vec3)))
{
return "bad position stride";
}
m_positions.resize(count);
for (int i = 0; i < count; ++i)
{
const float* const p = (const float*)(((const char*)pVec3) + ((size_t)i * stride));
if (!_finite(p[0]) || !_finite(p[1]) || !_finite(p[2]))
{
m_positions.clear();
return "Illegal (NAN) vertex position. Fix the 3d Model.";
}
m_positions[i].x = p[0] * scale;
m_positions[i].y = p[1] * scale;
m_positions[i].z = p[2] * scale;
}
return 0;
}
const char* SetTopologyIds(const int* pTopo, int count, int stride)
{
if (count <= 0)
{
return "bad topologyId count";
}
if (stride < 0 || (stride > 0 && stride < sizeof(int)))
{
return "bad topologyId stride";
}
m_topologyIds.resize(count);
for (int i = 0; i < count; ++i)
{
const int* const p = (const int*)(((const char*)pTopo) + ((size_t)i * stride));
m_topologyIds[i] = p[0];
}
return 0;
}
const char* SetNormals(const float* pVec3, int count, int stride)
{
if (count <= 0)
{
return "bad normal count";
}
if (stride < 0 || (stride > 0 && stride < sizeof(Vec3)))
{
return "bad normal stride";
}
m_normals.resize(count);
for (int i = 0; i < count; ++i)
{
const float* const p = (const float*)(((const char*)pVec3) + ((size_t)i * stride));
if (!_finite(p[0]) || !_finite(p[1]) || !_finite(p[2]))
{
m_normals.clear();
return "Illegal (NAN) vertex normal. Fix the 3d Model.";
}
m_normals[i].x = p[0];
m_normals[i].y = p[1];
m_normals[i].z = p[2];
m_normals[i] = m_normals[i].GetNormalizedSafe(Vec3_OneZ);
}
return 0;
}
const char* SetTexCoords(const float* pVec2, int count, int stride, bool bFlipT, uint streamIndex)
{
if (count <= 0)
{
return "bad texCoord count";
}
if (stride < 0 || (stride > 0 && stride < sizeof(float) * 2))
{
return "bad texCoord stride";
}
if (m_texCoords.size() <= streamIndex)
{
m_texCoords.resize(streamIndex + 1);
}
m_texCoords[streamIndex].resize(count);
for (int i = 0; i < count; ++i)
{
const float* const p = (const float*)(((const char*)pVec2) + ((size_t)i * stride));
if (!_finite(p[0]) || !_finite(p[1]))
{
m_texCoords[streamIndex].clear();
return "Illegal (NAN) texture coordinate. Fix the 3d Model.";
}
m_texCoords[streamIndex][i].x = p[0];
m_texCoords[streamIndex][i].y = bFlipT ? 1 - p[1] : p[1];
}
return 0;
}
const char* SetColors(const uint8* pRgb, int count, int stride)
{
if (count <= 0)
{
return "bad color count";
}
if (stride < 0 || (stride > 0 && stride < 3))
{
return "bad color stride";
}
m_colors.resize(count);
for (int i = 0; i < count; ++i)
{
const uint8* const p = (((const uint8*)pRgb) + ((size_t)i * stride));
m_colors[i].r = p[0];
m_colors[i].g = p[1];
m_colors[i].b = p[2];
}
return 0;
}
const char* SetAlphas(const uint8* pAlpha, int count, int stride)
{
if (count <= 0)
{
return "bad alpha count";
}
if (stride < 0)
{
return "bad alpha stride";
}
m_alphas.resize(count);
for (int i = 0; i < count; ++i)
{
const uint8* const p = (((const uint8*)pAlpha) + ((size_t)i * stride));
m_alphas[i] = p[0];
}
return 0;
}
const char* SetFaces(const int* pVertIdx3, int count, int stride)
{
if (count <= 0)
{
return "bad face count";
}
if (stride < 0 || (stride > 0 && stride < 3 * sizeof(int)))
{
return "bad face stride";
}
m_faces.resize(count);
for (int i = 0; i < count; ++i)
{
const int* const p = (const int*)(((const char*)pVertIdx3) + ((size_t)i * stride));
for (int j = 0; j < 3; ++j)
{
if (p[j] < 0 || p[j] >= m_positions.size())
{
return "bad vertex index found in a face";
}
m_faces[i].vertexIndex[j] = p[j];
}
}
return 0;
}
const char* SetFaceMatIds(const int* pMatIds, int count, int stride, int maxMaterialId)
{
if (count <= 0)
{
return "bad face materialId count";
}
if (stride < 0 || (stride > 0 && stride < sizeof(int)))
{
return "bad face materialIdstride";
}
m_faceMatIds.resize(count);
for (int i = 0; i < count; ++i)
{
const int* const p = (const int*)(((const char*)pMatIds) + ((size_t)i * stride));
if (p[0] < 0)
{
return "negative material ID found in a face";
}
if (p[0] >= maxMaterialId)
{
return "material ID found in a face is outside of allowed ranges";
}
m_faceMatIds[i] = p[0];
}
return 0;
}
const char* SetAux(size_t auxSizeof, const void* pData, int count, int stride)
{
if (auxSizeof <= 0)
{
return "bad aux sizeof";
}
if (count <= 0)
{
return "bad aux count";
}
if (stride < 0 || (stride > 0 && stride < auxSizeof))
{
return "bad aux stride";
}
m_auxSizeof = auxSizeof;
m_aux.resize(count * m_auxSizeof);
for (int i = 0; i < count; ++i)
{
const uint8* const p = (((const uint8*)pData) + ((size_t)i * stride));
memcpy(&m_aux[i * m_auxSizeof], p, m_auxSizeof);
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
// Validation
// Returns 0 if ok, or pointer to the error text
const char* Validate() const
{
const int nVerts = (int)m_positions.size();
if (nVerts <= 0)
{
return "No vertices";
}
const int nFaces = (int)m_faces.size();
if (nFaces <= 0)
{
return "No faces";
}
if (!m_topologyIds.empty() && nVerts != (int)m_topologyIds.size())
{
return "Mismatch in the number of topology IDs";
}
if (!m_normals.empty() && nVerts != (int)m_normals.size())
{
return "Mismatch in the number of normals";
}
for (uint streamIndex = 0; streamIndex < m_texCoords.size(); ++streamIndex)
{
if (!m_texCoords[streamIndex].empty() && nVerts != (int)m_texCoords[streamIndex].size())
{
return "Mismatch in the number of texture coordinates";
}
}
if (!m_colors.empty() && nVerts != (int)m_colors.size())
{
return "Mismatch in the number of colors";
}
if (!m_alphas.empty() && nVerts != (int)m_alphas.size())
{
return "Mismatch in the number of alphas";
}
if (!m_links.empty() && nVerts != (int)m_links.size())
{
return "Mismatch in the number of vertex-bone links";
}
for (size_t i = 0; i < m_links.size(); ++i)
{
if (m_links[i].links.empty())
{
return "Found a vertex without bone linking";
}
}
if (!m_vertexMatIds.empty() && nVerts != (int)m_vertexMatIds.size())
{
return "Mismatch in the number of vertex materials";
}
if (!m_aux.empty() && nVerts != (int)(m_aux.size() / m_auxSizeof))
{
return "Mismatch in the number of auxiliary elements";
}
if (!m_faceMatIds.empty() && nFaces != (int)m_faceMatIds.size())
{
return "Mismatch in the number of face materials";
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
// Computation
void RemoveDegenerateFaces()
{
int writePos = 0;
for (int readPos = 0; readPos < (int)m_faces.size(); ++readPos)
{
const Face& face = m_faces[readPos];
if (face.vertexIndex[0] != face.vertexIndex[1] &&
face.vertexIndex[1] != face.vertexIndex[2] &&
face.vertexIndex[0] != face.vertexIndex[2])
{
m_faces[writePos] = m_faces[readPos];
if (!m_faceMatIds.empty())
{
m_faceMatIds[writePos] = m_faceMatIds[readPos];
}
++writePos;
}
}
m_faces.resize(writePos);
if (!m_faceMatIds.empty())
{
m_faceMatIds.resize(writePos);
}
}
int AddVertexCopy(int sourceVertexIndex)
{
if (sourceVertexIndex < 0 || sourceVertexIndex >= m_positions.size())
{
assert(0);
return -1;
}
m_positions.push_back(m_positions[sourceVertexIndex]);
if (!m_topologyIds.empty())
{
m_topologyIds.push_back(m_topologyIds[sourceVertexIndex]);
}
if (!m_normals.empty())
{
m_normals.push_back(m_normals[sourceVertexIndex]);
}
for (uint streamIndex = 0; streamIndex < m_texCoords.size(); ++streamIndex)
{
if (!m_texCoords[streamIndex].empty())
{
m_texCoords[streamIndex].push_back(m_texCoords[streamIndex][sourceVertexIndex]);
}
}
if (!m_colors.empty())
{
m_colors.push_back(m_colors[sourceVertexIndex]);
}
if (!m_alphas.empty())
{
m_alphas.push_back(m_alphas[sourceVertexIndex]);
}
if (!m_links.empty())
{
m_links.push_back(m_links[sourceVertexIndex]);
}
if (!m_vertexMatIds.empty())
{
m_vertexMatIds.push_back(m_vertexMatIds[sourceVertexIndex]);
}
if (!m_aux.empty())
{
m_aux.resize(m_aux.size() + m_auxSizeof);
memcpy(&m_aux[m_aux.size() - m_auxSizeof], &m_aux[sourceVertexIndex * m_auxSizeof], m_auxSizeof);
}
return (int)m_positions.size() - 1;
}
// Note: might create new vertices and modify vertex indices in faces
void SetVertexMaterialIdsFromFaceMaterialIds()
{
m_vertexMatIds.clear();
if (m_faceMatIds.empty())
{
return;
}
m_vertexMatIds.resize(m_positions.size(), -1);
for (size_t i = 0; i < m_faces.size(); ++i)
{
const int faceMatId = m_faceMatIds[i];
for (int j = 0; j < 3; ++j)
{
int v = m_faces[i].vertexIndex[j];
if (m_vertexMatIds[v] >= 0 && m_vertexMatIds[v] != faceMatId)
{
v = AddVertexCopy(v);
m_faces[i].vertexIndex[j] = v;
}
m_vertexMatIds[v] = faceMatId;
}
}
}
// Computes m_vertexOldToNew and m_vertexNewToOld by detecting duplicate vertices
void ComputeVertexRemapping()
{
const size_t nVerts = m_positions.size();
m_vertexNewToOld.resize(nVerts);
for (size_t i = 0; i < nVerts; ++i)
{
m_vertexNewToOld[i] = i;
}
VertexLess less(*this);
std::sort(m_vertexNewToOld.begin(), m_vertexNewToOld.end(), less);
m_vertexOldToNew.resize(nVerts);
int nVertsNew = 0;
for (size_t i = 0; i < nVerts; ++i)
{
if (i == 0 || less(m_vertexNewToOld[i - 1], m_vertexNewToOld[i]))
{
m_vertexNewToOld[nVertsNew++] = m_vertexNewToOld[i];
}
m_vertexOldToNew[m_vertexNewToOld[i]] = nVertsNew - 1;
}
m_vertexNewToOld.resize(nVertsNew);
}
// Changes order of vertices, number of vertices, vertex indices in faces
void RemoveVerticesByUsingComputedRemapping()
{
CompactVertices(m_positions, m_vertexNewToOld);
CompactVertices(m_topologyIds, m_vertexNewToOld);
CompactVertices(m_normals, m_vertexNewToOld);
for (uint streamIndex = 0; streamIndex < m_texCoords.size(); ++streamIndex)
{
CompactVertices(m_texCoords[streamIndex], m_vertexNewToOld);
}
CompactVertices(m_colors, m_vertexNewToOld);
CompactVertices(m_alphas, m_vertexNewToOld);
CompactVertices(m_links, m_vertexNewToOld);
CompactVertices(m_vertexMatIds, m_vertexNewToOld);
CompactVerticesRaw(m_aux, m_auxSizeof, m_vertexNewToOld);
for (size_t i = 0, count = m_faces.size(); i < count; ++i)
{
for (int j = 0; j < 3; ++j)
{
const int oldVertedIdx = m_faces[i].vertexIndex[j];
assert(oldVertedIdx >= 0 && (size_t)oldVertedIdx < m_vertexOldToNew.size());
const int newVertexIndex = m_vertexOldToNew[oldVertedIdx];
m_faces[i].vertexIndex[j] = newVertexIndex;
}
}
}
// Deleting degraded faces (faces with two or more vertices
// sharing same position in space)
void RemoveDegradedFaces()
{
size_t j = 0;
for (size_t i = 0, count = m_faces.size(); i < count; ++i)
{
const Vec3& p0 = m_positions[m_faces[i].vertexIndex[0]];
const Vec3& p1 = m_positions[m_faces[i].vertexIndex[1]];
const Vec3& p2 = m_positions[m_faces[i].vertexIndex[2]];
if (p0 != p1 && p1 != p2 && p2 != p0)
{
m_faces[j] = m_faces[i];
if (!m_faceMatIds.empty())
{
m_faceMatIds[j] = m_faceMatIds[i];
}
++j;
}
}
m_faces.resize(j);
if (!m_faceMatIds.empty())
{
m_faceMatIds.resize(j);
}
}
private:
//////////////////////////////////////////////////////////////////////////
// Internal helpers
template<class T>
static void CompactVertices(std::vector<T>& arr, const std::vector<int>& newToOld)
{
if (arr.empty())
{
return;
}
const size_t newCount = newToOld.size();
std::vector<T> tmp;
tmp.reserve(newCount);
for (size_t i = 0; i < newCount; ++i)
{
tmp.push_back(arr[newToOld[i]]);
}
arr.swap(tmp);
}
static void CompactVerticesRaw(std::vector<uint8>& arr, size_t elemSizeof, const std::vector<int>& newToOld)
{
if (arr.empty())
{
return;
}
const size_t newCount = newToOld.size();
std::vector<uint8> tmp;
tmp.resize(newCount * elemSizeof);
for (size_t i = 0; i < newCount; ++i)
{
memcpy(&tmp[i * elemSizeof], &arr[newToOld[i] * elemSizeof], elemSizeof);
}
arr.swap(tmp);
}
struct VertexLess
{
const Mesh& m;
VertexLess(const Mesh& mesh)
: m(mesh)
{
}
bool operator()(int a, int b) const
{
if (!m.m_topologyIds.empty())
{
const int res = m.m_topologyIds[a] - m.m_topologyIds[b];
if (res != 0)
{
return res < 0;
}
}
{
const int res = memcmp(&m.m_positions[a], &m.m_positions[b], sizeof(m.m_positions[0]));
if (res != 0)
{
return res < 0;
}
}
int res = 0;
if (res == 0 && !m.m_normals.empty())
{
res = memcmp(&m.m_normals[a], &m.m_normals[b], sizeof(m.m_normals[0]));
}
for (uint streamIndex = 0; streamIndex < m.m_texCoords.size(); ++streamIndex)
{
if (res == 0 && !m.m_texCoords[streamIndex].empty())
{
res = memcmp(&m.m_texCoords[streamIndex][a], &m.m_texCoords[streamIndex][b], sizeof(m.m_texCoords[streamIndex][0]));
}
}
if (res == 0 && !m.m_colors.empty())
{
res = memcmp(&m.m_colors[a], &m.m_colors[b], sizeof(m.m_colors[0]));
}
if (res == 0 && !m.m_alphas.empty())
{
res = (int)m.m_alphas[a] - (int)m.m_alphas[b];
}
if (res == 0 && !m.m_links.empty())
{
if (m.m_links[a].links.size() != m.m_links[b].links.size())
{
res = (m.m_links[a].links.size() < m.m_links[b].links.size()) ? -1 : +1;
}
else
{
res = memcmp(&m.m_links[a].links[0], &m.m_links[b].links[0], sizeof(m.m_links[a].links[0]) * m.m_links[a].links.size());
}
}
if (res == 0 && !m.m_vertexMatIds.empty())
{
res = m.m_vertexMatIds[a] - m.m_vertexMatIds[b];
}
if (res == 0 && !m.m_aux.empty())
{
res = memcmp(&m.m_aux[a * m.m_auxSizeof], &m.m_aux[b * m.m_auxSizeof], m.m_auxSizeof);
}
return res < 0;
}
};
};
} // namespace MeshUtils
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MESHUTILS_H
@@ -1,118 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "ModelData.h"
int ModelData::AddModel(const void* handle, const char* modelName, int parentModelIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString)
{
int modelIndex = int(m_models.size());
m_models.push_back(ModelEntry(handle, modelName, parentModelIndex, geometry, helperData, propertiesString));
if (parentModelIndex >= 0)
{
m_models[parentModelIndex].children.push_back(modelIndex);
}
else
{
m_roots.push_back(modelIndex);
}
return modelIndex;
}
const void* ModelData::GetModelHandle(int modelIndex) const
{
return m_models[modelIndex].handle;
}
const char* ModelData::GetModelName(int modelIndex) const
{
return m_models[modelIndex].name.c_str();
}
void ModelData::SetTranslationRotationScale(int const modelIndex, const float* const translation, const float* const rotation, const float* const scale)
{
for (int i = 0; i < 3; ++i)
{
m_models[modelIndex].translation[i] = translation[i];
m_models[modelIndex].rotation[i] = rotation[i];
m_models[modelIndex].scale[i] = scale[i];
}
}
void ModelData::GetTranslationRotationScale(int const modelIndex, float* const translation, float* const rotation, float* const scale) const
{
for (int i = 0; i < 3; ++i)
{
translation[i] = m_models[modelIndex].translation[i];
rotation[i] = m_models[modelIndex].rotation[i];
scale[i] = m_models[modelIndex].scale[i];
}
}
const SHelperData& ModelData::GetHelperData(int modelIndex) const
{
return m_models[modelIndex].helperData;
}
const std::string& ModelData::GetProperties(int modelIndex) const
{
return m_models[modelIndex].propertiesString;
}
bool ModelData::IsRoot(int modelIndex) const
{
return (m_models[modelIndex].parentIndex < 0);
}
int ModelData::GetModelCount() const
{
return int(m_models.size());
}
int ModelData::GetRootCount() const
{
return int(m_roots.size());
}
int ModelData::GetRootIndex(int rootIndex) const
{
return m_roots[rootIndex];
}
int ModelData::GetChildCount(int modelIndex) const
{
return int(m_models[modelIndex].children.size());
}
int ModelData::GetChildIndex(int modelIndex, int childIndexIndex) const
{
return m_models[modelIndex].children[childIndexIndex];
}
bool ModelData::HasGeometry(int modelIndex) const
{
return m_models[modelIndex].geometry;
}
ModelData::ModelEntry::ModelEntry(const void* a_handle, const std::string& a_name, int a_parentIndex, bool a_geometry, const SHelperData& a_helperData, const std::string& a_propertiesString)
: handle(a_handle)
, name(a_name)
, parentIndex(a_parentIndex)
, geometry(a_geometry)
, helperData(a_helperData)
, propertiesString(a_propertiesString)
{
translation[0] = translation[1] = translation[2] = 0.0f;
rotation[0] = rotation[1] = rotation[2] = 0.0f;
scale[0] = scale[1] = scale[2] = 1.0f;
}
@@ -1,63 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MODELDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MODELDATA_H
#pragma once
#include "IModelData.h"
class ModelData
: public IModelData
{
public:
// IModelData
virtual int AddModel(const void* handle, const char* name, int parentModelIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString);
virtual int GetModelCount() const;
virtual const void* GetModelHandle(int modelIndex) const;
virtual const char* GetModelName(int modelIndex) const;
virtual void SetTranslationRotationScale(int modelIndex, const float* translation, const float* rotation, const float* scale);
virtual void GetTranslationRotationScale(int modelIndex, float* translation, float* rotation, float* scale) const;
virtual const SHelperData& GetHelperData(int modelIndex) const;
virtual const std::string& GetProperties(int modelIndex) const;
virtual bool IsRoot(int modelIndex) const;
int GetRootCount() const;
int GetRootIndex(int rootIndex) const;
int GetChildCount(int modelIndex) const;
int GetChildIndex(int modelIndex, int childIndexIndex) const;
bool HasGeometry(int modelIndex) const;
private:
struct ModelEntry
{
ModelEntry(const void* handle, const std::string& name, int parentIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString);
const void* handle;
std::string name;
int parentIndex;
bool geometry;
std::vector<int> children;
float translation[3];
float rotation[3];
float scale[3];
SHelperData helperData;
std::string propertiesString;
};
std::vector<ModelEntry> m_models;
std::vector<int> m_roots;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MODELDATA_H
@@ -1,55 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "MorphData.h"
MorphData::MorphData()
: m_handle(0)
{
}
void MorphData::SetHandle(const void* handle)
{
m_handle = handle;
}
void MorphData::AddMorph(const void* handle, const char* name, const char* fullname)
{
m_morphs.push_back(Entry(handle, name, fullname ? fullname : ""));
}
const void* MorphData::GetHandle() const
{
return m_handle;
}
int MorphData::GetMorphCount() const
{
return int(m_morphs.size());
}
std::string MorphData::GetMorphName(int morphIndex) const
{
return m_morphs[morphIndex].name;
}
std::string MorphData::GetMorphFullName(int morphIndex) const
{
return m_morphs[morphIndex].fullname.length() > 0 ? m_morphs[morphIndex].fullname : m_morphs[morphIndex].name;
}
const void* MorphData::GetMorphHandle(int morphIndex) const
{
return m_morphs[morphIndex].handle;
}
@@ -1,52 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MORPHDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MORPHDATA_H
#pragma once
#include "IMorphData.h"
class MorphData
: public IMorphData
{
public:
MorphData();
virtual void SetHandle(const void* handle);
virtual void AddMorph(const void* handle, const char* name, const char* fullname);
virtual const void* GetHandle() const;
virtual int GetMorphCount() const;
virtual const void* GetMorphHandle(int morphIndex) const;
std::string GetMorphName(int morphIndex) const;
std::string GetMorphFullName(int morphIndex) const;
private:
struct Entry
{
Entry(const void* handle, const std::string& name, const std::string& fullname)
: handle(handle)
, name(name)
, fullname(fullname) {}
const void* handle;
std::string name;
std::string fullname;
};
const void* m_handle;
std::vector<Entry> m_morphs;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MORPHDATA_H
@@ -1,86 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "SingleAnimationExportSourceAdapter.h"
#include "IGeometryFileData.h"
#include <cassert>
SingleAnimationExportSourceAdapter::SingleAnimationExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex)
: ExportSourceDecoratorBase(source)
, animationIndex(animationIndex)
, geometryFileData(geometryFileData)
, geometryFileIndex(geometryFileIndex)
{
assert(this->animationIndex < this->source->GetAnimationCount());
}
float SingleAnimationExportSourceAdapter::GetDCCFrameRate() const
{
return this->source->GetDCCFrameRate();
}
void SingleAnimationExportSourceAdapter::ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData)
{
const int geometryFileIndex = geometryFileData->AddGeometryFile(
this->geometryFileData->GetGeometryFileHandle(this->geometryFileIndex),
this->geometryFileData->GetGeometryFileName(this->geometryFileIndex),
this->geometryFileData->GetProperties(this->geometryFileIndex));
}
void SingleAnimationExportSourceAdapter::ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData)
{
assert(geometryFileIndex == 0);
this->source->ReadModels(this->geometryFileData, this->geometryFileIndex, modelData);
}
void SingleAnimationExportSourceAdapter::ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* const modelData, int modelIndex, ISkeletonData* skeletonData)
{
this->source->ReadSkinning(context, skinningData, modelData, modelIndex, skeletonData);
}
bool SingleAnimationExportSourceAdapter::ReadSkeleton(const IGeometryFileData* const geometryFileData, int geometryFileIndex, const IModelData* const modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData)
{
assert(geometryFileIndex == 0);
return this->source->ReadSkeleton(this->geometryFileData, this->geometryFileIndex, modelData, modelIndex, materialData, skeletonData);
}
int SingleAnimationExportSourceAdapter::GetAnimationCount() const
{
return 1;
}
std::string SingleAnimationExportSourceAdapter::GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const
{
assert(geometryFileIndex == 0);
assert(animationIndex == 0);
return this->source->GetAnimationName(this->geometryFileData, this->geometryFileIndex, this->animationIndex);
}
void SingleAnimationExportSourceAdapter::GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const
{
assert(animationIndex == 0);
this->source->GetAnimationTimeSpan(start, stop, this->animationIndex);
}
void SingleAnimationExportSourceAdapter::ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const
{
assert(animationIndex == 0);
this->source->ReadAnimationFlags(context, animationData, geometryFileData, modelData, modelIndex, skeletonData, this->animationIndex);
}
IAnimationData* SingleAnimationExportSourceAdapter::ReadAnimation(IExportContext* context, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const
{
assert(animationIndex == 0);
return this->source->ReadAnimation(context, geometryFileData, modelData, modelIndex, skeletonData, this->animationIndex, fps);
}
@@ -1,45 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SINGLEANIMATIONEXPORTSOURCEADAPTER_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SINGLEANIMATIONEXPORTSOURCEADAPTER_H
#pragma once
#include "ExportSourceDecoratorBase.h"
class SingleAnimationExportSourceAdapter
: public ExportSourceDecoratorBase
{
public:
SingleAnimationExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryData, int geometryFileIndex, int animationIndex);
virtual float GetDCCFrameRate() const;
virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData);
virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData);
virtual void ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* modelData, int modelIndex, ISkeletonData* skeletonData);
virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData);
virtual int GetAnimationCount() const;
virtual std::string GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const;
virtual void GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const;
virtual void ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const;
virtual IAnimationData* ReadAnimation(IExportContext* context, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const;
private:
int animationIndex;
IGeometryFileData* geometryFileData;
int geometryFileIndex;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SINGLEANIMATIONEXPORTSOURCEADAPTER_H
@@ -1,309 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "SkeletonData.h"
#include <cctype>
int SkeletonData::AddBone(const void* handle, const char* name, int parentIndex)
{
int modelIndex = int(m_bones.size());
m_bones.push_back(BoneEntry(handle, name, parentIndex));
m_nameBoneIndexMap.insert(std::make_pair(name, modelIndex));
if (parentIndex >= 0)
{
m_bones[parentIndex].children.push_back(modelIndex);
}
else
{
m_roots.push_back(modelIndex);
}
return modelIndex;
}
int SkeletonData::FindBone(const char* name) const
{
std::map<std::string, int>::const_iterator modelPos = m_nameBoneIndexMap.find(name);
return (modelPos != m_nameBoneIndexMap.end() ? (*modelPos).second : -1);
}
const void* SkeletonData::GetBoneHandle(int boneIndex) const
{
return m_bones[boneIndex].handle;
}
int SkeletonData::GetBoneParentIndex(int boneIndex) const
{
return m_bones[boneIndex].parentIndex;
}
int SkeletonData::GetBoneCount() const
{
return int(m_bones.size());
}
void SkeletonData::SetTranslation(int modelIndex, const float* vec)
{
for (int i = 0; i < 3; ++i)
{
m_bones[modelIndex].translation[i] = vec[i];
}
}
void SkeletonData::SetRotation(int modelIndex, const float* vec)
{
for (int i = 0; i < 3; ++i)
{
m_bones[modelIndex].rotation[i] = vec[i];
}
}
void SkeletonData::SetScale(int modelIndex, const float* vec)
{
for (int i = 0; i < 3; ++i)
{
m_bones[modelIndex].scale[i] = vec[i];
}
}
void SkeletonData::SetParentFrameTranslation(int boneIndex, const float* vec)
{
EnsureParentFrameExists(boneIndex);
std::copy(vec, vec + 3, m_bones[boneIndex].parentFrameTranslation);
}
void SkeletonData::SetParentFrameRotation(int boneIndex, const float* vec)
{
EnsureParentFrameExists(boneIndex);
std::copy(vec, vec + 3, m_bones[boneIndex].parentFrameRotation);
}
void SkeletonData::SetParentFrameScale(int boneIndex, const float* vec)
{
EnsureParentFrameExists(boneIndex);
std::copy(vec, vec + 3, m_bones[boneIndex].parentFrameScale);
}
void SkeletonData::SetLimit(int boneIndex, Axis axis, Limit extreme, float limit)
{
m_bones[boneIndex].limits.insert(std::make_pair(AxisLimit(axis, extreme), limit));
}
void SkeletonData::SetSpringTension(int boneIndex, Axis axis, float springTension)
{
m_bones[boneIndex].springTensions.insert(std::make_pair(axis, springTension));
}
void SkeletonData::SetSpringAngle(int boneIndex, Axis axis, float springAngle)
{
m_bones[boneIndex].springAngles.insert(std::make_pair(axis, springAngle));
}
void SkeletonData::SetAxisDamping(int boneIndex, Axis axis, float damping)
{
m_bones[boneIndex].dampings.insert(std::make_pair(axis, damping));
}
void SkeletonData::SetPhysicalized(int boneIndex, bool physicalized)
{
m_bones[boneIndex].physicalized = physicalized;
}
void SkeletonData::SetHasGeometry(int boneIndex, bool hasGeometry)
{
m_bones[boneIndex].hasGeometry = hasGeometry;
}
void SkeletonData::SetBoneProperties(int boneIndex, const char* propertiesString)
{
m_bones[boneIndex].propertiesString = propertiesString;
}
void SkeletonData::SetBoneGeomProperties(int boneIndex, const char* propertiesString)
{
m_bones[boneIndex].geomPropertiesString = propertiesString;
}
bool SkeletonData::HasParentFrame(int boneIndex) const
{
return m_bones[boneIndex].hasParentFrame;
}
void SkeletonData::GetParentFrameTranslation(int boneIndex, float* vec) const
{
std::copy(m_bones[boneIndex].parentFrameTranslation, m_bones[boneIndex].parentFrameTranslation + 3, vec);
}
void SkeletonData::GetParentFrameRotation(int boneIndex, float* vec) const
{
std::copy(m_bones[boneIndex].parentFrameRotation, m_bones[boneIndex].parentFrameRotation + 3, vec);
}
void SkeletonData::GetParentFrameScale(int boneIndex, float* vec) const
{
std::copy(m_bones[boneIndex].parentFrameScale, m_bones[boneIndex].parentFrameScale + 3, vec);
}
bool SkeletonData::HasLimit(int boneIndex, Axis axis, Limit extreme) const
{
return m_bones[boneIndex].limits.find(AxisLimit(axis, extreme)) != m_bones[boneIndex].limits.end();
}
float SkeletonData::GetLimit(int boneIndex, Axis axis, Limit extreme) const
{
return (*m_bones[boneIndex].limits.find(AxisLimit(axis, extreme))).second;
}
bool SkeletonData::HasSpringTension(int boneIndex, Axis axis) const
{
return m_bones[boneIndex].springTensions.find(axis) != m_bones[boneIndex].springTensions.end();
}
float SkeletonData::GetSpringTension(int boneIndex, Axis axis) const
{
return (*m_bones[boneIndex].springTensions.find(axis)).second;
}
bool SkeletonData::HasSpringAngle(int boneIndex, Axis axis) const
{
return m_bones[boneIndex].springAngles.find(axis) != m_bones[boneIndex].springAngles.end();
}
float SkeletonData::GetSpringAngle(int boneIndex, Axis axis) const
{
return (*m_bones[boneIndex].springAngles.find(axis)).second;
}
bool SkeletonData::HasAxisDamping(int boneIndex, Axis axis) const
{
return m_bones[boneIndex].dampings.find(axis) != m_bones[boneIndex].dampings.end();
}
float SkeletonData::GetAxisDamping(int boneIndex, Axis axis) const
{
return (*m_bones[boneIndex].dampings.find(axis)).second;
}
bool SkeletonData::GetPhysicalized(int boneIndex) const
{
return m_bones[boneIndex].physicalized;
}
bool SkeletonData::HasGeometry(int boneIndex) const
{
return m_bones[boneIndex].hasGeometry;
}
int SkeletonData::GetRootCount() const
{
return int(m_roots.size());
}
int SkeletonData::GetRootIndex(int rootIndex) const
{
return m_roots[rootIndex];
}
int SkeletonData::GetParentIndex(int modelIndex) const
{
return m_bones[modelIndex].parentIndex;
}
const std::string SkeletonData::GetName(int modelIndex) const
{
std::string copy(m_bones[modelIndex].name);
for (int i = 0, count = int(copy.size()); i < count; ++i)
{
if (!std::isalnum(copy[i]) && copy[i] != ' ')
{
copy[i] = '_';
}
}
return copy;
}
const std::string SkeletonData::GetSafeName(int modelIndex) const
{
std::string name = GetName(modelIndex);
std::replace_if(name.begin(), name.end(), std::isspace, '_');
return name;
}
int SkeletonData::GetChildCount(int modelIndex) const
{
return int(m_bones[modelIndex].children.size());
}
int SkeletonData::GetChildIndex(int modelIndex, int childIndexIndex) const
{
return m_bones[modelIndex].children[childIndexIndex];
}
void SkeletonData::GetTranslation(float* vec, int modelIndex) const
{
for (int i = 0; i < 3; ++i)
{
vec[i] = m_bones[modelIndex].translation[i];
}
}
void SkeletonData::GetRotation(float* vec, int modelIndex) const
{
for (int i = 0; i < 3; ++i)
{
vec[i] = m_bones[modelIndex].rotation[i];
}
}
void SkeletonData::GetScale(float* vec, int modelIndex) const
{
for (int i = 0; i < 3; ++i)
{
vec[i] = m_bones[modelIndex].scale[i];
}
}
const std::string SkeletonData::GetBoneProperties(int boneIndex) const
{
return m_bones[boneIndex].propertiesString;
}
const std::string SkeletonData::GetBoneGeomProperties(int boneIndex) const
{
return m_bones[boneIndex].geomPropertiesString;
}
void SkeletonData::EnsureParentFrameExists(int boneIndex)
{
if (!m_bones[boneIndex].hasParentFrame)
{
std::fill(m_bones[boneIndex].parentFrameTranslation, m_bones[boneIndex].parentFrameTranslation + 3, 0.0f);
std::fill(m_bones[boneIndex].parentFrameRotation, m_bones[boneIndex].parentFrameRotation + 3, 0.0f);
std::fill(m_bones[boneIndex].parentFrameScale, m_bones[boneIndex].parentFrameScale + 3, 0.0f);
m_bones[boneIndex].hasParentFrame = true;
}
}
SkeletonData::BoneEntry::BoneEntry(const void* handle, const std::string& name, int parentIndex)
: handle(handle)
, name(name)
, parentIndex(parentIndex)
, hasParentFrame(false)
, physicalized(false)
, hasGeometry(hasGeometry)
{
translation[0] = translation[1] = translation[2] = 0.0f;
rotation[0] = rotation[1] = rotation[2] = 0.0f;
scale[0] = scale[1] = scale[2] = 1.0f;
}
@@ -1,116 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKELETONDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKELETONDATA_H
#pragma once
#include "ISkeletonData.h"
#include <string>
#include <vector>
#include <map>
class SkeletonData
: public ISkeletonData
{
public:
// ISkeletonData
virtual int AddBone(const void* handle, const char* name, int parentIndex);
virtual int FindBone(const char* name) const;
virtual const void* GetBoneHandle(int boneIndex) const;
virtual int GetBoneParentIndex(int boneIndex) const;
virtual int GetBoneCount() const;
virtual void SetTranslation(int boneIndex, const float* vec);
virtual void SetRotation(int boneIndex, const float* vec);
virtual void SetScale(int boneIndex, const float* vec);
virtual void SetParentFrameTranslation(int boneIndex, const float* vec);
virtual void SetParentFrameRotation(int boneIndex, const float* vec);
virtual void SetParentFrameScale(int boneIndex, const float* vec);
virtual void SetLimit(int boneIndex, Axis axis, Limit extreme, float limit);
virtual void SetSpringTension(int boneIndex, Axis axis, float springTension);
virtual void SetSpringAngle(int boneIndex, Axis axis, float springAngle);
virtual void SetAxisDamping(int boneIndex, Axis axis, float damping);
virtual void SetPhysicalized(int boneIndex, bool physicalized);
virtual void SetHasGeometry(int boneIndex, bool hasGeometry);
virtual void SetBoneProperties(int boneIndex, const char* propertiesString);
virtual void SetBoneGeomProperties(int boneIndex, const char* propertiesString);
bool HasParentFrame(int boneIndex) const;
void GetParentFrameTranslation(int boneIndex, float* vec) const;
void GetParentFrameRotation(int boneIndex, float* vec) const;
void GetParentFrameScale(int boneIndex, float* vec) const;
bool HasLimit(int boneIndex, Axis axis, Limit extreme) const;
float GetLimit(int boneIndex, Axis axis, Limit extreme) const;
bool HasSpringTension(int boneIndex, Axis axis) const;
float GetSpringTension(int boneIndex, Axis axis) const;
bool HasSpringAngle(int boneIndex, Axis axis) const;
float GetSpringAngle(int boneIndex, Axis axis) const;
bool HasAxisDamping(int boneIndex, Axis axis) const;
float GetAxisDamping(int boneIndex, Axis axis) const;
bool GetPhysicalized(int boneIndex) const;
bool HasGeometry(int boneIndex) const;
int GetRootCount() const;
int GetRootIndex(int rootIndex) const;
int GetParentIndex(int boneIndex) const;
const std::string GetName(int boneIndex) const;
const std::string GetSafeName(int boneIndex) const;
int GetChildCount(int boneIndex) const;
int GetChildIndex(int boneIndex, int childIndexIndex) const;
void GetTranslation(float* vec, int boneIndex) const;
void GetRotation(float* vec, int boneIndex) const;
void GetScale(float* vec, int boneIndex) const;
const std::string GetBoneProperties(int boneIndex) const;
const std::string GetBoneGeomProperties(int boneIndex) const;
private:
void EnsureParentFrameExists(int boneIndex);
typedef std::pair<Axis, Limit> AxisLimit;
typedef std::map<AxisLimit, float> AxisLimitLimitMap;
typedef std::map<Axis, float> AxisSpringTensionMap;
typedef std::map<Axis, float> AxisSpringAngleMap;
typedef std::map<Axis, float> AxisDampingMap;
struct BoneEntry
{
public:
BoneEntry(const void* handle, const std::string& name, int parentIndex);
const void* handle;
std::string name;
int parentIndex;
AxisLimitLimitMap limits;
AxisSpringTensionMap springTensions;
AxisSpringAngleMap springAngles;
AxisDampingMap dampings;
bool hasParentFrame;
float parentFrameTranslation[3];
float parentFrameRotation[3];
float parentFrameScale[3];
bool physicalized;
std::vector<int> children;
float translation[3];
float rotation[3];
float scale[3];
bool hasGeometry;
std::string propertiesString;
std::string geomPropertiesString;
};
std::vector<BoneEntry> m_bones;
std::vector<int> m_roots;
std::map<std::string, int> m_nameBoneIndexMap;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKELETONDATA_H
@@ -1,45 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "SkinningData.h"
void SkinningData::SetVertexCount(int vertexCount)
{
m_weights.resize(vertexCount);
}
void SkinningData::AddWeight(int vertexIndex, int boneIndex, float weight)
{
m_weights[vertexIndex].push_back(BoneWeight(boneIndex, weight));
}
int SkinningData::GetVertexCount() const
{
return int(m_weights.size());
}
int SkinningData::GetBoneLinkCount(int vertexIndex) const
{
return int(m_weights[vertexIndex].size());
}
int SkinningData::GetBoneIndex(int vertexIndex, int linkIndex) const
{
return m_weights[vertexIndex][linkIndex].boneIndex;
}
float SkinningData::GetWeight(int vertexIndex, int linkIndex) const
{
return m_weights[vertexIndex][linkIndex].weight;
}
@@ -1,46 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKINNINGDATA_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKINNINGDATA_H
#pragma once
#include "ISkinningData.h"
class SkinningData
: public ISkinningData
{
public:
virtual void SetVertexCount(int vertexCount);
virtual void AddWeight(int vertexIndex, int boneIndex, float weight);
int GetVertexCount() const;
int GetBoneLinkCount(int vertexIndex) const;
int GetBoneIndex(int vertexIndex, int linkIndex) const;
float GetWeight(int vertexIndex, int linkIndex) const;
private:
struct BoneWeight
{
BoneWeight(int boneIndex, float weight)
: boneIndex(boneIndex)
, weight(weight) {}
int boneIndex;
float weight;
};
std::vector<std::vector<BoneWeight> > m_weights;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKINNINGDATA_H
@@ -1,119 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_TRANSFORMHELPERS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_TRANSFORMHELPERS_H
#pragma once
#include "Cry_Math.h"
namespace TransformHelpers
{
// Format of forwardUpAxes: "<signOfForwardAxis><forwardAxis><signOfUpAxis><upAxis>".
// Example of forwardUpAxes: "-Y+Z".
// Returns 0 if successful, or returns a pointer to an error message in case of an error.
// In case of success: X axis in res represents "forward" direction,
// Y axis represents "up" direction.
inline const char* GetForwardUpAxesMatrix(Matrix33& res, const char* forwardUpAxes)
{
Vec3 axisX(ZERO);
Vec3 axisY(ZERO);
for (int i = 0; i < 2; ++i)
{
Vec3& v = (i == 0) ? axisX : axisY;
const float val = forwardUpAxes[i * 2 + 0] == '-' ? -1.0f : +1.0f;
switch (forwardUpAxes[i * 2 + 1])
{
case 'X':
case 'x':
v.x = val;
break;
case 'Y':
case 'y':
v.y = val;
break;
case 'Z':
case 'z':
v.z = val;
break;
default:
assert(0);
return "Found a bad axis character in forwardUpAxes string";
}
}
if (axisX == axisY)
{
assert(0);
return "Forward and up axes are equal in forwardUpAxes string";
}
const Vec3 axisZ = axisX.cross(axisY);
res.SetFromVectors(axisX, axisY, axisZ);
return 0;
}
// Computes transform matrix that converts everything from forwardUpAxesSrc
// coordinate system to forwardUpAxesDst coordinate system.
// Format of forwardUpAxesXXX: "<signOfForwardAxis><forwardAxis><signOfUpAxis><upAxis>".
// Example of forwardUpAxesXXX: "-Y+Z".
// Returns 0 if successful, or returns a pointer to an error message in case of an error.
// In case of success puts computed transform into res.
// See comments to GetForwardUpAxesMatrix().
inline const char* ComputeForwardUpAxesTransform(Matrix34& res, const char* forwardUpAxesSrc, const char* forwardUpAxesDst)
{
Matrix33 srcToWorld;
Matrix33 dstToWorld;
const char* const err0 = GetForwardUpAxesMatrix(srcToWorld, forwardUpAxesSrc);
const char* const err1 = GetForwardUpAxesMatrix(dstToWorld, forwardUpAxesDst);
if (err0 || err1)
{
return err0 ? err0 : err1;
}
res = Matrix34(dstToWorld * srcToWorld.GetTransposed());
return 0;
}
inline Matrix34 ComputeOrthonormalMatrix(const Matrix34& m)
{
Vec3 x = m.GetColumn0();
x.Normalize();
Vec3 y = m.GetColumn1();
Vec3 z = x.cross(y);
z.Normalize();
y = z.cross(x);
Matrix34 result;
result.SetFromVectors(x, y, z, m.GetTranslation());
return result;
}
}
#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_TRANSFORMHELPERS_H
-175
View File
@@ -1,175 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include <platform.h>
#include "FileUtil.h"
#include "PathHelpers.h"
#include "StringHelpers.h"
#include <AzFramework/IO/LocalFileIO.h>
#include <AzCore/std/functional.h>
//////////////////////////////////////////////////////////////////////////
// returns true if 'dir' is a subdirectory of 'baseDir' or same directory as 'baseDir'
// note: returns false in case of wrong names passed
static bool IsSubdirOrSameDir(const char* dir, const char* baseDir)
{
AZ::IO::LocalFileIO localFileIO;
char szFullPathDir[AZ_MAX_PATH_LEN];
if(!localFileIO.ConvertToAbsolutePath(dir, szFullPathDir, sizeof(szFullPathDir)))
{
return false;
}
char szFullPathBaseDir[2 * 1024];
if(!localFileIO.ConvertToAbsolutePath(baseDir, szFullPathBaseDir, sizeof(szFullPathBaseDir)))
{
return false;
}
const char* p = szFullPathDir;
const char* q = szFullPathBaseDir;
for (;; ++p, ++q)
{
if (tolower(*p) == tolower(*q))
{
if (*p == 0)
{
// dir is exactly same as baseDir
return true;
}
continue;
}
if ((*p == '/' || *p == '\\') && (*q == '/' || *q == '\\'))
{
continue;
}
if (*p == 0)
{
// dir length is shorter than baseDir length. so it's not a subdir
return false;
}
if (*q == 0)
{
// baseDir is shorter than dir. so may be it's a subdir.
const bool isSubdir = (*p == '/' || *p == '\\');
return isSubdir;
}
return false;
}
}
//////////////////////////////////////////////////////////////////////////
// the paths must have trailing slash
static bool ScanDirectoryRecursive(const string& root, const string& path, const string& file, std::vector<string>& files, bool recursive, const string& dirToIgnore)
{
bool anyFound = false;
if (!dirToIgnore.empty())
{
if (IsSubdirOrSameDir(root.c_str(), dirToIgnore.c_str()))
{
return anyFound;
}
}
AZ::IO::LocalFileIO localFileIO;
localFileIO.FindFiles(root.c_str(), file.c_str(), [&](const char* filePath) -> bool
{
bool isDir = localFileIO.IsDirectory(filePath);
if (!isDir)
{
const string foundFilename(filePath);
if (StringHelpers::MatchesWildcardsIgnoreCase(foundFilename, file))
{
anyFound = true;
files.push_back(PathHelpers::Join(path, PathHelpers::GetFilename(filePath)));
}
}
return true; // Keep iterating
});
if (recursive)
{
localFileIO.FindFiles(root.c_str(), "*", [&](const char* filePath) -> bool
{
bool isDir = localFileIO.IsDirectory(filePath);
// If recursive.
if (isDir && strcmp(filePath, ".") && strcmp(filePath, ".."))
{
if (ScanDirectoryRecursive(filePath, PathHelpers::Join(path, PathHelpers::GetFilename(filePath)), file, files, recursive, dirToIgnore))
{
anyFound = true;
}
}
return true; // Keep iterating
});
}
return anyFound;
}
//////////////////////////////////////////////////////////////////////////
bool FileUtil::ScanDirectory(const string& path, const string& file, std::vector<string>& files, bool recursive, const string& dirToIgnore)
{
return ScanDirectoryRecursive(path, "", file, files, recursive, dirToIgnore);
}
bool FileUtil::EnsureDirectoryExists(const char* szPathIn)
{
if (!szPathIn || !szPathIn[0])
{
return true;
}
if (DirectoryExists(szPathIn))
{
return true;
}
std::vector<char> path(szPathIn, szPathIn + strlen(szPathIn) + 1);
char* p = &path[0];
// Skip '/' and '//' in the beginning
while (*p == '/' || *p == '\\')
{
++p;
}
for (;; )
{
while (*p != '/' && *p != '\\' && *p)
{
++p;
}
const char saved = *p;
*p = 0;
AZ::IO::LocalFileIO().CreatePath(&path[0]);
*p++ = saved;
if (saved == 0)
{
break;
}
}
return DirectoryExists(szPathIn);
}
-311
View File
@@ -1,311 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_FILEUTIL_H
#define CRYINCLUDE_CRYCOMMONTOOLS_FILEUTIL_H
#pragma once
#include <AzFramework/IO/LocalFileIO.h>
#include <AzCore/IO/SystemFile.h>
#include <AzCore/PlatformIncl.h>
#if AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX)
#include <utime.h>
#endif
#if defined(AZ_PLATFORM_LINUX)
#include "Linux64Specific.h"
#endif // defined(AZ_PLATFORM_LINUX)
#include <platform.h>
#include <vector>
namespace FileUtil
{
// Magic number explanation:
// Both epochs are Gregorian. 1970 - 1601 = 369. Assuming a leap
// year every four years, 369 / 4 = 92. However, 1700, 1800, and 1900
// were NOT leap years, so 89 leap years, 280 non-leap years.
// 89 * 366 + 280 * 365 = 134744 days between epochs. Of course
// 60 * 60 * 24 = 86400 seconds per day, so 134744 * 86400 =
// 11644473600 = SECS_BETWEEN_EPOCHS.
//
// This result is also confirmed in the MSDN documentation on how
// to convert a time_t value to a win32 FILETIME.
#define SECS_BETWEEN_EPOCHS 11644473600ll
/* 10^7 */
#define SECS_TO_100NS 10000000ll
// Find all files matching filespec.
bool ScanDirectory(const string& path, const string& filespec, std::vector<string>& files, bool recursive, const string& dirToIgnore);
// Ensures that directory specified by szPathIn exists by creating all needed (sub-)directories.
// Returns false in case of a failure.
// Example: "c:\temp\test" ("c:\temp\test\" also works) - ensures that "c:\temp\test" exists.
bool EnsureDirectoryExists(const char* szPathIn);
// converts the FILETIME to the C Timestamp (compatible with dbghelp.dll)
inline DWORD FiletimeToUnixTime(const FILETIME& ft)
{
return (DWORD)((((int64&)ft) / SECS_TO_100NS) - SECS_BETWEEN_EPOCHS);
}
// converts the FILETIME to 64bit C timestamp
inline AZ::u64 FiletimeTo64BitUnixTime(const FILETIME& fileTime)
{
const AZ::u64 time = static_cast<AZ::u64>(fileTime.dwHighDateTime) << 32 | fileTime.dwLowDateTime;
return ((time / SECS_TO_100NS) - SECS_BETWEEN_EPOCHS);
}
// converts the C Timestamp (compatible with dbghelp.dll) to FILETIME
inline FILETIME UnixTimeToFiletime(DWORD nCTime)
{
const int64 time = (nCTime + SECS_BETWEEN_EPOCHS) * SECS_TO_100NS;
return (FILETIME&)time;
}
//converts the 64 bit C Timestamp to FILETIME
inline void UnixTime64BitToFiletime(AZ::u64 nCTime, FILETIME& fileTime)
{
const AZ::u64 time = (nCTime + SECS_BETWEEN_EPOCHS) * SECS_TO_100NS;
fileTime.dwLowDateTime = static_cast<DWORD>(time);
fileTime.dwHighDateTime = static_cast<DWORD>(time >> 32);
}
inline FILETIME GetInvalidFileTime()
{
FILETIME fileTime;
fileTime.dwLowDateTime = 0;
fileTime.dwHighDateTime = 0;
return fileTime;
}
// returns file time stamps
#if defined(AZ_PLATFORM_WINDOWS)
inline bool GetFileTimes(const char* filename, FILETIME* ftimeCreate = nullptr, FILETIME* ftimeAccess = nullptr, FILETIME* ftimeModify = nullptr)
{
WIN32_FIND_DATAA FindFileData;
const HANDLE hFind = FindFirstFileA(filename, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
return false;
}
if (ftimeModify == nullptr && ftimeCreate == nullptr && ftimeAccess == nullptr)
{
FindClose(hFind);
return true;
}
FindClose(hFind);
if (ftimeCreate)
{
ftimeCreate->dwLowDateTime = FindFileData.ftCreationTime.dwLowDateTime;
ftimeCreate->dwHighDateTime = FindFileData.ftCreationTime.dwHighDateTime;
}
if (ftimeModify)
{
ftimeModify->dwLowDateTime = FindFileData.ftLastWriteTime.dwLowDateTime;
ftimeModify->dwHighDateTime = FindFileData.ftLastWriteTime.dwHighDateTime;
}
if (ftimeAccess)
{
ftimeAccess->dwLowDateTime = FindFileData.ftLastAccessTime.dwLowDateTime;
ftimeAccess->dwHighDateTime = FindFileData.ftCreationTime.dwHighDateTime;
}
return true;
}
#else
inline bool GetFileTimes(const char* filename, AZ::u64* timeCreate = nullptr, AZ::u64* timeAccess = nullptr, AZ::u64* timeModify = nullptr)
{
struct stat statResult;
if (stat(filename, &statResult) != 0)
{
return false;
}
if (timeCreate)
{
*timeCreate =static_cast<AZ::u64>(statResult.st_ctime);
}
if (timeModify)
{
*timeModify =static_cast<AZ::u64>(statResult.st_mtime);
}
if (timeAccess)
{
*timeAccess =static_cast<AZ::u64>(statResult.st_atime);
}
return true;
}
#endif
inline FILETIME GetLastWriteFileTime(const char* filename)
{
FILETIME timeModify = GetInvalidFileTime();
#if defined(AZ_PLATFORM_WINDOWS)
GetFileTimes(filename, nullptr, nullptr, &timeModify);
#else
AZ::u64 modTime = 0;
GetFileTimes(filename, nullptr, nullptr, &modTime);
if(modTime != 0)
{
UnixTime64BitToFiletime(modTime, timeModify);
}
#endif
return timeModify;
}
inline bool FileTimesAreEqual(const FILETIME& fileTime0, const FILETIME& fileTime1)
{
return
(fileTime0.dwLowDateTime == fileTime1.dwLowDateTime) &&
(fileTime0.dwHighDateTime == fileTime1.dwHighDateTime);
}
inline bool FileTimesAreEqual(const char* const srcfilename, const char* const targetfilename)
{
FILETIME ftSource = FileUtil::GetLastWriteFileTime(srcfilename);
FILETIME ftTarget = FileUtil::GetLastWriteFileTime(targetfilename);
return FileTimesAreEqual(ftSource, ftTarget);
}
inline bool FileTimeIsValid(const FILETIME& fileTime)
{
return !FileTimesAreEqual(GetInvalidFileTime(), fileTime);
}
inline bool SetFileTimes(const char* const filename, const FILETIME& creationFileTime, const FILETIME& accessFileTime, const FILETIME& modifcationFileTime)
{
#if defined(AZ_PLATFORM_WINDOWS)
const HANDLE hf = CreateFileA(filename, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (hf != INVALID_HANDLE_VALUE)
{
if (SetFileTime(hf, &creationFileTime, &accessFileTime, &modifcationFileTime))
{
if (CloseHandle(hf))
{
return true;
}
}
CloseHandle(hf);
}
#else
AZ::u64 creationTime = FiletimeTo64BitUnixTime(creationFileTime);
AZ::u64 modificationTime = FiletimeTo64BitUnixTime(modifcationFileTime);
struct utimbuf puttime;
puttime.modtime = modificationTime;
puttime.actime = creationTime;
if (utime(filename, &puttime) == 0)
{
return true;
}
#endif
return false;
}
inline bool SetFileTimes(const char* const filename, const FILETIME& fileTime)
{
#if defined(AZ_PLATFORM_WINDOWS)
const HANDLE hf = CreateFileA(filename, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (hf != INVALID_HANDLE_VALUE)
{
if (SetFileTime(hf, &fileTime, &fileTime, &fileTime))
{
if (CloseHandle(hf))
{
return true;
}
}
CloseHandle(hf);
}
#else
AZ::u64 newTime = FiletimeTo64BitUnixTime(fileTime);
struct utimbuf puttime;
puttime.modtime = newTime;
puttime.actime = newTime;
if (utime(filename, &puttime) == 0)
{
return true;
}
#endif
return false;
}
inline bool SetFileTimes(const char* const srcfilename, const char* const targetfilename)
{
#if defined(AZ_PLATFORM_WINDOWS)
FILETIME creationFileTime, accessFileTime, modifcationFileTime;
if (GetFileTimes(srcfilename, &creationFileTime, &accessFileTime, &modifcationFileTime))
{
const HANDLE hf = CreateFileA(targetfilename, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (hf != INVALID_HANDLE_VALUE)
{
if (SetFileTime(hf, &creationFileTime, &accessFileTime, &modifcationFileTime))
{
if (CloseHandle(hf))
{
return true;
}
}
CloseHandle(hf);
}
}
#else
AZ::u64 creationFileTime, accessFileTime, modifcationFileTime;
if (GetFileTimes(srcfilename, &creationFileTime, &accessFileTime, &modifcationFileTime))
{
struct utimbuf puttime;
puttime.modtime = modifcationFileTime;
puttime.actime = accessFileTime;
if (utime(targetfilename, &puttime) == 0)
{
return true;
}
}
#endif
return false;
}
inline uint64 GetFileSize(const char* const filename)
{
AZ::u64 fileSize = AZ::IO::SystemFile::Length(filename);
return fileSize >= 0? fileSize : -1;
}
inline bool FileExists(const char* szPath)
{
return AZ::IO::LocalFileIO().Exists(szPath);
}
inline bool DirectoryExists(const char* szPath)
{
return AZ::IO::LocalFileIO().IsDirectory(szPath);
}
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_FILEUTIL_H
@@ -1,48 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_FILEXMLBUFFERSOURCE_H
#define CRYINCLUDE_CRYCOMMONTOOLS_FILEXMLBUFFERSOURCE_H
#pragma once
class FileXmlBufferSource
: public IXmlBufferSource
{
public:
FileXmlBufferSource(const char* path)
{
file = std::fopen(path, "r");
}
~FileXmlBufferSource()
{
if (file)
{
std::fclose(file);
}
}
virtual int Read(void* buffer, int size) const
{
if (!file)
{
return 0;
}
return std::fread(buffer, 1, size, file);
}
private:
mutable std::FILE* file;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_FILEXMLBUFFERSOURCE_H
-53
View File
@@ -1,53 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ILOGGER_H
#define CRYINCLUDE_CRYCOMMONTOOLS_ILOGGER_H
#pragma once
#include <stdarg.h>
#include <stdio.h>
class ILogger
{
public:
enum ESeverity
{
eSeverity_Debug,
eSeverity_Info,
eSeverity_Warning,
eSeverity_Error
};
virtual ~ILogger()
{
}
void Log(ESeverity eSeverity, const char* const format, ...)
{
char buffer[2048];
{
va_list args;
va_start(args, format);
_vsnprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, format, args);
va_end(args);
}
LogImpl(eSeverity, buffer);
}
protected:
virtual void LogImpl(ESeverity eSeverity, const char* text) = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_ILOGGER_H
-49
View File
@@ -1,49 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_IPAKSYSTEM_H
#define CRYINCLUDE_CRYCOMMONTOOLS_IPAKSYSTEM_H
#pragma once
#include <platform.h>
struct PakSystemFile;
struct PakSystemArchive;
struct IPakSystem
{
virtual PakSystemFile* Open(const char* filename, const char* mode) = 0;
virtual bool ExtractNoOverwrite(const char* filename, const char* extractToFile = 0) = 0;
virtual void Close(PakSystemFile* file) = 0;
virtual int GetLength(PakSystemFile* file) const = 0;
virtual int Read(PakSystemFile* file, void* buffer, int size) = 0;
virtual bool EoF(PakSystemFile* file) = 0;
virtual PakSystemArchive* OpenArchive(const char* path, size_t fileAlignment = 1, bool encrypted = false, const uint32 encryptionKey[4] = 0) = 0;
virtual void CloseArchive(PakSystemArchive* archive) = 0;
// Summary:
// Adds a new file to the pak or update an existing one.
// Adds a directory (creates several nested directories if needed)
// Arguments:
// path - relative path inside archive
// data, size - file content
// modTime - modification timestamp of the file
// compressionLevel - level of compression (correnponds to zlib-levels):
// -1 or [0-9] where -1=default compression, 0=no compression, 9=best compression
virtual void AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, int64 modTime, int compressionLevel = -1) = 0;
virtual bool DeleteFromArchive(PakSystemArchive* archive, const char* path) = 0;
virtual bool CheckIfFileExist(PakSystemArchive* archive, const char* path, int64 modTime) = 0;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_IPAKSYSTEM_H
-57
View File
@@ -1,57 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ISETTINGS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_ISETTINGS_H
#pragma once
class ISettings
{
public:
virtual bool GetSettingString(char* buffer, int bufferSizeInBytes, const char* key) = 0;
virtual bool GetSettingInt(int& value, const char* key) = 0;
};
inline bool GetSettingByRef(ISettings* settings, const string& key, string& value)
{
char buffer[1024];
bool success = false;
if (settings)
{
success = settings->GetSettingString(buffer, sizeof(buffer), key.c_str());
}
if (success)
{
value = buffer;
}
return success;
}
inline bool GetSettingByRef(ISettings* settings, const string& key, int& value)
{
return settings->GetSettingInt(value, key.c_str());
}
template <typename T>
inline T GetSetting(ISettings* settings, const string& key, const T& dflt)
{
T value;
if (!GetSettingByRef(settings, key, value))
{
value = dflt;
}
return value;
}
#endif // CRYINCLUDE_CRYCOMMONTOOLS_ISETTINGS_H
@@ -1,27 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include <platform.h>
#include "LocaleChanger.h"
#include <locale.h>
LocaleChanger::LocaleChanger(int category, const char* newLocale)
{
m_category = category;
m_oldLocale = setlocale(category, newLocale);
}
LocaleChanger::~LocaleChanger()
{
setlocale(m_category, m_oldLocale.c_str());
}
-30
View File
@@ -1,30 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_LOCALECHANGER_H
#define CRYINCLUDE_CRYCOMMONTOOLS_LOCALECHANGER_H
#pragma once
class LocaleChanger
{
public:
LocaleChanger(int category, const char* newLocale);
~LocaleChanger();
private:
int m_category;
string m_oldLocale;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_LOCALECHANGER_H
-79
View File
@@ -1,79 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include <platform.h>
#include "LogFile.h"
LogFile::LogFile(const char* const filename)
: m_file(0)
, m_hasWarnings(false)
, m_hasErrors(false)
{
m_file = std::fopen(filename, "w");
}
LogFile::~LogFile()
{
if (m_file)
{
fclose(m_file);
}
}
bool LogFile::IsOpen() const
{
return m_file != 0;
}
bool LogFile::HasWarningsOrErrors() const
{
return m_hasWarnings || m_hasErrors;
}
void LogFile::LogImpl(ESeverity eSeverity, const char* const text)
{
const char* severityMessage = 0;
switch (eSeverity)
{
case eSeverity_Debug:
severityMessage = " ";
break;
case eSeverity_Info:
severityMessage = " ";
break;
case eSeverity_Warning:
severityMessage = "W: ";
break;
case eSeverity_Error:
severityMessage = "E: ";
break;
default:
severityMessage = "?: ";
break;
}
if (eSeverity == eSeverity_Warning)
{
m_hasWarnings = true;
}
if (eSeverity == eSeverity_Error)
{
m_hasErrors = true;
}
if (m_file)
{
fprintf(m_file, "%s%s\n", severityMessage, text);
fflush(m_file);
}
}
-40
View File
@@ -1,40 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_LOGFILE_H
#define CRYINCLUDE_CRYCOMMONTOOLS_LOGFILE_H
#pragma once
#include "ILogger.h"
class LogFile
: public ILogger
{
public:
LogFile(const char* filename);
~LogFile();
bool IsOpen() const;
bool HasWarningsOrErrors() const;
// ILogger
virtual void LogImpl(ESeverity eSeverity, const char* message);
private:
std::FILE* m_file;
bool m_hasWarnings;
bool m_hasErrors;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_LOGFILE_H
-72
View File
@@ -1,72 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_MATHHELPERS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_MATHHELPERS_H
#pragma once
#include <float.h>
#if (_M_IX86_FP > 0)
#include <intrin.h>
#endif
namespace MathHelpers
{
#if (_M_IX86_FP > 0)
inline int FastRoundFloatTowardZero(float f)
{
return _mm_cvtt_ss2si(_mm_set_ss(f));
}
#else
inline int FastRoundFloatTowardZero(float f)
{
return int(f);
}
#endif
#if defined(AZ_PLATFORM_WINDOWS)
inline unsigned int EnableFloatingPointExceptions(unsigned int mask)
{
_clearfp();
unsigned int oldMask;
_controlfp_s(&oldMask, 0, 0);
unsigned int newMask;
_controlfp_s(&newMask, ~mask, _MCW_EM);
return ~oldMask;
}
class AutoFloatingPointExceptions
{
public:
AutoFloatingPointExceptions(const unsigned int mask)
: m_mask(EnableFloatingPointExceptions(mask))
{
}
~AutoFloatingPointExceptions()
{
EnableFloatingPointExceptions(m_mask);
}
private:
unsigned int m_mask;
};
#endif //AZ_PLATFORM_WINDOWS
}
#endif // CRYINCLUDE_CRYCOMMONTOOLS_MATHHELPERS_H
@@ -1,44 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include <platform.h>
#include "ModuleHelpers.h"
HMODULE ModuleHelpers::GetCurrentModule(CurrentModuleSpecifier moduleSpecifier)
{
switch (moduleSpecifier)
{
case CurrentModuleSpecifier_Executable:
return GetModuleHandle(0);
case CurrentModuleSpecifier_Library:
MEMORY_BASIC_INFORMATION mbi;
static int dummy;
VirtualQuery(&dummy, &mbi, sizeof(mbi));
HMODULE instance = reinterpret_cast<HMODULE>(mbi.AllocationBase);
return instance;
}
return 0;
}
std::basic_string<TCHAR> ModuleHelpers::GetCurrentModulePath(CurrentModuleSpecifier moduleSpecifier)
{
// Here's a trick that will get you the handle of the module
// you're running in without any a-priori knowledge:
// http://www.dotnet247.com/247reference/msgs/13/65259.aspx
HMODULE instance = GetCurrentModule(moduleSpecifier);
TCHAR moduleNameBuffer[MAX_PATH];
GetModuleFileName(instance, moduleNameBuffer, sizeof(moduleNameBuffer) / sizeof(moduleNameBuffer[0]));
return moduleNameBuffer;
}
-380
View File
@@ -1,380 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include <platform.h>
#include "PakSystem.h"
#include "PathHelpers.h"
#include "StringHelpers.h"
#include "ZipDir/ZipDir.h"
#include <zlib.h>
#include <AzFramework/IO/LocalFileIO.h>
#include <AzCore/std/functional.h>
PakSystemFile::PakSystemFile()
{
type = PakSystemFileType_Unknown;
file = NULL;
zip = NULL;
fileEntry = NULL;
data = NULL;
dataPosition = 0;
}
PakSystem::PakSystem()
{
}
PakSystemFile* PakSystem::Open(const char* a_path, const char* a_mode)
{
string normalPath = a_path;
string const zipExt = ".zip";
bool bZip = StringHelpers::EndsWithIgnoreCase(normalPath, zipExt);
if (bZip)
{
// If it's a .zip file, then we'll try to look for a file without .zip extension inside of the .zip file
normalPath.erase(normalPath.length() - zipExt.length(), zipExt.length());
}
string zipPath = normalPath + zipExt;
string filename = PathHelpers::GetFilename(normalPath);
if (!normalPath.empty() && normalPath[0] == '@')
{
// File is inside pak file.
int splitter = normalPath.find_first_of("|;,");
if (splitter >= 0)
{
zipPath = normalPath.substr(1, splitter - 1);
filename = StringHelpers::MakeLowerCase(normalPath.substr(splitter + 1));
bZip = true;
}
else
{
return 0;
}
}
if (!bZip)
{
// Try to open the file.
FILE* f = nullptr;
azfopen(&f, normalPath.c_str(), a_mode);
if (f)
{
std::unique_ptr<PakSystemFile> file(new PakSystemFile());
file->type = PakSystemFileType_File;
file->file = f;
return file.release();
}
}
// if it's simple and read-only, it's assumed it's read-only
unsigned const nFactoryFlags = ZipDir::CacheFactory::FLAGS_DONT_COMPACT | ZipDir::CacheFactory::FLAGS_READ_ONLY;
bool bFileExists = false;
const uint32* decryptionKey = 0; // use default one
if (bZip)
{
// a caller asked to open a .zip file. check if the .zip file on disk exist
FILE* f = nullptr;
azfopen(&f, zipPath.c_str(), "rb");
if (f)
{
fclose(f);
bFileExists = true;
}
}
else
{
// a caller specified normal file. we already failed to find it on disk,
// so the file could be within a .pak file. let's find all 'potential'
// pak files and look within these for a matching file
std::vector<string> foundFileCountainer; // pak files found
for (string dirToSearch = normalPath;; )
{
dirToSearch = PathHelpers::GetDirectory(dirToSearch);
AZ::IO::LocalFileIO localFileIO;
localFileIO.FindFiles(dirToSearch.c_str(), "*.pak", [&](const char* filePath) -> bool
{
const string foundFilename(filePath);
if (StringHelpers::EqualsIgnoreCase(PathHelpers::FindExtension(foundFilename), "pak"))
{
foundFileCountainer.push_back(foundFilename);
}
return true; // continue iterating
});
if (PathHelpers::GetFilename(dirToSearch).empty())
{
// We've reached the top of the path
break;
}
}
// iterate through found containers and look for relevant files within them
for (int iFile = 0; iFile < foundFileCountainer.size(); ++iFile)
{
zipPath = foundFileCountainer[ iFile ];
string pathToZip = PathHelpers::GetDirectory(zipPath);
// construct filename by removing path to zip from path to filename
string pathToFile = PathHelpers::GetDirectory(string(normalPath));
string pureFileName = PathHelpers::GetFilename(string(normalPath));
if (pathToFile.length() != pathToZip.length() && pathToZip.length() > 0)
{
pathToFile = pathToFile.substr(pathToZip.length() + 1);
}
filename = pathToFile.empty()
? pureFileName
: pathToFile + "\\" + pureFileName;
ZipDir::CacheFactory factory(ZipDir::ZD_INIT_FAST, nFactoryFlags);
ZipDir::CachePtr testZip = factory.New(zipPath.c_str(), decryptionKey);
ZipDir::FileEntry* testFileEntry = (testZip ? testZip->FindFile(filename.c_str()) : 0);
// break out if we have a testFileEntry, as we've found our first (and best) candidate.
if (testFileEntry)
{
bFileExists = true;
break;
}
}
}
{
ZipDir::CacheFactory factory(ZipDir::ZD_INIT_FAST, nFactoryFlags);
ZipDir::CachePtr zip = (bFileExists ? factory.New(zipPath.c_str(), decryptionKey) : 0);
ZipDir::FileEntry* fileEntry = (zip ? zip->FindFile(filename.c_str()) : 0);
if (fileEntry)
{
std::unique_ptr<PakSystemFile> file(new PakSystemFile());
file->type = PakSystemFileType_PakFile;
file->zip = zip;
file->fileEntry = fileEntry;
file->data = zip->AllocAndReadFile(file->fileEntry);
file->dataPosition = 0;
return file.release();
}
}
return 0;
}
//Extracts archived file to disk without overwriting any files
//returns true on success, false on failure (due to potential overwrite or no file
//in archive
bool PakSystem::ExtractNoOverwrite(const char* fileToExtract, const char* extractToFile)
{
if (0 == extractToFile)
{
extractToFile = fileToExtract;
}
//open file using pak system
PakSystemFile* fileZip = Open(fileToExtract, "r");
if (!fileZip)
{
return false;
}
// Try to open a writable file
FILE* fFileOnDisk = nullptr;
azfopen(&fFileOnDisk, extractToFile, "wb");
if (!fFileOnDisk)
{
Close(fileZip);
return false;
}
fwrite(fileZip->data, fileZip->fileEntry->desc.lSizeUncompressed, 1, fFileOnDisk);
fclose(fFileOnDisk);
Close(fileZip);
return true;
}
void PakSystem::Close(PakSystemFile* file)
{
if (file)
{
switch (file->type)
{
case PakSystemFileType_File:
fclose(file->file);
break;
case PakSystemFileType_PakFile:
file->zip->Free(file->data);
break;
}
delete file;
}
}
int PakSystem::GetLength(PakSystemFile* file) const
{
if (file)
{
switch (file->type)
{
case PakSystemFileType_File:
{
if (file->file)
{
long pos = ftell(file->file);
fseek(file->file, 0, SEEK_END);
int result = ftell(file->file);
fseek(file->file, pos, SEEK_SET);
return result;
}
break;
}
case PakSystemFileType_PakFile:
{
if (file->fileEntry)
{
return file->fileEntry->desc.lSizeUncompressed;
}
break;
}
default:
{
break;
}
}
}
return 0;
}
int PakSystem::Read(PakSystemFile* file, void* buffer, int size)
{
int readBytes = 0;
if (file)
{
switch (file->type)
{
case PakSystemFileType_File:
{
readBytes = fread(buffer, 1, size, file->file);
}
break;
case PakSystemFileType_PakFile:
{
int fileSize = file->fileEntry->desc.lSizeUncompressed;
readBytes = (fileSize - file->dataPosition > size ? size : fileSize - file->dataPosition);
memcpy(buffer, static_cast<char*>(file->data) + file->dataPosition, readBytes);
file->dataPosition += readBytes;
}
break;
}
}
return readBytes;
}
bool PakSystem::EoF(PakSystemFile* file)
{
bool EoF = true;
if (file)
{
switch (file->type)
{
case PakSystemFileType_File:
{
EoF = (0 != feof(file->file));
}
break;
case PakSystemFileType_PakFile:
{
int fileSize = file->fileEntry->desc.lSizeUncompressed;
EoF = (file->dataPosition >= fileSize);
}
break;
}
}
return EoF;
}
PakSystemArchive* PakSystem::OpenArchive(const char* path, size_t fileAlignment, bool encrypted, const uint32 encryptionKey[4])
{
//unsigned nFactoryFlags = ZipDir::CacheFactory::FLAGS_DONT_COMPACT | ZipDir::CacheFactory::FLAGS_CREATE_NEW;
unsigned nFactoryFlags = 0;
ZipDir::CacheFactory factory(ZipDir::ZD_INIT_FAST, nFactoryFlags);
ZipDir::CacheRWPtr cache = factory.NewRW(path, fileAlignment, encrypted, encryptionKey);
PakSystemArchive* archive = (cache ? new PakSystemArchive() : 0);
if (archive)
{
archive->zip = cache;
}
return archive;
}
void PakSystem::CloseArchive(PakSystemArchive* archive)
{
if (archive)
{
archive->zip->Close();
delete archive;
}
}
void PakSystem::AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, int64 modTime, int compressionLevel)
{
int compressionMethod = ZipFile::METHOD_DEFLATE;
if (compressionLevel == 0)
{
compressionMethod = ZipFile::METHOD_STORE;
}
archive->zip->UpdateFile(path, data, size, compressionMethod, compressionLevel, modTime);
}
//////////////////////////////////////////////////////////////////////////
bool PakSystem::CheckIfFileExist(PakSystemArchive* archive, const char* path, int64 modTime)
{
assert(archive);
ZipDir::FileEntry* pFileEntry = archive->zip->FindFile(path);
if (pFileEntry)
{
return pFileEntry->CompareFileTimeNTFS(modTime);
}
return false;
}
//////////////////////////////////////////////////////////////////////////
bool PakSystem::DeleteFromArchive(PakSystemArchive* archive, const char* path)
{
ZipDir::ErrorEnum err = archive->zip->RemoveFile(path);
return ZipDir::ZD_ERROR_SUCCESS == err;
}
-69
View File
@@ -1,69 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H
#define CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H
#pragma once
#include "IPakSystem.h"
#include "ZipDir/ZipDir.h" // TODO: get rid of thid include
enum PakSystemFileType
{
PakSystemFileType_Unknown,
PakSystemFileType_File,
PakSystemFileType_PakFile
};
struct PakSystemFile
{
PakSystemFile();
PakSystemFileType type;
// PakSystemFileType_File
FILE* file;
// PakSystemFileType_PakFile
ZipDir::CachePtr zip;
ZipDir::FileEntry* fileEntry;
void* data;
int dataPosition;
};
struct PakSystemArchive
{
ZipDir::CacheRWPtr zip;
};
class PakSystem
: public IPakSystem
{
public:
PakSystem();
// IPakSystem
virtual PakSystemFile* Open(const char* filename, const char* mode);
virtual bool ExtractNoOverwrite(const char* filename, const char* extractToFile = 0);
virtual void Close(PakSystemFile* file);
virtual int GetLength(PakSystemFile* file) const;
virtual int Read(PakSystemFile* file, void* buffer, int size);
virtual bool EoF(PakSystemFile* file);
virtual PakSystemArchive* OpenArchive(const char* path, size_t fileAlignment, bool encrypted, const uint32 encryptionKey[4]);
virtual void CloseArchive(PakSystemArchive* archive);
virtual void AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, int64 modTime, int compressionLevel);
virtual bool DeleteFromArchive(PakSystemArchive* archive, const char* path);
virtual bool CheckIfFileExist(PakSystemArchive* archive, const char* path, int64 modTime);
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H
@@ -1,74 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PAKXMLFILEBUFFERSOURCE_H
#define CRYINCLUDE_CRYCOMMONTOOLS_PAKXMLFILEBUFFERSOURCE_H
#pragma once
#include "../CryXML/IXMLSerializer.h"
#include "IPakSystem.h"
class PakXmlFileBufferSource
: public IXmlBufferSource
{
public:
PakXmlFileBufferSource(IPakSystem* pakSystem, const char* path)
: pakSystem(pakSystem)
{
file = pakSystem->Open(path, "r");
}
~PakXmlFileBufferSource()
{
if (file)
{
pakSystem->Close(file);
}
}
virtual int Read(void* buffer, int size) const
{
return pakSystem->Read(file, buffer, size);
};
IPakSystem* pakSystem;
PakSystemFile* file;
};
class PakXmlBufferSource
: public IXmlBufferSource
{
public:
PakXmlBufferSource(const char* buffer, size_t length)
: position(buffer)
, end(buffer + length)
{
}
virtual int Read(void* output, int size) const
{
size_t bytesLeft = end - position;
size_t bytesToCopy = size < bytesLeft ? size : bytesLeft;
if (bytesToCopy > 0)
{
memcpy(output, position, bytesToCopy);
position += bytesToCopy;
}
return bytesToCopy;
};
mutable const char* position;
const char* end;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_PAKXMLFILEBUFFERSOURCE_H
-621
View File
@@ -1,621 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include <platform.h>
#include "PathHelpers.h"
#include "StringHelpers.h"
#include "Util.h"
#include <AzCore/std/string/conversions.h>
#include <AzFramework/IO/LocalFileIO.h>
#include <AzCore/IO/SystemFile.h>
#include <AzFramework/StringFunc/StringFunc.h>
#include <AzCore/PlatformIncl.h>
// Returns position of last extension in last name (string::npos if not found)
// note: returns string::npos for names starting from '.' and having no
// '.' later (for example 'aaa/.ccc', 'a:.abc', '.rc')
template <class TS>
static inline size_t findExtensionPosition_Tpl(const TS& path)
{
const size_t dotPos = path.rfind('.');
if (dotPos == TS::npos)
{
return TS::npos;
}
static const typename TS::value_type separators[] = { '\\', '/', ':', 0 };
const size_t separatorPos = path.find_last_of(separators);
if (separatorPos != TS::npos)
{
if (separatorPos + 1 >= dotPos)
{
return TS::npos;
}
}
else if (dotPos == 0)
{
return TS::npos;
}
return dotPos + 1;
}
static size_t findExtensionPosition(const string& path)
{
return findExtensionPosition_Tpl(path);
}
static size_t findExtensionPosition(const wstring& path)
{
return findExtensionPosition_Tpl(path);
}
string PathHelpers::FindExtension(const string& path)
{
const size_t extPos = findExtensionPosition(path);
return (extPos == string::npos) ? string() : path.substr(extPos, string::npos);
}
wstring PathHelpers::FindExtension(const wstring& path)
{
const size_t extPos = findExtensionPosition(path);
return (extPos == wstring::npos) ? wstring() : path.substr(extPos, wstring::npos);
}
template <class TS>
static inline TS ReplaceExtension_Tpl(const TS& path, const TS& newExtension)
{
if (path.empty())
{
return TS();
}
if (newExtension.empty())
{
return PathHelpers::RemoveExtension(path);
}
const typename TS::value_type last = path[path.length() - 1];
if ((last == '\\') || (last == '/') || (last == ':') || (last == '.'))
{
return path;
}
const size_t extPos = findExtensionPosition(path);
static const typename TS::value_type dot[] = { '.', 0 };
return ((extPos == TS::npos) ? path + dot : path.substr(0, extPos)) + newExtension;
}
string PathHelpers::ReplaceExtension(const string& path, const string& newExtension)
{
return ReplaceExtension_Tpl(path, newExtension);
}
wstring PathHelpers::ReplaceExtension(const wstring& path, const wstring& newExtension)
{
return ReplaceExtension_Tpl(path, newExtension);
}
string PathHelpers::RemoveExtension(const string& path)
{
const size_t extPos = findExtensionPosition(path);
return (extPos == string::npos) ? path : path.substr(0, extPos - 1);
}
wstring PathHelpers::RemoveExtension(const wstring& path)
{
const size_t extPos = findExtensionPosition(path);
return (extPos == wstring::npos) ? path : path.substr(0, extPos - 1);
}
template <class TS>
static inline TS GetDirectory_Tpl(const TS& path)
{
static const typename TS::value_type separators[] = { '/', '\\', ':', 0 };
const size_t pos = path.find_last_of(separators);
if (pos == TS::npos)
{
return TS();
}
if (path[pos] == ':' || pos == 0 || path[pos - 1] == ':')
{
return path.substr(0, pos + 1);
}
// Handle paths like "\\machine"
if (pos == 1 && (path[0] == '/' || path[0] == '\\'))
{
return path;
}
return path.substr(0, pos);
}
string PathHelpers::GetDirectory(const string& path)
{
return GetDirectory_Tpl(path);
}
wstring PathHelpers::GetDirectory(const wstring& path)
{
return GetDirectory_Tpl(path);
}
template <class TS>
static inline TS GetFilename_Tpl(const TS& path)
{
static const typename TS::value_type separators[] = { '/', '\\', ':', 0 };
const size_t pos = path.find_last_of(separators);
if (pos == TS::npos)
{
return path;
}
// Handle paths like "\\machine"
if (pos == 1 && (path[0] == '/' || path[0] == '\\'))
{
return TS();
}
return path.substr(pos + 1, TS::npos);
}
string PathHelpers::GetFilename(const string& path)
{
return GetFilename_Tpl(path);
}
wstring PathHelpers::GetFilename(const wstring& path)
{
return GetFilename_Tpl(path);
}
template <class TS>
static inline TS AddSeparator_Tpl(const TS& path)
{
if (path.empty())
{
return TS();
}
const typename TS::value_type last = path[path.length() - 1];
if (last == '/' || last == '\\' || last == ':')
{
return path;
}
#if defined(AZ_PLATFORM_WINDOWS)
static const typename TS::value_type separator[] = { '\\', 0 };
#else
static const typename TS::value_type separator[] = { '/', 0 };
#endif
return path + separator;
}
string PathHelpers::AddSeparator(const string& path)
{
return AddSeparator_Tpl(path);
}
wstring PathHelpers::AddSeparator(const wstring& path)
{
return AddSeparator_Tpl(path);
}
template <class TS>
static inline TS RemoveSeparator_Tpl(const TS& path)
{
if (path.empty())
{
return TS();
}
const typename TS::value_type last = path[path.length() - 1];
if ((last == '/' || last == '\\') && path.length() > 1 && path[path.length() - 2] != ':')
{
return path.substr(0, path.length() - 1);
}
return path;
}
string PathHelpers::RemoveSeparator(const string& path)
{
return RemoveSeparator_Tpl(path);
}
wstring PathHelpers::RemoveSeparator(const wstring& path)
{
return RemoveSeparator_Tpl(path);
}
template <class TS>
static inline TS RemoveDuplicateSeparators_Tpl(const TS& path)
{
if (path.length() <= 1)
{
return path;
}
TS ret;
ret.reserve(path.length());
const typename TS::value_type* p = path.c_str();
// We start from the second char just to avoid damaging UNC paths with double backslash at the beginning (e.g. "\\Server04\file.txt")
ret += *p++;
while (*p)
{
ret += *p++;
if (p[-1] == '\\' || p[-1] == '/')
{
while (*p == '\\' || *p == '/')
{
++p;
}
}
}
return ret;
}
string PathHelpers::RemoveDuplicateSeparators(const string& path)
{
return RemoveDuplicateSeparators_Tpl(path);
}
wstring PathHelpers::RemoveDuplicateSeparators(const wstring& path)
{
return RemoveDuplicateSeparators_Tpl(path);
}
template <class TS>
static inline TS Join_Tpl(const TS& path1, const TS& path2)
{
if (path1.empty())
{
return path2;
}
if (path2.empty())
{
return path1;
}
if (!PathHelpers::IsRelative(path2))
{
assert(0 && "Join(): path2 is not relative");
return TS();
}
const typename TS::value_type last = path1[path1.length() - 1];
if (last == '/' || last == '\\' || last == ':')
{
return path1 + path2;
}
#if defined(AZ_PLATFORM_WINDOWS)
static const typename TS::value_type separator[] = { '\\', 0 };
#else
static const typename TS::value_type separator[] = { '/', 0 };
#endif
return path1 + separator + path2;
}
string PathHelpers::Join(const string& path1, const string& path2)
{
return Join_Tpl(path1, path2);
}
wstring PathHelpers::Join(const wstring& path1, const wstring& path2)
{
return Join_Tpl(path1, path2);
}
template <class TS>
static inline bool IsRelative_Tpl(const TS& path)
{
if (path.empty())
{
return true;
}
return path[0] != '/' && path[0] != '\\' && path.find(':') == TS::npos;
}
bool PathHelpers::IsRelative(const string& path)
{
return IsRelative_Tpl(path);
}
bool PathHelpers::IsRelative(const wstring& path)
{
return IsRelative_Tpl(path);
}
string PathHelpers::ToUnixPath(const string& path)
{
return StringHelpers::Replace(path, '\\', '/');
}
wstring PathHelpers::ToUnixPath(const wstring& path)
{
wstring s(path);
std::replace(s.begin(), s.end(), L'\\', L'/');
return s;
}
string PathHelpers::ToDosPath(const string& path)
{
return StringHelpers::Replace(path, '/', '\\');
}
wstring PathHelpers::ToDosPath(const wstring& path)
{
wstring s(path);
std::replace(s.begin(), s.end(), L'/', L'\\');
return s;
}
string PathHelpers::ToPlatformPath(const string& path)
{
#if defined(AZ_PLATFORM_WINDOWS)
return ToDosPath(path);
#else
return ToUnixPath(path);
#endif
}
wstring PathHelpers::ToPlatformPath(const wstring& path)
{
#if defined(AZ_PLATFORM_WINDOWS)
return ToDosPath(path);
#else
return ToUnixPath(path);
#endif
}
string PathHelpers::GetAsciiPath(const char* pPath)
{
AZStd::wstring wstr;
AZStd::to_wstring(wstr, pPath);
return GetAsciiPath(wstr.c_str());
}
string PathHelpers::GetAsciiPath(const wchar_t* pPath)
{
if (!pPath[0])
{
return string();
}
wstring w = ToPlatformPath(RemoveSeparator(wstring(pPath)));
if (StringHelpers::Utf16ContainsAsciiOnly(w.c_str()))
{
return StringHelpers::ConvertAsciiUtf16ToAscii(w.c_str());
}
// The path is non-ASCII, so let's resort to using short
// filenames where needed (short names are always ASCII-only)
// Long names components
std::vector<wstring> p0;
StringHelpers::Split(w, wstring(L"\\"), true, p0);
// find last component that is not in ASCII char set
int lastNonAscii;
for (lastNonAscii = (int)p0.size() - 1; lastNonAscii >= 0; --lastNonAscii)
{
if (!StringHelpers::Utf16ContainsAsciiOnly(p0[lastNonAscii].c_str()))
{
break;
}
}
assert(lastNonAscii >= 0);
string res;
res.reserve(w.length());
w.clear();
for (int i = 0; i <= lastNonAscii; ++i)
{
w.append(p0[i]);
if (i < lastNonAscii)
{
w.push_back('\\');
}
}
enum
{
kBufferLen = AZ_MAX_PATH_LEN
};
wchar_t bufferWchars[kBufferLen];
#if defined(AZ_PLATFORM_WINDOWS)
const int charCount = GetShortPathNameW(w.c_str(), bufferWchars, kBufferLen);
#else
const int charCount = w.length();
wcsncpy(bufferWchars, w.c_str(), kBufferLen);
#endif
if (charCount <= 0 || charCount >= kBufferLen)
{
return string();
}
#if defined(AZ_PLATFORM_WINDOWS)
// Paranoid
if (!StringHelpers::Utf16ContainsAsciiOnly(bufferWchars))
{
assert(0);
return string();
}
#endif
// Short names components
std::vector<wstring> p1;
StringHelpers::Split(wstring(bufferWchars), wstring(L"\\"), true, p1);
for (size_t i = 0; i < (int)p0.size(); ++i)
{
if (!p0[i].empty())
{
const wstring& p =
(i > lastNonAscii || StringHelpers::Utf16ContainsAsciiOnly(p0[i].c_str()))
? p0[i]
: p1[i];
res.append(StringHelpers::ConvertAsciiUtf16ToAscii(p.c_str()));
}
if (i + 1 < (int)p0.size())
{
res.push_back('\\');
}
}
return res;
}
string PathHelpers::GetAbsoluteAsciiPath(const char* pPath)
{
char fullPath[AZ_MAX_PATH_LEN];
AZ::IO::LocalFileIO localFileIO;
AZStd::string normalizedPath(pPath);
AzFramework::StringFunc::Path::Normalize(normalizedPath);
localFileIO.ConvertToAbsolutePath(normalizedPath.c_str(), fullPath, AZ_MAX_PATH_LEN);
fullPath[sizeof(fullPath) - 1] = '\0';
AZStd::wstring wstr;
AZStd::to_wstring(wstr, fullPath);
return GetAsciiPath(wstr.c_str());
}
string PathHelpers::GetAbsoluteAsciiPath(const wchar_t* pPath)
{
AZStd::string str;
AZStd::to_string(str, pPath);
AzFramework::StringFunc::Path::Normalize(str);
char fullPath[AZ_MAX_PATH_LEN];
AZ::IO::LocalFileIO localFileIO;
localFileIO.ConvertToAbsolutePath(str.c_str(), fullPath, AZ_MAX_PATH_LEN);
fullPath[sizeof(fullPath) - 1] = '\0';
AZStd::wstring wstr;
AZStd::to_wstring(wstr, fullPath);
return GetAsciiPath(wstr.c_str());
}
string PathHelpers::GetShortestRelativeAsciiPath(const string& baseFolder, const string& dependentPath)
{
const string d = GetAbsoluteAsciiPath(dependentPath.c_str());
if (d.empty())
{
return PathHelpers::CanonicalizePath(dependentPath);
}
const string b = GetAbsoluteAsciiPath(baseFolder.c_str());
if (b.empty())
{
return PathHelpers::CanonicalizePath(dependentPath);
}
const string b2 = AddSeparator(b);
if (StringHelpers::StartsWithIgnoreCase(d, b2))
{
const size_t len = d.length() - b2.length();
// note: len == 0 is possible in case of "C:\" and "C:\".
return (len == 0) ? string(".") : d.substr(b2.length(), len);
}
std::vector<string> p0;
StringHelpers::Split(b2, string("\\"), true, p0);
std::vector<string> p1;
StringHelpers::Split(d, string("\\"), true, p1);
if (!StringHelpers::EqualsIgnoreCase(p0[0], p1[0]))
{
// got different drive letters
return PathHelpers::CanonicalizePath(dependentPath);
}
if (StringHelpers::EqualsIgnoreCase(d, b))
{
// exactly same path
return string(".");
}
// Search for first non-matching component
for (int i = 1; i < (int)p0.size(); ++i)
{
if (StringHelpers::EqualsIgnoreCase(p0[i], p1[i]))
{
continue;
}
string s;
s.reserve(Util::getMax(d.length(), b.length()));
for (int j = i; j < (int)p0.size(); ++j)
{
if (!p0[j].empty())
{
s.append("..\\");
}
}
for (int j = i; j < (int)p1.size(); ++j)
{
s.append(p1[j]);
if (j + 1 < (int)p1.size())
{
s.push_back('\\');
}
}
return s;
}
assert(0);
return string();
}
string PathHelpers::CanonicalizePath(const string& path)
{
string result = RemoveSeparator(path);
// remove .\ or ./ at the path beginning.
if (result.length() > 2)
{
if (result[0] == '.' && (result[1] == '\\' || result[1] == '/'))
{
result = result.substr(2);
}
}
return result;
}
-110
View File
@@ -1,110 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PATHHELPERS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_PATHHELPERS_H
#pragma once
#include <CryString.h>
namespace PathHelpers
{
// checks to see what the extension is in a string path
// returns the extension if found or an empty string if not found
string FindExtension(const string& path);
wstring FindExtension(const wstring& path);
// replace an extension of a string path with a new specified extension
// returns a string with the replaced extension or the original string if unable to replace the extension
string ReplaceExtension(const string& path, const string& newExtension);
wstring ReplaceExtension(const wstring& path, const wstring& newExtension);
// removes the extension of a specified string path
// returns a string with the extension removed or the original string if no extension was found
string RemoveExtension(const string& path);
wstring RemoveExtension(const wstring& path);
// "abc/def/ghi" -> "abc/def"
// "abc/def/ghi/" -> "abc/def/ghi"
// "/" -> "/"
// gets the directory path out of a specified string path
// returns a string of the directory path
string GetDirectory(const string& path);
wstring GetDirectory(const wstring& path);
// gets the file name out of a specified string path
// returns a string of the file name
string GetFilename(const string& path);
wstring GetFilename(const wstring& path);
// add a backslash to a specified path if it doesn't already have a separator
// returns a path with the appended backslash unless there was already a separator
string AddSeparator(const string& path);
wstring AddSeparator(const wstring& path);
// removes a forward slash or backslash from the end of a specified string path if found
// returns a string with the separator removed
string RemoveSeparator(const string& path);
wstring RemoveSeparator(const wstring& path);
// removes extra forward slashes and backslashes if they're contained within the string path
// returns a string with the extra forward slashes and backslashes removed
string RemoveDuplicateSeparators(const string& path);
wstring RemoveDuplicateSeparators(const wstring& path);
// It's not allowed to pass an absolute path in path2.
// Join(GetDirectory(fname), GetFilename(fname)) returns fname.
// merges two string paths together into one
// returns the merged string paths
string Join(const string& path1, const string& path2);
wstring Join(const wstring& path1, const wstring& path2);
// checks to see if the path is a relative path
// returns true if it is or false if it is not
bool IsRelative(const string& path);
bool IsRelative(const wstring& path);
// converts a string path to a unix path format
// returns the path in unix format
string ToUnixPath(const string& path);
wstring ToUnixPath(const wstring& path);
// converts a string path to a dos path format
// returns the path in dos format
string ToDosPath(const string& path);
wstring ToDosPath(const wstring& path);
// converts a string to the platform's path format.
// returns the path in the platform's path format.
string ToPlatformPath(const string& path);
wstring ToPlatformPath(const wstring& path);
// char* pPath: in ASCII or UTF-8 encoding
// wchar_t* pPath: in UTF-16 encoding
// Non-ASCII components of pPath (everything from &pPath[0] to last non-ASCII
// part, inclusively) should exist on disk, otherwise an empty string is returned.
string GetAsciiPath(const char* pPath);
string GetAsciiPath(const wchar_t* pPath);
// pPath passed should be in ASCII or UTF-8 encoding
string GetAbsoluteAsciiPath(const char* pPath);
// pPath passed should be in UTF-16 encoding
string GetAbsoluteAsciiPath(const wchar_t* pPath);
// baseFolder and dependentPath passed should be in ASCII or UTF-8 encoding
string GetShortestRelativeAsciiPath(const string& baseFolder, const string& dependentPath);
string CanonicalizePath(const string& path);
}
#endif // CRYINCLUDE_CRYCOMMONTOOLS_PATHHELPERS_H
@@ -1,15 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#define AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(file, offset, s) fseek(file, offset, s)
#define AZ_TRAIT_CRYCOMMONTOOLS_FTELL(file) ftell(file)
@@ -1,16 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h>
#define AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 0
@@ -1,15 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h>
#include <ZipDir/ZipDir_Traits_Linux.h>
@@ -1,16 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h>
#define AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 1
@@ -1,14 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <ZipDir/ZipDir_Traits_Mac.h>
@@ -1,14 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <ZipDir/ZipDir_Traits_Windows.h>
@@ -1,16 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#define AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(file, offset, s) _fseeki64(file, (__int64)offset, s)
#define AZ_TRAIT_CRYCOMMONTOOLS_FTELL(file) (size_t)_ftelli64(file)
#define AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 1
-89
View File
@@ -1,89 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PROGRESSRANGE_H
#define CRYINCLUDE_CRYCOMMONTOOLS_PROGRESSRANGE_H
#pragma once
class ProgressRange
{
public:
template <typename T>
ProgressRange(T* object, void (T::* setter)(float progress))
: m_target(new MethodTarget<T>(object, setter))
, m_progress(0.0f)
, m_start(0.0f)
, m_scale(1.0f)
{
m_target->Set(m_start);
}
ProgressRange(ProgressRange& parent, float scale)
: m_target(new ParentRangeTarget(parent))
, m_progress(0.0f)
, m_start(parent.m_progress)
, m_scale(scale)
{
m_target->Set(m_start);
}
~ProgressRange()
{
m_target->Set(m_start + m_scale);
delete m_target;
}
void SetProgress(float progress)
{
assert(progress > -0.01f && progress < 1.1f);
m_progress = progress;
m_target->Set(m_start + m_scale * progress);
}
private:
struct ITarget
{
virtual ~ITarget() {}
virtual void Set(float progress) = 0;
};
struct ParentRangeTarget
: public ITarget
{
ParentRangeTarget(ProgressRange& range)
: range(range) {}
virtual void Set(float progress) {range.SetProgress(progress); }
ProgressRange& range;
};
template <typename T>
struct MethodTarget
: public ITarget
{
typedef void (T::* Setter)(float progress);
MethodTarget(T* object, Setter setter)
: object(object)
, setter(setter) {}
virtual void Set(float progress) {(object->*setter)(progress); }
T* object;
Setter setter;
};
ITarget* m_target;
float m_progress;
float m_start;
float m_scale;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_PROGRESSRANGE_H
@@ -1,125 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include <platform.h>
#include "PropertyHelpers.h"
#include "StringHelpers.h"
bool PropertyHelpers::GetPropertyValue(const string& a_propertiesString, const char* a_propertyName, string& a_value)
{
if ((a_propertyName == 0) || (a_propertyName[0] == 0))
{
return false;
}
const char* lineStart = a_propertiesString.c_str();
while (*lineStart)
{
string key;
string value;
const size_t lineEndPosition = strcspn(lineStart, "\n");
const size_t equalPosition = strcspn(lineStart, "=");
if (equalPosition < lineEndPosition)
{
key = string(lineStart, equalPosition);
value = string(lineStart + equalPosition + 1, lineEndPosition - equalPosition - 1);
}
else
{
key = string(lineStart, lineEndPosition);
value = "";
}
key = StringHelpers::Trim(key);
if (_stricmp(key.c_str(), a_propertyName) == 0)
{
a_value = StringHelpers::Trim(value);
return true;
}
lineStart += lineEndPosition;
if (*lineStart)
{
++lineStart;
}
}
return false;
}
void PropertyHelpers::SetPropertyValue(string& a_propertiesString, const char* a_propertyName, const char* a_value)
{
if ((a_propertyName == 0) || (a_propertyName[0] == 0))
{
return;
}
const string newValue = StringHelpers::Trim(string(a_value));
const char* lineStart = a_propertiesString.c_str();
while (*lineStart)
{
const size_t lineEndPosition = strcspn(lineStart, "\n");
const size_t equalPosition = strcspn(lineStart, "=");
const string key = StringHelpers::Trim(string(lineStart, ((equalPosition < lineEndPosition) ? equalPosition : lineEndPosition)));
if (_stricmp(key.c_str(), a_propertyName) == 0)
{
const size_t prefixSz = lineStart - a_propertiesString.c_str();
const size_t expressionSz = lineEndPosition;
if (newValue.empty())
{
a_propertiesString = a_propertiesString.substr(0, prefixSz) + string(a_propertyName) + a_propertiesString.substr(prefixSz + expressionSz, string::npos);
}
else
{
a_propertiesString = a_propertiesString.substr(0, prefixSz) + string(a_propertyName) + string("=") + newValue + a_propertiesString.substr(prefixSz + expressionSz, string::npos);
}
return;
}
lineStart += lineEndPosition;
if (*lineStart)
{
++lineStart;
}
}
if (a_propertiesString.empty() || (a_propertiesString[a_propertiesString.size() - 1] != '\n'))
{
a_propertiesString += string("\r\n");
}
if (newValue.empty())
{
a_propertiesString += string(a_propertyName);
}
else
{
a_propertiesString += string(a_propertyName) + string("=") + newValue;
}
}
bool PropertyHelpers::HasProperty(const string& a_propertiesString, const char* a_propertyName)
{
string value;
return PropertyHelpers::GetPropertyValue(a_propertiesString, a_propertyName, value);
}
@@ -1,28 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PROPERTYHELPERS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_PROPERTYHELPERS_H
#pragma once
namespace PropertyHelpers
{
bool GetPropertyValue(const string& propertiesString, const char* propertyName, string& value);
void SetPropertyValue(string& a_propertiesString, const char* propertyName, const char* value);
bool HasProperty(const string& propertiesString, const char* propertyName);
}
#endif // CRYINCLUDE_CRYCOMMONTOOLS_PROPERTYHELPERS_H
-14
View File
@@ -1,14 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include <platform.h>
-54
View File
@@ -1,54 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_STLHELPERS_H
#define CRYINCLUDE_CRYCOMMONTOOLS_STLHELPERS_H
#pragma once
#include <functional>
namespace STLHelpers
{
template <class Type>
inline const char* constchar_cast(const Type& type)
{
return type;
}
template <>
inline const char* constchar_cast(const std::string& type)
{
return type.c_str();
}
template <class Type>
struct less_strcmp
{
bool operator()(const Type& left, const Type& right) const
{
return strcmp(constchar_cast(left), constchar_cast(right)) < 0;
}
};
template <class Type>
struct less_stricmp
{
bool operator()(const Type& left, const Type& right) const
{
return _stricmp(constchar_cast(left), constchar_cast(right)) < 0;
}
};
}
#endif // CRYINCLUDE_CRYCOMMONTOOLS_STLHELPERS_H
-508
View File
@@ -1,508 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#pragma once
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_SIMPLEBITMAP_H
#define CRYINCLUDE_CRYCOMMONTOOLS_SIMPLEBITMAP_H
#include <assert.h>
#include <vector> // STL vector
#include "platform.h" // uint32
#include "Cry_Math.h" // uint32
#include "Util.h" // getMin()
enum EImageFilteringMode
{
eifm2DBorder = 0,
eifmCubemapFilter = 1,
};
namespace
{
enum ECubeFace
{
ecfPosX = 0,
ecfNegX = 1,
ecfPosY = 2,
ecfNegY = 3,
ecfPosZ = 4,
ecfNegZ = 5,
ecfUnknown = -1,
};
struct JumpEntry
{
ECubeFace face;
int rot;
};
static const JumpEntry XJmpTable[] =
{
{ecfNegZ, 0}, {ecfPosZ, 2}, // ecfPosXa
{ecfPosZ, 0}, {ecfNegZ, 2}, // ecfNegXa
{ecfPosX, 1}, {ecfNegX, 3}, // ecfPosYa
{ecfPosX, 3}, {ecfNegX, 1}, // ecfNegYa
{ecfPosX, 0}, {ecfNegX, 0}, // ecfPosZa
{ecfPosX, 2}, {ecfNegX, 2} // ecfNegZa
};
static const JumpEntry YJmpTable[] =
{
{ecfPosY, 3}, {ecfNegY, 1}, // ecfPosXa
{ecfPosY, 1}, {ecfNegY, 3}, // ecfNegXa
{ecfNegZ, 2}, {ecfPosZ, 0}, // ecfPosYa
{ecfPosZ, 0}, {ecfNegZ, 2}, // ecfNegYa
{ecfNegY, 0}, {ecfPosY, 2}, // ecfPosZa
{ecfNegY, 2}, {ecfPosY, 0} // ecfNegZa
};
}
//! memory block used as bitmap
//! if you might need mipmaps please consider using ImageObject instead
template <class RasterElement>
class CSimpleBitmap
{
public:
CSimpleBitmap()
: m_dwWidth(0)
, m_dwHeight(0)
{
}
~CSimpleBitmap()
{
}
// copy constructor
CSimpleBitmap(const CSimpleBitmap<RasterElement>& rhs)
: m_dwWidth(0)
, m_dwHeight(0)
{
*this = rhs; // call assignment operator
}
// assignment operator
CSimpleBitmap<RasterElement>& operator=(const CSimpleBitmap<RasterElement>& rhs)
{
if (&rhs != this)
{
m_data = rhs.m_data;
m_dwWidth = rhs.m_dwWidth;
m_dwHeight = rhs.m_dwHeight;
}
return *this;
}
//! free all the memory resources
void FreeData()
{
m_data = std::vector<RasterElement>();
m_dwWidth = 0;
m_dwHeight = 0;
}
//! /return true=success, false=failed because of low memory
bool SetSize(const uint32 indwWidth, const uint32 indwHeight)
{
if (m_dwWidth * m_dwHeight != indwWidth * indwHeight)
{
FreeData();
m_data.resize(indwWidth * indwHeight);
m_dwWidth = indwWidth;
m_dwHeight = indwHeight;
}
return true;
}
private:
ECubeFace JumpX(const ECubeFace srcFace, const bool isdXPos, int* rotCoords) const
{
int index = (int)srcFace * 2 + (isdXPos ? 0 : 1);
assert(index < sizeof(XJmpTable));
const JumpEntry& jmp = XJmpTable[index];
(*rotCoords) += jmp.rot;
return jmp.face;
}
ECubeFace JumpY(const ECubeFace srcFace, const bool isdYPos, int* rotCoords) const
{
int index = (int)srcFace * 2 + (isdYPos ? 0 : 1);
assert(index < sizeof(YJmpTable));
const JumpEntry& jmp = YJmpTable[index];
(*rotCoords) += jmp.rot;
return jmp.face;
}
// table that shows to which face we jump
ECubeFace JumpTable(const ECubeFace srcFace, int isdXPos, int isdYPos, int* rotCoords) const
{
if (isdXPos != 0) // recursive jump until dx==0
{
int newSwap = 0;
ECubeFace newFace = JumpX(srcFace, isdXPos > 0, &newSwap);
(*rotCoords) += newSwap;
isdXPos -= ((isdXPos > 0) ? 1 : -1);
RotateCoord(&isdXPos, &isdYPos, newSwap);
return JumpTable(newFace, isdXPos, isdYPos, rotCoords);
}
if (isdYPos != 0) // recursive jump until dy==0
{
int newSwap = 0;
ECubeFace newFace = JumpY(srcFace, isdYPos > 0, &newSwap);
(*rotCoords) += newSwap;
isdYPos -= ((isdYPos > 0) ? 1 : -1);
RotateCoord(&isdXPos, &isdYPos, newSwap);
return JumpTable(newFace, isdXPos, isdYPos, rotCoords);
}
assert(isdXPos == 0 && isdYPos == 0);
return srcFace;
}
void RotateCoord(int* x, int* y, int mode) const
{
if (mode != 0)
{
if (mode == 2) // 180 degrees
{
(*x) = -(*x);
(*y) = -(*y);
}
else
{
if (mode == 1) // 90 dergees
{
int tmp = (*y);
(*y) = (*x);
(*x) = -tmp;
}
else // 270 degrees
{
assert(mode == 3);
int tmp = (*y);
(*y) = -(*x);
(*x) = tmp;
}
}
}
}
public:
//! works only within the Bitmap for filter kernels
//! /param inX 0..m_dwWidth-1 or the method returns false
//! /param inY 0..m_dwHeight-1 or the method returns false
//! /param outValue
//! /return pointer to the raster element value if position was in the bitmap, NULL otherwise
const RasterElement* GetForFiltering_2D(const int inX, const int inY) const
{
return Get(inX, inY);
}
//! works only within the Bitmap for filter kernels
//! /param inX 0..m_dwWidth-1 or the method returns false
//! /param inY 0..m_dwHeight-1 or the method returns false
//! /param outValue
//! /return pointer to the raster element value if position was in the bitmap, NULL otherwise
const RasterElement* GetForFiltering_Cubemap(const int inX, const int inY, const int srcX, const int srcY) const
{
if (m_data.empty())
{
return false;
}
assert(m_dwWidth == m_dwHeight * 6);
assert(srcX >= 0 && srcX < m_dwWidth);
assert(srcY >= 0 && srcY < m_dwHeight);
const int sideSize = m_dwHeight;
ECubeFace srcFace = (ECubeFace)(srcX / sideSize);
if (inX >= 0 && inX < m_dwWidth && inY >= 0 && inY < m_dwHeight) // if we're inside the cubemap
{
ECubeFace destFace = (ECubeFace)(inX / sideSize);
if (destFace == srcFace) // we have the same face as src texel
{
return &m_data[inY * m_dwWidth + inX];
}
}
const int halfSideSize = Util::getMax(1, sideSize / 2);
// ternary logic
const int isdXPositive = int(floorf((float)inX / sideSize) - floorf((float)srcX / sideSize));
const int isdYPositive = int(floorf((float)inY / sideSize) - floorf((float)srcY / sideSize));
//if(isdXPositive==0&&isdYPositive<0&&srcFace==ecfPosY)
//{
// int tmp = 0;
//}
assert(isdXPositive != 0 || isdYPositive != 0);
int rotCoords = 0; // quadrants to rotate coords
ECubeFace destFace = JumpTable(srcFace, isdXPositive, isdYPositive, &rotCoords);
rotCoords = ((rotCoords % 4) + 4) % 4;
int destX = inX - srcFace * sideSize;
int destY = inY;
// rotate coords
destX -= halfSideSize; // center coords
destY -= halfSideSize;
RotateCoord(&destX, &destY, rotCoords);
destX += halfSideSize; // shift back
destY += halfSideSize;
destX = ((destX + sideSize) % sideSize + sideSize) % sideSize; // tile in the face
destY = ((destY + sideSize) % sideSize + sideSize) % sideSize;
destX = Util::getMin(destX, sideSize - 1);
destY = Util::getMin(destY, sideSize - 1);
destX += sideSize * destFace;
assert(destX < m_dwWidth);
assert((ECubeFace)(destX / sideSize) == destFace);
return &m_data[destY * m_dwWidth + destX];
}
const RasterElement* GetForFiltering(const Vec3& inDir) const
{
Vec3 vcAbsDir(fabsf(inDir.x), fabsf(inDir.y), fabsf(inDir.z));
ECubeFace face;
int rotQuadrant = 0;
Vec2 texCoord;
if (vcAbsDir.x > vcAbsDir.y && vcAbsDir.x > vcAbsDir.z)
{
if (inDir.x > 0)
{
rotQuadrant = 3;
face = ecfPosX;
}
else
{
rotQuadrant = 1;
face = ecfNegX;
}
texCoord = Vec2(inDir.y, inDir.z) / vcAbsDir.x;
}
else if (vcAbsDir.y > vcAbsDir.x && vcAbsDir.y > vcAbsDir.z)
{
if (inDir.y > 0)
{
rotQuadrant = 2;
face = ecfPosY;
}
else
{
rotQuadrant = 0;
face = ecfNegY;
}
texCoord = Vec2(inDir.x, inDir.z) / vcAbsDir.y;
}
else
{
assert(vcAbsDir.z >= vcAbsDir.x && vcAbsDir.z >= vcAbsDir.y);
if (inDir.z > 0)
{
rotQuadrant = 1;
face = ecfPosZ;
}
else
{
rotQuadrant = 3;
face = ecfNegZ;
}
texCoord = Vec2(inDir.x, inDir.y) / vcAbsDir.z;
}
texCoord = texCoord * .5f + Vec2(.5f, .5f);
assert(texCoord.x <= 1.f && texCoord.x >= 0);
assert(texCoord.y <= 1.f && texCoord.y >= 0);
Vec2i texelPos(texCoord.x * (m_dwHeight - 1), texCoord.y * (m_dwHeight - 1));
texelPos.x += face * m_dwHeight; // plus face
return &m_data[texelPos.y * m_dwWidth + texelPos.x];
}
//! works only within the Bitmap
//! /param inX 0..m_dwWidth-1 or the method returns false
//! /param inY 0..m_dwHeight-1 or the method returns false
//! /param outValue
//! /return pointer to raster element value if position was in the bitmap, NULL otherwise
const RasterElement* Get(const uint32 inX, const uint32 inY) const
{
if (m_data.empty())
{
return 0;
}
if (inX >= m_dwWidth || inY >= m_dwHeight)
{
return 0;
}
return &m_data[inY * m_dwWidth + inX];
}
//! bilinear, works only well within 0..1
bool GetFiltered(const float infX, const float infY, RasterElement& outValue) const
{
float fIX = floorf(infX), fIY = floorf(infY);
float fFX = infX - fIX, fFY = infY - fIY;
int iXa = (int)fIX, iYa = (int)fIY;
int iXb = iXa + 1, iYb = iYa + 1;
if (iXb == m_dwWidth)
{
iXb = 0;
}
if (iYb == m_dwHeight)
{
iYb = 0;
}
const RasterElement* p[4];
if ((p[0] = Get(iXa, iYa)) && (p[1] = Get(iXb, iYa)) && (p[2] = Get(iXa, iYb)) && (p[3] = Get(iXb, iYb)))
{
outValue =
(*p[0]) * ((1.0f - fFX) * (1.0f - fFY)) + // left top
(*p[1]) * ((fFX) * (1.0f - fFY)) + // right top
(*p[2]) * ((1.0f - fFX) * (fFY)) + // left bottom
(*p[3]) * ((fFX) * (fFY)); // right bottom
return true;
}
return false;
}
//! works only within the Bitmap
//! /param inX 0..m_dwWidth-1 or the method returns false
//! /param inY 0..m_dwHeight-1 or the method returns false
const RasterElement& GetRef(const uint32 inX, const uint32 inY) const
{
assert(!m_data.empty());
assert(inX < m_dwWidth && inY < m_dwHeight);
return m_data[inY * m_dwWidth + inX];
}
//! works only within the Bitmap
//! /param inX 0..m_dwWidth-1 or the method returns false
//! /param inY 0..m_dwHeight-1 or the method returns false
RasterElement& GetRef(const uint32 inX, const uint32 inY)
{
assert(!m_data.empty());
assert(inX < m_dwWidth && inY < m_dwHeight);
return m_data[inY * m_dwWidth + inX];
}
//! works even outside of the Bitmap (tiled)
//! /param inX 0..m_dwWidth-1 or the method returns false
//! /param inY 0..m_dwHeight-1 or the method returns false
RasterElement& GetTiledRef(const uint32 inX, const uint32 inY)
{
assert(!m_data.empty());
const uint32 x = inX % m_dwWidth;
const uint32 y = inY % m_dwHeight;
return m_data[y * m_dwWidth + x];
}
//! works only within the Bitmap
//! /param inX 0..m_dwWidth-1 or the method returns false
//! /param inY 0..m_dwHeight-1 or the method returns false
//! /param inValue
bool Set(const uint32 inX, const uint32 inY, const RasterElement& inValue)
{
if (m_data.empty())
{
assert(!m_data.empty());
return false;
}
if (inX >= m_dwWidth || inY >= m_dwHeight)
{
return false;
}
m_data[inY * m_dwWidth + inX] = inValue;
return true;
}
uint32 GetWidth() const
{
return m_dwWidth;
}
uint32 GetHeight() const
{
return m_dwHeight;
}
// Returns size of one line in bytes
size_t GetPitch() const
{
return m_dwWidth * sizeof(RasterElement);
}
uint32 GetBitmapSizeInBytes() const
{
return m_dwWidth * m_dwHeight * sizeof(RasterElement);
}
//! /return could be 0 if the pixel is outside the bitmap
const RasterElement* GetPointer(const uint32 inX = 0, const uint32 inY = 0) const
{
if (inX >= m_dwWidth || inY >= m_dwHeight)
{
return 0;
}
return &m_data[inY * m_dwWidth + inX];
}
//! /return could be 0 if the pixel is outside the bitmap
RasterElement* GetPointer(const uint32 inX = 0, const uint32 inY = 0)
{
if (inX >= m_dwWidth || inY >= m_dwHeight)
{
return 0;
}
return &m_data[inY * m_dwWidth + inX];
}
void Fill(const RasterElement& inValue)
{
const uint32 n = m_dwHeight * m_dwWidth;
for (uint32 i = 0; i < n; ++i)
{
m_data[i] = inValue;
}
}
bool IsValid() const
{
return !m_data.empty();
}
protected: // ------------------------------------------------------
std::vector<RasterElement> m_data; //!< [m_dwWidth * m_dwHeight]
uint32 m_dwWidth;
uint32 m_dwHeight;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_SIMPLEBITMAP_H
@@ -1,249 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_SIMPLESTRINGPOOL_H
#define CRYINCLUDE_CRYCOMMONTOOLS_SIMPLESTRINGPOOL_H
#pragma once
#include <algorithm>
/////////////////////////////////////////////////////////////////////
// String pool implementation.
// Inspired by expat implementation.
/////////////////////////////////////////////////////////////////////
class CSimpleStringPool
{
public:
enum
{
STD_BLOCK_SIZE = 4096
};
struct BLOCK
{
BLOCK* next;
int size;
char s[1];
};
unsigned int m_blockSize;
BLOCK* m_blocks;
BLOCK* m_free_blocks;
const char* m_end;
char* m_ptr;
char* m_start;
int nUsedSpace;
int nUsedBlocks;
CSimpleStringPool()
{
m_blockSize = STD_BLOCK_SIZE;
m_blocks = 0;
m_start = 0;
m_ptr = 0;
m_end = 0;
nUsedSpace = 0;
nUsedBlocks = 0;
m_free_blocks = 0;
}
~CSimpleStringPool()
{
BLOCK* pBlock = m_blocks;
while (pBlock)
{
BLOCK* temp = pBlock->next;
//nFree++;
free(pBlock);
pBlock = temp;
}
pBlock = m_free_blocks;
while (pBlock)
{
BLOCK* temp = pBlock->next;
//nFree++;
free(pBlock);
pBlock = temp;
}
m_blocks = 0;
m_ptr = 0;
m_start = 0;
m_end = 0;
}
void SetBlockSize(unsigned int nBlockSize)
{
if (nBlockSize > 1024 * 1024)
{
nBlockSize = 1024 * 1024;
}
unsigned int size = 512;
while (size < nBlockSize)
{
size *= 2;
}
m_blockSize = size - offsetof(BLOCK, s);
}
void Clear()
{
if (m_free_blocks)
{
BLOCK* pLast = m_blocks;
while (pLast)
{
BLOCK* temp = pLast->next;
if (!temp)
{
break;
}
pLast = temp;
}
if (pLast)
{
pLast->next = m_free_blocks;
}
}
m_free_blocks = m_blocks;
m_blocks = 0;
m_start = 0;
m_ptr = 0;
m_end = 0;
nUsedSpace = 0;
}
char* Append(const char* ptr, int nStrLen)
{
char* ret = m_ptr;
if (m_ptr && nStrLen + 1 < (m_end - m_ptr))
{
memcpy(m_ptr, ptr, nStrLen);
m_ptr = m_ptr + nStrLen;
*m_ptr++ = 0; // add null termination.
}
else
{
int nNewBlockSize = (std::max)(nStrLen + 1, (int)m_blockSize);
AllocBlock(nNewBlockSize, nStrLen + 1);
memcpy(m_ptr, ptr, nStrLen);
m_ptr = m_ptr + nStrLen;
*m_ptr++ = 0; // add null termination.
ret = m_start;
}
nUsedSpace += nStrLen;
return ret;
}
char* ReplaceString(const char* str1, const char* str2)
{
int nStrLen1 = check_cast<int>(strlen(str1));
int nStrLen2 = check_cast<int>(strlen(str2));
// undo ptr1 add.
if (m_ptr != m_start)
{
m_ptr = m_ptr - nStrLen1 - 1;
}
assert(m_ptr == str1);
int nStrLen = nStrLen1 + nStrLen2;
char* ret = m_ptr;
if (m_ptr && nStrLen + 1 < (m_end - m_ptr))
{
memcpy(m_ptr, str1, nStrLen1);
memcpy(m_ptr + nStrLen1, str2, nStrLen2);
m_ptr = m_ptr + nStrLen;
*m_ptr++ = 0; // add null termination.
}
else
{
int nNewBlockSize = (std::max)(nStrLen + 1, check_cast<int>(m_blockSize));
if (m_ptr == m_start)
{
ReallocBlock(nNewBlockSize * 2); // Reallocate current block.
memcpy(m_ptr + nStrLen1, str2, nStrLen2);
}
else
{
AllocBlock(nNewBlockSize, nStrLen + 1);
memcpy(m_ptr, str1, nStrLen1);
memcpy(m_ptr + nStrLen1, str2, nStrLen2);
}
m_ptr = m_ptr + nStrLen;
*m_ptr++ = 0; // add null termination.
ret = m_start;
}
nUsedSpace += nStrLen;
return ret;
}
private:
void AllocBlock(int blockSize, int nMinBlockSize)
{
if (m_free_blocks)
{
BLOCK* pBlock = m_free_blocks;
BLOCK* pPrev = 0;
while (pBlock)
{
if (pBlock->size >= nMinBlockSize)
{
// Reuse free block
if (pPrev)
{
pPrev->next = pBlock->next;
}
else
{
m_free_blocks = pBlock->next;
}
pBlock->next = m_blocks;
m_blocks = pBlock;
m_ptr = pBlock->s;
m_start = pBlock->s;
m_end = pBlock->s + pBlock->size;
return;
}
pPrev = pBlock;
pBlock = pBlock->next;
}
}
size_t nMallocSize = offsetof(BLOCK, s) + blockSize * sizeof(char);
//nMallocs++;
BLOCK* pBlock = (BLOCK*)malloc(nMallocSize);
pBlock->size = blockSize;
pBlock->next = m_blocks;
m_blocks = pBlock;
m_ptr = pBlock->s;
m_start = pBlock->s;
m_end = pBlock->s + blockSize;
nUsedBlocks++;
}
void ReallocBlock(int blockSize)
{
BLOCK* pThisBlock = m_blocks;
BLOCK* pPrevBlock = m_blocks->next;
m_blocks = pPrevBlock;
size_t nMallocSize = offsetof(BLOCK, s) + blockSize * sizeof(char);
//nMallocs++;
BLOCK* pBlock = (BLOCK*)realloc(pThisBlock, nMallocSize);
pBlock->size = blockSize;
pBlock->next = m_blocks;
m_blocks = pBlock;
m_ptr = pBlock->s;
m_start = pBlock->s;
m_end = pBlock->s + blockSize;
}
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_SIMPLESTRINGPOOL_H
@@ -1,580 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include <platform.h>
#include "StealingThreadPool.h"
#include "ThreadUtils.h"
#include <AzCore/std/bind/bind.h>
#include <AzCore/std/parallel/thread.h>
#include <Cry_Math.h>
namespace ThreadUtils {
class StealingWorker
{
public:
StealingWorker(StealingThreadPool* pool, int index, bool trace, AZStd::condition_variable& jobsCV)
: m_pool(pool)
, m_index(index)
, m_tracingEnabled(trace)
, m_lastStartTime(0)
, m_exitFlag(0)
, m_jobsCV(jobsCV)
{
}
static unsigned int __stdcall ThreadFunc(void* param)
{
StealingWorker* self = (StealingWorker*)(param);
self->Work();
return 0;
}
void Start(int startTime)
{
m_lastStartTime = startTime;
string threadName;
threadName.Format("StealingWorker %d", m_index);
AZStd::thread_desc threadDesc;
threadDesc.m_name = threadName.c_str();
m_thread = AZStd::thread(AZStd::bind(StealingWorker::ThreadFunc, (void*)this), &threadDesc);
}
bool GetJobLockless(Job& job)
{
if (m_jobs.empty())
{
return false;
}
job = m_jobs.front();
m_jobs.pop_front();
return true;
}
bool GetJob(Job& job)
{
AZStd::lock_guard<AZStd::mutex> lock(m_lockJobs);
return GetJobLockless(job);
}
void ExecuteJob(Job& job)
{
--m_pool->m_numJobsWaitingForExecution;
job.Run();
if (m_tracingEnabled)
{
int time = (int)GetTickCount();
JobTrace trace;
trace.m_job = job;
trace.m_duration = time - m_lastStartTime;
m_traces.push_back(trace);
m_lastStartTime = time;
}
--m_pool->m_numJobs;
m_pool->m_jobFinishedCV.notify_all();
}
bool TryToStealJob(Job& job)
{
while (true)
{
StealingWorker* victim = m_pool->FindBestVictim(m_index);
if (!victim)
{
return false;
}
if (StealJobs(job, victim))
{
return true;
}
}
}
void Work()
{
Job job;
while (true)
{
AZStd::mutex loadMutex;
AZStd::unique_lock<AZStd::mutex> loadLock(loadMutex, AZStd::defer_lock_t());
while (m_pool->m_numJobsWaitingForExecution == 0)
{
m_jobsCV.wait(loadLock);
if (m_exitFlag == 1)
{
return;
}
}
if (GetJob(job))
{
ExecuteJob(job);
}
else if (TryToStealJob(job))
{
ExecuteJob(job);
}
}
}
// Called from different worker thread
bool StealJobs(Job& job, StealingWorker* victim)
{
if (victim == this)
{
assert(0 && "Trying to steal own jobs");
return false;
}
bool order = m_index < victim->m_index;
AZStd::lock_guard<AZStd::mutex> lock1(order ? m_lockJobs : victim->m_lockJobs);
AZStd::lock_guard<AZStd::mutex> lock2(order ? victim->m_lockJobs : m_lockJobs);
if (victim->m_jobs.empty())
{
return false;
}
int numJobs = (int)victim->m_jobs.size();
size_t stealUntil = numJobs - numJobs / 2;
Jobs::iterator begin = victim->m_jobs.begin();
Jobs::iterator end = victim->m_jobs.begin() + stealUntil;
m_jobs.insert(m_jobs.end(), begin, end);
victim->m_jobs.erase(begin, end);
return GetJobLockless(job);
}
// Called from any thread
void Submit(const Job& job)
{
AZStd::lock_guard<AZStd::mutex> lock(m_lockJobs);
m_jobs.push_back(job);
m_jobs.back().m_debugInitialThread = m_index;
m_jobsCV.notify_one();
}
// Called from any thread
void Submit(const Jobs& jobs)
{
const size_t numJobs = jobs.size();
AZStd::lock_guard<AZStd::mutex> lock(m_lockJobs);
m_jobs.insert(m_jobs.begin(), jobs.begin(), jobs.end());
for (size_t i = 0; i < numJobs; ++i)
{
m_jobs[i].m_debugInitialThread = m_index;
}
m_jobsCV.notify_one();
}
long NumJobsPending() const
{
AZStd::lock_guard<AZStd::mutex> lock(m_lockJobs);
return m_jobs.size();
}
// Called from main thread
void SignalExit()
{
CryInterlockedCompareExchange(&m_exitFlag, 1, 0);
}
void GetTraces(JobTraces& traces)
{
if (m_tracingEnabled)
{
m_traces.swap(traces);
}
}
private:
StealingThreadPool* m_pool;
AZStd::thread m_thread;
int m_index;
bool m_tracingEnabled;
int m_lastStartTime;
JobTraces m_traces;
Jobs m_jobs;
mutable AZStd::mutex m_lockJobs;
AZStd::condition_variable& m_jobsCV;
LONG m_exitFlag;
friend class StealingThreadPool;
};
// ---------------------------------------------------------------------------
StealingThreadPool::StealingThreadPool(int numThreads, bool enableTracing)
: m_numThreads(numThreads)
, m_numJobs(0)
, m_numJobsWaitingForExecution(0)
, m_enableTracing(enableTracing)
{
m_workers.resize(numThreads);
for (int i = 0; i < numThreads; ++i)
{
m_workers[i] = new StealingWorker(this, i, m_enableTracing, m_jobsCV);
}
}
StealingThreadPool::~StealingThreadPool()
{
WaitAllJobs();
size_t numThreads = m_workers.size();
for (size_t i = 0; i < numThreads; ++i)
{
m_workers[i]->SignalExit();
}
m_jobsCV.notify_all();
m_threadTraces.resize(numThreads);
for (size_t i = 0; i < numThreads; ++i)
{
m_workers[i]->GetTraces(m_threadTraces[i]);
}
}
void StealingThreadPool::Start()
{
int startTime = (int)GetTickCount();
size_t numThreads = m_workers.size();
for (int i = 0; i < numThreads; ++i)
{
m_workers[i]->Start(startTime);
}
}
void StealingThreadPool::WaitAllJobs()
{
AZStd::mutex loadMutex;
AZStd::unique_lock<AZStd::mutex> loadLock(loadMutex, AZStd::defer_lock_t());
while (m_numJobs > 0)
{
m_jobsCV.wait(loadLock);
}
}
// Called from any thread
void StealingThreadPool::Submit(const Job& job)
{
++m_numJobs;
++m_numJobsWaitingForExecution;
if (StealingWorker* worker = FindWorstWorker())
{
worker->Submit(job);
}
}
// Called from any thread
void StealingThreadPool::Submit(const Jobs& jobs)
{
m_numJobs += jobs.size();
m_numJobsWaitingForExecution += jobs.size();
if (StealingWorker* worker = FindWorstWorker())
{
worker->Submit(jobs);
}
}
JobGroup* StealingThreadPool::CreateJobGroup(JobFunc func, void* data)
{
return new JobGroup(this, func, data);
}
StealingWorker* StealingThreadPool::FindBestVictim(int exceptFor) const
{
int maxJobs = 0;
StealingWorker* bestVictim = 0;
for (size_t i = 0; i < m_workers.size(); ++i)
{
if (i == exceptFor)
{
continue;
}
StealingWorker* worker = m_workers[i];
long numJobs = worker->NumJobsPending();
if (numJobs > maxJobs)
{
maxJobs = numJobs;
bestVictim = worker;
}
}
return bestVictim;
}
StealingWorker* StealingThreadPool::FindWorstWorker() const
{
if (m_workers.empty())
{
return 0;
}
int minJobs = INT_MAX;
StealingWorker* worstWorker = m_workers[0];
for (size_t i = 0; i < m_workers.size(); ++i)
{
StealingWorker* worker = m_workers[i];
long numJobs = worker->NumJobsPending();
if (numJobs < minJobs)
{
minJobs = numJobs;
worstWorker = worker;
}
}
return worstWorker;
}
static bool WriteString(FILE* f, const char* str)
{
return fwrite(str, strlen(str), 1, f) == 1;
}
static int Interpolate(int a, int b, float phase)
{
return int(float(a) + float(b - a) * phase);
}
static int InterpolateColor(int c1, int c2, float phase)
{
const int r1 = (c1 & 0x0000ff);
const int g1 = (c1 & 0x00ff00) >> 8;
const int b1 = (c1 & 0xff0000) >> 16;
const int r2 = (c2 & 0x0000ff);
const int g2 = (c2 & 0x00ff00) >> 8;
const int b2 = (c2 & 0xff0000) >> 16;
const int r = min(255, max(0, Interpolate(r1, r2, phase)));
const int g = min(255, max(0, Interpolate(g1, g2, phase)));
const int b = min(255, max(0, Interpolate(b1, b2, phase)));
return r + (g << 8) + (b << 16);
}
static const int g_animColors[] = {
0xff0000, 0x0000ff, 0x00ff00,
0xffff00, 0xff00ff, 0x00ffff,
0xff8080, 0x8080ff, 0x80ff80,
0xffff80, 0xff80ff, 0x80ffff
};
static int ColorizeJobTrace(const ThreadUtils::JobTrace& trace)
{
const int numColors = sizeof(g_animColors) / sizeof(g_animColors[0]);
const int initialThread = trace.m_job.m_debugInitialThread;
const int index = initialThread % numColors;
const float brightness = aznumeric_cast<float>(pow(0.5f, initialThread / numColors));
return InterpolateColor(0, InterpolateColor(g_animColors[index], 0xffffff, 0.5f), brightness);
}
bool StealingThreadPool::SaveTracesGraph(const char* filename)
{
if (!m_enableTracing)
{
return false;
}
const float screenWidth = 1240.0f;
float duration = 0;
for (size_t t = 0; t < m_threadTraces.size(); ++t)
{
float threadDuration = 0;
const JobTraces& traces = m_threadTraces[t];
for (int i = 0; i < traces.size(); ++i)
{
threadDuration += traces[i].m_duration;
}
duration = max(threadDuration, duration);
}
const float padding = 10.0f;
const float rowHeight = 60.0f;
const float xScale = fabsf(duration) > FLT_EPSILON ? (screenWidth - padding * 2.0f) / duration : 1.0f;
const float width = screenWidth;
const float height = (m_threadTraces.size() + 0.5f) * rowHeight;
FILE* f = nullptr;
azfopen(&f, filename, "wt");
if (!f)
{
return false;
}
char buf[4096];
azsnprintf(buf, sizeof(buf),
"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
"<svg\n"
" xmlns:dc='http://purl.org/dc/elements/1.1/'\n"
" xmlns:cc='http://creativecommons.org/ns#'\n"
" xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'\n"
" xmlns:svg='http://www.w3.org/2000/svg'\n"
" xmlns='http://www.w3.org/2000/svg'\n"
" xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd'\n"
" xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape'\n"
" width='%f'\n"
" height='%f'\n"
" id='svg2'\n"
" version='1.1'\n"
" >\n",
width, height
);
if (!WriteString(f, buf))
{
return false;
}
for (size_t t = 0; t < m_threadTraces.size(); ++t)
{
float x = padding;
float y = rowHeight * 0.5f + rowHeight * t;
azsnprintf(buf, sizeof(buf),
" <text\n"
" xml:space='preserve'\n"
" style='font-size:40px;font-style:normal;font-weight:normal;line-height:125%%;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;font-family:Sans'\n"
" x='%f'\n"
" y='%f'\n"
" sodipodi:linespacing='125%%'><tspan sodipodi:role='line' x='%f' y='%f' style='font-size:12px;fill:#000000'>Thread %i</tspan></text>\n",
x, y, x, y, static_cast<int>(t + 1));
if (!WriteString(f, buf))
{
return false;
}
y += padding;
const ThreadUtils::JobTraces& traces = m_threadTraces[t];
for (int i = 0; i < traces.size(); ++i)
{
const float width2 = traces[i].m_duration * xScale;
const float height2 = rowHeight * 0.5f;
const int color = ColorizeJobTrace(traces[i]);
const int strokeColor = 0;
azsnprintf(buf, sizeof(buf),
" <rect\n"
" style='fill:#%06x;fill-rule:evenodd;stroke:#%06x;stroke-width:0.25px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1'\n"
" width='%f'\n"
" height='%f'\n"
" x='%f'\n"
" y='%f' />\n",
color, strokeColor, width2, height2, x, y);
if (!WriteString(f, buf))
{
return false;
}
x += width2;
}
y += rowHeight;
}
if (!WriteString(f, "\n</svg>\n"))
{
return false;
}
fclose(f);
return true;
}
// ---------------------------------------------------------------------------
void JobGroup::Process(JobGroup::GroupInfo* info)
{
info->m_job.Run();
long jobsLeft = --info->m_group->m_numJobsRunning;
assert(jobsLeft >= 0);
if (jobsLeft == 0)
{
info->m_group->m_finishJob.Run();
delete info->m_group;
}
}
JobGroup::JobGroup(StealingThreadPool* pool, JobFunc func, void* data)
: m_pool(pool)
, m_numJobsRunning(0)
, m_finishJob(func, data)
, m_submited(false)
{
}
void JobGroup::Submit()
{
if (m_submited)
{
assert(0);
return;
}
if (m_numJobsRunning == 0)
{
m_pool->Submit(m_finishJob);
return;
}
Jobs jobs;
jobs.resize(m_infos.size());
for (size_t i = 0; i < m_infos.size(); ++i)
{
jobs[i] = Job((JobFunc) & JobGroup::Process, &m_infos[i]);
}
m_pool->Submit(jobs);
}
void JobGroup::Add(JobFunc func, void* data)
{
if (m_submited)
{
assert(0);
return;
}
GroupInfo info;
info.m_job = Job(func, data);
info.m_group = this;
m_infos.push_back(info);
++m_numJobsRunning;
}
}
@@ -1,123 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_STEALINGTHREADPOOL_H
#define CRYINCLUDE_CRYCOMMONTOOLS_STEALINGTHREADPOOL_H
#pragma once
#include "ThreadUtils.h"
#include <AzCore/std/parallel/condition_variable.h>
#include <AzCore/std/parallel/atomic.h>
#include <BaseTypes.h>
#include <AzCore/Casting/numeric_cast.h>
#if AZ_TRAIT_OS_PLATFORM_APPLE
#include "AppleSpecific.h"
#endif
namespace ThreadUtils {
class StealingWorker;
class JobGroup;
// Simple stealing thread pool
class StealingThreadPool
{
public:
explicit StealingThreadPool(int numThreads, bool enableTracing = false);
~StealingThreadPool();
void Start();
void WaitAllJobs();
const std::vector<JobTraces>& Traces() const{ return m_threadTraces; }
bool SaveTracesGraph(const char* filename);
// Submits single independent job
template<class T>
void Submit(void(* jobFunc)(T*), T* data)
{
Submit(Job((JobFunc)jobFunc, data));
}
// Create a group of jobs. A group of jobs can be followed by one "finishing" job.
// It is a way to express dependencies between jobs.
template<class T>
JobGroup* CreateJobGroup(void(* jobFunc)(T*), T* data)
{
return CreateJobGroup((JobFunc)jobFunc, (void*)data);
}
uint GetNumThreads() const { return aznumeric_cast<uint>(m_numThreads); }
private:
StealingWorker* FindBestVictim(int exceptFor) const;
StealingWorker* FindWorstWorker() const;
void Submit(const Job& job);
void Submit(const Jobs& jobs);
JobGroup* CreateJobGroup(JobFunc, void* data);
size_t m_numThreads;
typedef std::vector<class StealingWorker*> ThreadWorkers;
ThreadWorkers m_workers;
bool m_enableTracing;
std::vector<JobTraces> m_threadTraces;
AZStd::atomic_long m_numJobsWaitingForExecution;
AZStd::atomic_long m_numJobs;
AZStd::condition_variable m_jobsCV;
AZStd::condition_variable m_jobFinishedCV;
friend class JobGroup;
friend class StealingWorker;
};
// JobGroup represents a group of jobs that can be followed by one "finishing"
// job. This is a way to express dependencies between jobs.
class JobGroup
{
public:
template<class T>
void Add(void(* jobFunc)(T*), T* data)
{
Add((JobFunc)jobFunc, data);
}
// Submits group to thread pool
void Submit();
private:
struct GroupInfo
{
Job m_job;
JobGroup* m_group;
};
typedef std::vector<GroupInfo> GroupInfos;
JobGroup(StealingThreadPool* pool, JobFunc func, void* data);
static void Process(JobGroup::GroupInfo* job);
void Add(JobFunc func, void* data);
volatile LONG m_numJobsRunning;
StealingThreadPool* m_pool;
GroupInfos m_infos;
Job m_finishJob;
bool m_submited;
friend class StealingThreadPool;
};
}
#endif // CRYINCLUDE_CRYCOMMONTOOLS_STEALINGTHREADPOOL_H
-59
View File
@@ -1,59 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_SUFFIXUTIL_H
#define CRYINCLUDE_CRYCOMMONTOOLS_SUFFIXUTIL_H
#pragma once
// convenience class to work with suffixes in filenames, like in like dirt_ddn.dds
class SuffixUtil
{
public:
// filename allowed to have many suffixes (e.g. "test_ddn_bump.dds" has "bump" and "ddn"
// as suffixes (assuming that suffixSeparator is '_').
// suffixes in file extension are also considered (e.g. "test_abc.my_data" has "abc" and "data" as suffixes)
// suffixes in path part are also considered. if it's not what you want - remove path before calling this function.
// comparison is case insensitive
static bool HasSuffix(const char* const filename, const char suffixSeparator, const char* const suffix)
{
assert(filename);
assert(suffix && suffix[0]);
const size_t suffixLen = strlen(suffix);
for (const char* p = filename; *p; ++p)
{
if (p[0] != suffixSeparator)
{
continue;
}
if (azmemicmp(&p[1], suffix, suffixLen) != 0)
{
continue;
}
const char c = p[1 + suffixLen];
if ((c == 0) || (c == suffixSeparator) || (c == '.'))
{
return true;
}
}
return false;
}
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_SUFFIXUTIL_H
@@ -1,442 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include <platform.h>
#include <stdio.h>
#include <assert.h> // assert()
#include <math.h> // floorf()
#include "SummedAreaFilterKernel.h" // CSummedAreaFilterKernel
CSummedAreaFilterKernel::CSummedAreaFilterKernel()
{
m_eFilterType = eEmpty;
m_fCorrectionFactor = 0.0f;
}
// http://www.sixsigma.de/english/sixsigma/6s_e_gauss.htm
bool CSummedAreaFilterKernel::CreateFromGauss(const unsigned long indwSize)
{
assert(indwSize > 2);
int iInit = 0;
if (!Alloc(indwSize, indwSize, &iInit))
{
return false;
}
for (unsigned long y = 0; y < indwSize; y++)
{
for (unsigned long x = 0; x < indwSize; x++)
{
float fX = (float)(x) - (float)(indwSize) * 0.5f;
float fY = (float)(y) - (float)(indwSize) * 0.5f;
double r1 = sqrt(fX * fX + fY * fY) / (indwSize * 0.5 - 2.0);
if (r1 > 1)
{
m_pData[y * indwSize + x] = 0;
}
else
{
double fSigma = 1.0 / 3.0; // we aim for 6*sigma = 99,99996 of all values
double fWeight = exp(-r1 * r1 / (2 * fSigma * fSigma));
fWeight -= (1.0 - 0.9999996);
m_pData[y * indwSize + x] = (int)(255.0f * fWeight);
}
}
}
m_eFilterType = eGaussBlur;
_SumUpTableAndNormalize();
return true;
}
// create summed area table
void CSummedAreaFilterKernel::_SumUpTableAndNormalize()
{
for (unsigned long y = 0; y < m_dwHeight; y++)
{
int iFromLeft = 0;
for (unsigned long x = 0; x < m_dwWidth; x++)
{
iFromLeft += m_pData[y * m_dwWidth + x];
if (y != 0)
{
m_pData[y * m_dwWidth + x] = iFromLeft + m_pData[(y - 1) * m_dwWidth + x];
}
else
{
m_pData[y * m_dwWidth + x] = iFromLeft;
}
}
}
m_fCorrectionFactor = 1.0f / ((float)m_pData[m_dwHeight * m_dwWidth - 1]);
}
// windows size 16x16 = radius 8
bool CSummedAreaFilterKernel::CreateFromSincCalc(const unsigned long indwSize)
{
assert(indwSize > 2);
int iInit = 0;
if (!Alloc(indwSize, indwSize, &iInit))
{
return false;
}
for (unsigned long y = 0; y < indwSize; y++)
{
for (unsigned long x = 0; x < indwSize; x++)
{
float fX = (float)(x - indwSize * 0.5f);
float fY = (float)(y - indwSize * 0.5f);
float r1 = sqrtf(fX * fX + fY * fY) / (indwSize * 0.5f - 2.0f);
if (r1 > 1.0f)
{
m_pData[y * indwSize + x] = 0;
}
else
{
r1 *= 3.1415926535897932384626433832795f;
float r2 = r1 * 8.0f;
// http://home.no.net/dmaurer/~dersch/interpolator/interpolator.html
// weight = [ sin(x*pi) / (x*pi) ] * [ sin(x*pi / 8) / (x*pi/8) ]
// http://www.binbooks.com/books/photo/i/l/57186AF8DE
// sinc(x) = sin(pi * x) / (pi * x)
// L8interp(x) = sinc(x) * sinc(x/8) if abs(x) <= 8
// = 0 if abs(x) > 8
float fWeight = (sinf(r1) * sinf(r2)) / (r1 * r2);
m_pData[y * indwSize + x] = (int)(255.0f * fWeight);
}
}
}
m_eFilterType = eSinc;
_SumUpTableAndNormalize();
return true;
}
bool CSummedAreaFilterKernel::CreateFromRAWFile(const char* filename, const unsigned long indwSize, const int iniMidValue)
{
assert(iniMidValue >= 0 && iniMidValue < 255);
int iInit = 0;
if (!Alloc(indwSize, indwSize, &iInit))
{
return false;
}
FILE* in = fopen(filename, "rb");
if (!in)
{
return false;
}
for (unsigned long y = 0; y < m_dwHeight; y++)
{
for (unsigned long x = 0; x < m_dwWidth; x++)
{
unsigned char val;
if (fread(&val, 1, 1, in) != 1)
{
fclose(in);
return false;
}
m_pData[y * m_dwWidth + x] = (int)val - iniMidValue;
}
}
fclose(in);
m_eFilterType = eRAW;
_SumUpTableAndNormalize();
return true;
}
std::string CSummedAreaFilterKernel::GetInfoString(void) const
{
std::string sRet = "FilterKernel(";
switch (m_eFilterType)
{
case eEmpty:
sRet += "Empty";
break;
case eSinc:
sRet += "Sinc16x16";
break;
case eRAW:
sRet += "RAW";
break;
case eGaussBlur:
sRet += "GaussBlur";
break;
case eGaussSharp:
sRet += "GaussSharp";
break;
default:
assert(0);
}
sRet += ")";
return(sRet);
}
float CSummedAreaFilterKernel::GetAreaNonAA(float infAx, float infAy, float infDx, float infDy) const
{
assert(m_eFilterType != eEmpty);
int ax = (int)floorf(infAx * 127.5f + 127.5f);
int ay = (int)floorf(infAy * 127.5f + 127.5f);
int dx = (int)floorf(infDx * 127.5f + 127.5f);
int dy = (int)floorf(infDy * 127.5f + 127.5f);
if (ax < 0)
{
ax = 0;
}
else if (ax > 255)
{
ax = 255;
}
if (dx < 0)
{
dx = 0;
}
else if (dx > 255)
{
dx = 255;
}
if (ay < 0)
{
ay = 0;
}
else if (ay > 255)
{
ay = 255;
}
if (dy < 0)
{
dy = 0;
}
else if (dy > 255)
{
dy = 255;
}
unsigned long area = m_pData[dy * m_dwWidth + dx] - m_pData[dy * m_dwWidth + ax] - m_pData[ay * m_dwWidth + dx] + m_pData[ay * m_dwWidth + ax];
return(m_fCorrectionFactor * (float)area);
}
// optimizable
float CSummedAreaFilterKernel::GetAreaAA(float infAx, float infAy, float infDx, float infDy) const
{
assert(m_eFilterType != eEmpty);
infAx = infAx * 127.5f + 127.5f;
infAy = infAy * 127.5f + 127.5f;
infDx = infDx * 127.5f + 127.5f;
infDy = infDy * 127.5f + 127.5f;
float fSum = _GetBilinearFiltered(infDx, infDy)
- _GetBilinearFiltered(infAx, infDy)
- _GetBilinearFiltered(infDx, infAy)
+ _GetBilinearFiltered(infAx, infAy);
return(fSum * m_fCorrectionFactor);
}
float CSummedAreaFilterKernel::_GetBilinearFiltered(const float infX, const float infY) const
{
float fIX = floorf(infX), fIY = floorf(infY);
float fFX = infX - fIX, fFY = infY - fIY;
int iX = (int)fIX, iY = (int)fIY;
if (iX < 0)
{
iX = 0;
}
else if (iX > 254)
{
iX = 254;
}
if (iY < 0)
{
iY = 0;
}
else if (iY > 254)
{
iY = 254;
}
float fArea = m_pData[ iY * m_dwWidth + iX ] * ((1.0f - fFX) * (1.0f - fFY)) // left top
+ m_pData[ iY * m_dwWidth + iX + 1 ] * ((fFX) * (1.0f - fFY)) // right top
+ m_pData[(iY + 1) * m_dwWidth + iX ] * ((1.0f - fFX) * (fFY)) // left bottom
+ m_pData[ iY * m_dwWidth + iX + 257] * ((fFX) * (fFY)); // right bottom
return(fArea);
}
bool CSummedAreaFilterKernel::CreateWeightFilter(CSimpleBitmap<float>& outFilter, const float infX, const float infY,
const float infWeight, const float infR) const
{
assert(infX >= 0.0f);
assert(infX < 1.0f);
assert(infY >= 0.0f);
assert(infY < 1.0f);
assert(infWeight >= 0.0f);
assert(infR > 0.0f);
float fLeftTop = ceilf(infR);
int iSide = 2 * (int)fLeftTop + 1;
float fInit = 0.0f;
if (!outFilter.Alloc(iSide, iSide, &fInit))
{
return false;
}
AddWeights(outFilter, infX + fLeftTop, infY + fLeftTop, infWeight, infR);
return true;
}
bool CSummedAreaFilterKernel::CreateWeightFilterBlock(CSimpleBitmap<float>& outFilter, const unsigned long indwSideLength,
const float infR) const
{
assert(indwSideLength >= 0);
assert(infR > 0.0f);
float fLeftTop = ceilf(infR);
int iSide = 2 * (int)fLeftTop + 1;
float fInit = 0.0f;
if (!outFilter.Alloc(iSide, iSide, &fInit))
{
return false;
}
float fStep = 1.0f / (float)indwSideLength;
float fHalf = fStep * 0.5f;
float fWeight = fStep * fStep;
for (float y = fHalf; y < 1.0f; y += fStep)
{
for (float x = fHalf; x < 1.0f; x += fStep)
{
AddWeights(outFilter, x + fLeftTop, y + fLeftTop, fWeight, infR);
}
}
// check
#ifdef _DEBUG
float fSum = 0.0f;
for (int y = 0; y < iSide; y++)
{
for (int x = 0; x < iSide; x++)
{
float f;
outFilter.Get(x, y, f);
fSum += f;
}
}
assert(fSum >= 0.98f);
assert(fSum <= 1.02f);
#endif
return true;
}
void CSummedAreaFilterKernel::AddWeights(CSimpleBitmap<float>& inoutFilter, const float infX, const float infY,
const float infWeight, const float infR) const
{
assert(infWeight >= 0.0f);
assert(infR > 0.0f);
if (infWeight <= 0.0f)
{
return;
}
float fInvR = 1.0f / infR;
float sx = floorf(infX - infR);
float sy = floorf(infY - infR);
int iax = (int)sx;
int iay = (int)sy;
int iex = (int)ceilf(infX + infR);
int iey = (int)ceilf(infY + infR);
float x, y;
int ix, iy;
for (iy = iay, y = (sy - infY) * fInvR; iy <= iey; iy++, y += fInvR)
{
for (ix = iax, x = (sx - infX) * fInvR; ix <= iex; ix++, x += fInvR)
{
float fArea = GetAreaAA(x, y, x + fInvR, y + fInvR); // better quality
// float fArea=m_Filter.GetAreaNonAA(x,y,x+fInvR,y+fInvR); // faster
// assert(fArea<=1.0f); // may be wrong if we use sharpening filter
float fOldVal;
inoutFilter.Get(ix, iy, fOldVal);
inoutFilter.Set(ix, iy, fOldVal + fArea * infWeight);
}
}
}
@@ -1,112 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#pragma once
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_SUMMEDAREAFILTERKERNEL_H
#define CRYINCLUDE_CRYCOMMONTOOLS_SUMMEDAREAFILTERKERNEL_H
#include <string> // STL string
#include "SimpleBitmap.h" // SimpleBitmap<>
// squared of any size (summed area tables limit the size and/or values)
// normalized(sum=1)
// optimized for high quality, not speed
// for faster filter kernels extract the neccessary size and use this 1:1
// based on summed area tables
class CSummedAreaFilterKernel
: public CSimpleBitmap<int>
{
public:
//! constructor init is eEmpty
CSummedAreaFilterKernel();
//! load 8 bit photoshop 256x256 raw image - slow
//! typical filtersize for a gaussian filter kernel is 1.44
//! /param iniMidValue [0..255[ this enables sharpening - sharpening may expand the result range
bool CreateFromRAWFile(const char* filename, const unsigned long indwSize = 256, const int iniMidValue = 0);
//! sharpest possible result - filter diameter size has to be 16*pixelsize (256 samples per pixel)
//! theory: http://home.no.net/dmaurer/~dersch/interpolator/interpolator.html
//! /param indwSize >2
bool CreateFromSincCalc(const unsigned long indwSize = 256);
//! shttp://www.sixsigma.de/english/sixsigma/6s_e_gauss.htm
//! /param indwSize >2
bool CreateFromGauss(const unsigned long indwSize = 256);
//! optimizable O(k*1) with high k
//! bokeh is in the range ([-1..1],[-1..1])
//! return normalized result
float GetAreaAA(float infAx, float infAy, float infDx, float infDy) const;
//! O(k*1) with low k
//! bokeh is in the range ([-1..1],[-1..1])
//! return normalized result
float GetAreaNonAA(float infAx, float infAy, float infDx, float infDy) const;
//!
//! /return e.g. "FilterKernel(Sinc16x16)"
std::string GetInfoString(void) const;
//! /param infX [0..1[
//! /param infY [0..1[
//! /param infWeight [0..[
//! /param infR >0, radius
bool CreateWeightFilter(CSimpleBitmap<float>& outFilter, const float infX, const float infY,
const float infWeight, const float infR) const;
//! weight for the whole block is 1.0
//! /param indwSideLength [1,..[ e.g. 3 for 3x3 block
//! /param infR >0, radius
bool CreateWeightFilterBlock(CSimpleBitmap<float>& outFilter, const unsigned long indwSideLength, const float infR) const;
//! with user filter kernel
//! /param infX
//! /param infY
//! /param infWeight [0..[
//! /param infR >0, radius
void AddWeights(CSimpleBitmap<float>& inoutFilter, const float infX, const float infY,
const float infWeight, const float infR) const;
private: // --------------------------------------------------------------------
enum EFilterState
{
eEmpty, //!< after calling constructor
eSinc, //!< from CreateFromSincCalc
eRAW, //!< from CreateFromRAWFile
eGaussBlur, //!< from CreateFromGauss
eDisc, //!< not implemented
eGaussSharp //!< not implemented
};
EFilterState m_eFilterType; //!< for error checks and GetInfoString()
float m_fCorrectionFactor; //!< to get the normalized (whole kernel has sum of 1) result
//! optimizable
//! bokeh is in the range ([0..255],[0..255])
//! /param infX
//! /param infY
//! /return not normalized result
float _GetBilinearFiltered(const float infX, const float infY) const;
//! sum the stored values in the bitmap together
//! calculate m_fCorrectionFactor
void _SumUpTableAndNormalize(void);
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_SUMMEDAREAFILTERKERNEL_H
@@ -1,129 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Opens a temporary file for read only access, where the file could be
// located in a zip or pak file. Note that if the file specified
// already exists it does not delete it when finished.
#include "TempFilePakExtraction.h"
#include "FileUtil.h"
#include "PathHelpers.h"
#include "IPakSystem.h"
TempFilePakExtraction::TempFilePakExtraction(const char* filename, const char* tempPath, IPakSystem* pPakSystem)
: m_strOriginalFileName(filename)
, m_strTempFileName(filename)
{
if (!pPakSystem || !tempPath)
{
return;
}
{
FILE* fileOnDisk = nullptr;
azfopen(&fileOnDisk, m_strOriginalFileName.c_str(), "rb");
if (fileOnDisk)
{
fclose(fileOnDisk);
return;
}
}
// Choose the name for the temporary file.
string tempFullFileName;
{
uint32 tempNumber = 0;
{
LARGE_INTEGER performanceCount;
if (QueryPerformanceCounter(&performanceCount))
{
tempNumber = performanceCount.u.LowPart;
}
}
string tempName;
{
// CryEngine's pak system supports filenames in format "@pakFilename|fileInPak",
// so let's handle such cases by using fileInPak part of the filename.
const size_t pos = m_strOriginalFileName.find_last_of('|');
if (pos != string::npos)
{
tempName = m_strOriginalFileName.substr(pos + 1, string::npos);
if (tempName.empty())
{
tempName = "BadFilenameSyntax";
}
}
else
{
tempName = m_strOriginalFileName;
}
tempName = PathHelpers::GetFilename(tempName);
}
int tryCount = 2000;
while (--tryCount >= 0)
{
tempFullFileName.Format("%sRC%04x_%s", tempPath, (tempNumber & 0xFFFF), tempName.c_str());
if (!FileUtil::FileExists(tempFullFileName.c_str()))
{
FILE* f = nullptr;
azfopen(&f, tempFullFileName.c_str(), "wb");
if (f)
{
fclose(f);
break;
}
}
tempFullFileName.clear();
++tempNumber;
}
if (tempFullFileName.empty())
{
return;
}
}
if (pPakSystem->ExtractNoOverwrite(m_strOriginalFileName.c_str(), tempFullFileName.c_str()))
{
m_strTempFileName = tempFullFileName;
AZ::IO::SystemFile::SetWritable(m_strTempFileName.c_str(), false);
}
else
{
AZ::IO::LocalFileIO().Remove(tempFullFileName.c_str());
}
}
TempFilePakExtraction::~TempFilePakExtraction()
{
if (HasTempFile())
{
#if defined(AZ_PLATFORM_WINDOWS)
SetFileAttributesA(m_strTempFileName.c_str(), FILE_ATTRIBUTE_ARCHIVE);
#endif
AZ::IO::LocalFileIO().Remove(m_strTempFileName.c_str());
}
}
bool TempFilePakExtraction::HasTempFile() const
{
return (m_strOriginalFileName != m_strTempFileName);
}
@@ -1,50 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Opens a temporary file for read only access, where the file could be
// located in a zip or pak file. Note that if the file specified
// already exists it does not delete it when finished.
#ifndef CRYINCLUDE_CRYCOMMONTOOLS_TEMPFILEPAKEXTRACTION_H
#define CRYINCLUDE_CRYCOMMONTOOLS_TEMPFILEPAKEXTRACTION_H
#pragma once
#include <platform.h>
struct IPakSystem;
class TempFilePakExtraction
{
public:
TempFilePakExtraction(const char* filename, const char* tempPath, IPakSystem* pPakSystem);
~TempFilePakExtraction();
const string& GetTempName() const
{
return m_strTempFileName;
}
const string& GetOriginalName() const
{
return m_strOriginalFileName;
}
bool HasTempFile() const;
private:
string m_strTempFileName;
string m_strOriginalFileName;
};
#endif // CRYINCLUDE_CRYCOMMONTOOLS_TEMPFILEPAKEXTRACTION_H
-171
View File
@@ -1,171 +0,0 @@
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include <platform.h>
#include "ThreadUtils.h"
#include <AzCore/std/parallel/thread.h>
#include <AzCore/std/bind/bind.h>
#include <AzCore/std/parallel/lock.h>
#include <CryAssert.h>
namespace ThreadUtils
{
class SimpleWorker
{
public:
SimpleWorker(SimpleThreadPool* pool, int index, bool trace)
: m_pool(pool)
, m_index(index)
, m_trace(trace)
{
}
void Start(int startTime)
{
m_lastStartTime = startTime;
m_handle = AZStd::thread(AZStd::bind(SimpleWorker::ThreadFunc, (void*)this));
}
static unsigned int __stdcall ThreadFunc(void* param)
{
SimpleWorker* self = (SimpleWorker*)(param);
self->Work();
return 0;
}
void ExecuteJob(Job& job)
{
job.Run();
if (m_trace)
{
int time = (int)GetTickCount();
JobTrace trace;
trace.m_job = job;
trace.m_duration = time - m_lastStartTime;
m_traces.push_back(trace);
m_lastStartTime = time;
}
}
void Work()
{
Job job;
for (;; )
{
if (m_pool->GetJob(job, m_index))
{
ExecuteJob(job);
}
else
{
return;
}
}
}
// Called from main thread
void Join(JobTraces& traces)
{
if(m_handle.joinable())
{
m_handle.join();
}
if (m_trace)
{
m_traces.swap(traces);
}
}
private:
SimpleThreadPool* m_pool;
AZStd::thread m_handle;
int m_index;
bool m_trace;
int m_lastStartTime;
JobTraces m_traces;
friend SimpleThreadPool;
};
// ---------------------------------------------------------------------------
SimpleThreadPool::SimpleThreadPool(bool trace)
: m_trace(trace)
, m_started(false)
, m_numProcessedJobs(0)
{
}
SimpleThreadPool::~SimpleThreadPool()
{
WaitAllJobs();
}
void SimpleThreadPool::Start(int numThreads)
{
m_workers.resize(numThreads);
for (int i = 0; i < numThreads; ++i)
{
m_workers[i] = new SimpleWorker(this, i, m_trace);
}
m_started = true;
int startTime = (int)GetTickCount();
for (int i = 0; i < numThreads; ++i)
{
m_workers[i]->Start(startTime);
}
}
void SimpleThreadPool::WaitAllJobs()
{
size_t numThreads = m_workers.size();
m_threadTraces.resize(numThreads);
for (size_t i = 0; i < numThreads; ++i)
{
m_workers[i]->Join(m_threadTraces[i]);
}
for (size_t i = 0; i < numThreads; ++i)
{
delete m_workers[i];
}
m_workers.clear();
m_started = false;
}
void SimpleThreadPool::Submit(const Job& job)
{
assert(!m_started);
m_jobs.push_back(job);
}
bool SimpleThreadPool::GetJob(Job& job, [[maybe_unused]] int threadIndex)
{
AZStd::lock_guard<AZStd::mutex> lock(m_lockJobs);
if (m_numProcessedJobs >= m_jobs.size())
{
return false;
}
job = m_jobs[m_numProcessedJobs];
++m_numProcessedJobs;
return true;
}
}

Some files were not shown because too many files have changed in this diff Show More