Merge branch 'master' of /home/noisy3/OpenFOAM/OpenFOAM-dev

This commit is contained in:
mattijs
2009-02-13 09:01:17 +00:00
524 changed files with 7768 additions and 3231 deletions

View File

@ -0,0 +1,3 @@
buoyantBoussinesqFoam.C
EXE = $(FOAM_APPBIN)/buoyantBoussinesqFoam

View File

@ -0,0 +1,12 @@
EXE_INC = \
-I$(LIB_SRC)/finiteVolume/lnInclude \
-I$(LIB_SRC)/turbulenceModels \
-I$(LIB_SRC)/turbulenceModels/incompressible/RAS/lnInclude \
-I$(LIB_SRC)/transportModels \
-I$(LIB_SRC)/transportModels/incompressible/singlePhaseTransportModel
EXE_LIBS = \
-lfiniteVolume \
-lmeshTools \
-lincompressibleRASModels \
-lincompressibleTransportModels

View File

@ -0,0 +1,18 @@
{
volScalarField kappaEff
(
"kappaEff",
turbulence->nu() + turbulence->nut()/Prt
);
fvScalarMatrix TEqn
(
fvm::ddt(T)
+ fvm::div(phi, T)
- fvm::laplacian(kappaEff, T)
);
TEqn.relax();
TEqn.solve();
}

View File

@ -0,0 +1,23 @@
// Solve the momentum equation
tmp<fvVectorMatrix> UEqn
(
fvm::ddt(U)
+ fvm::div(phi, U)
+ turbulence->divDevReff(U)
);
UEqn().relax();
solve
(
UEqn()
==
-fvc::reconstruct
(
(
fvc::snGrad(pd)
- betaghf*fvc::snGrad(T)
) * mesh.magSf()
)
);

View File

@ -0,0 +1,108 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2009 OpenCFD Ltd.
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Application
buoyantBoussinesqSimpleFoam
Description
Steady-state solver for buoyant, turbulent flow of incompressible fluids
Uses the Boussinesq approximation:
\f[
rho_{eff} = 1 - beta(T - T_{ref})
\f]
where:
\f$ rho_{eff} \f$ = the effective (driving) density
beta = thermal expansion coefficient [1/K]
T = temperature [K]
\f$ T_{ref} \f$ = reference temperature [K]
Valid when:
\f[
rho_{eff} << 1
\f]
\*---------------------------------------------------------------------------*/
#include "fvCFD.H"
#include "singlePhaseTransportModel.H"
#include "RASModel.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
int main(int argc, char *argv[])
{
# include "setRootCase.H"
# include "createTime.H"
# include "createMesh.H"
# include "readEnvironmentalProperties.H"
# include "createFields.H"
# include "initContinuityErrs.H"
# include "readTimeControls.H"
# include "CourantNo.H"
# include "setInitialDeltaT.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Info<< "\nStarting time loop\n" << endl;
for (runTime++; !runTime.end(); runTime++)
{
Info<< "Time = " << runTime.timeName() << nl << endl;
# include "readTimeControls.H"
# include "readPISOControls.H"
# include "CourantNo.H"
# include "setDeltaT.H"
# include "UEqn.H"
// --- PISO loop
for (int corr=0; corr<nCorr; corr++)
{
# include "TEqn.H"
# include "pdEqn.H"
}
turbulence->correct();
if (runTime.write())
{
# include "writeAdditionalFields.H"
}
Info<< "ExecutionTime = " << runTime.elapsedCpuTime() << " s"
<< " ClockTime = " << runTime.elapsedClockTime() << " s"
<< nl << endl;
}
Info<< "End\n" << endl;
return 0;
}
// ************************************************************************* //

View File

@ -0,0 +1,67 @@
Info<< "Reading thermophysical properties\n" << endl;
Info<< "Reading field T\n" << endl;
volScalarField T
(
IOobject
(
"T",
runTime.timeName(),
mesh,
IOobject::MUST_READ,
IOobject::AUTO_WRITE
),
mesh
);
// kinematic pd
Info<< "Reading field pd\n" << endl;
volScalarField pd
(
IOobject
(
"pd",
runTime.timeName(),
mesh,
IOobject::MUST_READ,
IOobject::AUTO_WRITE
),
mesh
);
Info<< "Reading field U\n" << endl;
volVectorField U
(
IOobject
(
"U",
runTime.timeName(),
mesh,
IOobject::MUST_READ,
IOobject::AUTO_WRITE
),
mesh
);
# include "createPhi.H"
# include "readTransportProperties.H"
Info<< "Creating turbulence model\n" << endl;
autoPtr<incompressible::RASModel> turbulence
(
incompressible::RASModel::New(U, phi, laminarTransport)
);
Info<< "Calculating field beta*(g.h)\n" << endl;
surfaceScalarField betaghf("betagh", beta*(g & mesh.Cf()));
label pdRefCell = 0;
scalar pdRefValue = 0.0;
setRefCell
(
pd,
mesh.solutionDict().subDict("SIMPLE"),
pdRefCell,
pdRefValue
);

View File

@ -0,0 +1,42 @@
{
volScalarField rUA("rUA", 1.0/UEqn().A());
surfaceScalarField rUAf("(1|A(U))", fvc::interpolate(rUA));
U = rUA*UEqn().H();
UEqn.clear();
surfaceScalarField phiU
(
(fvc::interpolate(U) & mesh.Sf())
+ fvc::ddtPhiCorr(rUA, U, phi)
);
phi = phiU + betaghf*fvc::snGrad(T)*rUAf*mesh.magSf();
for (int nonOrth=0; nonOrth<=nNonOrthCorr; nonOrth++)
{
fvScalarMatrix pdEqn
(
fvm::laplacian(rUAf, pd) == fvc::div(phi)
);
if (corr == nCorr-1 && nonOrth == nNonOrthCorr)
{
pdEqn.solve(mesh.solver(pd.name() + "Final"));
}
else
{
pdEqn.solve(mesh.solver(pd.name()));
}
if (nonOrth == nNonOrthCorr)
{
phi += pdEqn.flux();
}
}
U -= rUA*fvc::reconstruct((phi - phiU)/rUAf);
U.correctBoundaryConditions();
#include "continuityErrs.H"
}

View File

@ -0,0 +1,13 @@
singlePhaseTransportModel laminarTransport(U, phi);
// thermal expansion coefficient [1/K]
dimensionedScalar beta(laminarTransport.lookup("beta"));
// reference temperature [K]
dimensionedScalar TRef(laminarTransport.lookup("TRef"));
// reference kinematic pressure [m2/s2]
dimensionedScalar pRef(laminarTransport.lookup("pRef"));
// turbulent Prandtl number
dimensionedScalar Prt(laminarTransport.lookup("Prt"));

View File

@ -0,0 +1,29 @@
{
volScalarField rhoEff
(
IOobject
(
"rhoEff",
runTime.timeName(),
mesh,
IOobject::NO_READ,
IOobject::AUTO_WRITE
),
1.0 - beta*(T - TRef)
);
rhoEff.write();
volScalarField p
(
IOobject
(
"p",
runTime.timeName(),
mesh,
IOobject::NO_READ,
IOobject::AUTO_WRITE
),
pd + rhoEff*(g & mesh.C()) + pRef
);
p.write();
}

View File

@ -47,6 +47,7 @@ int main(int argc, char *argv[])
# include "createMesh.H" # include "createMesh.H"
# include "readEnvironmentalProperties.H" # include "readEnvironmentalProperties.H"
# include "createFields.H" # include "createFields.H"
# include "createRadiationModel.H"
# include "initContinuityErrs.H" # include "initContinuityErrs.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

View File

@ -1,9 +0,0 @@
// check convergence
if (maxResidual < convergenceCriterion)
{
Info<< "reached convergence criterion: " << convergenceCriterion << endl;
runTime.writeAndEnd();
Info<< "latestTime = " << runTime.timeName() << endl;
}

View File

@ -1,97 +0,0 @@
Info<< "Reading thermophysical properties\n" << endl;
autoPtr<basicThermo> thermo
(
basicThermo::New(mesh)
);
volScalarField rho
(
IOobject
(
"rho",
runTime.timeName(),
mesh,
IOobject::NO_READ,
IOobject::NO_WRITE
),
thermo->rho()
);
volScalarField& p = thermo->p();
volScalarField& h = thermo->h();
const volScalarField& T = thermo->T();
Info<< "Reading field U\n" << endl;
volVectorField U
(
IOobject
(
"U",
runTime.timeName(),
mesh,
IOobject::MUST_READ,
IOobject::AUTO_WRITE
),
mesh
);
# include "compressibleCreatePhi.H"
Info<< "Creating turbulence model\n" << endl;
autoPtr<compressible::RASModel> turbulence
(
compressible::RASModel::New
(
rho,
U,
phi,
thermo()
)
);
Info<< "Calculating field g.h\n" << endl;
volScalarField gh("gh", g & mesh.C());
surfaceScalarField ghf("gh", g & mesh.Cf());
dimensionedScalar pRef("pRef", p.dimensions(), thermo->lookup("pRef"));
Info<< "Creating field pd\n" << endl;
volScalarField pd
(
IOobject
(
"pd",
runTime.timeName(),
mesh,
IOobject::MUST_READ,
IOobject::AUTO_WRITE
),
mesh
);
p = pd + rho*gh + pRef;
thermo->correct();
label pdRefCell = 0;
scalar pdRefValue = 0.0;
setRefCell
(
pd,
mesh.solutionDict().subDict("SIMPLE"),
pdRefCell,
pdRefValue
);
Info<< "Creating radiation model\n" << endl;
autoPtr<radiation::radiationModel> radiation
(
radiation::radiationModel::New(T)
);
dimensionedScalar initialMass = fvc::domainIntegrate(rho);

View File

@ -0,0 +1,5 @@
Info<< "Creating radiation model\n" << endl;
autoPtr<radiation::radiationModel> radiation
(
radiation::radiationModel::New(thermo->T())
);

View File

@ -1,7 +0,0 @@
// initialize values for convergence checks
scalar eqnResidual = 1, maxResidual = 0;
scalar convergenceCriterion = 0;
simple.readIfPresent("convergence", convergenceCriterion);

View File

@ -2,7 +2,7 @@
========= | ========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | \\ / O peration |
\\ / A nd | Copyright (C) 1991-2008 OpenCFD Ltd. \\ / A nd | Copyright (C) 1991-2009 OpenCFD Ltd.
\\/ M anipulation | \\/ M anipulation |
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
License License

View File

@ -2,7 +2,7 @@
========= | ========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | \\ / O peration |
\\ / A nd | Copyright (C) 1991-2008 OpenCFD Ltd. \\ / A nd | Copyright (C) 1991-2009 OpenCFD Ltd.
\\/ M anipulation | \\/ M anipulation |
------------------------------------------------------------------------------- -------------------------------------------------------------------------------
License License

View File

@ -12,6 +12,6 @@
thermo.correct(); thermo.correct();
Info<< "Min/max T:" << min(thermo.T()) << ' ' << max(thermo.T()) Info<< "Min/max T:" << min(thermo.T()).value() << ' '
<< endl; << max(thermo.T()).value() << endl;
} }

View File

@ -52,27 +52,47 @@ int main(int argc, char *argv[])
list1 = -1; list1 = -1;
list1.print(Info); list1.print(Info);
Info<< "\ntest zero\n";
list1 = 0;
list1.print(Info);
Info<< "\ntest set() with default argument (max_value)\n";
list1.set(3);
list1.print(Info);
Info<< "\ntest assign between references\n"; Info<< "\ntest assign between references\n";
list1[2] = 3; list1[2] = 3;
list1[4] = list1[2]; list1[4] = list1[2];
list1.print(Info); list1.print(Info);
Info<< "\ntest assign between references, with chaining\n"; Info<< "\ntest assign between references, with chaining\n";
list1[4] = list1[2] = 1; list1[0] = list1[4] = 1;
list1.print(Info);
Info<< "\ntest assign between references, with chaining and auto-vivify\n";
list1[1] = list1[8] = list1[10] = list1[14] = 2;
list1.print(Info); list1.print(Info);
{ {
const PackedList<3>& constLst = list1; const PackedList<3>& constLst = list1;
Info<< "\ntest operator[] const with out-of-range index\n"; Info<< "\ntest operator[] const with out-of-range index\n";
constLst.print(Info); constLst.print(Info);
if (!constLst[20]) if (constLst[20])
{
Info<< "[20] is true (unexpected)\n";
}
else
{ {
Info<< "[20] is false (expected) list size should be unchanged (const)\n"; Info<< "[20] is false (expected) list size should be unchanged (const)\n";
} }
constLst.print(Info); constLst.print(Info);
Info<< "\ntest operator[] non-const with out-of-range index\n"; Info<< "\ntest operator[] non-const with out-of-range index\n";
if (!list1[20]) if (list1[20])
{
Info<< "[20] is true (unexpected)\n";
}
else
{ {
Info<< "[20] is false (expected) but list was resized?? (non-const)\n"; Info<< "[20] is false (expected) but list was resized?? (non-const)\n";
} }
@ -91,6 +111,14 @@ int main(int argc, char *argv[])
list1.resize(8, list1.max_value()); list1.resize(8, list1.max_value());
list1.print(Info); list1.print(Info);
Info<< "\ntest flip() function\n";
list1.flip();
list1.print(Info);
Info<< "\nre-flip()\n";
list1.flip();
list1.print(Info);
Info<< "\ntest set() function\n"; Info<< "\ntest set() function\n";
list1.set(1, 5); list1.set(1, 5);
list1.print(Info); list1.print(Info);
@ -188,15 +216,23 @@ int main(int argc, char *argv[])
{ {
Info<< "\ntest assignment of iterator\n"; Info<< "\ntest assignment of iterator\n";
list1.print(Info); list1.print(Info);
PackedList<3>::iterator cit = list1[25]; Info<< "cend()\n";
cit.print(Info);
list1.end().print(Info); list1.end().print(Info);
PackedList<3>::iterator cit = list1[100];
Info<< "out-of-range: ";
cit.print(Info);
cit = list1[15];
Info<< "in-range: ";
cit.print(Info);
Info<< "out-of-range: ";
cit = list1[1000];
cit.print(Info);
} }
for for
( (
PackedList<3>::iterator cit = list1[5]; PackedList<3>::iterator cit = list1[30];
cit != list1.end(); cit != list1.end();
++cit ++cit
) )
@ -204,14 +240,19 @@ int main(int argc, char *argv[])
cit.print(Info); cit.print(Info);
} }
// Info<< "\ntest operator[] auto-vivify\n"; Info<< "\ntest operator[] auto-vivify\n";
// const unsigned int val = list1[45]; Info<< "size:" << list1.size() << "\n";
//
// Info<< "list[45]:" << val << "\n"; const unsigned int val = list1[45];
// list1[45] = list1.max_value();
// Info<< "list[45]:" << list1[45] << "\n"; Info<< "list[45]:" << val << "\n";
// list1[49] = list1.max_value(); Info<< "size after read:" << list1.size() << "\n";
// list1.print(Info);
list1[45] = list1.max_value();
Info<< "size after write:" << list1.size() << "\n";
Info<< "list[45]:" << list1[45] << "\n";
list1[49] = list1[100];
list1.print(Info);
Info<< "\ntest copy constructor + append\n"; Info<< "\ntest copy constructor + append\n";
@ -235,6 +276,23 @@ int main(int argc, char *argv[])
Info<< "removed final value: " << list3.remove() << endl; Info<< "removed final value: " << list3.remove() << endl;
list3.print(Info); list3.print(Info);
List<bool> list4(4, true);
{
const List<bool>& constLst = list4;
Info<< "\ntest operator[] const with out-of-range index\n";
Info<< constLst << endl;
if (constLst[20])
{
Info<< "[20] is true (unexpected)\n";
}
else
{
Info<< "[20] is false (expected) list size should be unchanged (const)\n";
}
Info<< constLst << endl;
}
Info<< "\n\nDone.\n"; Info<< "\n\nDone.\n";
return 0; return 0;

View File

@ -32,6 +32,7 @@ Description
#include "fileName.H" #include "fileName.H"
#include "SubList.H" #include "SubList.H"
#include "IOobject.H"
#include "IOstreams.H" #include "IOstreams.H"
#include "OSspecific.H" #include "OSspecific.H"
@ -61,7 +62,8 @@ int main()
<< endl; << endl;
// try with different combination // try with different combination
for (label start = 0; start < wrdList.size(); ++start) // The final one should emit warnings
for (label start = 0; start <= wrdList.size(); ++start)
{ {
fileName instance, local; fileName instance, local;
word name; word name;
@ -69,26 +71,28 @@ int main()
fileName path(SubList<word>(wrdList, wrdList.size()-start, start)); fileName path(SubList<word>(wrdList, wrdList.size()-start, start));
fileName path2 = "." / path; fileName path2 = "." / path;
path.IOobjectComponents IOobject::fileNameComponents
( (
path,
instance, instance,
local, local,
name name
); );
Info<< "IOobjectComponents for " << path << nl Info<< "IOobject::fileNameComponents for " << path << nl
<< " instance = " << instance << nl << " instance = " << instance << nl
<< " local = " << local << nl << " local = " << local << nl
<< " name = " << name << endl; << " name = " << name << endl;
path2.IOobjectComponents IOobject::fileNameComponents
( (
path2,
instance, instance,
local, local,
name name
); );
Info<< "IOobjectComponents for " << path2 << nl Info<< "IOobject::fileNameComponents for " << path2 << nl
<< " instance = " << instance << nl << " instance = " << instance << nl
<< " local = " << local << nl << " local = " << local << nl
<< " name = " << name << endl; << " name = " << name << endl;

View File

@ -69,7 +69,7 @@ void checkFaceEdges
forAll(f, fp) forAll(f, fp)
{ {
label fp1 = (fp + 1) % f.size(); label fp1 = f.fcIndex(fp);
if (edges[myEdges[fp]] != edge(f[fp], f[fp1])) if (edges[myEdges[fp]] != edge(f[fp], f[fp1]))
{ {

View File

@ -0,0 +1,3 @@
testSHA1.C
EXE = $(FOAM_USER_APPBIN)/testSHA1

View File

@ -0,0 +1,135 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2009 OpenCFD Ltd.
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Application
testSHA1
Description
\*---------------------------------------------------------------------------*/
#include "OSHA1stream.H"
#include "IStringStream.H"
#include "dictionary.H"
using namespace Foam;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
int main(int argc, char * argv[])
{
SHA1 sha;
SHA1Digest shaDig;
std::string str("The quick brown fox jumps over the lazy dog");
Info<< shaDig << nl;
Info<< SHA1("The quick brown fox jumps over the lazy dog") << nl;
sha.append("The quick brown fox jumps over the lazy dog");
Info<< sha << nl;
sha.clear();
sha.append("The quick brown fox jumps over the lazy dog");
shaDig = sha;
sha.append("\n");
Info<< sha << nl;
Info<< shaDig << nl;
if (sha == shaDig)
{
Info<<"SHA1 digests are identical\n";
}
else
{
Info<<"SHA1 digests are different\n";
}
Info<<"lhs:" << sha << " rhs:" << shaDig << endl;
// start over:
sha.clear();
sha.append(str);
SHA1Digest shaDig_A = sha;
SHA1 sha_A = sha;
sha.append("\n");
Info<< "digest1: " << sha_A << nl;
Info<< "digest2: " << sha << nl;
// start over:
sha.clear();
sha.append("\"");
sha.append(str);
sha.append("\"");
Info<< "digest3: " << sha << nl;
// try the output buffer interface
{
OSHA1stream os;
os << str;
Info<< os.digest() << endl;
os << str;
Info<< os.digest() << endl;
os.rewind();
os << "The quick brown fox jumps over the lazy dog";
Info<< os.digest() << endl;
}
{
dictionary dict
(
IStringStream
(
"parent { Default_Boundary_Region { type zeroGradient; } }"
"inlet_1 { value inlet_1; }"
"inlet_2 { value inlet_2; }"
"inlet_3 { value inlet_3; }"
"\"inlet_.*\" { value XXX; }"
) ()
);
Info<< "dict:" << endl;
dict.write(Info, false);
dictionary dict2(dict);
OSHA1stream os;
dict.write(os, false);
Info<< os.digest() << endl;
Info<< dict2.digest() << endl;
}
return 0;
}

View File

@ -74,20 +74,17 @@ labelList getSortedEdges
const edge& e = edges[edgeI]; const edge& e = edges[edgeI];
label fp = findIndex(f, e[0]); label fp = findIndex(f, e[0]);
label fp1 = f.fcIndex(fp);
label fp1 = (fp+1) % f.size();
if (f[fp1] == e[1]) if (f[fp1] == e[1])
{ {
// Edgei in fp-fp1 order // EdgeI between fp -> fp1
faceEdges[fp] = edgeI; faceEdges[fp] = edgeI;
} }
else else
{ {
// Edgei between fp-1 and fp // EdgeI between fp-1 -> fp
label fpMin1 = (fp == 0 ? f.size()-1 : fp-1); faceEdges[f.rcIndex(fp)] = edgeI;
faceEdges[fpMin1] = edgeI;
} }
} }

View File

@ -277,7 +277,7 @@ void Foam::cellSplitter::setRefinement
label index = findIndex(f0, e[0]); label index = findIndex(f0, e[0]);
bool edgeInFaceOrder = (f0[(index+1) % f0.size()] == e[1]); bool edgeInFaceOrder = (f0[f0.fcIndex(index)] == e[1]);
// Check if cellI is the face owner // Check if cellI is the face owner
@ -323,7 +323,7 @@ void Foam::cellSplitter::setRefinement
label index = findIndex(f1, e[0]); label index = findIndex(f1, e[0]);
bool edgeInFaceOrder = (f1[(index+1) % f1.size()] == e[1]); bool edgeInFaceOrder = (f1[f1.fcIndex(index)] == e[1]);
// Check if cellI is the face owner // Check if cellI is the face owner

View File

@ -615,7 +615,7 @@ int main(int argc, char *argv[])
{ {
fileName ccmFile(args.additionalArgs()[0]); fileName ccmFile(args.additionalArgs()[0]);
if (!exists(ccmFile)) if (!isFile(ccmFile))
{ {
FatalErrorIn(args.executable()) FatalErrorIn(args.executable())
<< "Cannot read file " << ccmFile << "Cannot read file " << ccmFile

View File

@ -129,14 +129,14 @@ int main(int argc, char *argv[])
Info<< "Reading .face file for boundary information" << nl << endl; Info<< "Reading .face file for boundary information" << nl << endl;
} }
if (!exists(nodeFile) || !exists(eleFile)) if (!isFile(nodeFile) || !isFile(eleFile))
{ {
FatalErrorIn(args.executable()) FatalErrorIn(args.executable())
<< "Cannot read " << nodeFile << " or " << eleFile << "Cannot read " << nodeFile << " or " << eleFile
<< exit(FatalError); << exit(FatalError);
} }
if (readFaceFile && !exists(faceFile)) if (readFaceFile && !isFile(faceFile))
{ {
FatalErrorIn(args.executable()) FatalErrorIn(args.executable())
<< "Cannot read " << faceFile << endl << "Cannot read " << faceFile << endl

View File

@ -108,7 +108,11 @@ int main(int argc, char *argv[])
( (
new IOobject new IOobject
( (
( dictPath.isDir() ? dictPath/dictName : dictPath ), (
isDir(dictPath)
? dictPath/dictName
: dictPath
),
runTime, runTime,
IOobject::MUST_READ, IOobject::MUST_READ,
IOobject::NO_WRITE, IOobject::NO_WRITE,

View File

@ -79,6 +79,22 @@ topoSetSources
k (10 10 10); k (10 10 10);
} }
// Cells with centre within cylinder
cylinderToCell
{
p1 (0.2 0.2 -10); // start point on cylinder axis
p2 (0.2 0.2 0); // end point on cylinder axis
radius 5.0;
}
// Cells with centre within sphere
sphereToCell
{
centre (0.2 0.2 -10);
radius 5.0;
}
// Cells in cell zone // Cells in cell zone
zoneToCell zoneToCell
{ {

View File

@ -746,7 +746,8 @@ int main(int argc, char *argv[])
Pout<< "Reading commands from file " << batchFile << endl; Pout<< "Reading commands from file " << batchFile << endl;
if (!exists(batchFile)) // we also cannot handle .gz files
if (!isFile(batchFile, false))
{ {
FatalErrorIn(args.executable()) FatalErrorIn(args.executable())
<< "Cannot open file " << batchFile << exit(FatalError); << "Cannot open file " << batchFile << exit(FatalError);

View File

@ -627,7 +627,7 @@ autoPtr<mapPolyMesh> createRegionMesh
Info<< "Testing:" << io.objectPath() << endl; Info<< "Testing:" << io.objectPath() << endl;
if (!io.headerOk()) if (!io.headerOk())
//if (!exists(io.objectPath())) // if (!exists(io.objectPath()))
{ {
Info<< "Writing dummy " << regionName/io.name() << endl; Info<< "Writing dummy " << regionName/io.name() << endl;
dictionary dummyDict; dictionary dummyDict;

View File

@ -63,7 +63,6 @@ int main(int argc, char *argv[])
Info<< "Time = " << runTime.timeName() << nl << endl; Info<< "Time = " << runTime.timeName() << nl << endl;
const IOobjectList fieldObjs(mesh, runTime.timeName()); const IOobjectList fieldObjs(mesh, runTime.timeName());
const wordList objNames = fieldObjs.names(); const wordList objNames = fieldObjs.names();
PtrList<volScalarField> vsf(objNames.size()); PtrList<volScalarField> vsf(objNames.size());
@ -99,7 +98,7 @@ int main(int argc, char *argv[])
const polyBoundaryMesh& bm = mesh.boundaryMesh(); const polyBoundaryMesh& bm = mesh.boundaryMesh();
forAll(bm, patchI) forAll(bm, patchI)
{ {
Info<< "Patch: " << bm[patchI].name() << nl; Info<< bm[patchI].type() << ": " << bm[patchI].name() << nl;
outputFieldList<scalar>(vsf, patchI); outputFieldList<scalar>(vsf, patchI);
outputFieldList<vector>(vvf, patchI); outputFieldList<vector>(vvf, patchI);
outputFieldList<sphericalTensor>(vsptf, patchI); outputFieldList<sphericalTensor>(vsptf, patchI);

View File

@ -105,7 +105,7 @@ int main(int argc, char *argv[])
// determine the existing processor count directly // determine the existing processor count directly
label nProcs = 0; label nProcs = 0;
while (dir(runTime.path()/(word("processor") + name(nProcs)))) while (isDir(runTime.path()/(word("processor") + name(nProcs))))
{ {
++nProcs; ++nProcs;
} }
@ -480,7 +480,7 @@ int main(int argc, char *argv[])
// Any uniform data to copy/link? // Any uniform data to copy/link?
fileName uniformDir("uniform"); fileName uniformDir("uniform");
if (dir(runTime.timePath()/uniformDir)) if (isDir(runTime.timePath()/uniformDir))
{ {
Info<< "Detected additional non-decomposed files in " Info<< "Detected additional non-decomposed files in "
<< runTime.timePath()/uniformDir << runTime.timePath()/uniformDir

View File

@ -63,7 +63,7 @@ int main(int argc, char *argv[])
// determine the processor count directly // determine the processor count directly
label nProcs = 0; label nProcs = 0;
while (dir(args.path()/(word("processor") + name(nProcs)))) while (isDir(args.path()/(word("processor") + name(nProcs))))
{ {
++nProcs; ++nProcs;
} }
@ -383,7 +383,7 @@ int main(int argc, char *argv[])
// the master processor. // the master processor.
fileName uniformDir0 = databases[0].timePath()/"uniform"; fileName uniformDir0 = databases[0].timePath()/"uniform";
if (dir(uniformDir0)) if (isDir(uniformDir0))
{ {
cp(uniformDir0, runTime.timePath()); cp(uniformDir0, runTime.timePath());
} }

View File

@ -355,7 +355,7 @@ int main(int argc, char *argv[])
while while
( (
exists isDir
( (
args.rootPath() args.rootPath()
/ args.caseName() / args.caseName()

View File

@ -503,7 +503,7 @@ int main(int argc, char *argv[])
# include "setRootCase.H" # include "setRootCase.H"
// Create processor directory if non-existing // Create processor directory if non-existing
if (!Pstream::master() && !dir(args.path())) if (!Pstream::master() && !isDir(args.path()))
{ {
Pout<< "Creating case directory " << args.path() << endl; Pout<< "Creating case directory " << args.path() << endl;
mkDir(args.path()); mkDir(args.path());
@ -525,7 +525,7 @@ int main(int argc, char *argv[])
const fileName meshDir = runTime.path()/masterInstDir/polyMesh::meshSubDir; const fileName meshDir = runTime.path()/masterInstDir/polyMesh::meshSubDir;
boolList haveMesh(Pstream::nProcs(), false); boolList haveMesh(Pstream::nProcs(), false);
haveMesh[Pstream::myProcNo()] = dir(meshDir); haveMesh[Pstream::myProcNo()] = isDir(meshDir);
Pstream::gatherList(haveMesh); Pstream::gatherList(haveMesh);
Pstream::scatterList(haveMesh); Pstream::scatterList(haveMesh);
Info<< "Per processor mesh availability : " << haveMesh << endl; Info<< "Per processor mesh availability : " << haveMesh << endl;

View File

@ -131,7 +131,7 @@ int main(int argc, char *argv[])
if (Pstream::master()) if (Pstream::master())
{ {
if (dir(postProcPath)) if (isDir(postProcPath))
{ {
rmDir(postProcPath); rmDir(postProcPath);
} }

View File

@ -136,7 +136,7 @@ int main(int argc, char *argv[])
// Ensight and Ensight/data directories must exist // Ensight and Ensight/data directories must exist
// do not remove old data - we might wish to convert new results // do not remove old data - we might wish to convert new results
// or a particular time interval // or a particular time interval
if (dir(ensightDir)) if (isDir(ensightDir))
{ {
Info<<"Warning: reusing existing directory" << nl Info<<"Warning: reusing existing directory" << nl
<< " " << ensightDir << endl; << " " << ensightDir << endl;
@ -324,7 +324,7 @@ int main(int argc, char *argv[])
{ {
const word& cloudName = cloudIter.key(); const word& cloudName = cloudIter.key();
if (!dir(runTime.timePath()/regionPrefix/"lagrangian"/cloudName)) if (!isDir(runTime.timePath()/regionPrefix/"lagrangian"/cloudName))
{ {
continue; continue;
} }

View File

@ -260,7 +260,7 @@ int main(int argc, char *argv[])
// make a directory called FieldView in the case // make a directory called FieldView in the case
fileName fvPath(runTime.path()/"Fieldview"); fileName fvPath(runTime.path()/"Fieldview");
if (dir(fvPath)) if (isDir(fvPath))
{ {
rmDir(fvPath); rmDir(fvPath);
} }

View File

@ -333,7 +333,7 @@ int main(int argc, char *argv[])
regionPrefix = regionName; regionPrefix = regionName;
} }
if (dir(fvPath)) if (isDir(fvPath))
{ {
if if
( (

View File

@ -228,7 +228,7 @@ Foam::vtkPV3Foam::vtkPV3Foam
// avoid argList and get rootPath/caseName directly from the file // avoid argList and get rootPath/caseName directly from the file
fileName fullCasePath(fileName(FileName).path()); fileName fullCasePath(fileName(FileName).path());
if (!dir(fullCasePath)) if (!isDir(fullCasePath))
{ {
return; return;
} }
@ -518,7 +518,7 @@ double* Foam::vtkPV3Foam::findTimes(int& nTimeSteps)
if if
( (
file(runTime.path()/timeName/meshDir_/"points") isFile(runTime.path()/timeName/meshDir_/"points")
&& IOobject("points", timeName, meshDir_, runTime).headerOk() && IOobject("points", timeName, meshDir_, runTime).headerOk()
) )
{ {

View File

@ -156,7 +156,7 @@ class vtkPV3Foam
bool empty() const bool empty() const
{ {
return (size_ == 0); return !size_;
} }
void reset() void reset()

View File

@ -391,7 +391,7 @@ Foam::vtkFoam::vtkFoam(const char* const FileName, vtkFoamReader* reader)
{ {
fileName fullCasePath(fileName(FileName).path()); fileName fullCasePath(fileName(FileName).path());
if (!dir(fullCasePath)) if (!isDir(fullCasePath))
{ {
return; return;
} }

View File

@ -47,7 +47,7 @@ int USERD_set_filenames
} }
caseDir = tmp; caseDir = tmp;
if (!dir(rootDir/caseDir)) if (!isDir(rootDir/caseDir))
{ {
Info<< rootDir/caseDir << " is not a valid directory." Info<< rootDir/caseDir << " is not a valid directory."
<< endl; << endl;

View File

@ -132,8 +132,8 @@ static void errorMsg(const string& msg)
// Simple check if directory is valid case directory. // Simple check if directory is valid case directory.
static bool validCase(const fileName& rootAndCase) static bool validCase(const fileName& rootAndCase)
{ {
//if (dir(rootAndCase/"system") && dir(rootAndCase/"constant")) //if (isDir(rootAndCase/"system") && isDir(rootAndCase/"constant"))
if (dir(rootAndCase/"constant")) if (isDir(rootAndCase/"constant"))
{ {
return true; return true;
} }

View File

@ -63,7 +63,7 @@ void Foam::calc(const argList& args, const Time& runTime, const fvMesh& mesh)
volVectorField U(Uheader, mesh); volVectorField U(Uheader, mesh);
if (file(runTime.constantPath()/"thermophysicalProperties")) if (isFile(runTime.constantPath()/"thermophysicalProperties"))
{ {
// thermophysical Mach // thermophysical Mach
autoPtr<basicThermo> thermo autoPtr<basicThermo> thermo

View File

@ -1,3 +0,0 @@
surfaceCoordinateSystemTransform.C
EXE = $(FOAM_APPBIN)/surfaceCoordinateSystemTransform

View File

@ -1,5 +1,5 @@
EXE_INC = \ EXE_INC = \
-I$(LIB_SRC)/triSurface/lnInclude \ -I$(LIB_SRC)/meshTools/lnInclude \
-I$(LIB_SRC)/surfMesh/lnInclude -I$(LIB_SRC)/surfMesh/lnInclude
EXE_LIBS = -lsurfMesh EXE_LIBS = -lmeshTools -lsurfMesh

View File

@ -26,25 +26,30 @@ Application
surfaceMeshConvert surfaceMeshConvert
Description Description
Converts from one surface mesh format to another
Convert between surface formats with optional scaling or
transformations (rotate/translate) on a coordinateSystem.
Usage Usage
- surfaceMeshConvert inputFile outputFile [OPTION] - surfaceMeshConvert inputFile outputFile [OPTION]
@param -clean \n @param -clean \n
Perform some surface checking/cleanup on the input surface Perform some surface checking/cleanup on the input surface.
@param -orient \n @param -scaleIn \<scale\> \n
Check face orientation on the input surface Specify a scaling factor when reading files.
@param -scale \<scale\> \n @param -scaleOut \<scale\> \n
Specify a scaling factor for writing the files Specify a scaling factor when writing files.
@param -triSurface \n @param -dict \<dictionary\> \n
Use triSurface library for input/output Specify an alternative dictionary for constant/coordinateSystems.
@param -keyed \n @param -from \<coordinateSystem\> \n
Use keyedSurface for input/output Specify a coordinate System when reading files.
@param -to \<coordinateSystem\> \n
Specify a coordinate System when writing files.
Note Note
The filename extensions are used to determine the file format type. The filename extensions are used to determine the file format type.
@ -54,12 +59,9 @@ Note
#include "argList.H" #include "argList.H"
#include "timeSelector.H" #include "timeSelector.H"
#include "Time.H" #include "Time.H"
#include "polyMesh.H"
#include "triSurface.H"
#include "PackedBoolList.H"
#include "MeshedSurfaces.H" #include "MeshedSurfaces.H"
#include "UnsortedMeshedSurfaces.H" #include "coordinateSystems.H"
using namespace Foam; using namespace Foam;
@ -71,24 +73,21 @@ int main(int argc, char *argv[])
argList::noParallel(); argList::noParallel();
argList::validArgs.append("inputFile"); argList::validArgs.append("inputFile");
argList::validArgs.append("outputFile"); argList::validArgs.append("outputFile");
argList::validOptions.insert("clean", ""); argList::validOptions.insert("clean", "scale");
argList::validOptions.insert("orient", ""); argList::validOptions.insert("scaleIn", "scale");
argList::validOptions.insert("scale", "scale"); argList::validOptions.insert("scaleOut", "scale");
argList::validOptions.insert("triSurface", ""); argList::validOptions.insert("dict", "coordinateSystemsDict");
argList::validOptions.insert("unsorted", ""); argList::validOptions.insert("from", "sourceCoordinateSystem");
argList::validOptions.insert("triFace", ""); argList::validOptions.insert("to", "targetCoordinateSystem");
# include "setRootCase.H"
const stringList& params = args.additionalArgs();
scalar scaleFactor = 0; argList args(argc, argv);
if (args.options().found("scale")) Time runTime(args.rootPath(), args.caseName());
{ const stringList& params = args.additionalArgs();
IStringStream(args.options()["scale"])() >> scaleFactor;
}
fileName importName(params[0]); fileName importName(params[0]);
fileName exportName(params[1]); fileName exportName(params[1]);
// disable inplace editing
if (importName == exportName) if (importName == exportName)
{ {
FatalErrorIn(args.executable()) FatalErrorIn(args.executable())
@ -96,165 +95,161 @@ int main(int argc, char *argv[])
<< exit(FatalError); << exit(FatalError);
} }
// check that reading/writing is supported
if if
( (
!meshedSurface::canRead(importName, true) !MeshedSurface<face>::canRead(importName, true)
|| !meshedSurface::canWriteType(exportName.ext(), true) || !MeshedSurface<face>::canWriteType(exportName.ext(), true)
) )
{ {
return 1; return 1;
} }
if (args.options().found("triSurface"))
// get the coordinate transformations
autoPtr<coordinateSystem> fromCsys;
autoPtr<coordinateSystem> toCsys;
if (args.options().found("from") || args.options().found("to"))
{ {
triSurface surf(importName); autoPtr<IOobject> csDictIoPtr;
Info<< "Read surface:" << endl; if (args.options().found("dict"))
surf.writeStats(Info);
Info<< endl;
if (args.options().found("orient"))
{ {
Info<< "Checking surface orientation" << endl; fileName dictPath(args.options()["dict"]);
PatchTools::checkOrientation(surf, true);
Info<< endl;
}
if (args.options().found("clean")) csDictIoPtr.set
{ (
Info<< "Cleaning up surface" << endl; new IOobject
surf.cleanup(true); (
surf.writeStats(Info); (
Info<< endl; isDir(dictPath)
} ? dictPath/coordinateSystems::typeName
: dictPath
Info<< "writing " << exportName; ),
if (scaleFactor <= 0) runTime,
{ IOobject::MUST_READ,
Info<< " without scaling" << endl; IOobject::NO_WRITE,
false
)
);
} }
else else
{ {
Info<< " with scaling " << scaleFactor << endl; csDictIoPtr.set
surf.scalePoints(scaleFactor); (
surf.writeStats(Info); new IOobject
Info<< endl; (
coordinateSystems::typeName,
runTime.constant(),
runTime,
IOobject::MUST_READ,
IOobject::NO_WRITE,
false
)
);
} }
// write sorted by region
surf.write(exportName, true); if (!csDictIoPtr->headerOk())
{
FatalErrorIn(args.executable())
<< "Cannot open coordinateSystems file\n "
<< csDictIoPtr->objectPath() << nl
<< exit(FatalError);
}
coordinateSystems csLst(csDictIoPtr());
if (args.options().found("from"))
{
const word csName(args.options()["from"]);
label csId = csLst.find(csName);
if (csId < 0)
{
FatalErrorIn(args.executable())
<< "Cannot find -from " << csName << nl
<< "available coordinateSystems: " << csLst.toc() << nl
<< exit(FatalError);
}
fromCsys.reset(new coordinateSystem(csLst[csId]));
}
if (args.options().found("to"))
{
const word csName(args.options()["to"]);
label csId = csLst.find(csName);
if (csId < 0)
{
FatalErrorIn(args.executable())
<< "Cannot find -to " << csName << nl
<< "available coordinateSystems: " << csLst.toc() << nl
<< exit(FatalError);
}
toCsys.reset(new coordinateSystem(csLst[csId]));
}
// maybe fix this later
if (fromCsys.valid() && toCsys.valid())
{
FatalErrorIn(args.executable())
<< "Only allowed '-from' or '-to' option at the moment."
<< exit(FatalError);
}
} }
else if (args.options().found("unsorted"))
scalar scaleIn = 0;
scalar scaleOut = 0;
if (args.options().found("scaleIn"))
{ {
UnsortedMeshedSurface<face> surf(importName); IStringStream(args.options()["scaleIn"])() >> scaleIn;
Info<< "Read surface:" << endl;
surf.writeStats(Info);
Info<< endl;
if (args.options().found("orient"))
{
Info<< "Checking surface orientation" << endl;
PatchTools::checkOrientation(surf, true);
Info<< endl;
}
if (args.options().found("clean"))
{
Info<< "Cleaning up surface" << endl;
surf.cleanup(true);
surf.writeStats(Info);
Info<< endl;
}
Info<< "writing " << exportName;
if (scaleFactor <= 0)
{
Info<< " without scaling" << endl;
}
else
{
Info<< " with scaling " << scaleFactor << endl;
surf.scalePoints(scaleFactor);
surf.writeStats(Info);
Info<< endl;
}
surf.write(exportName);
} }
#if 1 if (args.options().found("scaleOut"))
else if (args.options().found("triFace"))
{ {
MeshedSurface<triFace> surf(importName); IStringStream(args.options()["scaleOut"])() >> scaleOut;
Info<< "Read surface:" << endl;
surf.writeStats(Info);
Info<< endl;
if (args.options().found("orient"))
{
Info<< "Checking surface orientation" << endl;
PatchTools::checkOrientation(surf, true);
Info<< endl;
}
if (args.options().found("clean"))
{
Info<< "Cleaning up surface" << endl;
surf.cleanup(true);
surf.writeStats(Info);
Info<< endl;
}
Info<< "writing " << exportName;
if (scaleFactor <= 0)
{
Info<< " without scaling" << endl;
}
else
{
Info<< " with scaling " << scaleFactor << endl;
surf.scalePoints(scaleFactor);
surf.writeStats(Info);
Info<< endl;
}
surf.write(exportName);
} }
#endif
else
{ {
MeshedSurface<face> surf(importName); MeshedSurface<face> surf(importName);
Info<< "Read surface:" << endl;
surf.writeStats(Info);
Info<< endl;
if (args.options().found("orient"))
{
Info<< "Checking surface orientation" << endl;
PatchTools::checkOrientation(surf, true);
Info<< endl;
}
if (args.options().found("clean")) if (args.options().found("clean"))
{ {
Info<< "Cleaning up surface" << endl;
surf.cleanup(true); surf.cleanup(true);
surf.writeStats(Info); }
Info<< endl;
if (scaleIn > 0)
{
Info<< " -scaleIn " << scaleIn << endl;
surf.scalePoints(scaleIn);
}
if (fromCsys.valid())
{
Info<< " -from " << fromCsys().name() << endl;
tmp<pointField> tpf = fromCsys().localPosition(surf.points());
surf.movePoints(tpf());
}
if (toCsys.valid())
{
Info<< " -to " << toCsys().name() << endl;
tmp<pointField> tpf = toCsys().globalPosition(surf.points());
surf.movePoints(tpf());
}
if (scaleOut > 0)
{
Info<< " -scaleOut " << scaleOut << endl;
surf.scalePoints(scaleOut);
} }
Info<< "writing " << exportName; Info<< "writing " << exportName;
if (scaleFactor <= 0)
{
Info<< " without scaling" << endl;
}
else
{
Info<< " with scaling " << scaleFactor << endl;
surf.scalePoints(scaleFactor);
surf.writeStats(Info);
Info<< endl;
}
surf.write(exportName); surf.write(exportName);
} }

View File

@ -0,0 +1,3 @@
surfaceMeshConvertTesting.C
EXE = $(FOAM_APPBIN)/surfaceMeshConvertTesting

View File

@ -0,0 +1,5 @@
EXE_INC = \
-I$(LIB_SRC)/triSurface/lnInclude \
-I$(LIB_SRC)/surfMesh/lnInclude
EXE_LIBS = -ltriSurface -lsurfMesh

View File

@ -0,0 +1,348 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2009 OpenCFD Ltd.
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Application
surfaceMeshConvertTesting
Description
Converts from one surface mesh format to another, but primarily
used for testing functionality.
Usage
- surfaceMeshConvertTesting inputFile outputFile [OPTION]
@param -clean \n
Perform some surface checking/cleanup on the input surface
@param -orient \n
Check face orientation on the input surface
@param -scale \<scale\> \n
Specify a scaling factor for writing the files
@param -triSurface \n
Use triSurface library for input/output
@param -keyed \n
Use keyedSurface for input/output
Note
The filename extensions are used to determine the file format type.
\*---------------------------------------------------------------------------*/
#include "argList.H"
#include "timeSelector.H"
#include "Time.H"
#include "polyMesh.H"
#include "triSurface.H"
#include "surfMesh.H"
#include "surfFields.H"
#include "surfPointFields.H"
#include "PackedBoolList.H"
#include "MeshedSurfaces.H"
#include "UnsortedMeshedSurfaces.H"
using namespace Foam;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Main program:
int main(int argc, char *argv[])
{
argList::noParallel();
argList::validArgs.append("inputFile");
argList::validArgs.append("outputFile");
argList::validOptions.insert("clean", "");
argList::validOptions.insert("orient", "");
argList::validOptions.insert("surfMesh", "");
argList::validOptions.insert("scale", "scale");
argList::validOptions.insert("triSurface", "");
argList::validOptions.insert("unsorted", "");
argList::validOptions.insert("triFace", "");
# include "setRootCase.H"
const stringList& params = args.additionalArgs();
scalar scaleFactor = 0;
if (args.options().found("scale"))
{
IStringStream(args.options()["scale"])() >> scaleFactor;
}
fileName importName(params[0]);
fileName exportName(params[1]);
if (importName == exportName)
{
FatalErrorIn(args.executable())
<< "Output file " << exportName << " would overwrite input file."
<< exit(FatalError);
}
if
(
!MeshedSurface<face>::canRead(importName, true)
|| !MeshedSurface<face>::canWriteType(exportName.ext(), true)
)
{
return 1;
}
if (args.options().found("triSurface"))
{
triSurface surf(importName);
Info<< "Read surface:" << endl;
surf.writeStats(Info);
Info<< endl;
if (args.options().found("orient"))
{
Info<< "Checking surface orientation" << endl;
PatchTools::checkOrientation(surf, true);
Info<< endl;
}
if (args.options().found("clean"))
{
Info<< "Cleaning up surface" << endl;
surf.cleanup(true);
surf.writeStats(Info);
Info<< endl;
}
Info<< "writing " << exportName;
if (scaleFactor <= 0)
{
Info<< " without scaling" << endl;
}
else
{
Info<< " with scaling " << scaleFactor << endl;
surf.scalePoints(scaleFactor);
surf.writeStats(Info);
Info<< endl;
}
// write sorted by region
surf.write(exportName, true);
}
else if (args.options().found("unsorted"))
{
UnsortedMeshedSurface<face> surf(importName);
Info<< "Read surface:" << endl;
surf.writeStats(Info);
Info<< endl;
if (args.options().found("orient"))
{
Info<< "Checking surface orientation" << endl;
PatchTools::checkOrientation(surf, true);
Info<< endl;
}
if (args.options().found("clean"))
{
Info<< "Cleaning up surface" << endl;
surf.cleanup(true);
surf.writeStats(Info);
Info<< endl;
}
Info<< "writing " << exportName;
if (scaleFactor <= 0)
{
Info<< " without scaling" << endl;
}
else
{
Info<< " with scaling " << scaleFactor << endl;
surf.scalePoints(scaleFactor);
surf.writeStats(Info);
Info<< endl;
}
surf.write(exportName);
}
#if 1
else if (args.options().found("triFace"))
{
MeshedSurface<triFace> surf(importName);
Info<< "Read surface:" << endl;
surf.writeStats(Info);
Info<< endl;
if (args.options().found("orient"))
{
Info<< "Checking surface orientation" << endl;
PatchTools::checkOrientation(surf, true);
Info<< endl;
}
if (args.options().found("clean"))
{
Info<< "Cleaning up surface" << endl;
surf.cleanup(true);
surf.writeStats(Info);
Info<< endl;
}
Info<< "writing " << exportName;
if (scaleFactor <= 0)
{
Info<< " without scaling" << endl;
}
else
{
Info<< " with scaling " << scaleFactor << endl;
surf.scalePoints(scaleFactor);
surf.writeStats(Info);
Info<< endl;
}
surf.write(exportName);
}
#endif
else
{
MeshedSurface<face> surf(importName);
Info<< "Read surface:" << endl;
surf.writeStats(Info);
Info<< endl;
if (args.options().found("orient"))
{
Info<< "Checking surface orientation" << endl;
PatchTools::checkOrientation(surf, true);
Info<< endl;
}
if (args.options().found("clean"))
{
Info<< "Cleaning up surface" << endl;
surf.cleanup(true);
surf.writeStats(Info);
Info<< endl;
}
Info<< "writing " << exportName;
if (scaleFactor <= 0)
{
Info<< " without scaling" << endl;
}
else
{
Info<< " with scaling " << scaleFactor << endl;
surf.scalePoints(scaleFactor);
surf.writeStats(Info);
Info<< endl;
}
surf.write(exportName);
if (args.options().found("surfMesh"))
{
Foam::Time runTime
(
args.rootPath(),
args.caseName()
);
surfMesh surfOut
(
IOobject
(
"mySurf",
runTime.instance(),
runTime
),
surf.xfer()
);
Info<< "writing surfMesh as well: " << surfOut.objectPath() << endl;
surfOut.write();
surfLabelField zoneIds
(
IOobject
(
"zoneIds",
surfOut.instance(),
surfOut,
IOobject::NO_READ,
IOobject::NO_WRITE
),
surfOut,
dimless
);
const surfZoneList& zones = surfOut.surfZones();
forAll(zones, zoneI)
{
SubList<label>
(
zoneIds,
zones[zoneI].size(),
zones[zoneI].start()
) = zoneI;
}
Info<< "write zoneIds (for testing only): "
<< zoneIds.objectPath() << endl;
zoneIds.write();
surfPointLabelField pointIds
(
IOobject
(
"pointIds",
surfOut.instance(),
"pointFields",
surfOut,
IOobject::NO_READ,
IOobject::NO_WRITE
),
surfOut,
dimless
);
forAll(pointIds, i)
{
pointIds[i] = i;
}
Info<< "write pointIds (for testing only): "
<< pointIds.objectPath() << endl;
pointIds.write();
}
}
Info<< "\nEnd\n" << endl;
return 0;
}
// ************************************************************************* //

View File

@ -0,0 +1,3 @@
surfaceMeshExport.C
EXE = $(FOAM_APPBIN)/surfaceMeshExport

View File

@ -23,27 +23,36 @@ License
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Application Application
surfaceMeshCoordinateSystemTransform surfaceMeshExport
Description Description
Export from surfMesh to various third-party surface formats with
Transform (scale/rotate/translate) a surface based on optional scaling or transformations (rotate/translate) on a
a coordinateSystem. coordinateSystem.
Usage Usage
- surfaceMeshCoordinateSystemTransform inputFile outputFile [OPTION] - surfaceMeshExport outputFile [OPTION]
@param -clean \n @param -clean \n
Perform some surface checking/cleanup on the input surface Perform some surface checking/cleanup on the input surface.
@param -scale \<scale\> \n @param -name \<name\> \n
Specify a scaling factor for writing the files Specify an alternative surface name when writing.
@param -triSurface \n @param -scaleIn \<scale\> \n
Use triSurface library for input/output Specify a scaling factor when reading files.
@param -scaleOut \<scale\> \n
Specify a scaling factor when writing files.
@param -dict \<dictionary\> \n @param -dict \<dictionary\> \n
Specify an alternative dictionary for coordinateSystems. Specify an alternative dictionary for constant/coordinateSystems.
@param -from \<coordinateSystem\> \n
Specify a coordinate System when reading files.
@param -to \<coordinateSystem\> \n
Specify a coordinate System when writing files.
Note Note
The filename extensions are used to determine the file format type. The filename extensions are used to determine the file format type.
@ -55,7 +64,6 @@ Note
#include "Time.H" #include "Time.H"
#include "MeshedSurfaces.H" #include "MeshedSurfaces.H"
#include "UnsortedMeshedSurfaces.H"
#include "coordinateSystems.H" #include "coordinateSystems.H"
using namespace Foam; using namespace Foam;
@ -66,36 +74,55 @@ using namespace Foam;
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
argList::noParallel(); argList::noParallel();
argList::validArgs.append("inputFile");
argList::validArgs.append("outputFile"); argList::validArgs.append("outputFile");
argList::validOptions.insert("scale", "scale"); argList::validOptions.insert("name", "name");
argList::validOptions.insert("unsorted", ""); argList::validOptions.insert("clean", "scale");
argList::validOptions.insert("scaleIn", "scale");
argList::validOptions.insert("scaleOut", "scale");
argList::validOptions.insert("dict", "coordinateSystemsDict");
argList::validOptions.insert("from", "sourceCoordinateSystem"); argList::validOptions.insert("from", "sourceCoordinateSystem");
argList::validOptions.insert("to", "targetCoordinateSystem"); argList::validOptions.insert("to", "targetCoordinateSystem");
argList::validOptions.insert("dict", "dictionary");
argList args(argc, argv); argList args(argc, argv);
Time runTime(args.rootPath(), args.caseName()); Time runTime(args.rootPath(), args.caseName());
const stringList& params = args.additionalArgs(); const stringList& params = args.additionalArgs();
const word dictName("coordinateSystems"); fileName exportName(params[0]);
word importName("default");
// check that writing is supported
if (!MeshedSurface<face>::canWriteType(exportName.ext(), true))
{
return 1;
}
if (args.options().found("name"))
{
importName = args.options()["name"];
}
// get the coordinate transformations
autoPtr<coordinateSystem> fromCsys; autoPtr<coordinateSystem> fromCsys;
autoPtr<coordinateSystem> toCsys; autoPtr<coordinateSystem> toCsys;
if (args.options().found("from") || args.options().found("to")) if (args.options().found("from") || args.options().found("to"))
{ {
autoPtr<IOobject> csDictIoPtr; autoPtr<IOobject> ioPtr;
if (args.options().found("dict")) if (args.options().found("dict"))
{ {
fileName dictPath(args.options()["dict"]); fileName dictPath(args.options()["dict"]);
csDictIoPtr.set ioPtr.set
( (
new IOobject new IOobject
( (
( dictPath.isDir() ? dictPath/dictName : dictPath ), (
isDir(dictPath)
? dictPath/coordinateSystems::typeName
: dictPath
),
runTime, runTime,
IOobject::MUST_READ, IOobject::MUST_READ,
IOobject::NO_WRITE, IOobject::NO_WRITE,
@ -105,11 +132,11 @@ int main(int argc, char *argv[])
} }
else else
{ {
csDictIoPtr.set ioPtr.set
( (
new IOobject new IOobject
( (
dictName, coordinateSystems::typeName,
runTime.constant(), runTime.constant(),
runTime, runTime,
IOobject::MUST_READ, IOobject::MUST_READ,
@ -120,15 +147,15 @@ int main(int argc, char *argv[])
} }
if (!csDictIoPtr->headerOk()) if (!ioPtr->headerOk())
{ {
FatalErrorIn(args.executable()) FatalErrorIn(args.executable())
<< "Cannot open coordinateSystems file\n " << "Cannot open coordinateSystems file\n "
<< csDictIoPtr->objectPath() << nl << ioPtr->objectPath() << nl
<< exit(FatalError); << exit(FatalError);
} }
coordinateSystems csLst(csDictIoPtr()); coordinateSystems csLst(ioPtr());
if (args.options().found("from")) if (args.options().found("from"))
{ {
@ -167,70 +194,81 @@ int main(int argc, char *argv[])
if (fromCsys.valid() && toCsys.valid()) if (fromCsys.valid() && toCsys.valid())
{ {
FatalErrorIn(args.executable()) FatalErrorIn(args.executable())
<< "Only allowed -from or -to option at the moment." << "Only allowed '-from' or '-to' option at the moment."
<< exit(FatalError); << exit(FatalError);
} }
} }
scalar scaleFactor = 0;
if (args.options().found("scale"))
{
IStringStream(args.options()["scale"])() >> scaleFactor;
}
fileName importName(params[0]); surfMesh smesh
fileName exportName(params[1]);
if (importName == exportName)
{
FatalErrorIn(args.executable())
<< "Output file " << exportName << " would overwrite input file."
<< exit(FatalError);
}
if
( (
!meshedSurface::canRead(importName, true) IOobject
|| !meshedSurface::canWriteType(exportName.ext(), true) (
) importName,
runTime.constant(),
runTime,
IOobject::MUST_READ,
IOobject::NO_WRITE
)
);
Info<< "read surfMesh:\n " << smesh.objectPath() << endl;
// Simply copy for now, but really should have a separate write method
MeshedSurface<face> surf(smesh);
if (args.options().found("clean"))
{ {
return 1; surf.cleanup(true);
}
scalar scaleIn = 0;
scalar scaleOut = 0;
if (args.options().found("scaleIn"))
{
IStringStream(args.options()["scaleIn"])() >> scaleIn;
}
if (args.options().found("scaleOut"))
{
IStringStream(args.options()["scaleOut"])() >> scaleOut;
} }
if (scaleIn > 0)
{ {
MeshedSurface<face> surf(importName); Info<< " -scaleIn " << scaleIn << endl;
surf.scalePoints(scaleIn);
if (args.options().found("clean"))
{
surf.cleanup(true);
}
if (fromCsys.valid())
{
tmp<pointField> tpf = fromCsys().localPosition(surf.points());
surf.movePoints(tpf());
}
if (toCsys.valid())
{
tmp<pointField> tpf = toCsys().globalPosition(surf.points());
surf.movePoints(tpf());
}
Info<< "writing " << exportName;
if (scaleFactor <= 0)
{
Info<< " without scaling" << endl;
}
else
{
Info<< " with scaling " << scaleFactor << endl;
surf.scalePoints(scaleFactor);
}
surf.write(exportName);
} }
if (fromCsys.valid())
{
Info<< " -from " << fromCsys().name() << endl;
tmp<pointField> tpf = fromCsys().localPosition(surf.points());
surf.movePoints(tpf());
}
if (toCsys.valid())
{
Info<< " -to " << toCsys().name() << endl;
tmp<pointField> tpf = toCsys().globalPosition(surf.points());
surf.movePoints(tpf());
}
if (scaleOut > 0)
{
Info<< " -scaleOut " << scaleOut << endl;
surf.scalePoints(scaleOut);
}
surf.writeStats(Info);
Info<< endl;
Info<< "writing " << exportName << endl;
surf.write(exportName);
Info<< "\nEnd\n" << endl; Info<< "\nEnd\n" << endl;
return 0; return 0;

View File

@ -0,0 +1,3 @@
surfaceMeshImport.C
EXE = $(FOAM_APPBIN)/surfaceMeshImport

View File

@ -0,0 +1,5 @@
EXE_INC = \
-I$(LIB_SRC)/meshTools/lnInclude \
-I$(LIB_SRC)/surfMesh/lnInclude
EXE_LIBS = -lmeshTools -lsurfMesh

View File

@ -0,0 +1,284 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2009 OpenCFD Ltd.
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Application
surfaceMeshImport
Description
Import from various third-party surface formats into surfMesh
with optional scaling or transformations (rotate/translate)
on a coordinateSystem.
Usage
- surfaceMeshImport inputFile [OPTION]
@param -clean \n
Perform some surface checking/cleanup on the input surface.
@param -name \<name\> \n
Specify an alternative surface name when writing.
@param -scaleIn \<scale\> \n
Specify a scaling factor when reading files.
@param -scaleOut \<scale\> \n
Specify a scaling factor when writing files.
@param -dict \<dictionary\> \n
Specify an alternative dictionary for constant/coordinateSystems.
@param -from \<coordinateSystem\> \n
Specify a coordinate System when reading files.
@param -to \<coordinateSystem\> \n
Specify a coordinate System when writing files.
Note
The filename extensions are used to determine the file format type.
\*---------------------------------------------------------------------------*/
#include "argList.H"
#include "timeSelector.H"
#include "Time.H"
#include "MeshedSurfaces.H"
#include "coordinateSystems.H"
using namespace Foam;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Main program:
int main(int argc, char *argv[])
{
argList::noParallel();
argList::validArgs.append("inputFile");
argList::validOptions.insert("name", "name");
argList::validOptions.insert("clean", "scale");
argList::validOptions.insert("scaleIn", "scale");
argList::validOptions.insert("scaleOut", "scale");
argList::validOptions.insert("dict", "coordinateSystemsDict");
argList::validOptions.insert("from", "sourceCoordinateSystem");
argList::validOptions.insert("to", "targetCoordinateSystem");
# include "setRootCase.H"
# include "createTime.H"
const stringList& params = args.additionalArgs();
// try for the latestTime, but create "constant" as needed
instantList Times = runTime.times();
if (Times.size())
{
label startTime = Times.size()-1;
runTime.setTime(Times[startTime], startTime);
}
else
{
runTime.setTime(instant(0, runTime.constant()), 0);
}
fileName importName(params[0]);
word exportName("default");
// check that reading is supported
if (!MeshedSurface<face>::canRead(importName, true))
{
return 1;
}
if (args.options().found("name"))
{
exportName = args.options()["name"];
}
// get the coordinate transformations
autoPtr<coordinateSystem> fromCsys;
autoPtr<coordinateSystem> toCsys;
if (args.options().found("from") || args.options().found("to"))
{
autoPtr<IOobject> ioPtr;
if (args.options().found("dict"))
{
fileName dictPath(args.options()["dict"]);
ioPtr.set
(
new IOobject
(
(
isDir(dictPath)
? dictPath/coordinateSystems::typeName
: dictPath
),
runTime,
IOobject::MUST_READ,
IOobject::NO_WRITE,
false
)
);
}
else
{
ioPtr.set
(
new IOobject
(
coordinateSystems::typeName,
runTime.constant(),
runTime,
IOobject::MUST_READ,
IOobject::NO_WRITE,
false
)
);
}
if (!ioPtr->headerOk())
{
FatalErrorIn(args.executable())
<< "Cannot open coordinateSystems file\n "
<< ioPtr->objectPath() << nl
<< exit(FatalError);
}
coordinateSystems csLst(ioPtr());
if (args.options().found("from"))
{
const word csName(args.options()["from"]);
label csId = csLst.find(csName);
if (csId < 0)
{
FatalErrorIn(args.executable())
<< "Cannot find -from " << csName << nl
<< "available coordinateSystems: " << csLst.toc() << nl
<< exit(FatalError);
}
fromCsys.reset(new coordinateSystem(csLst[csId]));
}
if (args.options().found("to"))
{
const word csName(args.options()["to"]);
label csId = csLst.find(csName);
if (csId < 0)
{
FatalErrorIn(args.executable())
<< "Cannot find -to " << csName << nl
<< "available coordinateSystems: " << csLst.toc() << nl
<< exit(FatalError);
}
toCsys.reset(new coordinateSystem(csLst[csId]));
}
// maybe fix this later
if (fromCsys.valid() && toCsys.valid())
{
FatalErrorIn(args.executable())
<< "Only allowed '-from' or '-to' option at the moment."
<< exit(FatalError);
}
}
MeshedSurface<face> surf(importName);
if (args.options().found("clean"))
{
surf.cleanup(true);
}
scalar scaleIn = 0;
scalar scaleOut = 0;
if (args.options().found("scaleIn"))
{
IStringStream(args.options()["scaleIn"])() >> scaleIn;
}
if (args.options().found("scaleOut"))
{
IStringStream(args.options()["scaleOut"])() >> scaleOut;
}
if (scaleIn > 0)
{
Info<< " -scaleIn " << scaleIn << endl;
surf.scalePoints(scaleIn);
}
if (fromCsys.valid())
{
Info<< " -from " << fromCsys().name() << endl;
tmp<pointField> tpf = fromCsys().localPosition(surf.points());
surf.movePoints(tpf());
}
if (toCsys.valid())
{
Info<< " -to " << toCsys().name() << endl;
tmp<pointField> tpf = toCsys().globalPosition(surf.points());
surf.movePoints(tpf());
}
if (scaleOut > 0)
{
Info<< " -scaleOut " << scaleOut << endl;
surf.scalePoints(scaleOut);
}
surfMesh smesh
(
IOobject
(
exportName,
runTime.constant(),
runTime
),
surf.xfer()
);
Info<< "writing surfMesh:\n " << smesh.objectPath() << endl;
smesh.write();
Info<< "\nEnd\n" << endl;
return 0;
}
// ************************************************************************* //

View File

@ -461,18 +461,8 @@ label sharedFace
label startIndex = findIndex(f, e.start()); label startIndex = findIndex(f, e.start());
bool edgeOrder; // points in face in same order as edge
bool edgeOrder = (f[f.fcIndex(startIndex)] == e.end());
if (f[(startIndex + 1) % f.size()] == e.end())
{
// points in face in same order as edge
edgeOrder = true;
}
else
{
// points in face in reverse order as edge
edgeOrder = false;
}
// Get faces using edge in sorted order. (sorted such that walking // Get faces using edge in sorted order. (sorted such that walking
// around them in anti-clockwise order corresponds to edge vector // around them in anti-clockwise order corresponds to edge vector
@ -485,19 +475,12 @@ label sharedFace
if (edgeOrder) if (edgeOrder)
{ {
// Get face before firstFaceI // Get face before firstFaceI
if (faceIndex == 0) return eFaces[eFaces.rcIndex(faceIndex)];
{
return eFaces[eFaces.size() - 1];
}
else
{
return eFaces[faceIndex - 1];
}
} }
else else
{ {
// Get face after firstFaceI // Get face after firstFaceI
return eFaces[(faceIndex+1) % eFaces.size()]; return eFaces[eFaces.fcIndex(faceIndex)];
} }
} }

View File

@ -23,7 +23,7 @@ License
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Description Description
UNIX versions of the functions declared in OSspecific.H. UNIX versions of the functions declared in OSspecific.H
\*---------------------------------------------------------------------------*/ \*---------------------------------------------------------------------------*/
@ -218,7 +218,7 @@ Foam::fileName Foam::findEtcFile(const fileName& name, bool mandatory)
// Search user files: // Search user files:
// ~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~
fileName searchDir = home()/".OpenFOAM"; fileName searchDir = home()/".OpenFOAM";
if (dir(searchDir)) if (isDir(searchDir))
{ {
// Check for user file in ~/.OpenFOAM/VERSION // Check for user file in ~/.OpenFOAM/VERSION
fileName fullName = searchDir/FOAMversion/name; fileName fullName = searchDir/FOAMversion/name;
@ -239,7 +239,7 @@ Foam::fileName Foam::findEtcFile(const fileName& name, bool mandatory)
// Search site files: // Search site files:
// ~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~
searchDir = getEnv("WM_PROJECT_INST_DIR"); searchDir = getEnv("WM_PROJECT_INST_DIR");
if (dir(searchDir)) if (isDir(searchDir))
{ {
// Check for site file in $WM_PROJECT_INST_DIR/site/VERSION // Check for site file in $WM_PROJECT_INST_DIR/site/VERSION
fileName fullName = searchDir/"site"/FOAMversion/name; fileName fullName = searchDir/"site"/FOAMversion/name;
@ -259,7 +259,7 @@ Foam::fileName Foam::findEtcFile(const fileName& name, bool mandatory)
// Search installation files: // Search installation files:
// ~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~
searchDir = getEnv("WM_PROJECT_DIR"); searchDir = getEnv("WM_PROJECT_DIR");
if (dir(searchDir)) if (isDir(searchDir))
{ {
// Check for shipped OpenFOAM file in $WM_PROJECT_DIR/etc // Check for shipped OpenFOAM file in $WM_PROJECT_DIR/etc
fileName fullName = searchDir/"etc"/name; fileName fullName = searchDir/"etc"/name;
@ -432,7 +432,7 @@ bool Foam::mkDir(const fileName& pathName, mode_t mode)
// Set the file mode // Set the file mode
bool Foam::chmod(const fileName& name, const mode_t m) bool Foam::chMod(const fileName& name, const mode_t m)
{ {
return ::chmod(name.c_str(), m) == 0; return ::chmod(name.c_str(), m) == 0;
} }
@ -476,24 +476,24 @@ Foam::fileName::Type Foam::type(const fileName& name)
// Does the name exist in the filing system? // Does the name exist in the filing system?
bool Foam::exists(const fileName& name) bool Foam::exists(const fileName& name)
{ {
return mode(name) || file(name); return mode(name) || isFile(name);
}
// Does the file exist
bool Foam::file(const fileName& name)
{
return S_ISREG(mode(name)) || S_ISREG(mode(name + ".gz"));
} }
// Does the directory exist // Does the directory exist
bool Foam::dir(const fileName& name) bool Foam::isDir(const fileName& name)
{ {
return S_ISDIR(mode(name)); return S_ISDIR(mode(name));
} }
// Does the file exist
bool Foam::isFile(const fileName& name, const bool checkGzip)
{
return S_ISREG(mode(name)) || (checkGzip && S_ISREG(mode(name + ".gz")));
}
// Return size of file // Return size of file
off_t Foam::fileSize(const fileName& name) off_t Foam::fileSize(const fileName& name)
{ {
@ -641,7 +641,7 @@ bool Foam::cp(const fileName& src, const fileName& dest)
} }
// Make sure the destination directory exists. // Make sure the destination directory exists.
if (!dir(destFile.path()) && !mkDir(destFile.path())) if (!isDir(destFile.path()) && !mkDir(destFile.path()))
{ {
return false; return false;
} }
@ -681,7 +681,7 @@ bool Foam::cp(const fileName& src, const fileName& dest)
} }
// Make sure the destination directory exists. // Make sure the destination directory exists.
if (!dir(destFile) && !mkDir(destFile)) if (!isDir(destFile) && !mkDir(destFile))
{ {
return false; return false;
} }
@ -719,19 +719,19 @@ bool Foam::cp(const fileName& src, const fileName& dest)
} }
// Create a softlink. destFile should not exist. Returns true if successful. // Create a softlink. dst should not exist. Returns true if successful.
bool Foam::ln(const fileName& src, const fileName& dest) bool Foam::ln(const fileName& src, const fileName& dst)
{ {
if (Unix::debug) if (Unix::debug)
{ {
Info<< "Create softlink from : " << src << " to " << dest Info<< "Create softlink from : " << src << " to " << dst
<< endl; << endl;
} }
if (exists(dest)) if (exists(dst))
{ {
WarningIn("ln(const fileName&, const fileName&)") WarningIn("ln(const fileName&, const fileName&)")
<< "destination " << dest << " already exists. Not linking." << "destination " << dst << " already exists. Not linking."
<< endl; << endl;
return false; return false;
} }
@ -743,40 +743,40 @@ bool Foam::ln(const fileName& src, const fileName& dest)
return false; return false;
} }
if (symlink(src.c_str(), dest.c_str()) == 0) if (symlink(src.c_str(), dst.c_str()) == 0)
{ {
return true; return true;
} }
else else
{ {
WarningIn("ln(const fileName&, const fileName&)") WarningIn("ln(const fileName&, const fileName&)")
<< "symlink from " << src << " to " << dest << " failed." << endl; << "symlink from " << src << " to " << dst << " failed." << endl;
return false; return false;
} }
} }
// Rename srcFile destFile // Rename srcFile dstFile
bool Foam::mv(const fileName& srcFile, const fileName& destFile) bool Foam::mv(const fileName& srcFile, const fileName& dstFile)
{ {
if (Unix::debug) if (Unix::debug)
{ {
Info<< "Move : " << srcFile << " to " << destFile << endl; Info<< "Move : " << srcFile << " to " << dstFile << endl;
} }
if if
( (
(destFile.type() == fileName::DIRECTORY) dstFile.type() == fileName::DIRECTORY
&& (srcFile.type() != fileName::DIRECTORY) && srcFile.type() != fileName::DIRECTORY
) )
{ {
const fileName destName(destFile/srcFile.name()); const fileName dstName(dstFile/srcFile.name());
return rename(srcFile.c_str(), destName.c_str()) == 0; return rename(srcFile.c_str(), dstName.c_str()) == 0;
} }
else else
{ {
return rename(srcFile.c_str(), destFile.c_str()) == 0; return rename(srcFile.c_str(), dstFile.c_str()) == 0;
} }
} }
@ -806,7 +806,7 @@ bool Foam::rmDir(const fileName& directory)
{ {
if (Unix::debug) if (Unix::debug)
{ {
Info<< "rmdir(const fileName&) : " Info<< "rmDir(const fileName&) : "
<< "removing directory " << directory << endl; << "removing directory " << directory << endl;
} }
@ -817,7 +817,7 @@ bool Foam::rmDir(const fileName& directory)
// Attempt to open directory and set the structure pointer // Attempt to open directory and set the structure pointer
if ((source = opendir(directory.c_str())) == NULL) if ((source = opendir(directory.c_str())) == NULL)
{ {
WarningIn("rmdir(const fileName&)") WarningIn("rmDir(const fileName&)")
<< "cannot open directory " << directory << endl; << "cannot open directory " << directory << endl;
return false; return false;
@ -837,7 +837,7 @@ bool Foam::rmDir(const fileName& directory)
{ {
if (!rmDir(path)) if (!rmDir(path))
{ {
WarningIn("rmdir(const fileName&)") WarningIn("rmDir(const fileName&)")
<< "failed to remove directory " << fName << "failed to remove directory " << fName
<< " while removing directory " << directory << " while removing directory " << directory
<< endl; << endl;
@ -851,7 +851,7 @@ bool Foam::rmDir(const fileName& directory)
{ {
if (!rm(path)) if (!rm(path))
{ {
WarningIn("rmdir(const fileName&)") WarningIn("rmDir(const fileName&)")
<< "failed to remove file " << fName << "failed to remove file " << fName
<< " while removing directory " << directory << " while removing directory " << directory
<< endl; << endl;
@ -867,7 +867,7 @@ bool Foam::rmDir(const fileName& directory)
if (!rm(directory)) if (!rm(directory))
{ {
WarningIn("rmdir(const fileName&)") WarningIn("rmDir(const fileName&)")
<< "failed to remove directory " << directory << endl; << "failed to remove directory " << directory << endl;
closedir(source); closedir(source);

View File

@ -45,6 +45,10 @@ $(strings)/fileName/fileNameIO.C
$(strings)/keyType/keyTypeIO.C $(strings)/keyType/keyTypeIO.C
$(strings)/wordRe/wordReIO.C $(strings)/wordRe/wordReIO.C
sha1 = primitives/hashes/SHA1
$(sha1)/SHA1.C
$(sha1)/SHA1Digest.C
primitives/random/Random.C primitives/random/Random.C
containers/HashTables/HashTable/HashTableName.C containers/HashTables/HashTable/HashTableName.C

View File

@ -226,7 +226,7 @@ bool Foam::HashTable<T, Key, Hash>::set
const bool protect const bool protect
) )
{ {
if (tableSize_ == 0) if (!tableSize_)
{ {
resize(2); resize(2);
} }
@ -556,7 +556,7 @@ void Foam::HashTable<T, Key, Hash>::operator=
} }
// could be zero-sized from a previous transfer() // could be zero-sized from a previous transfer()
if (tableSize_ == 0) if (!tableSize_)
{ {
resize(rhs.tableSize_); resize(rhs.tableSize_);
} }

View File

@ -54,7 +54,7 @@ inline Foam::label Foam::HashTable<T, Key, Hash>::size() const
template<class T, class Key, class Hash> template<class T, class Key, class Hash>
inline bool Foam::HashTable<T, Key, Hash>::empty() const inline bool Foam::HashTable<T, Key, Hash>::empty() const
{ {
return (nElmts_ == 0); return !nElmts_;
} }

View File

@ -41,7 +41,7 @@ inline Foam::label Foam::StaticHashTable<T, Key, Hash>::size() const
template<class T, class Key, class Hash> template<class T, class Key, class Hash>
inline bool Foam::StaticHashTable<T, Key, Hash>::empty() const inline bool Foam::StaticHashTable<T, Key, Hash>::empty() const
{ {
return (nElmts_ == 0); return !nElmts_;
} }

View File

@ -83,7 +83,7 @@ inline Foam::label Foam::DLListBase::size() const
inline bool Foam::DLListBase::empty() const inline bool Foam::DLListBase::empty() const
{ {
return (nElmts_ == 0); return !nElmts_;
} }

View File

@ -73,7 +73,7 @@ inline Foam::label Foam::SLListBase::size() const
inline bool Foam::SLListBase::empty() const inline bool Foam::SLListBase::empty() const
{ {
return (nElmts_ == 0); return !nElmts_;
} }

View File

@ -135,10 +135,21 @@ public:
inline label fcIndex(const label i) const; inline label fcIndex(const label i) const;
//- Return the reverse circular index, i.e. the previous index //- Return the reverse circular index, i.e. the previous index
// which returns to the last at the begining of the list // which returns to the last at the beginning of the list
inline label rcIndex(const label i) const; inline label rcIndex(const label i) const;
//- Return a const pointer to the first data element,
// similar to the STL front() method and the string::data() method
// This can be used (with caution) when interfacing with C code.
inline const T* cdata() const;
//- Return a pointer to the first data element,
// similar to the STL front() method and the string::data() method
// This can be used (with caution) when interfacing with C code.
inline T* data();
// Check // Check
//- Check start is within valid range (0 ... size-1). //- Check start is within valid range (0 ... size-1).
@ -174,10 +185,10 @@ public:
// Member operators // Member operators
//- Return subscript-checked element of FixedList. //- Return element of FixedList.
inline T& operator[](const label); inline T& operator[](const label);
//- Return subscript-checked element of constant FixedList. //- Return element of constant FixedList.
inline const T& operator[](const label) const; inline const T& operator[](const label) const;
//- Assignment from array operator. Takes linear time. //- Assignment from array operator. Takes linear time.
@ -282,7 +293,7 @@ public:
//- Return size of the largest possible FixedList. //- Return size of the largest possible FixedList.
inline label max_size() const; inline label max_size() const;
//- Return true if the FixedList is empty (i.e., if size() == 0). //- Return true if the FixedList is empty (ie, size() is zero).
inline bool empty() const; inline bool empty() const;
//- Swap two FixedLists of the same type in constant time. //- Swap two FixedLists of the same type in constant time.

View File

@ -121,7 +121,7 @@ inline Foam::label Foam::FixedList<T, Size>::fcIndex(const label i) const
template<class T, Foam::label Size> template<class T, Foam::label Size>
inline Foam::label Foam::FixedList<T, Size>::rcIndex(const label i) const inline Foam::label Foam::FixedList<T, Size>::rcIndex(const label i) const
{ {
return (i == 0 ? Size-1 : i-1); return (i ? i-1 : Size-1);
} }
@ -195,9 +195,26 @@ inline void Foam::FixedList<T, Size>::transfer(const FixedList<T, Size>& lst)
} }
} }
template<class T, Foam::label Size>
inline const T*
Foam::FixedList<T, Size>::cdata() const
{
return v_;
}
template<class T, Foam::label Size>
inline T*
Foam::FixedList<T, Size>::data()
{
return v_;
}
// * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * //
// Return subscript-checked element access // element access
template<class T, Foam::label Size> template<class T, Foam::label Size>
inline T& Foam::FixedList<T, Size>::operator[](const label i) inline T& Foam::FixedList<T, Size>::operator[](const label i)
{ {
@ -208,7 +225,7 @@ inline T& Foam::FixedList<T, Size>::operator[](const label i)
} }
// Return subscript-checked const element access // const element access
template<class T, Foam::label Size> template<class T, Foam::label Size>
inline const T& Foam::FixedList<T, Size>::operator[](const label i) const inline const T& Foam::FixedList<T, Size>::operator[](const label i) const
{ {

View File

@ -119,7 +119,7 @@ Foam::Istream& Foam::operator>>(Foam::Istream& is, FixedList<T, Size>& L)
} }
else else
{ {
is.read(reinterpret_cast<char*>(L.begin()), Size*sizeof(T)); is.read(reinterpret_cast<char*>(L.data()), Size*sizeof(T));
is.fatalCheck is.fatalCheck
( (
@ -231,7 +231,7 @@ Foam::Ostream& Foam::operator<<(Ostream& os, const FixedList<T, Size>& L)
} }
else else
{ {
os.write(reinterpret_cast<const char*>(L.v_), Size*sizeof(T)); os.write(reinterpret_cast<const char*>(L.cdata()), Size*sizeof(T));
} }
// Check state of IOstream // Check state of IOstream

View File

@ -117,7 +117,7 @@ Foam::Istream& Foam::operator>>(Istream& is, List<T>& L)
{ {
if (s) if (s)
{ {
is.read(reinterpret_cast<char*>(L.begin()), s*sizeof(T)); is.read(reinterpret_cast<char*>(L.data()), s*sizeof(T));
is.fatalCheck is.fatalCheck
( (

View File

@ -90,17 +90,31 @@ void duplicateOrder(const UList<T>&, labelList& order);
template<class T> template<class T>
void uniqueOrder(const UList<T>&, labelList& order); void uniqueOrder(const UList<T>&, labelList& order);
//- Extract elements of List whose region is certain value. //- Extract elements of List when select is a certain value.
// Use e.g. to extract all selected elements: // eg, to extract all selected elements:
// subset<boolList, labelList>(selectedElems, true, lst); // subset<bool, labelList>(selectedElems, true, lst);
template<class T, class ListType> template<class T, class ListType>
ListType subset(const UList<T>& regions, const T& region, const ListType&); ListType subset(const UList<T>& select, const T& value, const ListType&);
//- Inplace extract elements of List whose region is certain value. Use e.g. //- Inplace extract elements of List when select is a certain value.
// to extract all selected elements: // eg, to extract all selected elements:
// inplaceSubset<boolList, labelList>(selectedElems, true, lst); // inplaceSubset<bool, labelList>(selectedElems, true, lst);
template<class T, class ListType> template<class T, class ListType>
void inplaceSubset(const UList<T>& regions, const T& region, ListType&); void inplaceSubset(const UList<T>& select, const T& value, ListType&);
//- Extract elements of List when select is true
// eg, to extract all selected elements:
// subset<boolList, labelList>(selectedElems, lst);
// Note a labelHashSet could also be used for the bool-list
template<class BoolListType, class ListType>
ListType subset(const BoolListType& select, const ListType&);
//- Inplace extract elements of List when select is true
// eg, to extract all selected elements:
// inplaceSubset<boolList, labelList>(selectedElems, lst);
// Note a labelHashSet could also be used for the bool-list
template<class BoolListType, class ListType>
void inplaceSubset(const BoolListType& select, ListType&);
//- Invert one-to-one map. Unmapped elements will be -1. //- Invert one-to-one map. Unmapped elements will be -1.
labelList invert(const label len, const UList<label>&); labelList invert(const label len, const UList<label>&);
@ -108,8 +122,9 @@ labelList invert(const label len, const UList<label>&);
//- Invert one-to-many map. Unmapped elements will be size 0. //- Invert one-to-many map. Unmapped elements will be size 0.
labelListList invertOneToMany(const label len, const UList<label>&); labelListList invertOneToMany(const label len, const UList<label>&);
//- Invert many-to-many. Input and output types need to be inherited //- Invert many-to-many.
// from List. E.g. faces to pointFaces. // Input and output types need to be inherited from List.
// eg, faces to pointFaces.
template<class InList, class OutList> template<class InList, class OutList>
void invertManyToMany(const label len, const UList<InList>&, List<OutList>&); void invertManyToMany(const label len, const UList<InList>&, List<OutList>&);

View File

@ -243,16 +243,17 @@ void Foam::uniqueOrder
template<class T, class ListType> template<class T, class ListType>
ListType Foam::subset ListType Foam::subset
( (
const UList<T>& regions, const UList<T>& select,
const T& region, const T& value,
const ListType& lst const ListType& lst
) )
{ {
if (regions.size() < lst.size()) // select must at least cover the list range
if (select.size() < lst.size())
{ {
FatalErrorIn("subset(const UList<T>&, const T&, const ListType&)") FatalErrorIn("subset(const UList<T>&, const T&, const ListType&)")
<< "Regions is of size " << regions.size() << "select is of size " << select.size()
<< "; list it is supposed to index is of size " << lst.size() << "; but it must index a list of size " << lst.size()
<< abort(FatalError); << abort(FatalError);
} }
@ -261,7 +262,7 @@ ListType Foam::subset
label nElem = 0; label nElem = 0;
forAll(lst, elemI) forAll(lst, elemI)
{ {
if (regions[elemI] == region) if (select[elemI] == value)
{ {
newLst[nElem++] = lst[elemI]; newLst[nElem++] = lst[elemI];
} }
@ -275,23 +276,77 @@ ListType Foam::subset
template<class T, class ListType> template<class T, class ListType>
void Foam::inplaceSubset void Foam::inplaceSubset
( (
const UList<T>& regions, const UList<T>& select,
const T& region, const T& value,
ListType& lst ListType& lst
) )
{ {
if (regions.size() < lst.size()) // select must at least cover the list range
if (select.size() < lst.size())
{ {
FatalErrorIn("inplaceSubset(const UList<T>&, const T&, ListType&)") FatalErrorIn("inplaceSubset(const UList<T>&, const T&, ListType&)")
<< "Regions is of size " << regions.size() << "select is of size " << select.size()
<< "; list it is supposed to index is of size " << lst.size() << "; but it must index a list of size " << lst.size()
<< abort(FatalError); << abort(FatalError);
} }
label nElem = 0; label nElem = 0;
forAll(lst, elemI) forAll(lst, elemI)
{ {
if (regions[elemI] == region) if (select[elemI] == value)
{
if (nElem != elemI)
{
lst[nElem] = lst[elemI];
}
++nElem;
}
}
lst.setSize(nElem);
}
template<class BoolListType, class ListType>
ListType Foam::subset
(
const BoolListType& select,
const ListType& lst
)
{
// select can have a different size
// eg, when it is a PackedBoolList or a labelHashSet
ListType newLst(lst.size());
label nElem = 0;
forAll(lst, elemI)
{
if (select[elemI])
{
newLst[nElem++] = lst[elemI];
}
}
newLst.setSize(nElem);
return newLst;
}
template<class BoolListType, class ListType>
void Foam::inplaceSubset
(
const BoolListType& select,
ListType& lst
)
{
// select can have a different size
// eg, when it is a PackedBoolList or a labelHashSet
label nElem = 0;
forAll(lst, elemI)
{
if (select[elemI])
{ {
if (nElem != elemI) if (nElem != elemI)
{ {

View File

@ -83,25 +83,25 @@ unsigned int Foam::PackedList<nBits>::count() const
if (size_) if (size_)
{ {
// mask value for complete chunks // mask value for complete segments
unsigned int mask = maskLower(packing()); unsigned int mask = maskLower(packing());
unsigned int endIdx = size_ / packing(); const unsigned int endSeg = size_ / packing();
unsigned int endOff = size_ % packing(); const unsigned int endOff = size_ % packing();
// count bits in complete elements // count bits in complete segments
for (unsigned i = 0; i < endIdx; ++i) for (unsigned i = 0; i < endSeg; ++i)
{ {
register unsigned int bits = StorageList::operator[](i) & mask; register unsigned int bits = StorageList::operator[](i) & mask;
COUNT_PACKEDBITS(c, bits); COUNT_PACKEDBITS(c, bits);
} }
// count bits in partial chunk // count bits in partial segment
if (endOff) if (endOff)
{ {
mask = maskLower(endOff); mask = maskLower(endOff);
register unsigned int bits = StorageList::operator[](endIdx) & mask; register unsigned int bits = StorageList::operator[](endSeg) & mask;
COUNT_PACKEDBITS(c, bits); COUNT_PACKEDBITS(c, bits);
} }
} }
@ -118,7 +118,7 @@ bool Foam::PackedList<nBits>::trim()
return false; return false;
} }
// mask value for complete chunks // mask value for complete segments
unsigned int mask = maskLower(packing()); unsigned int mask = maskLower(packing());
label currElem = packedLength(size_) - 1; label currElem = packedLength(size_) - 1;
@ -130,7 +130,7 @@ bool Foam::PackedList<nBits>::trim()
StorageList::operator[](currElem) &= maskLower(endOff); StorageList::operator[](currElem) &= maskLower(endOff);
} }
// test entire chunk // test entire segment
while (currElem > 0 && !(StorageList::operator[](currElem) &= mask)) while (currElem > 0 && !(StorageList::operator[](currElem) &= mask))
{ {
currElem--; currElem--;
@ -162,10 +162,22 @@ bool Foam::PackedList<nBits>::trim()
} }
template<unsigned nBits>
void Foam::PackedList<nBits>::flip()
{
label packLen = packedLength(size_);
for (label i=0; i < packLen; i++)
{
StorageList::operator[](i) = ~StorageList::operator[](i);
}
}
template<unsigned nBits> template<unsigned nBits>
Foam::labelList Foam::PackedList<nBits>::values() const Foam::labelList Foam::PackedList<nBits>::values() const
{ {
labelList elems(size()); labelList elems(size_);
forAll(*this, i) forAll(*this, i)
{ {
@ -178,10 +190,11 @@ Foam::labelList Foam::PackedList<nBits>::values() const
template<unsigned nBits> template<unsigned nBits>
Foam::Ostream& Foam::PackedList<nBits>::iteratorBase::print(Ostream& os) const Foam::Ostream& Foam::PackedList<nBits>::iteratorBase::print(Ostream& os) const
{ {
os << "iterator<" << label(nBits) << "> [" os << "iterator<" << label(nBits) << "> ["
<< (index_ * packing() + offset_) << "]" << this->index_ << "]"
<< " index:" << index_ << " offset:" << offset_ << " segment:" << label(this->index_ / packing())
<< " value:" << unsigned(*this) << " offset:" << label(this->index_ % packing())
<< " value:" << this->get()
<< nl; << nl;
return os; return os;
@ -194,7 +207,7 @@ Foam::Ostream& Foam::PackedList<nBits>::print(Ostream& os) const
os << "PackedList<" << label(nBits) << ">" os << "PackedList<" << label(nBits) << ">"
<< " max_value:" << max_value() << " max_value:" << max_value()
<< " packing:" << packing() << nl << " packing:" << packing() << nl
<< "values: " << size() << "/" << capacity() << "( "; << "values: " << size_ << "/" << capacity() << "( ";
forAll(*this, i) forAll(*this, i)
{ {
os << get(i) << ' '; os << get(i) << ' ';
@ -205,17 +218,17 @@ Foam::Ostream& Foam::PackedList<nBits>::print(Ostream& os) const
os << ")\n" os << ")\n"
<< "storage: " << packLen << "/" << StorageList::size() << "( "; << "storage: " << packLen << "/" << StorageList::size() << "( ";
// mask value for complete chunks // mask value for complete segments
unsigned int mask = maskLower(packing()); unsigned int mask = maskLower(packing());
for (label i=0; i < packLen; i++) for (label i=0; i < packLen; i++)
{ {
const StorageType& rawBits = StorageList::operator[](i); const StorageType& rawBits = StorageList::operator[](i);
// the final storage may not be full, modify mask accordingly // the final segment may not be full, modify mask accordingly
if (i+1 == packLen) if (i+1 == packLen)
{ {
unsigned endOff = size_ % packing(); unsigned int endOff = size_ % packing();
if (endOff) if (endOff)
{ {
@ -229,7 +242,7 @@ Foam::Ostream& Foam::PackedList<nBits>::print(Ostream& os) const
for (unsigned int testBit = (1 << max_bits()); testBit; testBit >>= 1) for (unsigned int testBit = (1 << max_bits()); testBit; testBit >>= 1)
{ {
if (testBit & mask) if (mask & testBit)
{ {
if (rawBits & testBit) if (rawBits & testBit)
{ {

View File

@ -44,9 +44,9 @@ Note
Using the iteratorBase as a proxy allows assignment of values Using the iteratorBase as a proxy allows assignment of values
between list elements. Thus the following bit of code works as expected: between list elements. Thus the following bit of code works as expected:
@code @code
blist[1] = blist[5]; // value assignment, not iterator position list[1] = list[5]; // value assignment, not iterator position
blist[2] = blist[5] = 4; // propagates value list[2] = list[5] = 4; // propagates value
blist[1] = blist[5] = blist[6]; // propagates value list[1] = list[5] = list[6]; // propagates value
@endcode @endcode
Using get() or the '[]' operator are similarly fast. Looping and reading Using get() or the '[]' operator are similarly fast. Looping and reading
@ -58,11 +58,21 @@ Note
useful for branching on changed values. useful for branching on changed values.
@code @code
blist[5] = 4; list[5] = 4;
changed = blist.set(5, 8); changed = list.set(5, 8);
if (changed) ... if (changed) ...
@endcode @endcode
The lazy evaluation used means that reading an out-of-range element
returns zero, but does not affect the list size. Even in a non-const
context, only the assigment causes the element to be created.
For example,
@code
list.resize(4);
Info<< list[10] << "\n"; // print zero, but doesn't adjust list
list[8] = 1;
@endcode
SeeAlso SeeAlso
Foam::DynamicList Foam::DynamicList
@ -120,9 +130,6 @@ class PackedList
//- Calculate the list length when packed //- Calculate the list length when packed
inline static label packedLength(const label); inline static label packedLength(const label);
//- Check index I is within valid range [ 0 .. max_value() ]
inline void checkIndex(const label) const;
public: public:
// Public data // Public data
@ -172,22 +179,23 @@ public:
// Access // Access
//- The number of elements that can be stored before resizing //- The number of elements that can be stored before reallocating
inline label capacity() const; inline label capacity() const;
//- Number of entries. //- Number of entries.
inline label size() const; inline label size() const;
//- Return true if the list is empty (i.e., if size() == 0). //- Return true if the list is empty (ie, size() is zero).
inline bool empty() const; inline bool empty() const;
//- Get value at index I. //- Get value at index I.
// Does not auto-vivify entries. // Never auto-vivify entries.
inline unsigned int get(const label) const; inline unsigned int get(const label) const;
//- Set value at index I. Return true if value changed. //- Set value at index I. Return true if value changed.
// Does not auto-vivify entries. // Does auto-vivify for non-existent entries.
inline bool set(const label, const unsigned int val); // Default value set is the max_value.
inline bool set(const label, const unsigned int val = ~0u);
//- Return the underlying packed storage //- Return the underlying packed storage
inline List<unsigned int>& storage(); inline List<unsigned int>& storage();
@ -200,9 +208,6 @@ public:
// http://en.wikipedia.org/wiki/Hamming_weight // http://en.wikipedia.org/wiki/Hamming_weight
unsigned int count() const; unsigned int count() const;
//- Trim any trailing zero elements
bool trim();
//- Return the values as a labelList //- Return the values as a labelList
labelList values() const; labelList values() const;
@ -211,6 +216,12 @@ public:
// Edit // Edit
//- Trim any trailing zero elements
bool trim();
//- Invert the bits in the addressable region.
void flip();
//- Alter the size of the underlying storage. //- Alter the size of the underlying storage.
// The addressed size will be truncated if needed to fit, but will // The addressed size will be truncated if needed to fit, but will
// remain otherwise untouched. // remain otherwise untouched.
@ -255,12 +266,12 @@ public:
inline unsigned int remove(); inline unsigned int remove();
//- Get value at index I //- Get value at index I
// Does not auto-vivify entries. // Never auto-vivify entries.
inline unsigned int operator[](const label) const; inline unsigned int operator[](const label) const;
//- Set value at index I. //- Set value at index I.
// Returns iterator to perform the actual operation. // Returns iterator to perform the actual operation.
// Does not auto-vivify entries. // Does not auto-vivify entries, but will when assigned to.
inline iteratorBase operator[](const label); inline iteratorBase operator[](const label);
//- Assignment of all entries to the given value. Takes linear time. //- Assignment of all entries to the given value. Takes linear time.
@ -294,52 +305,27 @@ public:
// This also lets us use the default bitwise copy/assignment // This also lets us use the default bitwise copy/assignment
PackedList* list_; PackedList* list_;
//- Element index within storage //- Element index
unsigned index_; label index_;
//- Offset within storage element
unsigned offset_;
// Protected Member Functions // Protected Member Functions
//- Get value as unsigned //- Get value as unsigned, no range-checking
inline unsigned int get() const; inline unsigned int get() const;
//- Set value, returning true if changed //- Set value, returning true if changed, no range-checking
inline bool set(unsigned int); inline bool set(unsigned int);
//- Increment to new position
inline void incr();
//- Decrement to new position
inline void decr();
//- Move to new position, but not beyond end()
inline void seek(const iteratorBase&);
// Constructors // Constructors
//- Construct null //- Construct null
inline iteratorBase(); inline iteratorBase();
//- Copy construct
inline iteratorBase(const iteratorBase&);
//- Construct from base list and position index //- Construct from base list and position index
inline iteratorBase(const PackedList*, const label); inline iteratorBase(const PackedList*, const label);
public: public:
// Member Functions
//- Return true if the element is within addressable range
inline bool valid() const;
//- Move iterator to end() if it would otherwise be out-of-range
// Returns true if the element was already ok
inline bool validate();
// Member Operators // Member Operators
//- Compare positions //- Compare positions
@ -350,10 +336,12 @@ public:
// This allows packed[0] = packed[3] for assigning values // This allows packed[0] = packed[3] for assigning values
inline unsigned int operator=(const iteratorBase&); inline unsigned int operator=(const iteratorBase&);
//- Assign value //- Assign value.
// A non-existent entry will be auto-vivified.
inline unsigned int operator=(const unsigned int val); inline unsigned int operator=(const unsigned int val);
//- Conversion operator //- Conversion operator
// Never auto-vivify entries.
inline operator unsigned int () const; inline operator unsigned int () const;
//- Print value and information //- Print value and information
@ -378,6 +366,8 @@ public:
inline iterator(); inline iterator();
//- Construct from iterator base, eg iter(packedlist[i]) //- Construct from iterator base, eg iter(packedlist[i])
// but also "iterator iter = packedlist[i];"
// An out-of-range iterator is assigned end()
inline iterator(const iteratorBase&); inline iterator(const iteratorBase&);
//- Construct from base list and position index //- Construct from base list and position index
@ -386,6 +376,7 @@ public:
// Member Operators // Member Operators
//- Assign from iteratorBase, eg iter = packedlist[i] //- Assign from iteratorBase, eg iter = packedlist[i]
// An out-of-range iterator is assigned end()
inline iterator& operator=(const iteratorBase&); inline iterator& operator=(const iteratorBase&);
//- Return value //- Return value
@ -427,7 +418,9 @@ public:
//- Construct null //- Construct null
inline const_iterator(); inline const_iterator();
//- Construct from iterator base //- Construct from iterator base, eg iter(packedlist[i])
// but also "const_iterator iter = packedlist[i];"
// An out-of-range iterator is assigned end()
inline const_iterator(const iteratorBase&); inline const_iterator(const iteratorBase&);
//- Construct from base list and position index //- Construct from base list and position index
@ -439,7 +432,7 @@ public:
// Member operators // Member operators
//- Assign from iteratorBase or derived //- Assign from iteratorBase or derived
// eg, iter = packedlist[i] or iter = [non-const]list.begin() // eg, iter = packedlist[i] or even iter = list.begin()
inline const_iterator& operator=(const iteratorBase&); inline const_iterator& operator=(const iteratorBase&);
//- Return referenced value directly //- Return referenced value directly

View File

@ -65,24 +65,6 @@ inline Foam::label Foam::PackedList<nBits>::packedLength(const label nElem)
} }
template<unsigned nBits>
inline void Foam::PackedList<nBits>::checkIndex(const label i) const
{
if (!size_)
{
FatalErrorIn("PackedList<nBits>::checkIndex(const label)")
<< "attempt to access element from zero-sized list"
<< abort(FatalError);
}
else if (i < 0 || i >= size_)
{
FatalErrorIn("PackedList<nBits>::checkIndex(const label)")
<< "index " << i << " out of range 0 ... " << size_-1
<< abort(FatalError);
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
template<unsigned nBits> template<unsigned nBits>
@ -105,7 +87,7 @@ template<unsigned nBits>
inline Foam::PackedList<nBits>::PackedList(const PackedList<nBits>& lst) inline Foam::PackedList<nBits>::PackedList(const PackedList<nBits>& lst)
: :
StorageList(lst), StorageList(lst),
size_(lst.size()) size_(lst.size_)
{} {}
@ -132,20 +114,7 @@ template<unsigned nBits>
inline Foam::PackedList<nBits>::iteratorBase::iteratorBase() inline Foam::PackedList<nBits>::iteratorBase::iteratorBase()
: :
list_(0), list_(0),
index_(0), index_(0)
offset_(0)
{}
template<unsigned nBits>
inline Foam::PackedList<nBits>::iteratorBase::iteratorBase
(
const iteratorBase& iter
)
:
list_(iter.list_),
index_(iter.index_),
offset_(iter.offset_)
{} {}
@ -157,8 +126,7 @@ inline Foam::PackedList<nBits>::iteratorBase::iteratorBase
) )
: :
list_(const_cast<PackedList<nBits>*>(lst)), list_(const_cast<PackedList<nBits>*>(lst)),
index_(i / packing()), index_(i)
offset_(i % packing())
{} {}
@ -166,8 +134,11 @@ template<unsigned nBits>
inline unsigned int inline unsigned int
Foam::PackedList<nBits>::iteratorBase::get() const Foam::PackedList<nBits>::iteratorBase::get() const
{ {
const unsigned int& stored = list_->StorageList::operator[](index_); const unsigned int seg = index_ / packing();
return (stored >> (nBits * offset_)) & max_value(); const unsigned int off = index_ % packing();
const unsigned int& stored = list_->StorageList::operator[](seg);
return (stored >> (nBits * off)) & max_value();
} }
@ -175,114 +146,37 @@ template<unsigned nBits>
inline bool inline bool
Foam::PackedList<nBits>::iteratorBase::set(const unsigned int val) Foam::PackedList<nBits>::iteratorBase::set(const unsigned int val)
{ {
unsigned int& stored = list_->StorageList::operator[](index_); const unsigned int seg = index_ / packing();
const unsigned int off = index_ % packing();
unsigned int& stored = list_->StorageList::operator[](seg);
const unsigned int prev = stored; const unsigned int prev = stored;
const unsigned int startBit = nBits * offset_; const unsigned int startBit = nBits * off;
const unsigned int maskNew = max_value() << startBit; const unsigned int maskNew = max_value() << startBit;
if (val & ~max_value()) if (val & ~max_value())
{ {
# ifdef DEBUGList // overflow is max_value, fill everything
FatalErrorIn("PackedList<T>::iteratorBase::set(const unsigned int)")
<< "value " << label(val)
w << " out-of-range 0 ... " << label(max_value())
<< " representable by " << nBits << " bits"
<< abort(FatalError);
# endif
// treat overflow as max_value
stored |= maskNew; stored |= maskNew;
} }
else else
{ {
stored = (stored & ~maskNew) | (maskNew & (val << startBit)); stored &= ~maskNew;
stored |= maskNew & (val << startBit);
} }
return prev != stored; return prev != stored;
} }
template<unsigned nBits>
inline void
Foam::PackedList<nBits>::iteratorBase::incr()
{
offset_++;
if (offset_ >= packing())
{
offset_ = 0;
index_++;
}
}
template<unsigned nBits>
inline void
Foam::PackedList<nBits>::iteratorBase::decr()
{
if (!offset_)
{
offset_ = packing();
index_--;
}
offset_--;
}
template<unsigned nBits>
inline void
Foam::PackedList<nBits>::iteratorBase::seek
(
const iteratorBase& iter
)
{
list_ = iter.list_;
index_ = iter.index_;
offset_ = iter.offset_;
this->validate();
}
template<unsigned nBits>
inline bool
Foam::PackedList<nBits>::iteratorBase::valid() const
{
label elemI = offset_ + index_ * packing();
return (elemI < list_->size_);
}
template<unsigned nBits>
inline bool
Foam::PackedList<nBits>::iteratorBase::validate()
{
// avoid going past end()
unsigned endIdx = list_->size_ / packing();
unsigned endOff = list_->size_ % packing();
if (index_ > endIdx || (index_ == endIdx && offset_ > endOff))
{
index_ = endIdx;
offset_ = endOff;
return false;
}
else
{
return true;
}
}
template<unsigned nBits> template<unsigned nBits>
inline bool Foam::PackedList<nBits>::iteratorBase::operator== inline bool Foam::PackedList<nBits>::iteratorBase::operator==
( (
const iteratorBase& iter const iteratorBase& iter
) const ) const
{ {
return this->index_ == iter.index_ && this->offset_ == iter.offset_; return this->index_ == iter.index_;
} }
@ -292,7 +186,7 @@ inline bool Foam::PackedList<nBits>::iteratorBase::operator!=
const iteratorBase& iter const iteratorBase& iter
) const ) const
{ {
return this->index_ != iter.index_ || this->offset_ != iter.offset_; return this->index_ != iter.index_;
} }
@ -310,14 +204,11 @@ template<unsigned nBits>
inline unsigned int inline unsigned int
Foam::PackedList<nBits>::iteratorBase::operator=(const unsigned int val) Foam::PackedList<nBits>::iteratorBase::operator=(const unsigned int val)
{ {
# ifdef DEBUGList // lazy evaluation - increase size on assigment
// lazy evaluation would be nice to keep, but really slows things down if (index_ >= list_->size_)
label minsize = 1 + offset_ + index_ * packing();
if (minsize > list_->size_)
{ {
list_->resize(minsize); list_->resize(index_ + 1);
} }
#endif
this->set(val); this->set(val);
return val; return val;
@ -328,14 +219,11 @@ template<unsigned nBits>
inline Foam::PackedList<nBits>::iteratorBase::operator inline Foam::PackedList<nBits>::iteratorBase::operator
unsigned int () const unsigned int () const
{ {
# ifdef DEBUGList // lazy evaluation - return 0 for out-of-range
// lazy evaluation would be nice to keep, but really slows things down if (index_ >= list_->size_)
label minsize = 1 + offset_ + index_ * packing();
if (minsize > list_->size_)
{ {
return 0; return 0;
} }
#endif
return this->get(); return this->get();
} }
@ -365,7 +253,12 @@ inline Foam::PackedList<nBits>::iterator::iterator
: :
iteratorBase(iter) iteratorBase(iter)
{ {
this->validate(); // avoid going past end()
// eg, iter = iterator(list, Inf)
if (this->index_ > this->list_->size_)
{
this->index_ = this->list_->size_;
}
} }
@ -377,7 +270,12 @@ inline Foam::PackedList<nBits>::const_iterator::const_iterator
: :
iteratorBase(iter) iteratorBase(iter)
{ {
this->validate(); // avoid going past end()
// eg, iter = iterator(list, Inf)
if (this->index_ > this->list_->size_)
{
this->index_ = this->list_->size_;
}
} }
@ -417,7 +315,16 @@ template<unsigned nBits>
inline typename Foam::PackedList<nBits>::iterator& inline typename Foam::PackedList<nBits>::iterator&
Foam::PackedList<nBits>::iterator::operator=(const iteratorBase& iter) Foam::PackedList<nBits>::iterator::operator=(const iteratorBase& iter)
{ {
this->seek(iter); this->list_ = iter.list_;
this->index_ = iter.index_;
// avoid going past end()
// eg, iter = iterator(list, Inf)
if (this->index_ > this->list_->size_)
{
this->index_ = this->list_->size_;
}
return *this; return *this;
} }
@ -426,7 +333,16 @@ template<unsigned nBits>
inline typename Foam::PackedList<nBits>::const_iterator& inline typename Foam::PackedList<nBits>::const_iterator&
Foam::PackedList<nBits>::const_iterator::operator=(const iteratorBase& iter) Foam::PackedList<nBits>::const_iterator::operator=(const iteratorBase& iter)
{ {
this->seek(iter); this->list_ = iter.list_;
this->index_ = iter.index_;
// avoid going past end()
// eg, iter = iterator(list, Inf)
if (this->index_ > this->list_->size_)
{
this->index_ = this->list_->size_;
}
return *this; return *this;
} }
@ -435,7 +351,7 @@ template<unsigned nBits>
inline typename Foam::PackedList<nBits>::iterator& inline typename Foam::PackedList<nBits>::iterator&
Foam::PackedList<nBits>::iterator::operator++() Foam::PackedList<nBits>::iterator::operator++()
{ {
this->incr(); ++this->index_;
return *this; return *this;
} }
@ -444,7 +360,7 @@ template<unsigned nBits>
inline typename Foam::PackedList<nBits>::const_iterator& inline typename Foam::PackedList<nBits>::const_iterator&
Foam::PackedList<nBits>::const_iterator::operator++() Foam::PackedList<nBits>::const_iterator::operator++()
{ {
this->incr(); ++this->index_;
return *this; return *this;
} }
@ -454,7 +370,7 @@ inline typename Foam::PackedList<nBits>::iterator
Foam::PackedList<nBits>::iterator::operator++(int) Foam::PackedList<nBits>::iterator::operator++(int)
{ {
iterator old = *this; iterator old = *this;
this->incr(); ++this->index_;
return old; return old;
} }
@ -464,7 +380,7 @@ inline typename Foam::PackedList<nBits>::const_iterator
Foam::PackedList<nBits>::const_iterator::operator++(int) Foam::PackedList<nBits>::const_iterator::operator++(int)
{ {
const_iterator old = *this; const_iterator old = *this;
this->incr(); ++this->index_;
return old; return old;
} }
@ -473,7 +389,7 @@ template<unsigned nBits>
inline typename Foam::PackedList<nBits>::iterator& inline typename Foam::PackedList<nBits>::iterator&
Foam::PackedList<nBits>::iterator::operator--() Foam::PackedList<nBits>::iterator::operator--()
{ {
this->decr(); --this->index_;
return *this; return *this;
} }
@ -482,7 +398,7 @@ template<unsigned nBits>
inline typename Foam::PackedList<nBits>::const_iterator& inline typename Foam::PackedList<nBits>::const_iterator&
Foam::PackedList<nBits>::const_iterator::operator--() Foam::PackedList<nBits>::const_iterator::operator--()
{ {
this->decr(); --this->index_;
return *this; return *this;
} }
@ -492,7 +408,7 @@ inline typename Foam::PackedList<nBits>::iterator
Foam::PackedList<nBits>::iterator::operator--(int) Foam::PackedList<nBits>::iterator::operator--(int)
{ {
iterator old = *this; iterator old = *this;
this->decr(); --this->index_;
return old; return old;
} }
@ -502,7 +418,7 @@ inline typename Foam::PackedList<nBits>::const_iterator
Foam::PackedList<nBits>::const_iterator::operator--(int) Foam::PackedList<nBits>::const_iterator::operator--(int)
{ {
const_iterator old = *this; const_iterator old = *this;
this->decr(); --this->index_;
return old; return old;
} }
@ -567,7 +483,7 @@ template<unsigned nBits>
inline typename Foam::PackedList<nBits>::iterator inline typename Foam::PackedList<nBits>::iterator
Foam::PackedList<nBits>::end() Foam::PackedList<nBits>::end()
{ {
return iterator(this, this->size()); return iterator(this, size_);
} }
@ -575,7 +491,7 @@ template<unsigned nBits>
inline typename Foam::PackedList<nBits>::const_iterator inline typename Foam::PackedList<nBits>::const_iterator
Foam::PackedList<nBits>::end() const Foam::PackedList<nBits>::end() const
{ {
return const_iterator(this, this->size()); return const_iterator(this, size_);
} }
@ -583,7 +499,7 @@ template<unsigned nBits>
inline typename Foam::PackedList<nBits>::const_iterator inline typename Foam::PackedList<nBits>::const_iterator
Foam::PackedList<nBits>::cend() const Foam::PackedList<nBits>::cend() const
{ {
return const_iterator(this, this->size()); return const_iterator(this, size_);
} }
@ -617,20 +533,12 @@ inline void Foam::PackedList<nBits>::resize
// fill new elements or newly exposed elements // fill new elements or newly exposed elements
if (size_) if (size_)
{ {
// fill value for complete chunks // fill value for complete segments
unsigned int fill = val; unsigned int fill = val;
if (fill & ~max_value()) if (fill & ~max_value())
{ {
# ifdef DEBUGList // overflow is max_value, fill everything
FatalErrorIn("PackedList<T>::resize(label, const unsigned int)")
<< "value " << label(val)
<< " out-of-range 0 ... " << label(max_value())
<< " representable by " << nBits << " bits"
<< abort(FatalError);
# endif
// treat overflow as max_value, fill everything
fill = ~0; fill = ~0;
} }
else else
@ -641,26 +549,26 @@ inline void Foam::PackedList<nBits>::resize
} }
} }
unsigned begIdx = size_ / packing(); unsigned int seg = size_ / packing();
unsigned begOff = size_ % packing(); unsigned int off = size_ % packing();
unsigned endIdx = nElem / packing();
// partial chunk, preserve existing value // partial segment, preserve existing value
if (begOff) if (off)
{ {
unsigned int maskOld = maskLower(begOff); unsigned int maskOld = maskLower(off);
StorageList::operator[](begIdx) &= maskOld; StorageList::operator[](seg) &= maskOld;
StorageList::operator[](begIdx) |= ~maskOld & fill; StorageList::operator[](seg) |= ~maskOld & fill;
// continue with the next chunk // continue with the next segment
begIdx++; seg++;
} }
unsigned int endSeg = nElem / packing();
// fill in complete elements // fill in complete elements
while (begIdx < endIdx) while (seg < endSeg)
{ {
StorageList::operator[](begIdx++) = fill; StorageList::operator[](seg++) = fill;
} }
} }
else else
@ -786,17 +694,31 @@ Foam::PackedList<nBits>::xfer()
template<unsigned nBits> template<unsigned nBits>
inline unsigned int Foam::PackedList<nBits>::get(const label i) const inline unsigned int Foam::PackedList<nBits>::get(const label i) const
{ {
# ifdef DEBUGList # ifdef FULLDEBUG
checkIndex(i); if (i < 0)
{
FatalErrorIn("PackedList<nBits>::get(const label)")
<< "negative index " << i << " max=" << size_-1
<< abort(FatalError);
}
# endif # endif
return iteratorBase(this, i).get(); // lazy evaluation - return 0 for out-of-range
if (i < size_)
{
return iteratorBase(this, i).get();
}
else
{
return 0;
}
} }
template<unsigned nBits> template<unsigned nBits>
inline unsigned int Foam::PackedList<nBits>::operator[](const label i) const inline unsigned int Foam::PackedList<nBits>::operator[](const label i) const
{ {
// lazy evaluation - return 0 for out-of-range
if (i < size_) if (i < size_)
{ {
return iteratorBase(this, i).get(); return iteratorBase(this, i).get();
@ -815,18 +737,21 @@ inline bool Foam::PackedList<nBits>::set
const unsigned int val const unsigned int val
) )
{ {
# ifdef DEBUGList # ifdef FULLDEBUG
checkIndex(i); if (i < 0)
if (val & ~max_value())
{ {
FatalErrorIn("PackedList<T>::set(const label, const unsigned int)") FatalErrorIn("PackedList<nBits>::set(const label)")
<< "value " << label(val) << "negative index " << i << " max=" << size_-1
<< " out-of-range 0 ... " << label(max_value())
<< " representable by " << nBits << " bits"
<< abort(FatalError); << abort(FatalError);
} }
# endif #endif
// lazy evaluation - increase size on assigment
if (i >= size_)
{
resize(i + 1);
}
return iteratorBase(this, i).set(val); return iteratorBase(this, i).set(val);
} }
@ -879,14 +804,6 @@ inline void Foam::PackedList<nBits>::operator=(const unsigned int val)
if (fill & ~max_value()) if (fill & ~max_value())
{ {
# ifdef DEBUGList
FatalErrorIn("PackedList<T>::operator=(const unsigned int)")
<< "value " << label(val)
<< " out-of-range 0 ... " << label(max_value())
<< " representable by " << nBits << " bits"
<< abort(FatalError);
# endif
// treat overflow as max_value // treat overflow as max_value
fill = ~0; fill = ~0;
} }

View File

@ -158,7 +158,7 @@ public:
//- Return the number of elements in the PtrList //- Return the number of elements in the PtrList
inline label size() const; inline label size() const;
//- Return true if the PtrList is empty (i.e., if size() == 0). //- Return true if the PtrList is empty (ie, size() is zero).
inline bool empty() const; inline bool empty() const;

View File

@ -27,7 +27,7 @@ Class
Description Description
A 1D vector of objects of type \<T\>, where the size of the vector is A 1D vector of objects of type \<T\>, where the size of the vector is
known and used for subscript bounds checking, etc. known and can be used for subscript bounds checking, etc.
Storage is not allocated during construction or use but is supplied to Storage is not allocated during construction or use but is supplied to
the constructor as an argument. This type of list is particularly useful the constructor as an argument. This type of list is particularly useful
@ -140,6 +140,17 @@ public:
label byteSize() const; label byteSize() const;
//- Return a const pointer to the first data element,
// similar to the STL front() method and the string::data() method
// This can be used (with caution) when interfacing with C code.
inline const T* cdata() const;
//- Return a pointer to the first data element,
// similar to the STL front() method and the string::data() method
// This can be used (with caution) when interfacing with C code.
inline T* data();
// Check // Check
//- Check start is within valid range (0 ... size-1). //- Check start is within valid range (0 ... size-1).
@ -164,10 +175,12 @@ public:
// Member operators // Member operators
//- Return subscript-checked element of UList. //- Return element of UList.
inline T& operator[](const label); inline T& operator[](const label);
//- Return subscript-checked element of constant UList. //- Return element of constant UList.
// Note that the bool specialization adds lazy evaluation so reading
// an out-of-range element returns false without any ill-effects
inline const T& operator[](const label) const; inline const T& operator[](const label) const;
//- Allow cast to a const List<T>& //- Allow cast to a const List<T>&
@ -266,7 +279,7 @@ public:
//- Return size of the largest possible UList. //- Return size of the largest possible UList.
inline label max_size() const; inline label max_size() const;
//- Return true if the UList is empty (i.e., if size() == 0). //- Return true if the UList is empty (ie, size() is zero).
inline bool empty() const; inline bool empty() const;
//- Swap two ULists of the same type in constant time. //- Swap two ULists of the same type in constant time.

View File

@ -25,6 +25,7 @@ License
\*---------------------------------------------------------------------------*/ \*---------------------------------------------------------------------------*/
#include "error.H" #include "error.H"
#include "pTraits.H"
#include "Swap.H" #include "Swap.H"
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
@ -64,7 +65,7 @@ inline Foam::label Foam::UList<T>::fcIndex(const label i) const
template<class T> template<class T>
inline Foam::label Foam::UList<T>::rcIndex(const label i) const inline Foam::label Foam::UList<T>::rcIndex(const label i) const
{ {
return (i == 0 ? size()-1 : i-1); return (i ? i-1 : size()-1);
} }
@ -113,9 +114,24 @@ inline void Foam::UList<T>::checkIndex(const label i) const
} }
template<class T>
inline const T* Foam::UList<T>::cdata() const
{
return v_;
}
template<class T>
inline T* Foam::UList<T>::data()
{
return v_;
}
// * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * //
// Return subscript-checked element access
// element access
template<class T> template<class T>
inline T& Foam::UList<T>::operator[](const label i) inline T& Foam::UList<T>::operator[](const label i)
{ {
@ -126,7 +142,28 @@ inline T& Foam::UList<T>::operator[](const label i)
} }
// Return subscript-checked const element access namespace Foam
{
// Template specialization for bool
template<>
inline const bool& Foam::UList<bool>::operator[](const label i) const
{
// lazy evaluation - return false for out-of-range
if (i < size_)
{
return v_[i];
}
else
{
return Foam::pTraits<bool>::zero;
}
}
} // end of namespace Foam
// const element access
template<class T> template<class T>
inline const T& Foam::UList<T>::operator[](const label i) const inline const T& Foam::UList<T>::operator[](const label i) const
{ {
@ -248,7 +285,7 @@ inline Foam::label Foam::UList<T>::max_size() const
template<class T> template<class T>
inline bool Foam::UList<T>::empty() const inline bool Foam::UList<T>::empty() const
{ {
return (size_ == 0); return !size_;
} }

View File

@ -124,7 +124,7 @@ public:
//- Return the number of elements in the UPtrList //- Return the number of elements in the UPtrList
inline label size() const; inline label size() const;
//- Return true if the UPtrList is empty (i.e., if size() == 0). //- Return true if the UPtrList is empty (ie, size() is zero).
inline bool empty() const; inline bool empty() const;

View File

@ -35,6 +35,85 @@ namespace Foam
defineTypeNameAndDebug(IOobject, 0); defineTypeNameAndDebug(IOobject, 0);
} }
// * * * * * * * * * * * * Static Member Functions * * * * * * * * * * * * * //
// Return components following the IOobject requirements
//
// behaviour
// input IOobject(instance, local, name)
// ----- ------
// "foo" ("", "", "foo")
// "foo/bar" ("foo", "", "bar")
// "/XXX" ERROR - no absolute path
// "foo/bar/" ERROR - no name
// "foo/xxx/bar" ("foo", "xxx", "bar")
// "foo/xxx/yyy/bar" ("foo", "xxx/yyy", "bar")
bool Foam::IOobject::IOobject::fileNameComponents
(
const fileName& path,
fileName& instance,
fileName& local,
word& name
)
{
instance.clear();
local.clear();
name.clear();
// called with directory
if (!isDir(path))
{
WarningIn("IOobject::fileNameComponents(const fileName&, ...)")
<< " called with directory: " << path << "\n";
return false;
}
string::size_type first = path.find('/');
if (first == 0)
{
// called with absolute path
WarningIn("IOobject::fileNameComponents(const fileName&, ...)")
<< "called with absolute path: " << path << "\n";
return false;
}
if (first == string::npos)
{
// no '/' found - no instance or local
// check afterwards
name.string::operator=(path);
}
else
{
instance = path.substr(0, first);
string::size_type last = path.rfind('/');
if (last > first)
{
// with local
local = path.substr(first+1, last-first-1);
}
// check afterwards
name.string::operator=(path.substr(last+1));
}
// check for valid (and stripped) name, regardless of the debug level
if (name.empty() || string::stripInvalid<word>(name))
{
WarningIn("IOobject::fileNameComponents(const fileName&, ...)")
<< "has invalid word for name: \"" << name
<< "\"\nwhile processing path: " << path << "\n";
return false;
}
return true;
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::IOobject::IOobject Foam::IOobject::IOobject
@ -118,7 +197,15 @@ Foam::IOobject::IOobject
registerObject_(registerObject), registerObject_(registerObject),
objState_(GOOD) objState_(GOOD)
{ {
path.IOobjectComponents(instance_, local_, name_); if (!fileNameComponents(path, instance_, local_, name_))
{
FatalErrorIn
(
"IOobject::IOobject" "(const fileName&, const objectRegistry&, ...)"
)
<< " invalid path specification\n"
<< exit(FatalError);
}
if (objectRegistry::debug) if (objectRegistry::debug)
{ {
@ -182,7 +269,7 @@ Foam::fileName Foam::IOobject::filePath() const
fileName path = this->path(); fileName path = this->path();
fileName objectPath = path/name(); fileName objectPath = path/name();
if (file(objectPath)) if (isFile(objectPath))
{ {
return objectPath; return objectPath;
} }
@ -201,13 +288,13 @@ Foam::fileName Foam::IOobject::filePath() const
rootPath()/caseName() rootPath()/caseName()
/".."/instance()/db_.dbDir()/local()/name(); /".."/instance()/db_.dbDir()/local()/name();
if (file(parentObjectPath)) if (isFile(parentObjectPath))
{ {
return parentObjectPath; return parentObjectPath;
} }
} }
if (!dir(path)) if (!isDir(path))
{ {
word newInstancePath = time().findInstancePath(instant(instance())); word newInstancePath = time().findInstancePath(instant(instance()));
@ -219,7 +306,7 @@ Foam::fileName Foam::IOobject::filePath() const
/newInstancePath/db_.dbDir()/local()/name() /newInstancePath/db_.dbDir()/local()/name()
); );
if (file(fName)) if (isFile(fName))
{ {
return fName; return fName;
} }
@ -235,7 +322,7 @@ Foam::Istream* Foam::IOobject::objectStream()
{ {
fileName fName = filePath(); fileName fName = filePath();
if (fName != fileName::null) if (fName.size())
{ {
IFstream* isPtr = new IFstream(fName); IFstream* isPtr = new IFstream(fName);

View File

@ -149,7 +149,6 @@ private:
//- IOobject state //- IOobject state
objectState objState_; objectState objState_;
protected: protected:
// Protected member functions // Protected member functions
@ -168,6 +167,18 @@ public:
TypeName("IOobject"); TypeName("IOobject");
// Static Member Functions
//- Split path into instance, local, name components
static bool fileNameComponents
(
const fileName& path,
fileName& instance,
fileName& local,
word& name
);
// Constructors // Constructors
//- Construct from name, instance, registry, io options //- Construct from name, instance, registry, io options
@ -194,6 +205,7 @@ public:
); );
//- Construct from path, registry, io options //- Construct from path, registry, io options
// Uses fileNameComponents() to split path into components.
IOobject IOobject
( (
const fileName& path, const fileName& path,
@ -215,7 +227,7 @@ public:
virtual ~IOobject(); virtual ~IOobject();
// Member functions // Member Functions
// General access // General access

View File

@ -48,7 +48,7 @@ Foam::IOobjectList::IOobjectList
{ {
word newInstance = instance; word newInstance = instance;
if (!dir(db.path(instance))) if (!isDir(db.path(instance)))
{ {
newInstance = db.time().findInstancePath(instant(instance)); newInstance = db.time().findInstancePath(instant(instance));

View File

@ -54,7 +54,7 @@ Foam::IFstreamAllocator::IFstreamAllocator(const fileName& pathname)
ifPtr_ = new ifstream(pathname.c_str()); ifPtr_ = new ifstream(pathname.c_str());
// If the file is compressed, decompress it before reading. // If the file is compressed, decompress it before reading.
if (!ifPtr_->good() && file(pathname + ".gz")) if (!ifPtr_->good() && isFile(pathname + ".gz", false))
{ {
if (IFstream::debug) if (IFstream::debug)
{ {
@ -120,8 +120,8 @@ Foam::IFstream::IFstream
if (debug) if (debug)
{ {
Info<< "IFstream::IFstream(const fileName&," Info<< "IFstream::IFstream(const fileName&,"
"streamFormat format=ASCII," "streamFormat=ASCII,"
"versionNumber version=currentVersion) : " "versionNumber=currentVersion) : "
"could not open file for input" "could not open file for input"
<< endl << info() << endl; << endl << info() << endl;
} }
@ -159,17 +159,18 @@ Foam::IFstream& Foam::IFstream::operator()() const
{ {
if (!good()) if (!good())
{ {
if (!file(pathname_) && !file(pathname_ + ".gz")) // also checks .gz file
if (isFile(pathname_, true))
{
check("IFstream::operator()");
FatalIOError.exit();
}
else
{ {
FatalIOErrorIn("IFstream::operator()", *this) FatalIOErrorIn("IFstream::operator()", *this)
<< "file " << pathname_ << " does not exist" << "file " << pathname_ << " does not exist"
<< exit(FatalIOError); << exit(FatalIOError);
} }
else
{
check("IFstream::operator()");
FatalIOError.exit();
}
} }
return const_cast<IFstream&>(*this); return const_cast<IFstream&>(*this);

View File

@ -57,7 +57,8 @@ Foam::OFstreamAllocator::OFstreamAllocator
if (compression == IOstream::COMPRESSED) if (compression == IOstream::COMPRESSED)
{ {
if (file(pathname)) // get identically named uncompressed version out of the way
if (isFile(pathname, false))
{ {
rm(pathname); rm(pathname);
} }
@ -66,7 +67,8 @@ Foam::OFstreamAllocator::OFstreamAllocator
} }
else else
{ {
if (file(pathname + ".gz")) // get identically named compressed version out of the way
if (isFile(pathname + ".gz", false))
{ {
rm(pathname + ".gz"); rm(pathname + ".gz");
} }

View File

@ -0,0 +1,212 @@
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 1991-2009 OpenCFD Ltd.
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Class
Foam::OSHA1stream
Description
An output stream for calculating SHA1 digests.
SourceFiles
OSHA1stream.C
\*---------------------------------------------------------------------------*/
#ifndef OSHA1stream_H
#define OSHA1stream_H
#include "OSstream.H"
#include "SHA1.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
class osha1stream;
class OSHA1stream;
/*---------------------------------------------------------------------------*\
Class sha1streambuf Declaration
\*---------------------------------------------------------------------------*/
//- A streambuf class for calculating SHA1 digests
class sha1streambuf
:
public std::streambuf
{
// Private data
//- This does all the work and has its own buffering
SHA1 sha1_;
friend class osha1stream;
public:
// Constructors
//- Construct null
sha1streambuf()
{}
// Member Functions
// Write
//- Process unbuffered
virtual std::streamsize xsputn(const char* str, std::streamsize n)
{
sha1_.append(str, n);
return n;
}
};
/*---------------------------------------------------------------------------*\
Class osha1stream Declaration
\*---------------------------------------------------------------------------*/
//- A basic output stream for calculating SHA1 digests
class osha1stream
:
virtual public std::ios,
public std::ostream
{
// Private data
sha1streambuf sbuf_;
public:
// Constructors
//- Construct null
osha1stream()
:
std::ostream(&sbuf_)
{}
// Member Functions
// Access
//- This hides both signatures of std::basic_ios::rdbuf()
sha1streambuf* rdbuf()
{
return &sbuf_;
}
//- Full access to the sha1
SHA1& sha1()
{
return sbuf_.sha1_;
}
};
/*---------------------------------------------------------------------------*\
Class OSHA1stream Declaration
\*---------------------------------------------------------------------------*/
//- The output stream for calculating SHA1 digests
class OSHA1stream
:
public OSstream
{
// Private Member Functions
//- Disallow default bitwise copy construct
OSHA1stream(const OSHA1stream&);
//- Disallow default bitwise assignment
void operator=(const OSHA1stream&);
public:
// Constructors
//- Construct and set stream status
OSHA1stream
(
streamFormat format=ASCII,
versionNumber version=currentVersion
)
:
OSstream
(
*(new osha1stream),
"OSHA1stream.sinkFile_",
format,
version
)
{}
// Destructor
~OSHA1stream()
{
delete &dynamic_cast<osha1stream&>(stream());
}
// Member functions
// Access
//- Full access to the sha1
Foam::SHA1& sha1()
{
return dynamic_cast<osha1stream&>(stream()).sha1();
}
//- Return SHA1::Digest for the data processed until now
Foam::SHA1Digest digest()
{
return sha1().digest();
}
// Edit
//- Clear the SHA1 calculation
void rewind()
{
sha1().clear();
}
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //

View File

@ -31,11 +31,7 @@ License
// * * * * * * * * * * * * * Static Member Data * * * * * * * * * * * * * * // // * * * * * * * * * * * * * Static Member Data * * * * * * * * * * * * * * //
namespace Foam defineTypeNameAndDebug(Foam::Time, 0);
{
defineTypeNameAndDebug(Time, 0);
}
template<> template<>
const char* Foam::NamedEnum<Foam::Time::stopAtControls, 4>::names[] = const char* Foam::NamedEnum<Foam::Time::stopAtControls, 4>::names[] =
@ -100,9 +96,11 @@ void Foam::Time::adjustDeltaT()
void Foam::Time::setControls() void Foam::Time::setControls()
{ {
// default is to resume calculation from "latestTime" // default is to resume calculation from "latestTime"
word startFrom("latestTime"); word startFrom = controlDict_.lookupOrDefault<word>
(
controlDict_.readIfPresent("startFrom", startFrom); "startFrom",
"latestTime"
);
if (startFrom == "startTime") if (startFrom == "startTime")
{ {
@ -421,7 +419,7 @@ Foam::instant Foam::Time::findClosestTime(const scalar t) const
label nearestIndex = -1; label nearestIndex = -1;
scalar deltaT = GREAT; scalar deltaT = GREAT;
for (label i=1; i<times.size(); i++) for (label i=1; i < times.size(); i++)
{ {
scalar diff = mag(times[i].value() - t); scalar diff = mag(times[i].value() - t);
if (diff < deltaT) if (diff < deltaT)

View File

@ -283,7 +283,7 @@ public:
//- Return the location of "dir" containing the file "name". //- Return the location of "dir" containing the file "name".
// (Used in reading mesh data) // (Used in reading mesh data)
// If name is null search for a directory "dir" // If name is null search for the directory "dir" only
word findInstance word findInstance
( (
const fileName& dir, const fileName& dir,

View File

@ -42,78 +42,74 @@ Foam::word Foam::Time::findInstance
const IOobject::readOption rOpt const IOobject::readOption rOpt
) const ) const
{ {
// Is the mesh data in the current time directory ? // Note: if name is empty, just check the directory itself
// check the current time directory
if if
( (
(name.empty() && Foam::dir(path()/timeName()/dir)) name.empty()
|| ? isDir(path()/timeName()/dir)
:
( (
!name.empty() isFile(path()/timeName()/dir/name)
&& file(path()/timeName()/dir/name)
&& IOobject(name, timeName(), dir, *this).headerOk() && IOobject(name, timeName(), dir, *this).headerOk()
) )
) )
{ {
if (debug) if (debug)
{ {
Info<< "Time::findInstance(const word&, const word&) : " Info<< "Time::findInstance(const fileName&, const word&) : "
<< "found " << name << "found \"" << name
<< " in " << timeName()/dir << "\" in " << timeName()/dir
<< endl; << endl;
} }
return timeName(); return timeName();
} }
// Search back through the time directories list to find the time // Search back through the time directories to find the time
// closest to and lower than current time // closest to and lower than current time
instantList ts = times(); instantList ts = times();
label i; label instanceI;
for (i=ts.size()-1; i>=0; i--) for (instanceI = ts.size()-1; instanceI >= 0; --instanceI)
{ {
if (ts[i].value() <= timeOutputValue()) if (ts[instanceI].value() <= timeOutputValue())
{ {
break; break;
} }
} }
// Noting that the current directory has already been searched // continue searching from here
// for mesh data, start searching from the previously stored time directory for (; instanceI >= 0; --instanceI)
if (i>=0)
{ {
for (label j=i; j>=0; j--) if
{ (
if name.empty()
? isDir(path()/ts[instanceI].name()/dir)
:
( (
(name.empty() && Foam::dir(path()/ts[j].name()/dir)) isFile(path()/ts[instanceI].name()/dir/name)
|| && IOobject(name, ts[instanceI].name(), dir, *this).headerOk()
(
!name.empty()
&& file(path()/ts[j].name()/dir/name)
&& IOobject(name, ts[j].name(), dir, *this).headerOk()
)
) )
)
{
if (debug)
{ {
if (debug) Info<< "Time::findInstance"
{ "(const fileName&,const word&) : "
Info<< "Time::findInstance(const word&, " << "found \"" << name
<< "const word&) : " << "\" in " << ts[instanceI].name()/dir
<< "found " << name << endl;
<< " in " << ts[j].name()/dir
<< endl;
}
return ts[j].name();
} }
return ts[instanceI].name();
} }
} }
// If the mesh data is not in any of the time directories // not in any of the time directories, try constant
// Try in constant
// Note. This needs to be a hard-coded constant, rather than the // Note. This needs to be a hard-coded constant, rather than the
// constant function of the time, because the latter points to // constant function of the time, because the latter points to
@ -121,20 +117,21 @@ Foam::word Foam::Time::findInstance
if if
( (
(name.empty() && Foam::dir(path()/constant()/dir)) name.empty()
|| ( ? isDir(path()/constant()/dir)
!name.empty() :
&& file(path()/constant()/dir/name) (
isFile(path()/constant()/dir/name)
&& IOobject(name, constant(), dir, *this).headerOk() && IOobject(name, constant(), dir, *this).headerOk()
) )
) )
{ {
if (debug) if (debug)
{ {
Info<< "Time::findInstance(const word&, " Info<< "Time::findInstance"
<< "const word&) : " "(const fileName&,const word&) : "
<< "found " << name << "found \"" << name
<< " in " << constant()/dir << "\" in " << constant()/dir
<< endl; << endl;
} }
@ -143,7 +140,10 @@ Foam::word Foam::Time::findInstance
if (rOpt == IOobject::MUST_READ) if (rOpt == IOobject::MUST_READ)
{ {
FatalErrorIn("Time::findInstance(const word&, const word&)") FatalErrorIn
(
"Time::findInstance(const fileName&,const word&)"
)
<< "Cannot find file \"" << name << "\" in directory " << "Cannot find file \"" << name << "\" in directory "
<< constant()/dir << constant()/dir
<< exit(FatalError); << exit(FatalError);

View File

@ -103,7 +103,7 @@ Foam::List<Foam::instant> Foam::timeSelector::select
const List<instant>& Times const List<instant>& Times
) const ) const
{ {
return subset(selected(Times), true, Times); return subset(selected(Times), Times);
} }
@ -112,7 +112,7 @@ void Foam::timeSelector::inplaceSelect
List<instant>& Times List<instant>& Times
) const ) const
{ {
inplaceSubset(selected(Times), true, Times); inplaceSubset(selected(Times), Times);
} }
@ -219,7 +219,7 @@ Foam::List<Foam::instant> Foam::timeSelector::select
} }
} }
return subset(selectTimes, true, timeDirs); return subset(selectTimes, timeDirs);
} }
else else
{ {

View File

@ -28,6 +28,7 @@ License
#include "primitiveEntry.H" #include "primitiveEntry.H"
#include "dictionaryEntry.H" #include "dictionaryEntry.H"
#include "regExp.H" #include "regExp.H"
#include "OSHA1stream.H"
/* * * * * * * * * * * * * * * Static Member Data * * * * * * * * * * * * * */ /* * * * * * * * * * * * * * * Static Member Data * * * * * * * * * * * * * */
@ -232,6 +233,25 @@ Foam::label Foam::dictionary::endLineNumber() const
} }
Foam::SHA1Digest Foam::dictionary::digest() const
{
OSHA1stream os;
// process entries
for
(
IDLList<entry>::const_iterator iter = begin();
iter != end();
++iter
)
{
os << *iter;
}
return os.digest();
}
bool Foam::dictionary::found(const word& keyword, bool recursive) const bool Foam::dictionary::found(const word& keyword, bool recursive) const
{ {
if (hashedEntries_.found(keyword)) if (hashedEntries_.found(keyword))

View File

@ -69,6 +69,8 @@ namespace Foam
// Forward declaration of friend functions and operators // Forward declaration of friend functions and operators
class regExp; class regExp;
class dictionary; class dictionary;
class SHA1Digest;
Istream& operator>>(Istream&, dictionary&); Istream& operator>>(Istream&, dictionary&);
Ostream& operator<<(Ostream&, const dictionary&); Ostream& operator<<(Ostream&, const dictionary&);
@ -210,6 +212,9 @@ public:
//- Return line number of last token in dictionary //- Return line number of last token in dictionary
label endLineNumber() const; label endLineNumber() const;
//- Return the SHA1 digest of the dictionary contents
SHA1Digest digest() const;
// Search and lookup // Search and lookup

View File

@ -45,7 +45,7 @@ Foam::dictionaryEntry::dictionaryEntry
is.fatalCheck is.fatalCheck
( (
"dictionaryEntry::dictionaryEntry" "dictionaryEntry::dictionaryEntry"
"(const dictionary& parentDict, Istream& is)" "(const dictionary& parentDict, Istream&)"
); );
} }
@ -65,7 +65,7 @@ Foam::dictionaryEntry::dictionaryEntry
is.fatalCheck is.fatalCheck
( (
"dictionaryEntry::dictionaryEntry" "dictionaryEntry::dictionaryEntry"
"(const keyType& keyword, const dictionary& parentDict, Istream& is)" "(const keyType&, const dictionary& parentDict, Istream&)"
); );
} }
@ -74,7 +74,9 @@ Foam::dictionaryEntry::dictionaryEntry
void Foam::dictionaryEntry::write(Ostream& os) const void Foam::dictionaryEntry::write(Ostream& os) const
{ {
os.writeKeyword(keyword()); // write keyword with indent but without trailing spaces
os.indent();
os.write(keyword());
dictionary::write(os); dictionary::write(os);
} }

View File

@ -29,14 +29,10 @@ License
#include "Time.H" #include "Time.H"
#include "PstreamReduceOps.H" #include "PstreamReduceOps.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
Istream& regIOobject::readStream() Foam::Istream& Foam::regIOobject::readStream()
{ {
if (IFstream::debug) if (IFstream::debug)
{ {
@ -48,7 +44,7 @@ Istream& regIOobject::readStream()
if (readOpt() == NO_READ) if (readOpt() == NO_READ)
{ {
FatalErrorIn("regIOobject::readStream(const word&)") FatalErrorIn("regIOobject::readStream()")
<< "NO_READ specified for read-constructor of object " << name() << "NO_READ specified for read-constructor of object " << name()
<< " of class " << headerClassName() << " of class " << headerClassName()
<< abort(FatalError); << abort(FatalError);
@ -61,7 +57,7 @@ Istream& regIOobject::readStream()
{ {
FatalIOError FatalIOError
( (
"regIOobject::readStream(const word&)", "regIOobject::readStream()",
__FILE__, __FILE__,
__LINE__, __LINE__,
objectPath(), objectPath(),
@ -71,7 +67,7 @@ Istream& regIOobject::readStream()
} }
else if (!readHeader(*isPtr_)) else if (!readHeader(*isPtr_))
{ {
FatalIOErrorIn("regIOobject::readStream(const word&)", *isPtr_) FatalIOErrorIn("regIOobject::readStream()", *isPtr_)
<< "problem while reading header for object " << name() << "problem while reading header for object " << name()
<< exit(FatalIOError); << exit(FatalIOError);
} }
@ -86,7 +82,7 @@ Istream& regIOobject::readStream()
} }
Istream& regIOobject::readStream(const word& aType) Foam::Istream& Foam::regIOobject::readStream(const word& expectName)
{ {
if (IFstream::debug) if (IFstream::debug)
{ {
@ -106,14 +102,14 @@ Istream& regIOobject::readStream(const word& aType)
// instantiated is a dictionary // instantiated is a dictionary
if if
( (
aType != word::null expectName.size()
&& headerClassName() != aType && headerClassName() != expectName
&& headerClassName() != "dictionary" && headerClassName() != "dictionary"
) )
{ {
FatalIOErrorIn("regIOobject::readStream(const word&)", *isPtr_) FatalIOErrorIn("regIOobject::readStream(const word&)", *isPtr_)
<< "unexpected class name " << headerClassName() << "unexpected class name " << headerClassName()
<< " expected " << aType << endl << " expected " << expectName << endl
<< " while reading object " << name() << " while reading object " << name()
<< exit(FatalIOError); << exit(FatalIOError);
} }
@ -123,7 +119,7 @@ Istream& regIOobject::readStream(const word& aType)
} }
void regIOobject::close() void Foam::regIOobject::close()
{ {
if (IFstream::debug) if (IFstream::debug)
{ {
@ -140,13 +136,13 @@ void regIOobject::close()
} }
bool regIOobject::readData(Istream&) bool Foam::regIOobject::readData(Istream&)
{ {
return false; return false;
} }
bool regIOobject::read() bool Foam::regIOobject::read()
{ {
bool ok = readData(readStream(type())); bool ok = readData(readStream(type()));
close(); close();
@ -154,7 +150,7 @@ bool regIOobject::read()
} }
bool regIOobject::modified() const bool Foam::regIOobject::modified() const
{ {
return return
( (
@ -164,7 +160,7 @@ bool regIOobject::modified() const
} }
bool regIOobject::readIfModified() bool Foam::regIOobject::readIfModified()
{ {
if (lastModified_) if (lastModified_)
{ {
@ -213,8 +209,4 @@ bool regIOobject::readIfModified()
} }
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// ************************************************************************* // // ************************************************************************* //

View File

@ -123,7 +123,7 @@ Foam::List<Foam::scalar> Foam::scalarRanges::select
const List<scalar>& values const List<scalar>& values
) const ) const
{ {
return subset(selected(values), true, values); return subset(selected(values), values);
} }
@ -132,7 +132,7 @@ void Foam::scalarRanges::inplaceSelect
List<scalar>& values List<scalar>& values
) const ) const
{ {
inplaceSubset(selected(values), true, values); inplaceSubset(selected(values), values);
} }

View File

@ -123,7 +123,7 @@ public:
enum dimensionType enum dimensionType
{ {
MASS, // kilogram kg MASS, // kilogram kg
LENGTH, // meter m LENGTH, // metre m
TIME, // second s TIME, // second s
TEMPERATURE, // Kelvin K TEMPERATURE, // Kelvin K
MOLES, // mole mol MOLES, // mole mol

View File

@ -44,6 +44,7 @@ const Foam::dimensionSet Foam::dimVol(0, 3, 0, 0, 0, 0, 0);
const Foam::dimensionSet Foam::dimDensity(1, -3, 0, 0, 0, 0, 0); const Foam::dimensionSet Foam::dimDensity(1, -3, 0, 0, 0, 0, 0);
const Foam::dimensionSet Foam::dimForce(1, 1, -2, 0, 0, 0, 0); const Foam::dimensionSet Foam::dimForce(1, 1, -2, 0, 0, 0, 0);
const Foam::dimensionSet Foam::dimEnergy(1, 2, -2, 0, 0, 0, 0);
const Foam::dimensionSet Foam::dimVelocity(0, 1, -1, 0, 0, 0, 0); const Foam::dimensionSet Foam::dimVelocity(0, 1, -1, 0, 0, 0, 0);
const Foam::dimensionSet Foam::dimAcceleration(0, 1, -2, 0, 0, 0, 0); const Foam::dimensionSet Foam::dimAcceleration(0, 1, -2, 0, 0, 0, 0);

View File

@ -60,6 +60,7 @@ extern const dimensionSet dimVol;
extern const dimensionSet dimDensity; extern const dimensionSet dimDensity;
extern const dimensionSet dimForce; extern const dimensionSet dimForce;
extern const dimensionSet dimEnergy;
extern const dimensionSet dimVelocity; extern const dimensionSet dimVelocity;
extern const dimensionSet dimAcceleration; extern const dimensionSet dimAcceleration;

View File

@ -105,7 +105,7 @@ void pointPatchField<Type>::write(Ostream& os) const
{ {
os.writeKeyword("type") << type() << token::END_STATEMENT << nl; os.writeKeyword("type") << type() << token::END_STATEMENT << nl;
if (patchType_ != word::null) if (patchType_.size())
{ {
os.writeKeyword("patchType") << patchType_ os.writeKeyword("patchType") << patchType_
<< token::END_STATEMENT << nl; << token::END_STATEMENT << nl;

View File

@ -65,14 +65,14 @@ Foam::JobInfo::JobInfo()
<< Foam::exit(FatalError); << Foam::exit(FatalError);
} }
if (!dir(runningDir) && !mkDir(runningDir)) if (!isDir(runningDir) && !mkDir(runningDir))
{ {
FatalErrorIn("JobInfo::JobInfo()") FatalErrorIn("JobInfo::JobInfo()")
<< "Cannot make JobInfo directory " << runningDir << "Cannot make JobInfo directory " << runningDir
<< Foam::exit(FatalError); << Foam::exit(FatalError);
} }
if (!dir(finishedDir) && !mkDir(finishedDir)) if (!isDir(finishedDir) && !mkDir(finishedDir))
{ {
FatalErrorIn("JobInfo::JobInfo()") FatalErrorIn("JobInfo::JobInfo()")
<< "Cannot make JobInfo directory " << finishedDir << "Cannot make JobInfo directory " << finishedDir

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