Merge pull request #6108 from OPM/appfwk-clang-format

Use clang-format on AppFwk
This commit is contained in:
Magne Sjaastad 2020-06-19 09:01:11 +02:00 committed by GitHub
commit 6ad749030a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
409 changed files with 89072 additions and 42319 deletions

View File

@ -11,13 +11,20 @@ jobs:
sudo apt install clang-format-6.0
clang-format-6.0 --version
- uses: actions/checkout@v2
- name: Check format
- name: Check format - ApplicationCode
run: |
cd ApplicationCode
find -name "*.h" -o -name "*.cpp" -o -name "*.inl" | xargs clang-format-6.0 -i
find -name *.h -o -name *.cpp -o -name *.inl | xargs clang-format-6.0 -i
git diff
- name: Check format - AppFwk
run: |
cd Fwk/AppFwk
find -name *.h -o -name *.cpp -o -name *.inl | grep -v gtest | xargs clang-format-6.0 -i
git diff
- uses: peter-evans/create-pull-request@v2
with:
token: ${{ secrets.GITHUB_TOKEN }}
commit-message: 'Fixes by clang-format'
title: 'Fixes by clang-format'

79
Fwk/AppFwk/.clang-format Normal file
View File

@ -0,0 +1,79 @@
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: true
AlignEscapedNewlinesLeft: true
AlignOperands: true
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: true
AllowShortFunctionsOnASingleLine: InlineOnly
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: true
BinPackArguments: false
BinPackParameters: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Allman
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: true
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 120
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
- Regex: '^(<|"(gtest|isl|json)/)'
Priority: 3
- Regex: '.*'
Priority: 1
IncludeIsMainRegex: '$'
IndentCaseLabels: true
IndentWidth: 4
IndentWrappedFunctionNames: true
JavaScriptQuotes: Leave
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
PenaltyBreakAssignment: 13
PenaltyBreakBeforeFirstCallParameter: 10000
PenaltyBreakComment: 20
PenaltyBreakFirstLessLess: 12
PenaltyBreakString: 100
PenaltyExcessCharacter: 5
PenaltyReturnTypeOnItsOwnLine: 30
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: false
SpacesInCStyleCastParentheses: false
SpacesInParentheses: true
SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 4
UseTab: Never
...

View File

@ -45,33 +45,33 @@ namespace caf
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
ColorTable::ColorTable(const std::vector<cvf::Color3ub>& colors)
: m_colors(colors)
ColorTable::ColorTable( const std::vector<cvf::Color3ub>& colors )
: m_colors( colors )
{
CVF_ASSERT(m_colors.size() > 0);
CVF_ASSERT( m_colors.size() > 0 );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
ColorTable::ColorTable(const cvf::Color3ubArray& colors)
: m_colors(colors.begin(), colors.end())
ColorTable::ColorTable( const cvf::Color3ubArray& colors )
: m_colors( colors.begin(), colors.end() )
{
CVF_ASSERT(m_colors.size() > 0);
CVF_ASSERT( m_colors.size() > 0 );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f ColorTable::cycledColor3f(size_t itemIndex) const
cvf::Color3f ColorTable::cycledColor3f( size_t itemIndex ) const
{
return cvf::Color3f(cycledColor3ub(itemIndex));
return cvf::Color3f( cycledColor3ub( itemIndex ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3ub ColorTable::cycledColor3ub(size_t itemIndex) const
cvf::Color3ub ColorTable::cycledColor3ub( size_t itemIndex ) const
{
size_t modIndex = itemIndex % m_colors.size();
@ -81,10 +81,10 @@ cvf::Color3ub ColorTable::cycledColor3ub(size_t itemIndex) const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QColor ColorTable::cycledQColor(size_t itemIndex) const
QColor ColorTable::cycledQColor( size_t itemIndex ) const
{
cvf::Color3ub col = cycledColor3ub(itemIndex);
return QColor(col.r(), col.g(), col.b());
cvf::Color3ub col = cycledColor3ub( itemIndex );
return QColor( col.r(), col.g(), col.b() );
}
//--------------------------------------------------------------------------------------------------
@ -92,7 +92,7 @@ QColor ColorTable::cycledQColor(size_t itemIndex) const
//--------------------------------------------------------------------------------------------------
cvf::Color3ubArray ColorTable::color3ubArray() const
{
return cvf::Color3ubArray(m_colors);
return cvf::Color3ubArray( m_colors );
}
//--------------------------------------------------------------------------------------------------
@ -102,10 +102,10 @@ cvf::Color3fArray ColorTable::color3fArray() const
{
cvf::Color3fArray col3fArr;
col3fArr.reserve(m_colors.size());
for (const auto& c : m_colors)
col3fArr.reserve( m_colors.size() );
for ( const auto& c : m_colors )
{
col3fArr.add(cvf::Color3f(c));
col3fArr.add( cvf::Color3f( c ) );
}
return col3fArr;
@ -125,59 +125,59 @@ size_t ColorTable::size() const
caf::ColorTable ColorTable::inverted() const
{
std::vector<cvf::Color3ub> invertedColors = m_colors;
std::reverse(invertedColors.begin(), invertedColors.end());
return ColorTable(invertedColors);
std::reverse( invertedColors.begin(), invertedColors.end() );
return ColorTable( invertedColors );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3ub ColorTable::fromQColor(const QColor& color)
cvf::Color3ub ColorTable::fromQColor( const QColor& color )
{
return cvf::Color3ub(color.red(), color.green(), color.blue());
return cvf::Color3ub( color.red(), color.green(), color.blue() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3ubArray ColorTable::interpolateColorArray(const cvf::Color3ubArray& colorArray, size_t targetColorCount)
cvf::Color3ubArray ColorTable::interpolateColorArray( const cvf::Color3ubArray& colorArray, size_t targetColorCount )
{
size_t inputColorCount = colorArray.size();
CVF_ASSERT(inputColorCount > 1);
CVF_ASSERT(targetColorCount > 1);
CVF_ASSERT( inputColorCount > 1 );
CVF_ASSERT( targetColorCount > 1 );
cvf::Color3ubArray colors;
colors.reserve(targetColorCount);
colors.reserve( targetColorCount );
const size_t inputColorsMaxIdx = inputColorCount - 1;
const size_t outputColorsMaxIdx = targetColorCount - 1;
for (size_t outputLevelIdx = 0; outputLevelIdx < outputColorsMaxIdx; outputLevelIdx++)
for ( size_t outputLevelIdx = 0; outputLevelIdx < outputColorsMaxIdx; outputLevelIdx++ )
{
double dblInputLevelIndex = inputColorsMaxIdx * (outputLevelIdx / static_cast<double>(outputColorsMaxIdx));
double dblInputLevelIndex = inputColorsMaxIdx * ( outputLevelIdx / static_cast<double>( outputColorsMaxIdx ) );
const size_t inputLevelIndex = static_cast<size_t>(dblInputLevelIndex);
CVF_ASSERT(inputLevelIndex < inputColorsMaxIdx);
const size_t inputLevelIndex = static_cast<size_t>( dblInputLevelIndex );
CVF_ASSERT( inputLevelIndex < inputColorsMaxIdx );
double t = dblInputLevelIndex - inputLevelIndex;
CVF_ASSERT(t >= 0 && t <= 1.0);
CVF_ASSERT( t >= 0 && t <= 1.0 );
cvf::Color3ub c1 = colorArray[inputLevelIndex];
cvf::Color3ub c2 = colorArray[inputLevelIndex + 1];
int r = static_cast<int>(c1.r() + t * (c2.r() - c1.r()) + 0.5);
int g = static_cast<int>(c1.g() + t * (c2.g() - c1.g()) + 0.5);
int b = static_cast<int>(c1.b() + t * (c2.b() - c1.b()) + 0.5);
int r = static_cast<int>( c1.r() + t * ( c2.r() - c1.r() ) + 0.5 );
int g = static_cast<int>( c1.g() + t * ( c2.g() - c1.g() ) + 0.5 );
int b = static_cast<int>( c1.b() + t * ( c2.b() - c1.b() ) + 0.5 );
r = cvf::Math::clamp(r, 0, 255);
g = cvf::Math::clamp(g, 0, 255);
b = cvf::Math::clamp(b, 0, 255);
r = cvf::Math::clamp( r, 0, 255 );
g = cvf::Math::clamp( g, 0, 255 );
b = cvf::Math::clamp( b, 0, 255 );
cvf::Color3ub col((cvf::ubyte)r, (cvf::ubyte)g, (cvf::ubyte)b);
colors.add(col);
cvf::Color3ub col( (cvf::ubyte)r, (cvf::ubyte)g, (cvf::ubyte)b );
colors.add( col );
}
colors.add(colorArray[colorArray.size() - 1]);
colors.add( colorArray[colorArray.size() - 1] );
return colors;
}

View File

@ -53,12 +53,12 @@ namespace caf
class ColorTable
{
public:
explicit ColorTable(const std::vector<cvf::Color3ub>& colors);
explicit ColorTable(const cvf::Color3ubArray& colors);
explicit ColorTable( const std::vector<cvf::Color3ub>& colors );
explicit ColorTable( const cvf::Color3ubArray& colors );
cvf::Color3f cycledColor3f(size_t itemIndex) const;
cvf::Color3ub cycledColor3ub(size_t itemIndex) const;
QColor cycledQColor(size_t itemIndex) const;
cvf::Color3f cycledColor3f( size_t itemIndex ) const;
cvf::Color3ub cycledColor3ub( size_t itemIndex ) const;
QColor cycledQColor( size_t itemIndex ) const;
cvf::Color3ubArray color3ubArray() const;
cvf::Color3fArray color3fArray() const;
@ -67,8 +67,8 @@ public:
ColorTable inverted() const;
static cvf::Color3ub fromQColor(const QColor& color);
static cvf::Color3ubArray interpolateColorArray(const cvf::Color3ubArray& colorArray, size_t targetColorCount);
static cvf::Color3ub fromQColor( const QColor& color );
static cvf::Color3ubArray interpolateColorArray( const cvf::Color3ubArray& colorArray, size_t targetColorCount );
private:
const std::vector<cvf::Color3ub> m_colors;

View File

@ -24,69 +24,66 @@
#include "cafContourLines.h"
#include <algorithm>
#include <list>
#include <cmath>
#include <list>
const int caf::ContourLines::s_castab[3][3][3] =
{
{ {0,0,8},{0,2,5},{7,6,9} },
{ {0,3,4},{1,3,1},{4,3,0} },
{ {9,6,7},{5,2,0},{8,0,0} }
};
const int caf::ContourLines::s_castab[3][3][3] = {{{0, 0, 8}, {0, 2, 5}, {7, 6, 9}},
{{0, 3, 4}, {1, 3, 1}, {4, 3, 0}},
{{9, 6, 7}, {5, 2, 0}, {8, 0, 0}}};
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void caf::ContourLines::create(const std::vector<double>& dataXY, const std::vector<double>& xCoords, const std::vector<double>& yCoords, const std::vector<double>& contourLevels, std::vector<std::vector<cvf::Vec2d>>* polygons)
void caf::ContourLines::create( const std::vector<double>& dataXY,
const std::vector<double>& xCoords,
const std::vector<double>& yCoords,
const std::vector<double>& contourLevels,
std::vector<std::vector<cvf::Vec2d>>* polygons )
{
CVF_ASSERT(!contourLevels.empty());
int nContourLevels = static_cast<int>(contourLevels.size());
std::vector<int> sh(5, 0);
std::vector<double> h(5, 0.0), xh(5, 0.0), yh(5, 0.0);
CVF_ASSERT( !contourLevels.empty() );
int nContourLevels = static_cast<int>( contourLevels.size() );
std::vector<int> sh( 5, 0 );
std::vector<double> h( 5, 0.0 ), xh( 5, 0.0 ), yh( 5, 0.0 );
int nx = static_cast<int>(xCoords.size());
int ny = static_cast<int>(yCoords.size());
int nx = static_cast<int>( xCoords.size() );
int ny = static_cast<int>( yCoords.size() );
CVF_ASSERT(static_cast<int>(dataXY.size()) == nx * ny);
CVF_ASSERT( static_cast<int>( dataXY.size() ) == nx * ny );
polygons->resize(nContourLevels);
polygons->resize( nContourLevels );
int im[4] = { 0,1,1,0 }, jm[4] = { 0,0,1,1 };
int im[4] = {0, 1, 1, 0}, jm[4] = {0, 0, 1, 1};
for (int j = (ny - 2); j >= 0; j--)
for ( int j = ( ny - 2 ); j >= 0; j-- )
{
for (int i = 0; i < nx - 1; i++)
for ( int i = 0; i < nx - 1; i++ )
{
double temp1, temp2;
temp1 = std::min(saneValue(gridIndex1d(i, j, nx), dataXY, contourLevels),
saneValue(gridIndex1d(i, j + 1, nx), dataXY, contourLevels));
temp2 = std::min(saneValue(gridIndex1d(i + 1, j, nx), dataXY, contourLevels),
saneValue(gridIndex1d(i + 1, j + 1, nx), dataXY, contourLevels));
double dmin = std::min(temp1, temp2);
temp1 = std::max(saneValue(gridIndex1d(i, j, nx), dataXY, contourLevels),
saneValue(gridIndex1d(i, j + 1, nx), dataXY, contourLevels));
temp2 = std::max(saneValue(gridIndex1d(i + 1, j, nx), dataXY, contourLevels),
saneValue(gridIndex1d(i + 1, j + 1, nx), dataXY, contourLevels));
double dmax = std::max(temp1, temp2);
temp1 = std::min( saneValue( gridIndex1d( i, j, nx ), dataXY, contourLevels ),
saneValue( gridIndex1d( i, j + 1, nx ), dataXY, contourLevels ) );
temp2 = std::min( saneValue( gridIndex1d( i + 1, j, nx ), dataXY, contourLevels ),
saneValue( gridIndex1d( i + 1, j + 1, nx ), dataXY, contourLevels ) );
double dmin = std::min( temp1, temp2 );
temp1 = std::max( saneValue( gridIndex1d( i, j, nx ), dataXY, contourLevels ),
saneValue( gridIndex1d( i, j + 1, nx ), dataXY, contourLevels ) );
temp2 = std::max( saneValue( gridIndex1d( i + 1, j, nx ), dataXY, contourLevels ),
saneValue( gridIndex1d( i + 1, j + 1, nx ), dataXY, contourLevels ) );
double dmax = std::max( temp1, temp2 );
// Using dmax <= contourLevels[0] as a deviation from Bourke because it empirically
// Reduces gridding artifacts in our code.
if (dmax <= contourLevels[0] || dmin > contourLevels[nContourLevels - 1])
continue;
if ( dmax <= contourLevels[0] || dmin > contourLevels[nContourLevels - 1] ) continue;
for (int k = 0; k < nContourLevels; k++)
for ( int k = 0; k < nContourLevels; k++ )
{
if (contourLevels[k] < dmin || contourLevels[k] > dmax)
continue;
for (int m = 4; m >= 0; m--)
if ( contourLevels[k] < dmin || contourLevels[k] > dmax ) continue;
for ( int m = 4; m >= 0; m-- )
{
if (m > 0)
if ( m > 0 )
{
double value = saneValue(gridIndex1d(i + im[m - 1], j + jm[m - 1], nx), dataXY, contourLevels);
if (value == invalidValue(contourLevels))
double value = saneValue( gridIndex1d( i + im[m - 1], j + jm[m - 1], nx ), dataXY, contourLevels );
if ( value == invalidValue( contourLevels ) )
{
h[m] = invalidValue(contourLevels);
h[m] = invalidValue( contourLevels );
}
else
{
@ -97,13 +94,13 @@ void caf::ContourLines::create(const std::vector<double>& dataXY, const std::vec
}
else
{
h[0] = 0.25 * (h[1] + h[2] + h[3] + h[4]);
xh[0] = 0.5 * (xCoords[i] + xCoords[i + 1]);
yh[0] = 0.5 * (yCoords[j] + yCoords[j + 1]);
h[0] = 0.25 * ( h[1] + h[2] + h[3] + h[4] );
xh[0] = 0.5 * ( xCoords[i] + xCoords[i + 1] );
yh[0] = 0.5 * ( yCoords[j] + yCoords[j + 1] );
}
if (h[m] > 0.0)
if ( h[m] > 0.0 )
sh[m] = 1;
else if (h[m] < 0.0)
else if ( h[m] < 0.0 )
sh[m] = -1;
else
sh[m] = 0;
@ -133,17 +130,18 @@ void caf::ContourLines::create(const std::vector<double>& dataXY, const std::vec
vertex 1 +-------------------+ vertex 2
*/
/* Scan each triangle in the box */
for (int m = 1; m <= 4; m++) {
for ( int m = 1; m <= 4; m++ )
{
int m1 = m;
int m2 = 0;
int m3 = (m != 4) ? m + 1 : 1;
int m3 = ( m != 4 ) ? m + 1 : 1;
double x1 = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0;
int case_value = s_castab[sh[m1] + 1][sh[m2] + 1][sh[m3] + 1];
if (case_value == 0)
continue;
if ( case_value == 0 ) continue;
switch (case_value) {
switch ( case_value )
{
case 1: /* Line between vertices 1 and 2 */
x1 = xh[m1];
y1 = yh[m1];
@ -165,46 +163,46 @@ void caf::ContourLines::create(const std::vector<double>& dataXY, const std::vec
case 4: /* Line between vertex 1 and side 2-3 */
x1 = xh[m1];
y1 = yh[m1];
x2 = xsect(m2, m3, h, xh, yh);
y2 = ysect(m2, m3, h, xh, yh);
x2 = xsect( m2, m3, h, xh, yh );
y2 = ysect( m2, m3, h, xh, yh );
break;
case 5: /* Line between vertex 2 and side 3-1 */
x1 = xh[m2];
y1 = yh[m2];
x2 = xsect(m3, m1, h, xh, yh);
y2 = ysect(m3, m1, h, xh, yh);
x2 = xsect( m3, m1, h, xh, yh );
y2 = ysect( m3, m1, h, xh, yh );
break;
case 6: /* Line between vertex 3 and side 1-2 */
x1 = xh[m3];
y1 = yh[m3];
x2 = xsect(m1, m2, h, xh, yh);
y2 = ysect(m1, m2, h, xh, yh);
x2 = xsect( m1, m2, h, xh, yh );
y2 = ysect( m1, m2, h, xh, yh );
break;
case 7: /* Line between sides 1-2 and 2-3 */
x1 = xsect(m1, m2, h, xh, yh);
y1 = ysect(m1, m2, h, xh, yh);
x2 = xsect(m2, m3, h, xh, yh);
y2 = ysect(m2, m3, h, xh, yh);
x1 = xsect( m1, m2, h, xh, yh );
y1 = ysect( m1, m2, h, xh, yh );
x2 = xsect( m2, m3, h, xh, yh );
y2 = ysect( m2, m3, h, xh, yh );
break;
case 8: /* Line between sides 2-3 and 3-1 */
x1 = xsect(m2, m3, h, xh, yh);
y1 = ysect(m2, m3, h, xh, yh);
x2 = xsect(m3, m1, h, xh, yh);
y2 = ysect(m3, m1, h, xh, yh);
x1 = xsect( m2, m3, h, xh, yh );
y1 = ysect( m2, m3, h, xh, yh );
x2 = xsect( m3, m1, h, xh, yh );
y2 = ysect( m3, m1, h, xh, yh );
break;
case 9: /* Line between sides 3-1 and 1-2 */
x1 = xsect(m3, m1, h, xh, yh);
y1 = ysect(m3, m1, h, xh, yh);
x2 = xsect(m1, m2, h, xh, yh);
y2 = ysect(m1, m2, h, xh, yh);
x1 = xsect( m3, m1, h, xh, yh );
y1 = ysect( m3, m1, h, xh, yh );
x2 = xsect( m1, m2, h, xh, yh );
y2 = ysect( m1, m2, h, xh, yh );
break;
default:
break;
}
/* Finally draw the line */
polygons->at(k).push_back(cvf::Vec2d(x1, y1));
polygons->at(k).push_back(cvf::Vec2d(x2, y2));
polygons->at( k ).push_back( cvf::Vec2d( x1, y1 ) );
polygons->at( k ).push_back( cvf::Vec2d( x2, y2 ) );
} /* m */
} /* k - contour */
} /* i */
@ -214,27 +212,28 @@ void caf::ContourLines::create(const std::vector<double>& dataXY, const std::vec
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<caf::ContourLines::ListOfLineSegments> caf::ContourLines::create(const std::vector<double>& dataXY,
std::vector<caf::ContourLines::ListOfLineSegments> caf::ContourLines::create( const std::vector<double>& dataXY,
const std::vector<double>& xPositions,
const std::vector<double>& yPositions,
const std::vector<double>& contourLevels)
const std::vector<double>& contourLevels )
{
const double eps = 1.0e-4;
std::vector<std::vector<cvf::Vec2d>> contourLineSegments;
caf::ContourLines::create(dataXY, xPositions, yPositions, contourLevels, &contourLineSegments);
caf::ContourLines::create( dataXY, xPositions, yPositions, contourLevels, &contourLineSegments );
std::vector<ListOfLineSegments> listOfSegmentsPerLevel(contourLevels.size());
std::vector<ListOfLineSegments> listOfSegmentsPerLevel( contourLevels.size() );
for (size_t i = 0; i < contourLevels.size(); ++i)
for ( size_t i = 0; i < contourLevels.size(); ++i )
{
size_t nPoints = contourLineSegments[i].size();
size_t nSegments = nPoints / 2;
if (nSegments >= 3u) // Need at least three segments for a closed polygon
if ( nSegments >= 3u ) // Need at least three segments for a closed polygon
{
ListOfLineSegments unorderedSegments;
for (size_t j = 0; j < contourLineSegments[i].size(); j += 2)
for ( size_t j = 0; j < contourLineSegments[i].size(); j += 2 )
{
unorderedSegments.push_back(std::make_pair(cvf::Vec3d(contourLineSegments[i][j]), cvf::Vec3d(contourLineSegments[i][j + 1])));
unorderedSegments.push_back( std::make_pair( cvf::Vec3d( contourLineSegments[i][j] ),
cvf::Vec3d( contourLineSegments[i][j + 1] ) ) );
}
listOfSegmentsPerLevel[i] = unorderedSegments;
}
@ -246,32 +245,32 @@ std::vector<caf::ContourLines::ListOfLineSegments> caf::ContourLines::create(con
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double caf::ContourLines::contourRange(const std::vector<double>& contourLevels)
double caf::ContourLines::contourRange( const std::vector<double>& contourLevels )
{
CVF_ASSERT(!contourLevels.empty());
return std::max(1.0e-6, contourLevels.back() - contourLevels.front());
CVF_ASSERT( !contourLevels.empty() );
return std::max( 1.0e-6, contourLevels.back() - contourLevels.front() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double caf::ContourLines::invalidValue(const std::vector<double>& contourLevels)
double caf::ContourLines::invalidValue( const std::vector<double>& contourLevels )
{
return contourLevels.front() - 1000.0*contourRange(contourLevels);
return contourLevels.front() - 1000.0 * contourRange( contourLevels );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double caf::ContourLines::saneValue(int index, const std::vector<double>& dataXY, const std::vector<double>& contourLevels)
double caf::ContourLines::saneValue( int index, const std::vector<double>& dataXY, const std::vector<double>& contourLevels )
{
CVF_ASSERT(index >= 0 && index < static_cast<int>(dataXY.size()));
CVF_ASSERT( index >= 0 && index < static_cast<int>( dataXY.size() ) );
// Place all invalid values below the bottom contour level.
if (dataXY[index] == -std::numeric_limits<double>::infinity() ||
dataXY[index] == std::numeric_limits<double>::infinity())
if ( dataXY[index] == -std::numeric_limits<double>::infinity() ||
dataXY[index] == std::numeric_limits<double>::infinity() )
{
return invalidValue(contourLevels);
return invalidValue( contourLevels );
}
return dataXY[index];
}
@ -279,23 +278,31 @@ double caf::ContourLines::saneValue(int index, const std::vector<double>& dataXY
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double caf::ContourLines::xsect(int p1, int p2, const std::vector<double>& h, const std::vector<double>& xh, const std::vector<double>& yh)
double caf::ContourLines::xsect( int p1,
int p2,
const std::vector<double>& h,
const std::vector<double>& xh,
const std::vector<double>& yh )
{
return (h[p2] * xh[p1] - h[p1] * xh[p2]) / (h[p2] - h[p1]);
return ( h[p2] * xh[p1] - h[p1] * xh[p2] ) / ( h[p2] - h[p1] );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double caf::ContourLines::ysect(int p1, int p2, const std::vector<double>& h, const std::vector<double>& xh, const std::vector<double>& yh)
double caf::ContourLines::ysect( int p1,
int p2,
const std::vector<double>& h,
const std::vector<double>& xh,
const std::vector<double>& yh )
{
return (h[p2] * yh[p1] - h[p1] * yh[p2]) / (h[p2] - h[p1]);
return ( h[p2] * yh[p1] - h[p1] * yh[p2] ) / ( h[p2] - h[p1] );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
int caf::ContourLines::gridIndex1d(int i, int j, int nx)
int caf::ContourLines::gridIndex1d( int i, int j, int nx )
{
return j * nx + i;
}

View File

@ -40,24 +40,27 @@ public:
typedef std::pair<cvf::Vec3d, cvf::Vec3d> LineSegment;
typedef std::list<LineSegment> ListOfLineSegments;
static std::vector<ListOfLineSegments> create(const std::vector<double>& dataXY,
static std::vector<ListOfLineSegments> create( const std::vector<double>& dataXY,
const std::vector<double>& xPositions,
const std::vector<double>& yPositions,
const std::vector<double>& contourLevels);
const std::vector<double>& contourLevels );
private:
static void create(const std::vector<double>& dataXY,
static void create( const std::vector<double>& dataXY,
const std::vector<double>& xPositions,
const std::vector<double>& yPositions,
const std::vector<double>& contourLevels,
std::vector<std::vector<cvf::Vec2d>>* polygons);
static double contourRange(const std::vector<double>& contourLevels);
static double invalidValue(const std::vector<double>& contourLevels);
static double saneValue(int index, const std::vector<double>& dataXY, const std::vector<double>& contourLevels);
static double xsect(int p1, int p2, const std::vector<double>& h, const std::vector<double>& xh, const std::vector<double>& yh);
static double ysect(int p1, int p2, const std::vector<double>& h, const std::vector<double>& xh, const std::vector<double>& yh);
static int gridIndex1d(int i, int j, int nx);
std::vector<std::vector<cvf::Vec2d>>* polygons );
static double contourRange( const std::vector<double>& contourLevels );
static double invalidValue( const std::vector<double>& contourLevels );
static double saneValue( int index, const std::vector<double>& dataXY, const std::vector<double>& contourLevels );
static double
xsect( int p1, int p2, const std::vector<double>& h, const std::vector<double>& xh, const std::vector<double>& yh );
static double
ysect( int p1, int p2, const std::vector<double>& h, const std::vector<double>& xh, const std::vector<double>& yh );
static int gridIndex1d( int i, int j, int nx );
private:
static const int s_castab[3][3][3];
};
}
} // namespace caf

View File

@ -34,13 +34,11 @@
//
//##################################################################################################
#include "cafEffectGenerator.h"
#include "cafEffectCache.h"
#include "cafEffectGenerator.h"
namespace caf {
namespace caf
{
//==================================================================================================
//
// EffectCache
@ -65,25 +63,24 @@ EffectCache* EffectCache::instance()
return &staticInstance;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Effect* EffectCache::findEffect(const EffectGenerator* generator)
cvf::Effect* EffectCache::findEffect( const EffectGenerator* generator )
{
CVF_ASSERT(generator);
CVF_ASSERT( generator );
// Effect cache does not support mixing of effect types. Clear cache if type changes.
if (EffectGenerator::renderingMode() != m_effectType)
if ( EffectGenerator::renderingMode() != m_effectType )
{
clear();
m_effectType = EffectGenerator::renderingMode();
}
size_t i;
for (i = 0; i < m_effectCache.size(); i++)
for ( i = 0; i < m_effectCache.size(); i++ )
{
if (m_effectCache[i].first->isEqual(generator))
if ( m_effectCache[i].first->isEqual( generator ) )
{
cvf::ref<cvf::Effect> effect = m_effectCache[i].second;
return effect.p();
@ -99,7 +96,7 @@ cvf::Effect* EffectCache::findEffect(const EffectGenerator* generator)
void EffectCache::clear()
{
size_t i;
for (i = 0; i < m_effectCache.size(); i++)
for ( i = 0; i < m_effectCache.size(); i++ )
{
EffectGenerator* effGenerator = m_effectCache[i].first;
delete effGenerator;
@ -111,10 +108,10 @@ void EffectCache::clear()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void EffectCache::addEffect(const EffectGenerator* generator, cvf::Effect* effect)
void EffectCache::addEffect( const EffectGenerator* generator, cvf::Effect* effect )
{
EffectGenerator* myCopy = generator->copy();
m_effectCache.push_back(std::make_pair(myCopy, effect));
m_effectCache.push_back( std::make_pair( myCopy, effect ) );
}
//--------------------------------------------------------------------------------------------------
@ -122,11 +119,11 @@ void EffectCache::addEffect(const EffectGenerator* generator, cvf::Effect* effec
//--------------------------------------------------------------------------------------------------
void EffectCache::releaseUnreferencedEffects()
{
std::vector<std::pair<EffectGenerator*, cvf::ref<cvf::Effect> > > newCache;
std::vector<std::pair<EffectGenerator*, cvf::ref<cvf::Effect>>> newCache;
size_t i;
for (i = 0; i < m_effectCache.size(); i++)
for ( i = 0; i < m_effectCache.size(); i++ )
{
if (m_effectCache[i].second.p()->refCount() <= 1 )
if ( m_effectCache[i].second.p()->refCount() <= 1 )
{
m_effectCache[i].second = nullptr;
delete m_effectCache[i].first;
@ -134,12 +131,11 @@ void EffectCache::releaseUnreferencedEffects()
}
else
{
newCache.push_back(m_effectCache[i]);
newCache.push_back( m_effectCache[i] );
}
}
m_effectCache.swap(newCache);
m_effectCache.swap( newCache );
}
}
} // namespace caf

View File

@ -34,18 +34,16 @@
//
//##################################################################################################
#pragma once
#include "cvfBase.h"
#include "cvfObject.h"
#include "cvfEffect.h"
#include "cvfObject.h"
#include "cafEffectGenerator.h"
namespace caf {
namespace caf
{
//==================================================================================================
//
// Private class. Used only by caf::EffectGenerator to cache effects (with GPU resources)
@ -59,17 +57,15 @@ private:
static EffectCache* instance();
cvf::Effect* findEffect(const EffectGenerator* generator);
void addEffect(const EffectGenerator* generator, cvf::Effect* effect);
cvf::Effect* findEffect( const EffectGenerator* generator );
void addEffect( const EffectGenerator* generator, cvf::Effect* effect );
void releaseUnreferencedEffects();
void clear();
private:
EffectGenerator::RenderingModeType m_effectType;
std::vector<std::pair<EffectGenerator*, cvf::ref<cvf::Effect> > > m_effectCache;
std::vector<std::pair<EffectGenerator*, cvf::ref<cvf::Effect>>> m_effectCache;
};
}
} // namespace caf

File diff suppressed because it is too large Load Diff

View File

@ -34,33 +34,30 @@
//
//##################################################################################################
#pragma once
#include "cvfBase.h"
#include "cvfObject.h"
#include "cvfEffect.h"
#include "cvfScalarMapper.h"
#include "cvfTextureImage.h"
#include "cvfCollection.h"
#include "cvfString.h"
#include "cvfEffect.h"
#include "cvfObject.h"
#include "cvfRenderStatePolygonOffset.h"
#include "cvfScalarMapper.h"
#include "cvfString.h"
#include "cvfTextureImage.h"
namespace cvf
{
class RenderStatePolygonOffset;
class RenderStatePolygonOffset;
}
namespace caf {
namespace caf
{
class CommonShaderSources
{
public:
static cvf::String light_AmbientDiffuse();
};
// Enumerates different levels of polygon offsetting
enum PolygonOffset
{
@ -80,7 +77,6 @@ enum FaceCulling
FC_NONE
};
//==================================================================================================
//
//
@ -89,40 +85,42 @@ enum FaceCulling
class EffectGenerator
{
public:
enum RenderingModeType { FIXED_FUNCTION, SHADER_BASED };
enum RenderingModeType
{
FIXED_FUNCTION,
SHADER_BASED
};
EffectGenerator() {}
virtual ~EffectGenerator() {}
cvf::ref<cvf::Effect> generateUnCachedEffect() const;
cvf::ref<cvf::Effect> generateCachedEffect() const;
void updateEffect(cvf::Effect* effect) const;
void updateEffect( cvf::Effect* effect ) const;
static void setRenderingMode(RenderingModeType effectType);
static void setRenderingMode( RenderingModeType effectType );
static RenderingModeType renderingMode();
static void clearEffectCache();
static void releaseUnreferencedEffects();
static cvf::ref<cvf::RenderStatePolygonOffset> createAndConfigurePolygonOffsetRenderState(caf::PolygonOffset polygonOffset);
static cvf::ref<cvf::RenderStatePolygonOffset>
createAndConfigurePolygonOffsetRenderState( caf::PolygonOffset polygonOffset );
protected:
// Interface that must be implemented in base classes
virtual bool isEqual(const EffectGenerator* other) const = 0;
virtual bool isEqual( const EffectGenerator* other ) const = 0;
virtual EffectGenerator* copy() const = 0;
friend class EffectCache;
// When these are called, the effect is already cleared by updateEffect()
virtual void updateForShaderBasedRendering(cvf::Effect* effect) const = 0;
virtual void updateForFixedFunctionRendering(cvf::Effect* effect) const = 0;
virtual void updateForShaderBasedRendering( cvf::Effect* effect ) const = 0;
virtual void updateForFixedFunctionRendering( cvf::Effect* effect ) const = 0;
private:
static RenderingModeType sm_renderingMode;
};
//==================================================================================================
//
// SurfaceEffectGenerator
@ -131,25 +129,25 @@ private:
class SurfaceEffectGenerator : public EffectGenerator
{
public:
SurfaceEffectGenerator(const cvf::Color4f& color, PolygonOffset polygonOffset);
SurfaceEffectGenerator(const cvf::Color3f& color, PolygonOffset polygonOffset);
SurfaceEffectGenerator( const cvf::Color4f& color, PolygonOffset polygonOffset );
SurfaceEffectGenerator( const cvf::Color3f& color, PolygonOffset polygonOffset );
void setCullBackfaces(FaceCulling cullBackFaces) { m_cullBackfaces = cullBackFaces; }
void setCullBackfaces( FaceCulling cullBackFaces ) { m_cullBackfaces = cullBackFaces; }
void enableColorMask(bool enableColors) { m_enableColorMask = enableColors; }
void enableDepthTest(bool enableTest) { m_enableDepthTest = enableTest; }
void enableDepthWrite(bool enableWrite) { m_enableDepthWrite = enableWrite; }
void enableLighting(bool enableLighting) { m_enableLighting = enableLighting; }
void enableColorMask( bool enableColors ) { m_enableColorMask = enableColors; }
void enableDepthTest( bool enableTest ) { m_enableDepthTest = enableTest; }
void enableDepthWrite( bool enableWrite ) { m_enableDepthWrite = enableWrite; }
void enableLighting( bool enableLighting ) { m_enableLighting = enableLighting; }
protected:
bool isEqual(const EffectGenerator* other) const override;
bool isEqual( const EffectGenerator* other ) const override;
EffectGenerator* copy() const override;
void updateForShaderBasedRendering(cvf::Effect* effect) const override;
void updateForFixedFunctionRendering(cvf::Effect* effect) const override;
void updateForShaderBasedRendering( cvf::Effect* effect ) const override;
void updateForFixedFunctionRendering( cvf::Effect* effect ) const override;
private:
void updateCommonEffect(cvf::Effect* effect) const;
void updateCommonEffect( cvf::Effect* effect ) const;
private:
cvf::Color4f m_color;
@ -161,7 +159,6 @@ private:
bool m_enableLighting;
};
//==================================================================================================
//
// ScalarMapperEffectGenerator
@ -170,28 +167,30 @@ private:
class ScalarMapperEffectGenerator : public EffectGenerator
{
public:
ScalarMapperEffectGenerator(const cvf::ScalarMapper* scalarMapper, PolygonOffset polygonOffset);
ScalarMapperEffectGenerator( const cvf::ScalarMapper* scalarMapper, PolygonOffset polygonOffset );
void setOpacityLevel(float opacity) { m_opacityLevel = cvf::Math::clamp(opacity, 0.0f , 1.0f ); }
void setUndefinedColor(cvf::Color3f color) { m_undefinedColor = color; }
void setFaceCulling(FaceCulling faceCulling) { m_faceCulling = faceCulling; }
void enableDepthWrite(bool enableWrite) { m_enableDepthWrite = enableWrite; }
void disableLighting(bool disable) { m_disableLighting = disable; }
void discardTransparentFragments(bool discard) { m_discardTransparentFragments = discard; }
void setOpacityLevel( float opacity ) { m_opacityLevel = cvf::Math::clamp( opacity, 0.0f, 1.0f ); }
void setUndefinedColor( cvf::Color3f color ) { m_undefinedColor = color; }
void setFaceCulling( FaceCulling faceCulling ) { m_faceCulling = faceCulling; }
void enableDepthWrite( bool enableWrite ) { m_enableDepthWrite = enableWrite; }
void disableLighting( bool disable ) { m_disableLighting = disable; }
void discardTransparentFragments( bool discard ) { m_discardTransparentFragments = discard; }
public:
static cvf::ref<cvf::TextureImage> addAlphaAndUndefStripes(const cvf::TextureImage* texImg, const cvf::Color3f& undefScalarColor, float opacityLevel);
static bool isImagesEqual(const cvf::TextureImage* texImg1, const cvf::TextureImage* texImg2);
static cvf::ref<cvf::TextureImage> addAlphaAndUndefStripes( const cvf::TextureImage* texImg,
const cvf::Color3f& undefScalarColor,
float opacityLevel );
static bool isImagesEqual( const cvf::TextureImage* texImg1, const cvf::TextureImage* texImg2 );
protected:
bool isEqual(const EffectGenerator* other) const override;
bool isEqual( const EffectGenerator* other ) const override;
EffectGenerator* copy() const override;
void updateForShaderBasedRendering(cvf::Effect* effect) const override;
void updateForFixedFunctionRendering(cvf::Effect* effect) const override;
void updateForShaderBasedRendering( cvf::Effect* effect ) const override;
void updateForFixedFunctionRendering( cvf::Effect* effect ) const override;
private:
void updateCommonEffect(cvf::Effect* effect) const;
void updateCommonEffect( cvf::Effect* effect ) const;
private:
cvf::cref<cvf::ScalarMapper> m_scalarMapper;
@ -205,7 +204,6 @@ private:
bool m_discardTransparentFragments;
};
//==================================================================================================
//
// ScalarMapperMeshEffectGenerator
@ -214,20 +212,20 @@ private:
class ScalarMapperMeshEffectGenerator : public EffectGenerator
{
public:
explicit ScalarMapperMeshEffectGenerator(const cvf::ScalarMapper* scalarMapper);
explicit ScalarMapperMeshEffectGenerator( const cvf::ScalarMapper* scalarMapper );
void setOpacityLevel(float opacity) { m_opacityLevel = cvf::Math::clamp(opacity, 0.0f , 1.0f ); }
void setUndefinedColor(cvf::Color3f color) { m_undefinedColor = color; }
void setOpacityLevel( float opacity ) { m_opacityLevel = cvf::Math::clamp( opacity, 0.0f, 1.0f ); }
void setUndefinedColor( cvf::Color3f color ) { m_undefinedColor = color; }
protected:
bool isEqual(const EffectGenerator* other) const override;
bool isEqual( const EffectGenerator* other ) const override;
EffectGenerator* copy() const override;
void updateForShaderBasedRendering(cvf::Effect* effect) const override;
void updateForFixedFunctionRendering(cvf::Effect* effect) const override;
void updateForShaderBasedRendering( cvf::Effect* effect ) const override;
void updateForFixedFunctionRendering( cvf::Effect* effect ) const override;
private:
void updateCommonEffect(cvf::Effect* effect) const;
void updateCommonEffect( cvf::Effect* effect ) const;
private:
cvf::cref<cvf::ScalarMapper> m_scalarMapper;
@ -236,7 +234,6 @@ private:
cvf::Color3f m_undefinedColor;
};
//==================================================================================================
//
// MeshEffectGenerator
@ -245,16 +242,16 @@ private:
class MeshEffectGenerator : public EffectGenerator
{
public:
explicit MeshEffectGenerator(const cvf::Color3f& color);
void setLineStipple(bool enable) { m_lineStipple = enable; }
void setLineWidth(float lineWidth);
explicit MeshEffectGenerator( const cvf::Color3f& color );
void setLineStipple( bool enable ) { m_lineStipple = enable; }
void setLineWidth( float lineWidth );
protected:
bool isEqual(const EffectGenerator* other) const override;
bool isEqual( const EffectGenerator* other ) const override;
EffectGenerator* copy() const override;
void updateForShaderBasedRendering(cvf::Effect* effect) const override;
void updateForFixedFunctionRendering(cvf::Effect* effect) const override;
void updateForShaderBasedRendering( cvf::Effect* effect ) const override;
void updateForFixedFunctionRendering( cvf::Effect* effect ) const override;
private:
cvf::Color3f m_color;
@ -262,7 +259,6 @@ private:
float m_lineWidth;
};
//==================================================================================================
//
// TextEffectGenerator
@ -274,14 +270,13 @@ public:
TextEffectGenerator();
protected:
bool isEqual(const EffectGenerator* other) const override;
bool isEqual( const EffectGenerator* other ) const override;
EffectGenerator* copy() const override;
void updateForShaderBasedRendering(cvf::Effect* effect) const override;
void updateForFixedFunctionRendering(cvf::Effect* effect) const override;
void updateForShaderBasedRendering( cvf::Effect* effect ) const override;
void updateForFixedFunctionRendering( cvf::Effect* effect ) const override;
};
//==================================================================================================
//
// VectorEffectGenerator
@ -293,10 +288,10 @@ public:
VectorEffectGenerator();
protected:
bool isEqual(const EffectGenerator* other) const override;
bool isEqual( const EffectGenerator* other ) const override;
EffectGenerator* copy() const override;
void updateForShaderBasedRendering(cvf::Effect* effect) const override;
void updateForFixedFunctionRendering(cvf::Effect* effect) const override;
void updateForShaderBasedRendering( cvf::Effect* effect ) const override;
void updateForFixedFunctionRendering( cvf::Effect* effect ) const override;
};
}
} // namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#include "cvfBase.h"
#include "cvfTrace.h"
@ -42,161 +41,154 @@
#include "cafMessagePanel.h"
#include "cafUtils.h"
namespace caf {
namespace caf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void Log::info(const QString& msg)
void Log::info( const QString& msg )
{
infoMultiLine(msg, "");
infoMultiLine( msg, "" );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void Log::warning(const QString& msg)
void Log::warning( const QString& msg )
{
warningMultiLine(msg, "");
warningMultiLine( msg, "" );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool Log::error(const QString& err)
bool Log::error( const QString& err )
{
return errorMultiLine(err, "");
return errorMultiLine( err, "" );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void Log::infoMultiLine(const QString& line1, const QString& line2Etc)
void Log::infoMultiLine( const QString& line1, const QString& line2Etc )
{
MessagePanel* messagePanel = MessagePanel::instance();
bool generateTrace = true;
if (messagePanel)
if ( messagePanel )
{
QString msg = line1;
if (!line2Etc.isEmpty())
if ( !line2Etc.isEmpty() )
{
msg += "\n";
msg += Utils::indentString(2, line2Etc);
msg += Utils::indentString( 2, line2Etc );
}
messagePanel->showInfo(msg);
messagePanel->showInfo( msg );
}
if (generateTrace)
if ( generateTrace )
{
cvf::Trace::show("INF: %s", (const char*)line1.toLatin1());
if (!line2Etc.isEmpty())
cvf::Trace::show( "INF: %s", (const char*)line1.toLatin1() );
if ( !line2Etc.isEmpty() )
{
cvf::Trace::show((const char*)Utils::indentString(5, line2Etc).toLatin1());
cvf::Trace::show( (const char*)Utils::indentString( 5, line2Etc ).toLatin1() );
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void Log::warningMultiLine(const QString& line1, const QString& line2Etc)
void Log::warningMultiLine( const QString& line1, const QString& line2Etc )
{
MessagePanel* messagePanel = MessagePanel::instance();
bool generateTrace = true;
if (messagePanel)
if ( messagePanel )
{
QString msg = line1;
if (!line2Etc.isEmpty())
if ( !line2Etc.isEmpty() )
{
msg += "\n";
msg += Utils::indentString(2, line2Etc);
msg += Utils::indentString( 2, line2Etc );
}
messagePanel->showWarning(msg);
messagePanel->showWarning( msg );
}
if (generateTrace)
if ( generateTrace )
{
cvf::Trace::show("WRN: %s", (const char*)line1.toLatin1());
if (!line2Etc.isEmpty())
cvf::Trace::show( "WRN: %s", (const char*)line1.toLatin1() );
if ( !line2Etc.isEmpty() )
{
cvf::Trace::show((const char*)Utils::indentString(5, line2Etc).toLatin1());
cvf::Trace::show( (const char*)Utils::indentString( 5, line2Etc ).toLatin1() );
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool Log::errorMultiLine(const QString& line1, const QString& line2Etc)
bool Log::errorMultiLine( const QString& line1, const QString& line2Etc )
{
MessagePanel* messagePanel = MessagePanel::instance();
bool generateTrace = true;
if (messagePanel)
if ( messagePanel )
{
QString msg = line1;
if (!line2Etc.isEmpty())
if ( !line2Etc.isEmpty() )
{
msg += "\n";
msg += Utils::indentString(2, line2Etc);
msg += Utils::indentString( 2, line2Etc );
}
messagePanel->showError(msg);
messagePanel->showError( msg );
}
bool messagePanelVisible = messagePanel ? messagePanel->isVisibleToUser() : false;
if (!messagePanelVisible)
if ( !messagePanelVisible )
{
// if (mainWindow)
// {
// QString capt = QString(PD_APPLICATION_NAME) + " Error";
//
// QString msg = line1;
// if (!line2Etc.isEmpty())
// {
// msg += "\n";
// msg += line2Etc;
// }
//
// QMessageBox msgBox(mainWindow);
// msgBox.setIcon(QMessageBox::Critical);
// msgBox.setWindowTitle(capt);
// msgBox.setText(msg);
//
// msgBox.exec();
// }
// else
// {
// generateTrace = true;
// }
// if (mainWindow)
// {
// QString capt = QString(PD_APPLICATION_NAME) + " Error";
//
// QString msg = line1;
// if (!line2Etc.isEmpty())
// {
// msg += "\n";
// msg += line2Etc;
// }
//
// QMessageBox msgBox(mainWindow);
// msgBox.setIcon(QMessageBox::Critical);
// msgBox.setWindowTitle(capt);
// msgBox.setText(msg);
//
// msgBox.exec();
// }
// else
// {
// generateTrace = true;
// }
}
if (generateTrace)
if ( generateTrace )
{
cvf::Trace::show("\nERR: %s", (const char*)line1.toLatin1());
if (!line2Etc.isEmpty())
cvf::Trace::show( "\nERR: %s", (const char*)line1.toLatin1() );
if ( !line2Etc.isEmpty() )
{
cvf::Trace::show((const char*)Utils::indentString(5, line2Etc).toLatin1());
cvf::Trace::show( (const char*)Utils::indentString( 5, line2Etc ).toLatin1() );
}
}
return false;
}
// //--------------------------------------------------------------------------------------------------
// ///
// //--------------------------------------------------------------------------------------------------
@ -207,5 +199,4 @@ bool Log::errorMultiLine(const QString& line1, const QString& line2Etc)
//
// }
}
} // namespace caf

View File

@ -34,14 +34,12 @@
//
//##################################################################################################
#pragma once
class QString;
namespace caf {
namespace caf
{
//==================================================================================================
//
//
@ -50,18 +48,16 @@ namespace caf {
class Log
{
public:
//static void info(const char* formatStr, ...);
static void info(const QString& msg);
static void warning(const QString& msg);
static bool error(const QString& err);
// static void info(const char* formatStr, ...);
static void info( const QString& msg );
static void warning( const QString& msg );
static bool error( const QString& err );
static void infoMultiLine(const QString& line1, const QString& line2Etc);
static void warningMultiLine(const QString& line1, const QString& line2Etc);
static bool errorMultiLine(const QString& line1, const QString& line2Etc);
static void infoMultiLine( const QString& line1, const QString& line2Etc );
static void warningMultiLine( const QString& line1, const QString& line2Etc );
static bool errorMultiLine( const QString& line1, const QString& line2Etc );
static void pumpMessages();
};
}
} // namespace caf

View File

@ -34,17 +34,15 @@
//
//##################################################################################################
#include "cafMessagePanel.h"
#include <QWidget>
#include <QBoxLayout>
#include <QDockWidget>
#include <QTextEdit>
#include <QBoxLayout>
namespace caf {
#include <QWidget>
namespace caf
{
MessagePanel* MessagePanel::sm_messagePanelInstance = nullptr;
//==================================================================================================
@ -58,98 +56,92 @@ MessagePanel* MessagePanel::sm_messagePanelInstance = nullptr;
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
MessagePanel::MessagePanel(QDockWidget* parent)
: QWidget(parent)
MessagePanel::MessagePanel( QDockWidget* parent )
: QWidget( parent )
{
m_textEdit = new QTextEdit(this);
m_textEdit->setReadOnly(true);
m_textEdit->setLineWrapMode(QTextEdit::NoWrap);
m_textEdit = new QTextEdit( this );
m_textEdit->setReadOnly( true );
m_textEdit->setLineWrapMode( QTextEdit::NoWrap );
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(m_textEdit);
setLayout(layout);
layout->addWidget( m_textEdit );
setLayout( layout );
sm_messagePanelInstance = this;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void MessagePanel::showInfo(QString info)
void MessagePanel::showInfo( QString info )
{
convertStringToHTML(&info);
convertStringToHTML( &info );
QString str = "<font color='green'>";
str += info;
str += "</font>";
m_textEdit->append(str);
m_textEdit->append( str );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void MessagePanel::showWarning(QString warn)
void MessagePanel::showWarning( QString warn )
{
convertStringToHTML(&warn);
convertStringToHTML( &warn );
QString str = "<font color='maroon'>";
str += warn;
str += "</font>";
m_textEdit->append(str);
m_textEdit->append( str );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void MessagePanel::showError(QString error)
void MessagePanel::showError( QString error )
{
convertStringToHTML(&error);
convertStringToHTML( &error );
QString str = "<b><font color='red'>";
str += error;
str += "</font></b>";
m_textEdit->append(str);
m_textEdit->append( str );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void MessagePanel::convertStringToHTML(QString* str)
void MessagePanel::convertStringToHTML( QString* str )
{
str->replace("\n", "<br>");
str->replace(" ", "&nbsp;");
str->replace( "\n", "<br>" );
str->replace( " ", "&nbsp;" );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QSize MessagePanel::sizeHint () const
QSize MessagePanel::sizeHint() const
{
// As small as possible fow now
return QSize(20, 20);
return QSize( 20, 20 );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool MessagePanel::isVisibleToUser()
{
if (!isVisible()) return false;
if ( !isVisible() ) return false;
if (!m_textEdit) return false;
if (!m_textEdit->isVisible()) return false;
if ( !m_textEdit ) return false;
if ( !m_textEdit->isVisible() ) return false;
QRegion rgn = m_textEdit->visibleRegion();
if (rgn.isEmpty()) return false;
if ( rgn.isEmpty() ) return false;
return true;
}
@ -162,4 +154,4 @@ MessagePanel* MessagePanel::instance()
return sm_messagePanelInstance;
}
}
} // namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#pragma once
#include <QWidget>
@ -42,9 +41,8 @@
class QDockWidget;
class QTextEdit;
namespace caf {
namespace caf
{
//==================================================================================================
//
//
@ -55,19 +53,19 @@ class MessagePanel : public QWidget
Q_OBJECT
public:
explicit MessagePanel(QDockWidget* parent);
explicit MessagePanel( QDockWidget* parent );
static MessagePanel* instance();
void showInfo(QString info);
void showWarning(QString warn);
void showError(QString error);
void showInfo( QString info );
void showWarning( QString warn );
void showError( QString error );
QSize sizeHint () const override;
QSize sizeHint() const override;
bool isVisibleToUser();
private:
static void convertStringToHTML(QString* str);
static void convertStringToHTML( QString* str );
private:
static MessagePanel* sm_messagePanelInstance;
@ -75,4 +73,4 @@ private:
QTextEdit* m_textEdit;
};
}
} // namespace caf

View File

@ -34,20 +34,17 @@
//
//##################################################################################################
#include "cafMouseState.h"
#include "cvfBase.h"
#include "cvfMath.h"
#include "cafMouseState.h"
#include <QMouseEvent>
#include <QGraphicsSceneMouseEvent>
#include <QMouseEvent>
#include <cmath>
namespace caf {
namespace caf
{
//==================================================================================================
///
/// \class cvfqt::QtMouseState
@ -68,31 +65,30 @@ QtMouseState::QtMouseState()
reset();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void QtMouseState::updateFromMouseEvent(QMouseEvent* event)
void QtMouseState::updateFromMouseEvent( QMouseEvent* event )
{
// Always update with current state
m_mouseButtonState = event->buttons();
m_keyboardModifierFlags = event->modifiers();
// Now do the events themselves
// Mouse press events
if (event->type() == QEvent::MouseButtonPress)
if ( event->type() == QEvent::MouseButtonPress )
{
// Start by clearing them
m_cleanButtonPressButton = Qt::NoButton;
m_cleanButtonClickButton = Qt::NoButton;;
m_cleanButtonClickButton = Qt::NoButton;
;
m_cleanButtonPressPosX = cvf::UNDEFINED_INT;
m_cleanButtonPressPosY = cvf::UNDEFINED_INT;
Qt::MouseButton buttonPressed = event->button();
if (numMouseButtonsInState(m_mouseButtonState) == 1)
if ( numMouseButtonsInState( m_mouseButtonState ) == 1 )
{
m_cleanButtonPressButton = buttonPressed;
m_cleanButtonPressPosX = event->x();
@ -101,7 +97,7 @@ void QtMouseState::updateFromMouseEvent(QMouseEvent* event)
}
// Mouse button release events
else if (event->type() == QEvent::MouseButtonRelease)
else if ( event->type() == QEvent::MouseButtonRelease )
{
// Clear it now, might set it later
m_cleanButtonClickButton = Qt::NoButton;
@ -109,53 +105,51 @@ void QtMouseState::updateFromMouseEvent(QMouseEvent* event)
Qt::MouseButton buttonReleased = event->button();
// Check if we have a clean press/release sequence
if (m_cleanButtonPressButton == buttonReleased &&
m_cleanButtonPressPosX != cvf::UNDEFINED_INT &&
m_cleanButtonPressPosY != cvf::UNDEFINED_INT)
if ( m_cleanButtonPressButton == buttonReleased && m_cleanButtonPressPosX != cvf::UNDEFINED_INT &&
m_cleanButtonPressPosY != cvf::UNDEFINED_INT )
{
// We have a candidate, check if movement is within tolerance
if (cvf::Math::abs(double((m_cleanButtonPressPosX - event->x()))) <= m_cleanButtonClickTolerance &&
cvf::Math::abs(double((m_cleanButtonPressPosY - event->y()))) <= m_cleanButtonClickTolerance)
if ( cvf::Math::abs( double( ( m_cleanButtonPressPosX - event->x() ) ) ) <= m_cleanButtonClickTolerance &&
cvf::Math::abs( double( ( m_cleanButtonPressPosY - event->y() ) ) ) <= m_cleanButtonClickTolerance )
{
m_cleanButtonClickButton = buttonReleased;
}
m_cleanButtonPressButton = Qt::NoButton;;
m_cleanButtonPressButton = Qt::NoButton;
;
m_cleanButtonPressPosX = cvf::UNDEFINED_INT;
m_cleanButtonPressPosY = cvf::UNDEFINED_INT;
}
}
else if (event->type() == QEvent::MouseMove)
else if ( event->type() == QEvent::MouseMove )
{
// For now nothing to do
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void QtMouseState::updateFromMouseEvent(QGraphicsSceneMouseEvent* event)
void QtMouseState::updateFromMouseEvent( QGraphicsSceneMouseEvent* event )
{
// Always update with current state
m_mouseButtonState = event->buttons();
m_keyboardModifierFlags = event->modifiers();
// Now do the events themselves
if (event->type() == QEvent::GraphicsSceneMousePress)
if ( event->type() == QEvent::GraphicsSceneMousePress )
{
// Start by clearing them
m_cleanButtonPressButton = Qt::NoButton;
m_cleanButtonClickButton = Qt::NoButton;;
m_cleanButtonClickButton = Qt::NoButton;
;
m_cleanButtonPressPosX = cvf::UNDEFINED_INT;
m_cleanButtonPressPosY = cvf::UNDEFINED_INT;
Qt::MouseButton buttonPressed = event->button();
if (numMouseButtonsInState(m_mouseButtonState) == 1)
if ( numMouseButtonsInState( m_mouseButtonState ) == 1 )
{
m_cleanButtonPressButton = buttonPressed;
m_cleanButtonPressPosX = (int)event->scenePos().x();
@ -164,7 +158,7 @@ void QtMouseState::updateFromMouseEvent(QGraphicsSceneMouseEvent* event)
}
// Mouse button release events
else if (event->type() == QEvent::GraphicsSceneMouseRelease)
else if ( event->type() == QEvent::GraphicsSceneMouseRelease )
{
// Clear it now, might set it later
m_cleanButtonClickButton = Qt::NoButton;
@ -172,24 +166,26 @@ void QtMouseState::updateFromMouseEvent(QGraphicsSceneMouseEvent* event)
Qt::MouseButton buttonReleased = event->button();
// Check if we have a clean press/release sequence
if (m_cleanButtonPressButton == buttonReleased &&
m_cleanButtonPressPosX != cvf::UNDEFINED_INT &&
m_cleanButtonPressPosY != cvf::UNDEFINED_INT)
if ( m_cleanButtonPressButton == buttonReleased && m_cleanButtonPressPosX != cvf::UNDEFINED_INT &&
m_cleanButtonPressPosY != cvf::UNDEFINED_INT )
{
// We have a candidate, check if movement is within tolerance
if (cvf::Math::abs(double((m_cleanButtonPressPosX - event->scenePos().x()))) <= m_cleanButtonClickTolerance &&
cvf::Math::abs(double((m_cleanButtonPressPosY - event->scenePos().y()))) <= m_cleanButtonClickTolerance)
if ( cvf::Math::abs( double( ( m_cleanButtonPressPosX - event->scenePos().x() ) ) ) <=
m_cleanButtonClickTolerance &&
cvf::Math::abs( double( ( m_cleanButtonPressPosY - event->scenePos().y() ) ) ) <=
m_cleanButtonClickTolerance )
{
m_cleanButtonClickButton = buttonReleased;
}
m_cleanButtonPressButton = Qt::NoButton;;
m_cleanButtonPressButton = Qt::NoButton;
;
m_cleanButtonPressPosX = cvf::UNDEFINED_INT;
m_cleanButtonPressPosY = cvf::UNDEFINED_INT;
}
}
else if (event->type() == QEvent::GraphicsSceneMouseMove)
else if ( event->type() == QEvent::GraphicsSceneMouseMove )
{
// For now nothing to do
}
@ -208,7 +204,6 @@ void QtMouseState::reset()
m_cleanButtonClickButton = Qt::NoButton;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@ -217,7 +212,6 @@ Qt::MouseButtons QtMouseState::mouseButtonState() const
return m_mouseButtonState;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@ -226,7 +220,6 @@ Qt::KeyboardModifiers QtMouseState::keyboardModifierFlags() const
return m_keyboardModifierFlags;
}
//--------------------------------------------------------------------------------------------------
/// Get button that was cleanly clicked if any
//--------------------------------------------------------------------------------------------------
@ -235,22 +228,18 @@ Qt::MouseButton QtMouseState::cleanButtonClickButton() const
return m_cleanButtonClickButton;
}
//--------------------------------------------------------------------------------------------------
/// Static helper function to determine the number of mouse buttons pressed
//--------------------------------------------------------------------------------------------------
int QtMouseState::numMouseButtonsInState(Qt::MouseButtons buttonState)
int QtMouseState::numMouseButtonsInState( Qt::MouseButtons buttonState )
{
int iNum = 0;
if (buttonState & Qt::LeftButton) iNum++;
if (buttonState & Qt::RightButton) iNum++;
if (buttonState & Qt::MidButton) iNum++;
if ( buttonState & Qt::LeftButton ) iNum++;
if ( buttonState & Qt::RightButton ) iNum++;
if ( buttonState & Qt::MidButton ) iNum++;
return iNum;
}
} // namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#pragma once
class QMouseEvent;
@ -42,8 +41,8 @@ class QGraphicsSceneMouseEvent;
#include <Qt>
namespace caf {
namespace caf
{
//==================================================================================================
//
// Helper class for storing mouse positions and button states. Should be reset whenever widget looses focus.
@ -54,8 +53,8 @@ class QtMouseState
public:
QtMouseState();
void updateFromMouseEvent(QMouseEvent* event);
void updateFromMouseEvent(QGraphicsSceneMouseEvent* event);
void updateFromMouseEvent( QMouseEvent* event );
void updateFromMouseEvent( QGraphicsSceneMouseEvent* event );
void reset();
Qt::MouseButtons mouseButtonState() const;
@ -63,19 +62,22 @@ public:
Qt::MouseButton cleanButtonClickButton() const;
public:
static int numMouseButtonsInState(Qt::MouseButtons buttonState);
static int numMouseButtonsInState( Qt::MouseButtons buttonState );
private:
Qt::MouseButtons m_mouseButtonState; // Stores current mouse button state (combination of mouse buttons that are down)
Qt::KeyboardModifiers m_keyboardModifierFlags; // Stores current keyboard modifier flags (combination of keyboard modifier keys that are down)
Qt::KeyboardModifiers m_keyboardModifierFlags; // Stores current keyboard modifier flags (combination of keyboard
// modifier keys that are down)
int m_cleanButtonClickTolerance; // The movement tolerance in pixels for considering a mouse button press/release sequence a clean button click
Qt::MouseButton m_cleanButtonPressButton; // The mouse button that was last pressed 'cleanly', that is without any other mouse buttons down. Used to detect clean button clicks (for showing context menus etc)
int m_cleanButtonPressPosX; // The position of the mouse cursor in widget coordinates of the last clean button press. Used to check if cursor has moved when button is released
int m_cleanButtonClickTolerance; // The movement tolerance in pixels for considering a mouse button press/release
// sequence a clean button click
Qt::MouseButton m_cleanButtonPressButton; // The mouse button that was last pressed 'cleanly', that is without any
// other mouse buttons down. Used to detect clean button clicks (for
// showing context menus etc)
int m_cleanButtonPressPosX; // The position of the mouse cursor in widget coordinates of the last clean button
// press. Used to check if cursor has moved when button is released
int m_cleanButtonPressPosY; //
Qt::MouseButton m_cleanButtonClickButton; // The button (if any) that was last clicked 'cleanly'.
};
}
} // namespace caf

View File

@ -35,61 +35,60 @@
//##################################################################################################
#pragma once
#include <vector>
#include <cmath>
#include "cafAssert.h"
#include <cmath>
#include <vector>
namespace caf
{
class TickMarkGenerator
{
public:
TickMarkGenerator(double min, double max, double minAllowedStepSize)
TickMarkGenerator( double min, double max, double minAllowedStepSize )
{
if (minAllowedStepSize < 0.0) minAllowedStepSize = -minAllowedStepSize;
if ( minAllowedStepSize < 0.0 ) minAllowedStepSize = -minAllowedStepSize;
double step = roundUpToLog_1_2_5_10(minAllowedStepSize);
double step = roundUpToLog_1_2_5_10( minAllowedStepSize );
double startStepCount = ceil(min / step);
double startStepCount = ceil( min / step );
if ( startStepCount*step < (min + 0.5*minAllowedStepSize) )
if ( startStepCount * step < ( min + 0.5 * minAllowedStepSize ) )
{
++startStepCount;
}
double tick = startStepCount*step;
double tick = startStepCount * step;
double currentStepCount = startStepCount;
while ( tick < (max - 0.5*minAllowedStepSize) )
while ( tick < ( max - 0.5 * minAllowedStepSize ) )
{
m_tickMarkValues.push_back(tick);
m_tickMarkValues.push_back( tick );
++currentStepCount;
tick = currentStepCount*step;
tick = currentStepCount * step;
}
}
const std::vector<double>& tickMarkValues() { return m_tickMarkValues; }
static double roundUpToLog_1_2_5_10(double val)
static double roundUpToLog_1_2_5_10( double val )
{
CAF_ASSERT(val >= 0.0);
CAF_ASSERT( val >= 0.0 );
const static double logOf5 = log10(5.0);
const static double logOf2 = log10(2.0);
const static double logOf0_5 = log10(0.5);
const static double logOf0_2 = log10(0.2);
const static double logOf5 = log10( 5.0 );
const static double logOf2 = log10( 2.0 );
const static double logOf0_5 = log10( 0.5 );
const static double logOf0_2 = log10( 0.2 );
double logValue = log10(val);
double logValue = log10( val );
double intPart = 0.0;
double fraction = modf(logValue, &intPart);
double fraction = modf( logValue, &intPart );
double factor = 1.0;
if (fraction == 0.0)
if ( fraction == 0.0 )
{
factor = 1.0;
}
else if (fraction > 0.0)
else if ( fraction > 0.0 )
{
if ( fraction > logOf5 )
{
@ -106,7 +105,7 @@ public:
}
else
{
if (fraction > logOf0_5)
if ( fraction > logOf0_5 )
{
factor = 1;
}
@ -120,7 +119,7 @@ public:
}
}
double roundedValue = pow(10.0, intPart) * factor;
double roundedValue = pow( 10.0, intPart ) * factor;
return roundedValue;
}
@ -129,6 +128,4 @@ private:
std::vector<double> m_tickMarkValues;
};
}
} // namespace caf

View File

@ -34,11 +34,10 @@
//
//##################################################################################################
#include "cafUtils.h"
#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QLineEdit>
@ -47,20 +46,19 @@
#include <QFileDialog>
#include <QMessageBox>
namespace caf {
//--------------------------------------------------------------------------------------------------
namespace caf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double Utils::editToDouble(QLineEdit* lineEdit, double defaultVal)
double Utils::editToDouble( QLineEdit* lineEdit, double defaultVal )
{
if (!lineEdit) return false;
// CVF_ASSERT(lineEdit);
if ( !lineEdit ) return false;
// CVF_ASSERT(lineEdit);
bool ok = false;
double val = lineEdit->text().toDouble(&ok);
if (ok)
double val = lineEdit->text().toDouble( &ok );
if ( ok )
{
return val;
}
@ -70,55 +68,52 @@ double Utils::editToDouble(QLineEdit* lineEdit, double defaultVal)
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString Utils::absoluteFileName(const QString& fileName)
QString Utils::absoluteFileName( const QString& fileName )
{
QFileInfo fi(fileName);
return QDir::toNativeSeparators(fi.absoluteFilePath());
QFileInfo fi( fileName );
return QDir::toNativeSeparators( fi.absoluteFilePath() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QStringList Utils::getFilesInDirectory(const QString& dirPath,
const QString& nameFilter,
bool getAbsoluteFileNames)
QStringList Utils::getFilesInDirectory( const QString& dirPath, const QString& nameFilter, bool getAbsoluteFileNames )
{
QStringList nameFilters; nameFilters << nameFilter;
return getFilesInDirectory(dirPath, nameFilters, getAbsoluteFileNames);
QStringList nameFilters;
nameFilters << nameFilter;
return getFilesInDirectory( dirPath, nameFilters, getAbsoluteFileNames );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QStringList Utils::getFilesInDirectory(const QString& dirPath, const QStringList& nameFilters, bool getAbsoluteFileNames)
QStringList Utils::getFilesInDirectory( const QString& dirPath, const QStringList& nameFilters, bool getAbsoluteFileNames )
{
QDir::SortFlags sortFlags = QDir::SortFlags(QDir::Name | QDir::IgnoreCase);
QDir::SortFlags sortFlags = QDir::SortFlags( QDir::Name | QDir::IgnoreCase );
// Only get files
QDir::Filters typeFilter = QDir::Files;
QDir dir(dirPath);
dir.setFilter(typeFilter);
dir.setNameFilters(nameFilters);
dir.setSorting(sortFlags);
QDir dir( dirPath );
dir.setFilter( typeFilter );
dir.setNameFilters( nameFilters );
dir.setSorting( sortFlags );
QFileInfoList fileInfoList = dir.entryInfoList();
QStringList retFileNames;
QListIterator<QFileInfo> it(fileInfoList);
while (it.hasNext())
QListIterator<QFileInfo> it( fileInfoList );
while ( it.hasNext() )
{
QFileInfo fi = it.next();
QString entry = getAbsoluteFileNames ? fi.absoluteFilePath() : fi.fileName();
entry = QDir::toNativeSeparators(entry);
retFileNames.push_back(entry);
entry = QDir::toNativeSeparators( entry );
retFileNames.push_back( entry );
}
return retFileNames;
@ -127,39 +122,37 @@ QStringList Utils::getFilesInDirectory(const QString& dirPath, const QStringList
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString Utils::constructFullFileName(const QString& folder, const QString& baseFileName, const QString& extension)
QString Utils::constructFullFileName( const QString& folder, const QString& baseFileName, const QString& extension )
{
QFileInfo fi(folder, baseFileName + extension);
QFileInfo fi( folder, baseFileName + extension );
QString fullFileName = fi.filePath();
fullFileName = QDir::toNativeSeparators(fullFileName);
fullFileName = QDir::toNativeSeparators( fullFileName );
return fullFileName;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString Utils::makeValidFileBasename(const QString& fileBasenameCandidate)
QString Utils::makeValidFileBasename( const QString& fileBasenameCandidate )
{
QString cleanBasename = fileBasenameCandidate.trimmed();
cleanBasename.replace(".", "_");
cleanBasename.replace(",", "_");
cleanBasename.replace(":", "_");
cleanBasename.replace(";", "_");
cleanBasename.replace(" ", "_");
cleanBasename.replace("/", "_");
cleanBasename.replace("\\", "_");
cleanBasename.replace("<", "_");
cleanBasename.replace(">", "_");
cleanBasename.replace("\"", "_");
cleanBasename.replace("|", "_");
cleanBasename.replace("?", "_");
cleanBasename.replace("*", "_");
cleanBasename.replace("\n", "_");
cleanBasename.replace( ".", "_" );
cleanBasename.replace( ",", "_" );
cleanBasename.replace( ":", "_" );
cleanBasename.replace( ";", "_" );
cleanBasename.replace( " ", "_" );
cleanBasename.replace( "/", "_" );
cleanBasename.replace( "\\", "_" );
cleanBasename.replace( "<", "_" );
cleanBasename.replace( ">", "_" );
cleanBasename.replace( "\"", "_" );
cleanBasename.replace( "|", "_" );
cleanBasename.replace( "?", "_" );
cleanBasename.replace( "*", "_" );
cleanBasename.replace( "\n", "_" );
cleanBasename.replace(QRegExp("_+"), "_");
cleanBasename.replace( QRegExp( "_+" ), "_" );
return cleanBasename;
}
@ -167,58 +160,57 @@ QString Utils::makeValidFileBasename(const QString& fileBasenameCandidate)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString Utils::indentString(int numSpacesToIndent, const QString& str)
QString Utils::indentString( int numSpacesToIndent, const QString& str )
{
QString indentString;
indentString.fill(' ', numSpacesToIndent);
indentString.fill( ' ', numSpacesToIndent );
QStringList strList = str.split("\n");
QStringList strList = str.split( "\n" );
QString retStr = indentString + strList.join("\n" + indentString);
QString retStr = indentString + strList.join( "\n" + indentString );
return retStr;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool Utils::getSaveDirectoryAndCheckOverwriteFiles(const QString& defaultDir, std::vector<QString> fileNames, QString* saveDir)
bool Utils::getSaveDirectoryAndCheckOverwriteFiles( const QString& defaultDir, std::vector<QString> fileNames, QString* saveDir )
{
bool overWriteFiles = false;
(*saveDir) = QFileDialog::getExistingDirectory(nullptr, "Select save directory", defaultDir);
( *saveDir ) = QFileDialog::getExistingDirectory( nullptr, "Select save directory", defaultDir );
std::vector<QString> filesToOverwrite;
for (QString fileName : fileNames)
for ( QString fileName : fileNames )
{
QFileInfo fileInfo((*saveDir) + "/" +fileName);
if (fileInfo.exists())
QFileInfo fileInfo( ( *saveDir ) + "/" + fileName );
if ( fileInfo.exists() )
{
filesToOverwrite.push_back(fileName);
filesToOverwrite.push_back( fileName );
}
}
if (filesToOverwrite.size() == 0)
if ( filesToOverwrite.size() == 0 )
{
overWriteFiles = true;
return overWriteFiles;
}
else if (filesToOverwrite.size() > 0)
else if ( filesToOverwrite.size() > 0 )
{
QMessageBox msgBox;
QString message = "The following files will be overwritten in the export:";
for (QString fileName : filesToOverwrite)
for ( QString fileName : filesToOverwrite )
{
message += "\n" + (*saveDir) + "/" + fileName;
message += "\n" + ( *saveDir ) + "/" + fileName;
}
msgBox.setText(message);
msgBox.setText( message );
msgBox.setInformativeText("Do you want to continue?");
msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msgBox.setDefaultButton(QMessageBox::Ok);
msgBox.setInformativeText( "Do you want to continue?" );
msgBox.setStandardButtons( QMessageBox::Ok | QMessageBox::Cancel );
msgBox.setDefaultButton( QMessageBox::Ok );
int ret = msgBox.exec();
switch (ret)
switch ( ret )
{
case QMessageBox::Ok:
overWriteFiles = true;
@ -230,24 +222,22 @@ bool Utils::getSaveDirectoryAndCheckOverwriteFiles(const QString& defaultDir, st
// should never be reached
break;
}
}
return overWriteFiles;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool Utils::fileExists(const QString& fileName)
bool Utils::fileExists( const QString& fileName )
{
QFileInfo fi(fileName);
QFileInfo fi( fileName );
// QFileInfo::exists returns true for both files and folders
// Also check if the path points to a file
if (fi.exists() && fi.isFile())
if ( fi.exists() && fi.isFile() )
{
return true;
}
@ -258,9 +248,9 @@ bool Utils::fileExists(const QString& fileName)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString Utils::fileExtension(const QString & fileName)
QString Utils::fileExtension( const QString& fileName )
{
QFileInfo fi(fileName);
QFileInfo fi( fileName );
return fi.suffix();
}
@ -268,12 +258,12 @@ QString Utils::fileExtension(const QString & fileName)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool Utils::isFolderWritable(const QString& folderName)
bool Utils::isFolderWritable( const QString& folderName )
{
// See platform issues here
// http://doc.qt.io/qt-4.8/qfile.html#platform-specific-issues
QFileInfo dir(folderName);
QFileInfo dir( folderName );
return dir.isWritable();
}
@ -281,49 +271,52 @@ bool Utils::isFolderWritable(const QString& folderName)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool Utils::isStringMatch(const QString& filterString, const QString& value)
bool Utils::isStringMatch( const QString& filterString, const QString& value )
{
if (filterString.isEmpty()) return true;
if (filterString.trimmed() == "*")
if ( filterString.isEmpty() ) return true;
if ( filterString.trimmed() == "*" )
{
if (!value.isEmpty()) return true;
else return false;
if ( !value.isEmpty() )
return true;
else
return false;
}
QRegExp searcher(filterString, Qt::CaseInsensitive, QRegExp::WildcardUnix);
return searcher.exactMatch(value);
QRegExp searcher( filterString, Qt::CaseInsensitive, QRegExp::WildcardUnix );
return searcher.exactMatch( value );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool Utils::removeDirectoryAndFilesRecursively(const QString& dirName)
bool Utils::removeDirectoryAndFilesRecursively( const QString& dirName )
{
bool result = true;
QDir dir(dirName);
QDir dir( dirName );
if (dir.exists())
if ( dir.exists() )
{
QFileInfoList fileInfoList =
dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst);
for (const auto& fileInfo : fileInfoList)
dir.entryInfoList( QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files,
QDir::DirsFirst );
for ( const auto& fileInfo : fileInfoList )
{
if (fileInfo.isDir())
if ( fileInfo.isDir() )
{
result = removeDirectoryAndFilesRecursively(fileInfo.absoluteFilePath());
result = removeDirectoryAndFilesRecursively( fileInfo.absoluteFilePath() );
}
else
{
result = QFile::remove(fileInfo.absoluteFilePath());
result = QFile::remove( fileInfo.absoluteFilePath() );
}
if (!result)
if ( !result )
{
return result;
}
}
result = QDir().rmdir(dirName);
result = QDir().rmdir( dirName );
}
return result;

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#pragma once
#include <vector>
@ -43,8 +42,8 @@ class QLineEdit;
class QString;
class QStringList;
namespace caf {
namespace caf
{
//==================================================================================================
//
//
@ -53,24 +52,27 @@ namespace caf {
class Utils
{
public:
static double editToDouble(QLineEdit* lineEdit, double defaultVal);
static double editToDouble( QLineEdit* lineEdit, double defaultVal );
static QString absoluteFileName(const QString& fileName);
static QStringList getFilesInDirectory(const QString& dirPath, const QString& nameFilter, bool getAbsoluteFileNames);
static QStringList getFilesInDirectory(const QString& dirPath, const QStringList& nameFilters, bool getAbsoluteFileNames);
static QString constructFullFileName(const QString& folder, const QString& baseFileName, const QString& extension);
static QString makeValidFileBasename(const QString& fileBasenameCandidate);
static QString absoluteFileName( const QString& fileName );
static QStringList getFilesInDirectory( const QString& dirPath, const QString& nameFilter, bool getAbsoluteFileNames );
static QStringList
getFilesInDirectory( const QString& dirPath, const QStringList& nameFilters, bool getAbsoluteFileNames );
static QString constructFullFileName( const QString& folder, const QString& baseFileName, const QString& extension );
static QString makeValidFileBasename( const QString& fileBasenameCandidate );
static QString indentString(int numSpacesToIndent, const QString& str);
static QString indentString( int numSpacesToIndent, const QString& str );
static bool getSaveDirectoryAndCheckOverwriteFiles(const QString& defaultDir, std::vector<QString> fileNames, QString* saveDir);
static bool getSaveDirectoryAndCheckOverwriteFiles( const QString& defaultDir,
std::vector<QString> fileNames,
QString* saveDir );
static bool fileExists(const QString& fileName);
static QString fileExtension(const QString& fileName);
static bool isFolderWritable(const QString& folderName);
static bool fileExists( const QString& fileName );
static QString fileExtension( const QString& fileName );
static bool isFolderWritable( const QString& folderName );
static bool isStringMatch(const QString& filterString, const QString& value);
static bool removeDirectoryAndFilesRecursively(const QString& dirName);
static bool isStringMatch( const QString& filterString, const QString& value );
static bool removeDirectoryAndFilesRecursively( const QString& dirName );
};
}
} // namespace caf

View File

@ -36,14 +36,14 @@
#include "cafVecIjk.h"
namespace caf {
namespace caf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
VecIjk::VecIjk(size_t i, size_t j, size_t k)
VecIjk::VecIjk( size_t i, size_t j, size_t k )
{
m_values = { {i, j, k} };
m_values = {{i, j, k}};
}
//--------------------------------------------------------------------------------------------------
@ -70,4 +70,4 @@ size_t VecIjk::k() const
return m_values[2];
}
}; //namespace caf
}; // namespace caf

View File

@ -34,18 +34,16 @@
//
//##################################################################################################
#pragma once
#include <array>
namespace caf
{
class VecIjk
{
public:
VecIjk(size_t i, size_t j, size_t k);
VecIjk( size_t i, size_t j, size_t k );
size_t i() const;
size_t j() const;
@ -55,5 +53,4 @@ private:
std::array<size_t, 3> m_values;
};
}
} // namespace caf

View File

@ -34,14 +34,10 @@
//
//##################################################################################################
#include "cvfCellRange.h"
namespace cvf {
namespace cvf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@ -54,41 +50,41 @@ CellRange::CellRange()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CellRange::CellRange(cvf::Vec3st min, cvf::Vec3st max)
CellRange::CellRange( cvf::Vec3st min, cvf::Vec3st max )
{
setRange(min, max);
setRange( min, max );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CellRange::CellRange(size_t minI, size_t minJ, size_t minK, size_t maxI, size_t maxJ, size_t maxK)
CellRange::CellRange( size_t minI, size_t minJ, size_t minK, size_t maxI, size_t maxJ, size_t maxK )
{
setRange(Vec3st(minI, minJ, minK), Vec3st(maxI, maxJ, maxK));
setRange( Vec3st( minI, minJ, minK ), Vec3st( maxI, maxJ, maxK ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CellRange::setRange(const cvf::Vec3st& min, const cvf::Vec3st& max)
void CellRange::setRange( const cvf::Vec3st& min, const cvf::Vec3st& max )
{
m_min = min;
m_max = max;
CVF_ASSERT(m_min.x() != cvf::UNDEFINED_SIZE_T);
CVF_ASSERT(m_min.y() != cvf::UNDEFINED_SIZE_T);
CVF_ASSERT(m_min.z() != cvf::UNDEFINED_SIZE_T);
CVF_ASSERT(m_max.x() != cvf::UNDEFINED_SIZE_T);
CVF_ASSERT(m_max.y() != cvf::UNDEFINED_SIZE_T);
CVF_ASSERT(m_max.z() != cvf::UNDEFINED_SIZE_T);
CVF_ASSERT( m_min.x() != cvf::UNDEFINED_SIZE_T );
CVF_ASSERT( m_min.y() != cvf::UNDEFINED_SIZE_T );
CVF_ASSERT( m_min.z() != cvf::UNDEFINED_SIZE_T );
CVF_ASSERT( m_max.x() != cvf::UNDEFINED_SIZE_T );
CVF_ASSERT( m_max.y() != cvf::UNDEFINED_SIZE_T );
CVF_ASSERT( m_max.z() != cvf::UNDEFINED_SIZE_T );
CVF_ASSERT(normalize());
CVF_ASSERT( normalize() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CellRange::range(cvf::Vec3st& min, cvf::Vec3st& max) const
void CellRange::range( cvf::Vec3st& min, cvf::Vec3st& max ) const
{
min = m_min;
max = m_max;
@ -99,14 +95,14 @@ void CellRange::range(cvf::Vec3st& min, cvf::Vec3st& max) const
//--------------------------------------------------------------------------------------------------
bool CellRange::normalize()
{
if (m_min == cvf::Vec3st::UNDEFINED || m_max == cvf::Vec3st::UNDEFINED)
if ( m_min == cvf::Vec3st::UNDEFINED || m_max == cvf::Vec3st::UNDEFINED )
{
return false;
}
for (uint i = 0; i < 3; i++)
for ( uint i = 0; i < 3; i++ )
{
if (m_min[i] > m_max[i])
if ( m_min[i] > m_max[i] )
{
size_t tmp = m_max[i];
m_max[i] = m_min[i];
@ -120,13 +116,13 @@ bool CellRange::normalize()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool CellRange::isInRange(size_t i, size_t j, size_t k) const
bool CellRange::isInRange( size_t i, size_t j, size_t k ) const
{
cvf::Vec3st test(i, j, k);
cvf::Vec3st test( i, j, k );
for (uint idx = 0; idx < 3; idx++)
for ( uint idx = 0; idx < 3; idx++ )
{
if (test[idx] < m_min[idx] || m_max[idx] <= test[idx])
if ( test[idx] < m_min[idx] || m_max[idx] <= test[idx] )
{
return false;
}
@ -135,6 +131,4 @@ bool CellRange::isInRange(size_t i, size_t j, size_t k) const
return true;
}
} // namespace cvf

View File

@ -34,15 +34,13 @@
//
//##################################################################################################
#pragma once
#include "cvfBase.h"
#include "cvfVector3.h"
namespace cvf {
namespace cvf
{
//==================================================================================================
//
//==================================================================================================
@ -50,20 +48,19 @@ class CellRange
{
public:
CellRange();
CellRange(cvf::Vec3st min, cvf::Vec3st max);
CellRange(size_t minI, size_t minJ, size_t minK, size_t maxI, size_t maxJ, size_t maxK);
CellRange( cvf::Vec3st min, cvf::Vec3st max );
CellRange( size_t minI, size_t minJ, size_t minK, size_t maxI, size_t maxJ, size_t maxK );
void setRange(const cvf::Vec3st& min, const cvf::Vec3st& max);
void range(cvf::Vec3st& min, cvf::Vec3st& max) const;
void setRange( const cvf::Vec3st& min, const cvf::Vec3st& max );
void range( cvf::Vec3st& min, cvf::Vec3st& max ) const;
bool normalize();
bool isInRange(size_t i, size_t j, size_t k) const;
bool isInRange( size_t i, size_t j, size_t k ) const;
private:
cvf::Vec3st m_min;
cvf::Vec3st m_max;
};
} // End namespace cvf

View File

@ -34,31 +34,26 @@
//
//##################################################################################################
#include "cvfBase.h"
#include "cvfStructGrid.h"
#include "cvfBase.h"
namespace caf
{
template<>
void cvf::StructGridInterface::FaceEnum::setUp()
{
addItem(cvf::StructGridInterface::POS_I, "POS I", "");
addItem(cvf::StructGridInterface::NEG_I, "NEG I", "");
addItem(cvf::StructGridInterface::POS_J, "POS J", "");
addItem(cvf::StructGridInterface::NEG_J, "NEG J", "");
addItem(cvf::StructGridInterface::POS_K, "POS K", "");
addItem(cvf::StructGridInterface::NEG_K, "NEG K", "");
addItem(cvf::StructGridInterface::NO_FACE, "UnDef", "");
}
template <>
void cvf::StructGridInterface::FaceEnum::setUp()
{
addItem( cvf::StructGridInterface::POS_I, "POS I", "" );
addItem( cvf::StructGridInterface::NEG_I, "NEG I", "" );
addItem( cvf::StructGridInterface::POS_J, "POS J", "" );
addItem( cvf::StructGridInterface::NEG_J, "NEG J", "" );
addItem( cvf::StructGridInterface::POS_K, "POS K", "" );
addItem( cvf::StructGridInterface::NEG_K, "NEG K", "" );
addItem( cvf::StructGridInterface::NO_FACE, "UnDef", "" );
}
} // namespace caf
namespace cvf {
namespace cvf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@ -74,7 +69,7 @@ StructGridInterface::StructGridInterface()
//--------------------------------------------------------------------------------------------------
size_t StructGridInterface::cellCountI() const
{
if (gridPointCountI() == 0) return 0;
if ( gridPointCountI() == 0 ) return 0;
return gridPointCountI() - 1;
}
@ -84,7 +79,7 @@ size_t StructGridInterface::cellCountI() const
//--------------------------------------------------------------------------------------------------
size_t StructGridInterface::cellCountJ() const
{
if (gridPointCountJ() == 0) return 0;
if ( gridPointCountJ() == 0 ) return 0;
return gridPointCountJ() - 1;
}
@ -94,7 +89,7 @@ size_t StructGridInterface::cellCountJ() const
//--------------------------------------------------------------------------------------------------
size_t StructGridInterface::cellCountK() const
{
if (gridPointCountK() == 0) return 0;
if ( gridPointCountK() == 0 ) return 0;
return gridPointCountK() - 1;
}
@ -102,7 +97,7 @@ size_t StructGridInterface::cellCountK() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void StructGridInterface::cellFaceVertexIndices(FaceType face, cvf::ubyte vertexIndices[4])
void StructGridInterface::cellFaceVertexIndices( FaceType face, cvf::ubyte vertexIndices[4] )
{
//
// 7---------6
@ -114,42 +109,42 @@ void StructGridInterface::cellFaceVertexIndices(FaceType face, cvf::ubyte vertex
// |/ |/
// 0---------1
if (face == NEG_K)
if ( face == NEG_K )
{
vertexIndices[0] = 0;
vertexIndices[1] = 3;
vertexIndices[2] = 2;
vertexIndices[3] = 1;
}
else if (face == POS_K)
else if ( face == POS_K )
{
vertexIndices[0] = 4;
vertexIndices[1] = 5;
vertexIndices[2] = 6;
vertexIndices[3] = 7;
}
else if (face == NEG_J)
else if ( face == NEG_J )
{
vertexIndices[0] = 0;
vertexIndices[1] = 1;
vertexIndices[2] = 5;
vertexIndices[3] = 4;
}
else if (face == POS_I)
else if ( face == POS_I )
{
vertexIndices[0] = 1;
vertexIndices[1] = 2;
vertexIndices[2] = 6;
vertexIndices[3] = 5;
}
else if (face == POS_J)
else if ( face == POS_J )
{
vertexIndices[0] = 3;
vertexIndices[1] = 7;
vertexIndices[2] = 6;
vertexIndices[3] = 2;
}
else if (face == NEG_I)
else if ( face == NEG_I )
{
vertexIndices[0] = 0;
vertexIndices[1] = 4;
@ -161,21 +156,33 @@ void StructGridInterface::cellFaceVertexIndices(FaceType face, cvf::ubyte vertex
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
StructGridInterface::FaceType StructGridInterface::oppositeFace(FaceType face)
StructGridInterface::FaceType StructGridInterface::oppositeFace( FaceType face )
{
FaceType opposite;
switch (face)
switch ( face )
{
case NEG_I : opposite = POS_I; break;
case POS_I : opposite = NEG_I; break;
case NEG_J : opposite = POS_J; break;
case POS_J : opposite = NEG_J; break;
case NEG_K : opposite = POS_K; break;
case POS_K : opposite = NEG_K; break;
case NEG_I:
opposite = POS_I;
break;
case POS_I:
opposite = NEG_I;
break;
case NEG_J:
opposite = POS_J;
break;
case POS_J:
opposite = NEG_J;
break;
case NEG_K:
opposite = POS_K;
break;
case POS_K:
opposite = NEG_K;
break;
default:
opposite = POS_I;
CVF_ASSERT(false);
CVF_ASSERT( false );
}
return opposite;
@ -184,42 +191,62 @@ StructGridInterface::FaceType StructGridInterface::oppositeFace(FaceType face)
//--------------------------------------------------------------------------------------------------
/// Return values are set to cvf::UNDEFINED_SIZE_T if the neighbor is in the negative area
//--------------------------------------------------------------------------------------------------
void StructGridInterface::neighborIJKAtCellFace(size_t i, size_t j, size_t k, FaceType face, size_t* ni, size_t* nj, size_t* nk)
void StructGridInterface::neighborIJKAtCellFace( size_t i, size_t j, size_t k, FaceType face, size_t* ni, size_t* nj, size_t* nk )
{
*ni = i;
*nj = j;
*nk = k;
switch (face)
switch ( face )
{
case POS_I : (*ni)++; break;
case NEG_I : if (i > 0) (*ni)--; else (*ni) = cvf::UNDEFINED_SIZE_T; break;
case POS_J : (*nj)++; break;
case NEG_J : if (j > 0) (*nj)--; else (*nj) = cvf::UNDEFINED_SIZE_T; break;
case POS_K : (*nk)++; break;
case NEG_K : if (k > 0) (*nk)--; else (*nk) = cvf::UNDEFINED_SIZE_T; break;
case POS_I:
( *ni )++;
break;
case NEG_I:
if ( i > 0 )
( *ni )--;
else
( *ni ) = cvf::UNDEFINED_SIZE_T;
break;
case POS_J:
( *nj )++;
break;
case NEG_J:
if ( j > 0 )
( *nj )--;
else
( *nj ) = cvf::UNDEFINED_SIZE_T;
break;
case POS_K:
( *nk )++;
break;
case NEG_K:
if ( k > 0 )
( *nk )--;
else
( *nk ) = cvf::UNDEFINED_SIZE_T;
break;
default:
break;
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
StructGridInterface::GridAxisType StructGridInterface::gridAxisFromFace(FaceType face)
StructGridInterface::GridAxisType StructGridInterface::gridAxisFromFace( FaceType face )
{
GridAxisType axis = GridAxisType::NO_AXIS;
if (face == cvf::StructGridInterface::POS_I || face == cvf::StructGridInterface::NEG_I)
if ( face == cvf::StructGridInterface::POS_I || face == cvf::StructGridInterface::NEG_I )
{
axis = GridAxisType::AXIS_I;
}
else if (face == cvf::StructGridInterface::POS_J || face == cvf::StructGridInterface::NEG_J)
else if ( face == cvf::StructGridInterface::POS_J || face == cvf::StructGridInterface::NEG_J )
{
axis = GridAxisType::AXIS_J;
}
else if (face == cvf::StructGridInterface::POS_K || face == cvf::StructGridInterface::NEG_K)
else if ( face == cvf::StructGridInterface::POS_K || face == cvf::StructGridInterface::NEG_K )
{
axis = GridAxisType::AXIS_K;
}
@ -245,32 +272,30 @@ cvf::Vec3d StructGridInterface::displayModelOffset() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void StructGridInterface::characteristicCellSizes(double* iSize, double* jSize, double* kSize) const
void StructGridInterface::characteristicCellSizes( double* iSize, double* jSize, double* kSize ) const
{
CVF_ASSERT(iSize && jSize && kSize);
CVF_ASSERT( iSize && jSize && kSize );
if (m_characteristicCellSizeI == cvf::UNDEFINED_DOUBLE
|| m_characteristicCellSizeJ == cvf::UNDEFINED_DOUBLE
|| m_characteristicCellSizeK == cvf::UNDEFINED_DOUBLE)
if ( m_characteristicCellSizeI == cvf::UNDEFINED_DOUBLE || m_characteristicCellSizeJ == cvf::UNDEFINED_DOUBLE ||
m_characteristicCellSizeK == cvf::UNDEFINED_DOUBLE )
{
ubyte faceConnPosI[4];
cellFaceVertexIndices(StructGridInterface::POS_I, faceConnPosI);
cellFaceVertexIndices( StructGridInterface::POS_I, faceConnPosI );
ubyte faceConnNegI[4];
cellFaceVertexIndices(StructGridInterface::NEG_I, faceConnNegI);
cellFaceVertexIndices( StructGridInterface::NEG_I, faceConnNegI );
ubyte faceConnPosJ[4];
cellFaceVertexIndices(StructGridInterface::POS_J, faceConnPosJ);
cellFaceVertexIndices( StructGridInterface::POS_J, faceConnPosJ );
ubyte faceConnNegJ[4];
cellFaceVertexIndices(StructGridInterface::NEG_J, faceConnNegJ);
cellFaceVertexIndices( StructGridInterface::NEG_J, faceConnNegJ );
ubyte faceConnPosK[4];
cellFaceVertexIndices(StructGridInterface::POS_K, faceConnPosK);
cellFaceVertexIndices( StructGridInterface::POS_K, faceConnPosK );
ubyte faceConnNegK[4];
cellFaceVertexIndices(StructGridInterface::NEG_K, faceConnNegK);
cellFaceVertexIndices( StructGridInterface::NEG_K, faceConnNegK );
double iLengthAccumulated = 0.0;
double jLengthAccumulated = 0.0;
@ -280,33 +305,45 @@ void StructGridInterface::characteristicCellSizes(double* iSize, double* jSize,
size_t cellCount = 0;
size_t k;
for (k = 0; k < cellCountK(); k++)
for ( k = 0; k < cellCountK(); k++ )
{
size_t j;
for (j = 0; j < cellCountJ(); j++)
for ( j = 0; j < cellCountJ(); j++ )
{
size_t i;
for (i = 0; i < cellCountI(); i += 10) // NB! Evaluate every n-th cell
for ( i = 0; i < cellCountI(); i += 10 ) // NB! Evaluate every n-th cell
{
if (isCellValid(i, j, k))
if ( isCellValid( i, j, k ) )
{
size_t cellIndex = cellIndexFromIJK(i, j, k);
cellCornerVertices(cellIndex, cornerVerts);
size_t cellIndex = cellIndexFromIJK( i, j, k );
cellCornerVertices( cellIndex, cornerVerts );
iLengthAccumulated += (cornerVerts[faceConnPosI[0]] - cornerVerts[faceConnNegI[0]]).lengthSquared();
iLengthAccumulated += (cornerVerts[faceConnPosI[1]] - cornerVerts[faceConnNegI[3]]).lengthSquared();
iLengthAccumulated += (cornerVerts[faceConnPosI[2]] - cornerVerts[faceConnNegI[2]]).lengthSquared();
iLengthAccumulated += (cornerVerts[faceConnPosI[3]] - cornerVerts[faceConnNegI[1]]).lengthSquared();
iLengthAccumulated +=
( cornerVerts[faceConnPosI[0]] - cornerVerts[faceConnNegI[0]] ).lengthSquared();
iLengthAccumulated +=
( cornerVerts[faceConnPosI[1]] - cornerVerts[faceConnNegI[3]] ).lengthSquared();
iLengthAccumulated +=
( cornerVerts[faceConnPosI[2]] - cornerVerts[faceConnNegI[2]] ).lengthSquared();
iLengthAccumulated +=
( cornerVerts[faceConnPosI[3]] - cornerVerts[faceConnNegI[1]] ).lengthSquared();
jLengthAccumulated += (cornerVerts[faceConnPosJ[0]] - cornerVerts[faceConnNegJ[0]]).lengthSquared();
jLengthAccumulated += (cornerVerts[faceConnPosJ[1]] - cornerVerts[faceConnNegJ[3]]).lengthSquared();
jLengthAccumulated += (cornerVerts[faceConnPosJ[2]] - cornerVerts[faceConnNegJ[2]]).lengthSquared();
jLengthAccumulated += (cornerVerts[faceConnPosJ[3]] - cornerVerts[faceConnNegJ[1]]).lengthSquared();
jLengthAccumulated +=
( cornerVerts[faceConnPosJ[0]] - cornerVerts[faceConnNegJ[0]] ).lengthSquared();
jLengthAccumulated +=
( cornerVerts[faceConnPosJ[1]] - cornerVerts[faceConnNegJ[3]] ).lengthSquared();
jLengthAccumulated +=
( cornerVerts[faceConnPosJ[2]] - cornerVerts[faceConnNegJ[2]] ).lengthSquared();
jLengthAccumulated +=
( cornerVerts[faceConnPosJ[3]] - cornerVerts[faceConnNegJ[1]] ).lengthSquared();
kLengthAccumulated += (cornerVerts[faceConnPosK[0]] - cornerVerts[faceConnNegK[0]]).lengthSquared();
kLengthAccumulated += (cornerVerts[faceConnPosK[1]] - cornerVerts[faceConnNegK[3]]).lengthSquared();
kLengthAccumulated += (cornerVerts[faceConnPosK[2]] - cornerVerts[faceConnNegK[2]]).lengthSquared();
kLengthAccumulated += (cornerVerts[faceConnPosK[3]] - cornerVerts[faceConnNegK[1]]).lengthSquared();
kLengthAccumulated +=
( cornerVerts[faceConnPosK[0]] - cornerVerts[faceConnNegK[0]] ).lengthSquared();
kLengthAccumulated +=
( cornerVerts[faceConnPosK[1]] - cornerVerts[faceConnNegK[3]] ).lengthSquared();
kLengthAccumulated +=
( cornerVerts[faceConnPosK[2]] - cornerVerts[faceConnNegK[2]] ).lengthSquared();
kLengthAccumulated +=
( cornerVerts[faceConnPosK[3]] - cornerVerts[faceConnNegK[1]] ).lengthSquared();
cellCount++;
}
@ -316,11 +353,11 @@ void StructGridInterface::characteristicCellSizes(double* iSize, double* jSize,
double divisor = cellCount * 4.0;
if (divisor > 0.0)
if ( divisor > 0.0 )
{
m_characteristicCellSizeI = cvf::Math::sqrt(iLengthAccumulated / divisor);
m_characteristicCellSizeJ = cvf::Math::sqrt(jLengthAccumulated / divisor);
m_characteristicCellSizeK = cvf::Math::sqrt(kLengthAccumulated / divisor);
m_characteristicCellSizeI = cvf::Math::sqrt( iLengthAccumulated / divisor );
m_characteristicCellSizeJ = cvf::Math::sqrt( jLengthAccumulated / divisor );
m_characteristicCellSizeK = cvf::Math::sqrt( kLengthAccumulated / divisor );
}
}
@ -329,5 +366,4 @@ void StructGridInterface::characteristicCellSizes(double* iSize, double* jSize,
*kSize = m_characteristicCellSizeK;
}
} // namespace cvf

View File

@ -34,19 +34,16 @@
//
//##################################################################################################
#pragma once
#include <cstddef>
#include "cvfObject.h"
#include "cvfVector3.h"
#include <cstddef>
#include "cafAppEnum.h"
namespace cvf {
namespace cvf
{
class CellFilterBase;
// Navneforslag
@ -69,7 +66,6 @@ public:
typedef caf::AppEnum<StructGridInterface::FaceType> FaceEnum;
enum class GridAxisType
{
AXIS_I,
@ -89,35 +85,40 @@ public:
size_t cellCountJ() const;
size_t cellCountK() const;
virtual bool isCellValid(size_t i, size_t j, size_t k) const = 0;
virtual bool isCellValid( size_t i, size_t j, size_t k ) const = 0;
virtual cvf::Vec3d minCoordinate() const = 0;
virtual cvf::Vec3d maxCoordinate() const = 0;
void characteristicCellSizes(double* iSize, double* jSize, double* kSize) const;
void characteristicCellSizes( double* iSize, double* jSize, double* kSize ) const;
virtual cvf::Vec3d displayModelOffset() const;
virtual bool cellIJKNeighbor(size_t i, size_t j, size_t k, FaceType face, size_t* neighborCellIndex) const = 0;
virtual bool cellIJKNeighbor( size_t i, size_t j, size_t k, FaceType face, size_t* neighborCellIndex ) const = 0;
virtual size_t cellIndexFromIJK(size_t i, size_t j, size_t k) const = 0;
virtual bool ijkFromCellIndex(size_t cellIndex, size_t* i, size_t* j, size_t* k) const = 0;
virtual size_t cellIndexFromIJK( size_t i, size_t j, size_t k ) const = 0;
virtual bool ijkFromCellIndex( size_t cellIndex, size_t* i, size_t* j, size_t* k ) const = 0;
virtual bool cellIJKFromCoordinate(const cvf::Vec3d& coord, size_t* i, size_t* j, size_t* k) const = 0;
virtual bool cellIJKFromCoordinate( const cvf::Vec3d& coord, size_t* i, size_t* j, size_t* k ) const = 0;
virtual void cellCornerVertices(size_t cellIndex, cvf::Vec3d vertices[8]) const = 0;
virtual cvf::Vec3d cellCentroid(size_t cellIndex) const = 0;
virtual void cellMinMaxCordinates(size_t cellIndex, cvf::Vec3d* minCoordinate, cvf::Vec3d* maxCoordinate) const = 0;
virtual size_t gridPointIndexFromIJK(size_t i, size_t j, size_t k) const = 0;
virtual cvf::Vec3d gridPointCoordinate(size_t i, size_t j, size_t k) const = 0;
virtual void cellCornerVertices( size_t cellIndex, cvf::Vec3d vertices[8] ) const = 0;
virtual cvf::Vec3d cellCentroid( size_t cellIndex ) const = 0;
virtual void cellMinMaxCordinates( size_t cellIndex, cvf::Vec3d* minCoordinate, cvf::Vec3d* maxCoordinate ) const = 0;
virtual size_t gridPointIndexFromIJK( size_t i, size_t j, size_t k ) const = 0;
virtual cvf::Vec3d gridPointCoordinate( size_t i, size_t j, size_t k ) const = 0;
public:
static void cellFaceVertexIndices(FaceType face, cvf::ubyte vertexIndices[4]);
static FaceType oppositeFace(FaceType face);
static void neighborIJKAtCellFace(size_t i, size_t j, size_t k, StructGridInterface::FaceType face, size_t* ni, size_t* nj, size_t* nk);
static void cellFaceVertexIndices( FaceType face, cvf::ubyte vertexIndices[4] );
static FaceType oppositeFace( FaceType face );
static void neighborIJKAtCellFace( size_t i,
size_t j,
size_t k,
StructGridInterface::FaceType face,
size_t* ni,
size_t* nj,
size_t* nk );
static GridAxisType gridAxisFromFace(FaceType face);
static GridAxisType gridAxisFromFace( FaceType face );
private:
mutable double m_characteristicCellSizeI;

View File

@ -34,30 +34,27 @@
//
//##################################################################################################
#include "cvfBase.h"
#include "cvfStructGrid.h"
#include "cvfStructGridCutPlane.h"
#include "cvfStructGridScalarDataAccess.h"
#include "cvfGeometryBuilderDrawableGeo.h"
#include "cvfPrimitiveSetIndexedUInt.h"
#include "cvfDebugTimer.h"
#include "cvfPlane.h"
#include "cvfScalarMapper.h"
#include "cvfEdgeKey.h"
#include "cvfGeometryBuilderDrawableGeo.h"
#include "cvfMeshEdgeExtractor.h"
#include "cvfPlane.h"
#include "cvfPrimitiveSetIndexedUInt.h"
#include "cvfScalarMapper.h"
#include <map>
#include <cstring>
#include <map>
#include <math.h>
namespace cvf {
namespace cvf
{
//==================================================================================================
///
/// \class cvf::StructGridCutPlane
@ -71,44 +68,24 @@ namespace cvf {
// http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/
const uint StructGridCutPlane::sm_edgeTable[256] =
{
0x0 , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c,
0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,
0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c,
0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,
0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c,
0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,
0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac,
0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,
0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c,
0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,
0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc,
0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,
0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c,
0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,
0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc ,
0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,
0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc,
0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,
0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c,
0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,
0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc,
0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,
0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c,
0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460,
0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac,
0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0,
0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c,
0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230,
0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c,
0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190,
0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c,
0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0
};
{0x0, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,
0x190, 0x99, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,
0x230, 0x339, 0x33, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,
0x3a0, 0x2a9, 0x1a3, 0xaa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,
0x460, 0x569, 0x663, 0x76a, 0x66, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,
0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,
0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,
0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,
0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,
0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,
0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,
0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66, 0x76a, 0x663, 0x569, 0x460,
0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa, 0x1a3, 0x2a9, 0x3a0,
0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33, 0x339, 0x230,
0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99, 0x190,
0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0};
const int StructGridCutPlane::sm_triTable[256][16] =
{
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
const int StructGridCutPlane::sm_triTable[256][16] = {{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
@ -363,24 +340,21 @@ const int StructGridCutPlane::sm_triTable[256][16] =
{1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
};
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}};
//--------------------------------------------------------------------------------------------------
/// Constructor
//--------------------------------------------------------------------------------------------------
StructGridCutPlane::StructGridCutPlane(const StructGridInterface* grid)
: m_grid(grid),
m_mapScalarSetIndex(UNDEFINED_UINT),
m_scalarMapper(NULL),
m_mapNodeAveragedScalars(false),
m_mustRecompute(true)
StructGridCutPlane::StructGridCutPlane( const StructGridInterface* grid )
: m_grid( grid )
, m_mapScalarSetIndex( UNDEFINED_UINT )
, m_scalarMapper( NULL )
, m_mapNodeAveragedScalars( false )
, m_mustRecompute( true )
{
CVF_ASSERT(grid);
CVF_ASSERT( grid );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@ -388,24 +362,22 @@ StructGridCutPlane::~StructGridCutPlane()
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void StructGridCutPlane::setPlane(const Plane& plane)
void StructGridCutPlane::setPlane( const Plane& plane )
{
m_plane = plane;
m_mustRecompute = true;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void StructGridCutPlane::setMapScalar(uint scalarSetIndex, const ScalarMapper* mapper, bool nodeAveragedScalars)
void StructGridCutPlane::setMapScalar( uint scalarSetIndex, const ScalarMapper* mapper, bool nodeAveragedScalars )
{
CVF_ASSERT(mapper);
CVF_ASSERT( mapper );
m_mapScalarSetIndex = scalarSetIndex;
m_scalarMapper = mapper;
@ -414,7 +386,6 @@ void StructGridCutPlane::setMapScalar(uint scalarSetIndex, const ScalarMapper* m
m_mustRecompute = true;
}
//--------------------------------------------------------------------------------------------------
/// Generate cut plane geometry from current configuration
///
@ -424,117 +395,118 @@ void StructGridCutPlane::setMapScalar(uint scalarSetIndex, const ScalarMapper* m
/// Current implementation is not optimized in any way
/// Should set normal from plane normal instead of relying on caller to compute them
//--------------------------------------------------------------------------------------------------
ref<DrawableGeo> StructGridCutPlane::generateSurface(const cvf::StructGridScalarDataAccess* dataAccessObject)
ref<DrawableGeo> StructGridCutPlane::generateSurface( const cvf::StructGridScalarDataAccess* dataAccessObject )
{
if (m_mustRecompute)
if ( m_mustRecompute )
{
computeCutPlane(dataAccessObject);
computeCutPlane( dataAccessObject );
m_mustRecompute = false;
}
size_t numVertices = m_vertices.size();
size_t numTriangles = m_triangleIndices.size()/3;
if (numVertices == 0 || numTriangles == 0)
size_t numTriangles = m_triangleIndices.size() / 3;
if ( numVertices == 0 || numTriangles == 0 )
{
return NULL;
}
bool doMapScalar = false;
if (m_mapScalarSetIndex != UNDEFINED_UINT && m_scalarMapper.notNull())
if ( m_mapScalarSetIndex != UNDEFINED_UINT && m_scalarMapper.notNull() )
{
CVF_ASSERT(numVertices == m_vertexScalars.size());
CVF_ASSERT( numVertices == m_vertexScalars.size() );
doMapScalar = true;
}
ref<Vec3fArray> vertexArr = new Vec3fArray( m_vertices );
ref<Vec3fArray> vertexArr = new Vec3fArray(m_vertices);
ref<UIntArray> indices = new UIntArray( m_triangleIndices );
ref<PrimitiveSetIndexedUInt> primSet = new PrimitiveSetIndexedUInt( PT_TRIANGLES );
primSet->setIndices( indices.p() );
ref<UIntArray> indices = new UIntArray(m_triangleIndices);
ref<PrimitiveSetIndexedUInt> primSet = new PrimitiveSetIndexedUInt(PT_TRIANGLES);
primSet->setIndices(indices.p());
ref<cvf::DrawableGeo> geo = new cvf::DrawableGeo;
;
geo->setVertexArray( vertexArr.p() );
geo->addPrimitiveSet( primSet.p() );
ref<cvf::DrawableGeo> geo = new cvf::DrawableGeo;;
geo->setVertexArray(vertexArr.p());
geo->addPrimitiveSet(primSet.p());
if (doMapScalar)
if ( doMapScalar )
{
CVF_ASSERT(numVertices == m_vertexScalars.size());
CVF_ASSERT( numVertices == m_vertexScalars.size() );
ref<Color3ubArray> vertexColors = new Color3ubArray;
ref<Vec2fArray> textureCoords = new Vec2fArray;
vertexColors->reserve(numVertices);
textureCoords->reserve(numVertices);
vertexColors->reserve( numVertices );
textureCoords->reserve( numVertices );
size_t i;
for (i = 0; i < numVertices; i++)
for ( i = 0; i < numVertices; i++ )
{
Color3ub clr = m_scalarMapper->mapToColor(m_vertexScalars[i]);
vertexColors->add(clr);
Color3ub clr = m_scalarMapper->mapToColor( m_vertexScalars[i] );
vertexColors->add( clr );
Vec2f texCoord = m_scalarMapper->mapToTextureCoord(m_vertexScalars[i]);
textureCoords->add(texCoord);
Vec2f texCoord = m_scalarMapper->mapToTextureCoord( m_vertexScalars[i] );
textureCoords->add( texCoord );
}
geo->setColorArray(vertexColors.p());
geo->setTextureCoordArray(textureCoords.p());
geo->setColorArray( vertexColors.p() );
geo->setTextureCoordArray( textureCoords.p() );
}
//Trace::show("generateSurface(): Vertices:%d TriConns:%d Tris:%d", vertexArr->size(), indices->size(), indices->size()/3);
// Trace::show("generateSurface(): Vertices:%d TriConns:%d Tris:%d", vertexArr->size(), indices->size(),
// indices->size()/3);
return geo;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
ref<DrawableGeo> StructGridCutPlane::generateMesh(const cvf::StructGridScalarDataAccess* dataAccessObject)
ref<DrawableGeo> StructGridCutPlane::generateMesh( const cvf::StructGridScalarDataAccess* dataAccessObject )
{
if (m_mustRecompute)
if ( m_mustRecompute )
{
computeCutPlane(dataAccessObject);
computeCutPlane( dataAccessObject );
m_mustRecompute = false;
}
size_t numVertices = m_vertices.size();
size_t numLines = m_meshLineIndices.size()/2;
if (numVertices == 0 || numLines == 0)
size_t numLines = m_meshLineIndices.size() / 2;
if ( numVertices == 0 || numLines == 0 )
{
return NULL;
}
MeshEdgeExtractor ee;
ee.addPrimitives(2, &m_meshLineIndices[0], m_meshLineIndices.size());
ee.addPrimitives( 2, &m_meshLineIndices[0], m_meshLineIndices.size() );
ref<UIntArray> indices = ee.lineIndices();
ref<PrimitiveSetIndexedUInt> primSet = new PrimitiveSetIndexedUInt(PT_LINES);
primSet->setIndices(indices.p());
ref<PrimitiveSetIndexedUInt> primSet = new PrimitiveSetIndexedUInt( PT_LINES );
primSet->setIndices( indices.p() );
ref<Vec3fArray> vertexArr = new Vec3fArray(m_vertices);
ref<Vec3fArray> vertexArr = new Vec3fArray( m_vertices );
ref<cvf::DrawableGeo> geo = new cvf::DrawableGeo;;
geo->setVertexArray(vertexArr.p());
geo->addPrimitiveSet(primSet.p());
ref<cvf::DrawableGeo> geo = new cvf::DrawableGeo;
;
geo->setVertexArray( vertexArr.p() );
geo->addPrimitiveSet( primSet.p() );
//Trace::show("generateMesh(): Vertices:%d LineConns:%d Lines:%d", vertexArr->size(), indices->size(), indices->size()/2);
// Trace::show("generateMesh(): Vertices:%d LineConns:%d Lines:%d", vertexArr->size(), indices->size(),
// indices->size()/2);
return geo;
}
//--------------------------------------------------------------------------------------------------
/// Generate surface representation of the specified cut plane
///
/// \note Will compute normals before returning geometry
//--------------------------------------------------------------------------------------------------
void StructGridCutPlane::computeCutPlane(const cvf::StructGridScalarDataAccess* dataAccessObject)
void StructGridCutPlane::computeCutPlane( const cvf::StructGridScalarDataAccess* dataAccessObject )
{
if (!dataAccessObject) return;
if ( !dataAccessObject ) return;
DebugTimer tim("");
DebugTimer tim( "" );
bool doMapScalar = false;
if (m_mapScalarSetIndex != UNDEFINED_UINT && m_scalarMapper.notNull())
if ( m_mapScalarSetIndex != UNDEFINED_UINT && m_scalarMapper.notNull() )
{
doMapScalar = true;
}
@ -549,7 +521,6 @@ void StructGridCutPlane::computeCutPlane(const cvf::StructGridScalarDataAccess*
m_triangleIndices.clear();
m_meshLineIndices.clear();
// The indexing conventions for vertices and
// edges used in the algorithm:
// edg verts
@ -567,34 +538,33 @@ void StructGridCutPlane::computeCutPlane(const cvf::StructGridScalarDataAccess*
// vertex indices edge indices 11 3 - 7
//
size_t k;
for (k = 0; k < cellCountK; k++)
for ( k = 0; k < cellCountK; k++ )
{
size_t j;
for (j = 0; j < cellCountJ; j++)
for ( j = 0; j < cellCountJ; j++ )
{
size_t i;
for (i = 0; i < cellCountI; i++)
for ( i = 0; i < cellCountI; i++ )
{
size_t cellIndex = m_grid->cellIndexFromIJK(i, j, k);
size_t cellIndex = m_grid->cellIndexFromIJK( i, j, k );
Vec3d minCoord;
Vec3d maxCoord;
m_grid->cellMinMaxCordinates(cellIndex, &minCoord, &maxCoord);
m_grid->cellMinMaxCordinates( cellIndex, &minCoord, &maxCoord );
// Early reject for cells outside clipping box
if (m_clippingBoundingBox.isValid())
if ( m_clippingBoundingBox.isValid() )
{
BoundingBox cellBB(minCoord, maxCoord);
if (!m_clippingBoundingBox.intersects(cellBB))
BoundingBox cellBB( minCoord, maxCoord );
if ( !m_clippingBoundingBox.intersects( cellBB ) )
{
continue;
}
}
// Check if plane intersects this cell and skip if it doesn't
if (!isCellIntersectedByPlane(m_plane, minCoord, maxCoord))
if ( !isCellIntersectedByPlane( m_plane, minCoord, maxCoord ) )
{
continue;
}
@ -602,42 +572,42 @@ void StructGridCutPlane::computeCutPlane(const cvf::StructGridScalarDataAccess*
GridCell cell;
bool isClipped = false;
if (m_clippingBoundingBox.isValid())
if ( m_clippingBoundingBox.isValid() )
{
if (!m_clippingBoundingBox.contains(minCoord) || !m_clippingBoundingBox.contains(maxCoord))
if ( !m_clippingBoundingBox.contains( minCoord ) || !m_clippingBoundingBox.contains( maxCoord ) )
{
isClipped = true;
minCoord.x() = CVF_MAX(minCoord.x(), m_clippingBoundingBox.min().x());
minCoord.y() = CVF_MAX(minCoord.y(), m_clippingBoundingBox.min().y());
minCoord.z() = CVF_MAX(minCoord.z(), m_clippingBoundingBox.min().z());
minCoord.x() = CVF_MAX( minCoord.x(), m_clippingBoundingBox.min().x() );
minCoord.y() = CVF_MAX( minCoord.y(), m_clippingBoundingBox.min().y() );
minCoord.z() = CVF_MAX( minCoord.z(), m_clippingBoundingBox.min().z() );
maxCoord.x() = CVF_MIN(maxCoord.x(), m_clippingBoundingBox.max().x());
maxCoord.y() = CVF_MIN(maxCoord.y(), m_clippingBoundingBox.max().y());
maxCoord.z() = CVF_MIN(maxCoord.z(), m_clippingBoundingBox.max().z());
maxCoord.x() = CVF_MIN( maxCoord.x(), m_clippingBoundingBox.max().x() );
maxCoord.y() = CVF_MIN( maxCoord.y(), m_clippingBoundingBox.max().y() );
maxCoord.z() = CVF_MIN( maxCoord.z(), m_clippingBoundingBox.max().z() );
}
}
cell.p[0].set(minCoord.x(), maxCoord.y(), minCoord.z());
cell.p[1].set(maxCoord.x(), maxCoord.y(), minCoord.z());
cell.p[2].set(maxCoord.x(), minCoord.y(), minCoord.z());
cell.p[3].set(minCoord.x(), minCoord.y(), minCoord.z());
cell.p[4].set(minCoord.x(), maxCoord.y(), maxCoord.z());
cell.p[5].set(maxCoord.x(), maxCoord.y(), maxCoord.z());
cell.p[6].set(maxCoord.x(), minCoord.y(), maxCoord.z());
cell.p[7].set(minCoord.x(), minCoord.y(), maxCoord.z());
cell.p[0].set( minCoord.x(), maxCoord.y(), minCoord.z() );
cell.p[1].set( maxCoord.x(), maxCoord.y(), minCoord.z() );
cell.p[2].set( maxCoord.x(), minCoord.y(), minCoord.z() );
cell.p[3].set( minCoord.x(), minCoord.y(), minCoord.z() );
cell.p[4].set( minCoord.x(), maxCoord.y(), maxCoord.z() );
cell.p[5].set( maxCoord.x(), maxCoord.y(), maxCoord.z() );
cell.p[6].set( maxCoord.x(), minCoord.y(), maxCoord.z() );
cell.p[7].set( minCoord.x(), minCoord.y(), maxCoord.z() );
// Fetch scalar values
double cellScalarValue = 0;
if (doMapScalar)
if ( doMapScalar )
{
cellScalarValue = dataAccessObject->cellScalar(cellIndex);
cellScalarValue = dataAccessObject->cellScalar( cellIndex );
// If we're doing node averaging we must populate grid cell with scalar values interpolated to the grid points
if (m_mapNodeAveragedScalars)
// If we're doing node averaging we must populate grid cell with scalar values interpolated to the
// grid points
if ( m_mapNodeAveragedScalars )
{
CVF_ASSERT(false); // This is not supported in this code.
CVF_ASSERT( false ); // This is not supported in this code.
#if 0
// This is not supported now. This is possibly valid code for "neighbour regular grids" (Eg. Rectilinear or regular grids)
// but is not general for general struct grids. So the interpolation stuff must be handled specially for each "real" grid type
@ -677,31 +647,30 @@ void StructGridCutPlane::computeCutPlane(const cvf::StructGridScalarDataAccess*
}
}
Triangles triangles;
uint numTriangles = polygonise(m_plane, cell, &triangles);
if (numTriangles > 0)
uint numTriangles = polygonise( m_plane, cell, &triangles );
if ( numTriangles > 0 )
{
// Add all the referenced vertices
// At the same time registering their index in the 'global' vertex list
uint globalVertexIndices[12];
int iv;
for (iv = 0; iv < 12; iv++)
for ( iv = 0; iv < 12; iv++ )
{
if (triangles.usedVertices[iv])
if ( triangles.usedVertices[iv] )
{
globalVertexIndices[iv] = static_cast<uint>(m_vertices.size());
m_vertices.push_back(Vec3f(triangles.vertices[iv]));
globalVertexIndices[iv] = static_cast<uint>( m_vertices.size() );
m_vertices.push_back( Vec3f( triangles.vertices[iv] ) );
if (doMapScalar)
if ( doMapScalar )
{
if (m_mapNodeAveragedScalars)
if ( m_mapNodeAveragedScalars )
{
m_vertexScalars.push_back(triangles.scalars[iv]);
m_vertexScalars.push_back( triangles.scalars[iv] );
}
else
{
m_vertexScalars.push_back(cellScalarValue);
m_vertexScalars.push_back( cellScalarValue );
}
}
}
@ -714,122 +683,147 @@ void StructGridCutPlane::computeCutPlane(const cvf::StructGridScalarDataAccess*
// Build triangles from the cell
const size_t prevNumTriangleIndices = m_triangleIndices.size();
uint t;
for (t = 0; t < numTriangles; t++)
for ( t = 0; t < numTriangles; t++ )
{
m_triangleIndices.push_back(globalVertexIndices[triangles.triangleIndices[3*t]]);
m_triangleIndices.push_back(globalVertexIndices[triangles.triangleIndices[3*t + 1]]);
m_triangleIndices.push_back(globalVertexIndices[triangles.triangleIndices[3*t + 2]]);
m_triangleIndices.push_back( globalVertexIndices[triangles.triangleIndices[3 * t]] );
m_triangleIndices.push_back( globalVertexIndices[triangles.triangleIndices[3 * t + 1]] );
m_triangleIndices.push_back( globalVertexIndices[triangles.triangleIndices[3 * t + 2]] );
}
// Add mesh line indices
addMeshLineIndices(&m_triangleIndices[prevNumTriangleIndices], numTriangles);
addMeshLineIndices( &m_triangleIndices[prevNumTriangleIndices], numTriangles );
}
}
}
}
// Trace::show("Vertices:%d TriConns:%d Tris:%d", m_vertices.size(), m_triangleIndices.size(), m_triangleIndices.size()/3);
// tim.reportTimeMS("computeCutPlane()");
// Trace::show("Vertices:%d TriConns:%d Tris:%d", m_vertices.size(), m_triangleIndices.size(),
// m_triangleIndices.size()/3); tim.reportTimeMS("computeCutPlane()");
}
//--------------------------------------------------------------------------------------------------
/// Add mesh line indices by analyzing the triangle indices and only adding 'unique' edges
//--------------------------------------------------------------------------------------------------
void StructGridCutPlane::addMeshLineIndices(const uint* triangleIndices, uint triangleCount)
void StructGridCutPlane::addMeshLineIndices( const uint* triangleIndices, uint triangleCount )
{
std::vector<int64> edges;
edges.reserve(3*triangleCount);
edges.reserve( 3 * triangleCount );
std::vector<int64>::iterator it;
uint t;
for (t = 0; t < triangleCount; t++)
for ( t = 0; t < triangleCount; t++ )
{
uint i;
for (i = 0; i < 3; i++)
for ( i = 0; i < 3; i++ )
{
const uint vertexIdx1 = triangleIndices[3*t + i];
const uint vertexIdx2 = (i < 2) ? triangleIndices[3*t + i + 1] : triangleIndices[3*t];
const uint vertexIdx1 = triangleIndices[3 * t + i];
const uint vertexIdx2 = ( i < 2 ) ? triangleIndices[3 * t + i + 1] : triangleIndices[3 * t];
int64 edgeKeyVal = EdgeKey(vertexIdx1, vertexIdx2).toKeyVal();
it = find(edges.begin(), edges.end(), edgeKeyVal);
if (it == edges.end())
int64 edgeKeyVal = EdgeKey( vertexIdx1, vertexIdx2 ).toKeyVal();
it = find( edges.begin(), edges.end(), edgeKeyVal );
if ( it == edges.end() )
{
edges.push_back(edgeKeyVal);
edges.push_back( edgeKeyVal );
}
else
{
edges.erase(it);
edges.erase( it );
}
}
}
for (it = edges.begin(); it != edges.end(); ++it)
for ( it = edges.begin(); it != edges.end(); ++it )
{
EdgeKey ek = EdgeKey::fromkeyVal(*it);
m_meshLineIndices.push_back(ek.index1());
m_meshLineIndices.push_back(ek.index2());
EdgeKey ek = EdgeKey::fromkeyVal( *it );
m_meshLineIndices.push_back( ek.index1() );
m_meshLineIndices.push_back( ek.index2() );
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
uint StructGridCutPlane::polygonise(const Plane& plane, const GridCell& cell, Triangles* triangles)
uint StructGridCutPlane::polygonise( const Plane& plane, const GridCell& cell, Triangles* triangles )
{
int cubeindex = 0;
if (plane.distanceSquared(cell.p[0]) < 0) cubeindex |= 1;
if (plane.distanceSquared(cell.p[1]) < 0) cubeindex |= 2;
if (plane.distanceSquared(cell.p[2]) < 0) cubeindex |= 4;
if (plane.distanceSquared(cell.p[3]) < 0) cubeindex |= 8;
if (plane.distanceSquared(cell.p[4]) < 0) cubeindex |= 16;
if (plane.distanceSquared(cell.p[5]) < 0) cubeindex |= 32;
if (plane.distanceSquared(cell.p[6]) < 0) cubeindex |= 64;
if (plane.distanceSquared(cell.p[7]) < 0) cubeindex |= 128;
if ( plane.distanceSquared( cell.p[0] ) < 0 ) cubeindex |= 1;
if ( plane.distanceSquared( cell.p[1] ) < 0 ) cubeindex |= 2;
if ( plane.distanceSquared( cell.p[2] ) < 0 ) cubeindex |= 4;
if ( plane.distanceSquared( cell.p[3] ) < 0 ) cubeindex |= 8;
if ( plane.distanceSquared( cell.p[4] ) < 0 ) cubeindex |= 16;
if ( plane.distanceSquared( cell.p[5] ) < 0 ) cubeindex |= 32;
if ( plane.distanceSquared( cell.p[6] ) < 0 ) cubeindex |= 64;
if ( plane.distanceSquared( cell.p[7] ) < 0 ) cubeindex |= 128;
if (sm_edgeTable[cubeindex] == 0)
if ( sm_edgeTable[cubeindex] == 0 )
{
return 0;
}
// Compute vertex coordinates on the edges where we have intersections
if (sm_edgeTable[cubeindex] & 1) triangles->vertices[0] = planeLineIntersection(plane, cell.p[0], cell.p[1], cell.s[0], cell.s[1], &triangles->scalars[0] );
if (sm_edgeTable[cubeindex] & 2) triangles->vertices[1] = planeLineIntersection(plane, cell.p[1], cell.p[2], cell.s[1], cell.s[2], &triangles->scalars[1] );
if (sm_edgeTable[cubeindex] & 4) triangles->vertices[2] = planeLineIntersection(plane, cell.p[2], cell.p[3], cell.s[2], cell.s[3], &triangles->scalars[2] );
if (sm_edgeTable[cubeindex] & 8) triangles->vertices[3] = planeLineIntersection(plane, cell.p[3], cell.p[0], cell.s[3], cell.s[0], &triangles->scalars[3] );
if (sm_edgeTable[cubeindex] & 16) triangles->vertices[4] = planeLineIntersection(plane, cell.p[4], cell.p[5], cell.s[4], cell.s[5], &triangles->scalars[4] );
if (sm_edgeTable[cubeindex] & 32) triangles->vertices[5] = planeLineIntersection(plane, cell.p[5], cell.p[6], cell.s[5], cell.s[6], &triangles->scalars[5] );
if (sm_edgeTable[cubeindex] & 64) triangles->vertices[6] = planeLineIntersection(plane, cell.p[6], cell.p[7], cell.s[6], cell.s[7], &triangles->scalars[6] );
if (sm_edgeTable[cubeindex] & 128) triangles->vertices[7] = planeLineIntersection(plane, cell.p[7], cell.p[4], cell.s[7], cell.s[4], &triangles->scalars[7] );
if (sm_edgeTable[cubeindex] & 256) triangles->vertices[8] = planeLineIntersection(plane, cell.p[0], cell.p[4], cell.s[0], cell.s[4], &triangles->scalars[8] );
if (sm_edgeTable[cubeindex] & 512) triangles->vertices[9] = planeLineIntersection(plane, cell.p[1], cell.p[5], cell.s[1], cell.s[5], &triangles->scalars[9] );
if (sm_edgeTable[cubeindex] & 1024) triangles->vertices[10] = planeLineIntersection(plane, cell.p[2], cell.p[6], cell.s[2], cell.s[6], &triangles->scalars[10]);
if (sm_edgeTable[cubeindex] & 2048) triangles->vertices[11] = planeLineIntersection(plane, cell.p[3], cell.p[7], cell.s[3], cell.s[7], &triangles->scalars[11]);
if ( sm_edgeTable[cubeindex] & 1 )
triangles->vertices[0] =
planeLineIntersection( plane, cell.p[0], cell.p[1], cell.s[0], cell.s[1], &triangles->scalars[0] );
if ( sm_edgeTable[cubeindex] & 2 )
triangles->vertices[1] =
planeLineIntersection( plane, cell.p[1], cell.p[2], cell.s[1], cell.s[2], &triangles->scalars[1] );
if ( sm_edgeTable[cubeindex] & 4 )
triangles->vertices[2] =
planeLineIntersection( plane, cell.p[2], cell.p[3], cell.s[2], cell.s[3], &triangles->scalars[2] );
if ( sm_edgeTable[cubeindex] & 8 )
triangles->vertices[3] =
planeLineIntersection( plane, cell.p[3], cell.p[0], cell.s[3], cell.s[0], &triangles->scalars[3] );
if ( sm_edgeTable[cubeindex] & 16 )
triangles->vertices[4] =
planeLineIntersection( plane, cell.p[4], cell.p[5], cell.s[4], cell.s[5], &triangles->scalars[4] );
if ( sm_edgeTable[cubeindex] & 32 )
triangles->vertices[5] =
planeLineIntersection( plane, cell.p[5], cell.p[6], cell.s[5], cell.s[6], &triangles->scalars[5] );
if ( sm_edgeTable[cubeindex] & 64 )
triangles->vertices[6] =
planeLineIntersection( plane, cell.p[6], cell.p[7], cell.s[6], cell.s[7], &triangles->scalars[6] );
if ( sm_edgeTable[cubeindex] & 128 )
triangles->vertices[7] =
planeLineIntersection( plane, cell.p[7], cell.p[4], cell.s[7], cell.s[4], &triangles->scalars[7] );
if ( sm_edgeTable[cubeindex] & 256 )
triangles->vertices[8] =
planeLineIntersection( plane, cell.p[0], cell.p[4], cell.s[0], cell.s[4], &triangles->scalars[8] );
if ( sm_edgeTable[cubeindex] & 512 )
triangles->vertices[9] =
planeLineIntersection( plane, cell.p[1], cell.p[5], cell.s[1], cell.s[5], &triangles->scalars[9] );
if ( sm_edgeTable[cubeindex] & 1024 )
triangles->vertices[10] =
planeLineIntersection( plane, cell.p[2], cell.p[6], cell.s[2], cell.s[6], &triangles->scalars[10] );
if ( sm_edgeTable[cubeindex] & 2048 )
triangles->vertices[11] =
planeLineIntersection( plane, cell.p[3], cell.p[7], cell.s[3], cell.s[7], &triangles->scalars[11] );
// Create the triangles
memset(triangles->usedVertices, 0, sizeof(triangles->usedVertices));
memset( triangles->usedVertices, 0, sizeof( triangles->usedVertices ) );
const int* triConnects = sm_triTable[cubeindex];
uint n = 0;
while (triConnects[n] != -1)
while ( triConnects[n] != -1 )
{
triangles->triangleIndices[n] = triConnects[n];
triangles->usedVertices[triConnects[n]] = true;
n++;
}
uint numTriangles = n/3;
uint numTriangles = n / 3;
return numTriangles;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
Vec3d StructGridCutPlane::planeLineIntersection(const Plane& plane, const Vec3d& p1, const Vec3d& p2, const double s1, const double s2, double* s)
Vec3d StructGridCutPlane::planeLineIntersection( const Plane& plane,
const Vec3d& p1,
const Vec3d& p2,
const double s1,
const double s2,
double* s )
{
// From http://local.wasp.uwa.edu.au/~pbourke/geometry/planeline/
//
@ -841,22 +835,22 @@ Vec3d StructGridCutPlane::planeLineIntersection(const Plane& plane, const Vec3d&
// u = ---------------------------------
// A*(x1-x2) + B*(y1-y2) + C*(z1-z2)
CVF_ASSERT(s);
CVF_ASSERT( s );
const Vec3d v = p2 - p1;
double denominator = -(plane.A()*v.x() + plane.B()*v.y() + plane.C()*v.z());
if (denominator != 0)
double denominator = -( plane.A() * v.x() + plane.B() * v.y() + plane.C() * v.z() );
if ( denominator != 0 )
{
double u = (plane.A()*p1.x() + plane.B()*p1.y() + plane.C()*p1.z() + plane.D())/denominator;
if (u > 0.0 && u < 1.0)
double u = ( plane.A() * p1.x() + plane.B() * p1.y() + plane.C() * p1.z() + plane.D() ) / denominator;
if ( u > 0.0 && u < 1.0 )
{
*s = s1 + u*(s2 - s1);
return (p1 + u*v);
*s = s1 + u * ( s2 - s1 );
return ( p1 + u * v );
}
else
{
if (u >= 1.0)
if ( u >= 1.0 )
{
*s = s2;
return p2;
@ -875,40 +869,39 @@ Vec3d StructGridCutPlane::planeLineIntersection(const Plane& plane, const Vec3d&
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool StructGridCutPlane::isCellIntersectedByPlane(const Plane& plane, const Vec3d& cellMinCoord, const Vec3d& cellMaxCoord)
bool StructGridCutPlane::isCellIntersectedByPlane( const Plane& plane, const Vec3d& cellMinCoord, const Vec3d& cellMaxCoord )
{
// See http://zach.in.tu-clausthal.de/teaching/cg_literatur/lighthouse3d_view_frustum_culling/index.html
// Start by finding the "positive vertex" and the "negative vertex" relative to plane normal
Vec3d pVertex(cellMinCoord);
Vec3d nVertex(cellMaxCoord);
Vec3d pVertex( cellMinCoord );
Vec3d nVertex( cellMaxCoord );
if (plane.A() >= 0)
if ( plane.A() >= 0 )
{
pVertex.x() = cellMaxCoord.x();
nVertex.x() = cellMinCoord.x();
}
if (plane.B() >= 0)
if ( plane.B() >= 0 )
{
pVertex.y() = cellMaxCoord.y();
nVertex.y() = cellMinCoord.y();
}
if (plane.C() >= 0)
if ( plane.C() >= 0 )
{
pVertex.z() = cellMaxCoord.z();
nVertex.z() = cellMinCoord.z();
}
// Chek if both positive and negative vertex are on same side of plane
if (plane.distanceSquared(pVertex) < 0)
if ( plane.distanceSquared( pVertex ) < 0 )
{
if (plane.distanceSquared(nVertex) < 0)
if ( plane.distanceSquared( nVertex ) < 0 )
{
return false;
}
@ -919,7 +912,7 @@ bool StructGridCutPlane::isCellIntersectedByPlane(const Plane& plane, const Vec3
}
else
{
if (plane.distanceSquared(nVertex) >= 0)
if ( plane.distanceSquared( nVertex ) >= 0 )
{
return false;
}
@ -933,11 +926,9 @@ bool StructGridCutPlane::isCellIntersectedByPlane(const Plane& plane, const Vec3
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void StructGridCutPlane::setClippingBoundingBox(const BoundingBox& boundingBox)
void StructGridCutPlane::setClippingBoundingBox( const BoundingBox& boundingBox )
{
m_clippingBoundingBox = boundingBox;
}
} // namespace cvf

View File

@ -34,22 +34,20 @@
//
//##################################################################################################
#pragma once
#include "cvfPlane.h"
#include "cvfBoundingBox.h"
#include "cvfPlane.h"
#include <vector>
namespace cvf {
namespace cvf
{
class DrawableGeo;
class StructGridInterface;
class ScalarMapper;
class StructGridScalarDataAccess;
//==================================================================================================
//
//
@ -58,15 +56,15 @@ class StructGridScalarDataAccess;
class StructGridCutPlane : public Object
{
public:
explicit StructGridCutPlane(const StructGridInterface* grid);
explicit StructGridCutPlane( const StructGridInterface* grid );
~StructGridCutPlane();
void setPlane(const Plane& plane);
void setClippingBoundingBox(const BoundingBox& boundingBox);
void setMapScalar(uint scalarSetIndex, const ScalarMapper* mapper, bool nodeAveragedScalars);
void setPlane( const Plane& plane );
void setClippingBoundingBox( const BoundingBox& boundingBox );
void setMapScalar( uint scalarSetIndex, const ScalarMapper* mapper, bool nodeAveragedScalars );
ref<DrawableGeo> generateSurface(const cvf::StructGridScalarDataAccess* dataAccessObject);
ref<DrawableGeo> generateMesh(const cvf::StructGridScalarDataAccess* dataAccessObject);
ref<DrawableGeo> generateSurface( const cvf::StructGridScalarDataAccess* dataAccessObject );
ref<DrawableGeo> generateMesh( const cvf::StructGridScalarDataAccess* dataAccessObject );
private:
struct GridCell
@ -79,16 +77,22 @@ private:
{
Vec3d vertices[12]; // The vertices, one on each edge in the cell
double scalars[12]; // Interpolated scalar values for the vertices
bool usedVertices[12]; // Flag to indicate which of the vertices (and scalars) are being referenced by the triangle indices
int triangleIndices[15];// Triangle indices (into vertices), max 5 triangles.
bool usedVertices[12]; // Flag to indicate which of the vertices (and scalars) are being referenced by the
// triangle indices
int triangleIndices[15]; // Triangle indices (into vertices), max 5 triangles.
};
private:
void computeCutPlane(const cvf::StructGridScalarDataAccess* dataAccessObject);
void addMeshLineIndices(const uint* triangleIndices, uint triangleCount);
static uint polygonise(const Plane& plane, const GridCell& cell, Triangles* triangles);
static Vec3d planeLineIntersection(const Plane& plane, const Vec3d& p1, const Vec3d& p2, const double s1, const double s2, double* s);
static bool isCellIntersectedByPlane(const Plane& plane, const Vec3d& cellMinCoord, const Vec3d& cellMaxCoord);
void computeCutPlane( const cvf::StructGridScalarDataAccess* dataAccessObject );
void addMeshLineIndices( const uint* triangleIndices, uint triangleCount );
static uint polygonise( const Plane& plane, const GridCell& cell, Triangles* triangles );
static Vec3d planeLineIntersection( const Plane& plane,
const Vec3d& p1,
const Vec3d& p2,
const double s1,
const double s2,
double* s );
static bool isCellIntersectedByPlane( const Plane& plane, const Vec3d& cellMinCoord, const Vec3d& cellMaxCoord );
private:
cref<StructGridInterface> m_grid;
@ -97,8 +101,10 @@ private:
BoundingBox m_clippingBoundingBox;
uint m_mapScalarSetIndex; // Index of scalar set that should be mapped onto the cut plane. -1 for no mapping
cref<ScalarMapper> m_scalarMapper; // Scalar mapper to use when mapping. Both scalar set index and mapper must be set in order to get scalar mapping
bool m_mapNodeAveragedScalars; // If true we'll compute node averaged scalars before mapping them on the cut plane. If false per cell scalars will be mapped.
cref<ScalarMapper> m_scalarMapper; // Scalar mapper to use when mapping. Both scalar set index and mapper must be
// set in order to get scalar mapping
bool m_mapNodeAveragedScalars; // If true we'll compute node averaged scalars before mapping them on the cut plane.
// If false per cell scalars will be mapped.
bool m_mustRecompute; // Flag to indicate that cut plane must be recomputed
std::vector<Vec3f> m_vertices; // Vertices of computed surface
@ -110,4 +116,4 @@ private:
static const int sm_triTable[256][16];
};
}
} // namespace cvf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#include "cvfBase.h"
#include "cvfStructGrid.h"
@ -50,79 +49,87 @@
#include "cvfOutlineEdgeExtractor.h"
#include <cmath>
namespace cvf {
namespace cvf
{
//==================================================================================================
///
/// \class CellRangeFilter
///
//==================================================================================================
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CellRangeFilter::CellRangeFilter()
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CellRangeFilter::addCellIncludeRange(size_t minI, size_t minJ, size_t minK, size_t maxI, size_t maxJ, size_t maxK, bool applyToSubGridAreas)
void CellRangeFilter::addCellIncludeRange( size_t minI,
size_t minJ,
size_t minK,
size_t maxI,
size_t maxJ,
size_t maxK,
bool applyToSubGridAreas )
{
m_includeRanges.push_back(CellRange(minI, minJ, minK, maxI, maxJ, maxK, applyToSubGridAreas));
m_includeRanges.push_back( CellRange( minI, minJ, minK, maxI, maxJ, maxK, applyToSubGridAreas ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CellRangeFilter::addCellInclude(size_t i, size_t j, size_t k, bool applyToSubGridAreas)
void CellRangeFilter::addCellInclude( size_t i, size_t j, size_t k, bool applyToSubGridAreas )
{
m_includeRanges.push_back(CellRange(i, j, k, i + 1, j + 1, k + 1, applyToSubGridAreas));
m_includeRanges.push_back( CellRange( i, j, k, i + 1, j + 1, k + 1, applyToSubGridAreas ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CellRangeFilter::addCellExcludeRange(size_t minI, size_t minJ, size_t minK, size_t maxI, size_t maxJ, size_t maxK, bool applyToSubGridAreas)
void CellRangeFilter::addCellExcludeRange( size_t minI,
size_t minJ,
size_t minK,
size_t maxI,
size_t maxJ,
size_t maxK,
bool applyToSubGridAreas )
{
m_excludeRanges.push_back(CellRange(minI, minJ, minK, maxI, maxJ, maxK, applyToSubGridAreas));
m_excludeRanges.push_back( CellRange( minI, minJ, minK, maxI, maxJ, maxK, applyToSubGridAreas ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CellRangeFilter::addCellExclude(size_t i, size_t j, size_t k, bool applyToSubGridAreas)
void CellRangeFilter::addCellExclude( size_t i, size_t j, size_t k, bool applyToSubGridAreas )
{
m_excludeRanges.push_back(CellRange(i, j, k, i + 1, j + 1, k + 1, applyToSubGridAreas));
m_excludeRanges.push_back( CellRange( i, j, k, i + 1, j + 1, k + 1, applyToSubGridAreas ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool CellRangeFilter::isCellVisible(size_t i, size_t j, size_t k, bool isInSubGridArea) const
bool CellRangeFilter::isCellVisible( size_t i, size_t j, size_t k, bool isInSubGridArea ) const
{
if (m_includeRanges.size() == 0)
if ( m_includeRanges.size() == 0 )
{
return false;
}
size_t idx;
for (idx = 0; idx < m_excludeRanges.size(); idx++)
for ( idx = 0; idx < m_excludeRanges.size(); idx++ )
{
if (m_excludeRanges[idx].isInRange(i, j, k, isInSubGridArea))
if ( m_excludeRanges[idx].isInRange( i, j, k, isInSubGridArea ) )
{
return false;
}
}
for (idx = 0; idx < m_includeRanges.size(); idx++)
for ( idx = 0; idx < m_includeRanges.size(); idx++ )
{
if (m_includeRanges[idx].isInRange(i, j, k, isInSubGridArea))
if ( m_includeRanges[idx].isInRange( i, j, k, isInSubGridArea ) )
{
return true;
}
@ -131,15 +138,14 @@ bool CellRangeFilter::isCellVisible(size_t i, size_t j, size_t k, bool isInSubGr
return false;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool CellRangeFilter::isCellExcluded(size_t i, size_t j, size_t k, bool isInSubGridArea) const
bool CellRangeFilter::isCellExcluded( size_t i, size_t j, size_t k, bool isInSubGridArea ) const
{
for (size_t idx = 0; idx < m_excludeRanges.size(); idx++)
for ( size_t idx = 0; idx < m_excludeRanges.size(); idx++ )
{
if (m_excludeRanges[idx].isInRange(i, j, k, isInSubGridArea))
if ( m_excludeRanges[idx].isInRange( i, j, k, isInSubGridArea ) )
{
return true;
}
@ -153,13 +159,12 @@ bool CellRangeFilter::isCellExcluded(size_t i, size_t j, size_t k, bool isInSubG
//--------------------------------------------------------------------------------------------------
bool CellRangeFilter::hasIncludeRanges() const
{
if (m_includeRanges.size() > 0) return true;
else return false;
if ( m_includeRanges.size() > 0 )
return true;
else
return false;
}
//==================================================================================================
///
/// \class cvf::StructGridGeometry
@ -172,16 +177,15 @@ bool CellRangeFilter::hasIncludeRanges() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
StructGridGeometryGenerator::StructGridGeometryGenerator(const StructGridInterface* grid, bool useOpenMP)
: m_grid(grid),
m_useOpenMP(useOpenMP)
StructGridGeometryGenerator::StructGridGeometryGenerator( const StructGridInterface* grid, bool useOpenMP )
: m_grid( grid )
, m_useOpenMP( useOpenMP )
{
CVF_ASSERT(grid);
CVF_ASSERT( grid );
m_quadMapper = new StructGridQuadToCellFaceMapper;
m_triangleMapper = new StuctGridTriangleToCellFaceMapper(m_quadMapper.p());
m_triangleMapper = new StuctGridTriangleToCellFaceMapper( m_quadMapper.p() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@ -189,7 +193,6 @@ StructGridGeometryGenerator::~StructGridGeometryGenerator()
{
}
//--------------------------------------------------------------------------------------------------
/// Generate surface drawable geo from the specified region
///
@ -198,64 +201,59 @@ ref<DrawableGeo> StructGridGeometryGenerator::generateSurface()
{
computeArrays();
CVF_ASSERT(m_vertices.notNull());
CVF_ASSERT( m_vertices.notNull() );
if (m_vertices->size() == 0) return nullptr;
if ( m_vertices->size() == 0 ) return nullptr;
ref<DrawableGeo> geo = new DrawableGeo;
geo->setFromQuadVertexArray(m_vertices.p());
geo->setFromQuadVertexArray( m_vertices.p() );
return geo;
}
//--------------------------------------------------------------------------------------------------
/// Generates simplified mesh as line drawing
/// Must call generateSurface first
//--------------------------------------------------------------------------------------------------
ref<DrawableGeo> StructGridGeometryGenerator::createMeshDrawable()
{
if (!(m_vertices.notNull() && m_vertices->size() != 0)) return nullptr;
if ( !( m_vertices.notNull() && m_vertices->size() != 0 ) ) return nullptr;
ref<DrawableGeo> geo = new DrawableGeo;
geo->setVertexArray(m_vertices.p());
geo->setVertexArray( m_vertices.p() );
ref<UIntArray> indices = lineIndicesFromQuadVertexArray(m_vertices.p());
ref<PrimitiveSetIndexedUInt> prim = new PrimitiveSetIndexedUInt(PT_LINES);
prim->setIndices(indices.p());
ref<UIntArray> indices = lineIndicesFromQuadVertexArray( m_vertices.p() );
ref<PrimitiveSetIndexedUInt> prim = new PrimitiveSetIndexedUInt( PT_LINES );
prim->setIndices( indices.p() );
geo->addPrimitiveSet(prim.p());
geo->addPrimitiveSet( prim.p() );
return geo;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
ref<DrawableGeo> StructGridGeometryGenerator::createOutlineMeshDrawable(double creaseAngle)
ref<DrawableGeo> StructGridGeometryGenerator::createOutlineMeshDrawable( double creaseAngle )
{
if (!(m_vertices.notNull() && m_vertices->size() != 0)) return nullptr;
if ( !( m_vertices.notNull() && m_vertices->size() != 0 ) ) return nullptr;
cvf::OutlineEdgeExtractor ee(creaseAngle, *m_vertices);
cvf::OutlineEdgeExtractor ee( creaseAngle, *m_vertices );
ref<UIntArray> indices = lineIndicesFromQuadVertexArray(m_vertices.p());
ee.addPrimitives(4, *indices);
ref<UIntArray> indices = lineIndicesFromQuadVertexArray( m_vertices.p() );
ee.addPrimitives( 4, *indices );
ref<cvf::UIntArray> lineIndices = ee.lineIndices();
if (lineIndices->size() == 0)
if ( lineIndices->size() == 0 )
{
return nullptr;
}
ref<PrimitiveSetIndexedUInt> prim = new PrimitiveSetIndexedUInt(PT_LINES);
prim->setIndices(lineIndices.p());
ref<PrimitiveSetIndexedUInt> prim = new PrimitiveSetIndexedUInt( PT_LINES );
prim->setIndices( lineIndices.p() );
ref<DrawableGeo> geo = new DrawableGeo;
geo->setVertexArray(m_vertices.p());
geo->addPrimitiveSet(prim.p());
geo->setVertexArray( m_vertices.p() );
geo->addPrimitiveSet( prim.p() );
return geo;
}
@ -263,53 +261,51 @@ ref<DrawableGeo> StructGridGeometryGenerator::createOutlineMeshDrawable(double c
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
ref<DrawableGeo> StructGridGeometryGenerator::createMeshDrawableFromSingleCell(const StructGridInterface* grid,
size_t cellIndex)
ref<DrawableGeo> StructGridGeometryGenerator::createMeshDrawableFromSingleCell( const StructGridInterface* grid,
size_t cellIndex )
{
return createMeshDrawableFromSingleCell(grid,
cellIndex,
grid->displayModelOffset());
return createMeshDrawableFromSingleCell( grid, cellIndex, grid->displayModelOffset() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
ref<DrawableGeo> StructGridGeometryGenerator::createMeshDrawableFromSingleCell(const StructGridInterface* grid,
ref<DrawableGeo> StructGridGeometryGenerator::createMeshDrawableFromSingleCell( const StructGridInterface* grid,
size_t cellIndex,
const cvf::Vec3d& displayModelOffset)
const cvf::Vec3d& displayModelOffset )
{
cvf::Vec3d cornerVerts[8];
grid->cellCornerVertices(cellIndex, cornerVerts);
grid->cellCornerVertices( cellIndex, cornerVerts );
std::vector<Vec3f> vertices;
for (int enumInt = cvf::StructGridInterface::POS_I; enumInt < cvf::StructGridInterface::NO_FACE; enumInt++)
for ( int enumInt = cvf::StructGridInterface::POS_I; enumInt < cvf::StructGridInterface::NO_FACE; enumInt++ )
{
cvf::StructGridInterface::FaceType face = static_cast<cvf::StructGridInterface::FaceType>(enumInt);
cvf::StructGridInterface::FaceType face = static_cast<cvf::StructGridInterface::FaceType>( enumInt );
ubyte faceConn[4];
grid->cellFaceVertexIndices(face, faceConn);
grid->cellFaceVertexIndices( face, faceConn );
int n;
for (n = 0; n < 4; n++)
for ( n = 0; n < 4; n++ )
{
vertices.push_back(cvf::Vec3f(cornerVerts[faceConn[n]] - displayModelOffset));
vertices.push_back( cvf::Vec3f( cornerVerts[faceConn[n]] - displayModelOffset ) );
}
}
cvf::ref<cvf::Vec3fArray> cvfVertices = new cvf::Vec3fArray;
cvfVertices->assign(vertices);
cvfVertices->assign( vertices );
if (!(cvfVertices.notNull() && cvfVertices->size() != 0)) return nullptr;
if ( !( cvfVertices.notNull() && cvfVertices->size() != 0 ) ) return nullptr;
ref<DrawableGeo> geo = new DrawableGeo;
geo->setVertexArray(cvfVertices.p());
geo->setVertexArray( cvfVertices.p() );
ref<UIntArray> indices = lineIndicesFromQuadVertexArray(cvfVertices.p());
ref<PrimitiveSetIndexedUInt> prim = new PrimitiveSetIndexedUInt(PT_LINES);
prim->setIndices(indices.p());
ref<UIntArray> indices = lineIndicesFromQuadVertexArray( cvfVertices.p() );
ref<PrimitiveSetIndexedUInt> prim = new PrimitiveSetIndexedUInt( PT_LINES );
prim->setIndices( indices.p() );
geo->addPrimitiveSet(prim.p());
geo->addPrimitiveSet( prim.p() );
return geo;
}
@ -319,29 +315,29 @@ ref<DrawableGeo> StructGridGeometryGenerator::createMeshDrawableFromSingleCell(c
///
///
//--------------------------------------------------------------------------------------------------
ref<UIntArray> StructGridGeometryGenerator::lineIndicesFromQuadVertexArray(const Vec3fArray* vertexArray)
ref<UIntArray> StructGridGeometryGenerator::lineIndicesFromQuadVertexArray( const Vec3fArray* vertexArray )
{
CVF_ASSERT(vertexArray);
CVF_ASSERT( vertexArray );
size_t numVertices = vertexArray->size();
int numQuads = static_cast<int>(numVertices/4);
CVF_ASSERT(numVertices%4 == 0);
int numQuads = static_cast<int>( numVertices / 4 );
CVF_ASSERT( numVertices % 4 == 0 );
ref<UIntArray> indices = new UIntArray;
indices->resize(numQuads*8);
indices->resize( numQuads * 8 );
#pragma omp parallel for
for (int i = 0; i < numQuads; i++)
for ( int i = 0; i < numQuads; i++ )
{
int idx = 8*i;
indices->set(idx + 0, i*4 + 0);
indices->set(idx + 1, i*4 + 1);
indices->set(idx + 2, i*4 + 1);
indices->set(idx + 3, i*4 + 2);
indices->set(idx + 4, i*4 + 2);
indices->set(idx + 5, i*4 + 3);
indices->set(idx + 6, i*4 + 3);
indices->set(idx + 7, i*4 + 0);
int idx = 8 * i;
indices->set( idx + 0, i * 4 + 0 );
indices->set( idx + 1, i * 4 + 1 );
indices->set( idx + 2, i * 4 + 1 );
indices->set( idx + 3, i * 4 + 2 );
indices->set( idx + 4, i * 4 + 2 );
indices->set( idx + 5, i * 4 + 3 );
indices->set( idx + 6, i * 4 + 3 );
indices->set( idx + 7, i * 4 + 0 );
}
return indices;
@ -350,23 +346,21 @@ ref<UIntArray> StructGridGeometryGenerator::lineIndicesFromQuadVertexArray(const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void StructGridGeometryGenerator::addFaceVisibilityFilter(const CellFaceVisibilityFilter* cellVisibilityFilter)
void StructGridGeometryGenerator::addFaceVisibilityFilter( const CellFaceVisibilityFilter* cellVisibilityFilter )
{
m_cellVisibilityFilters.push_back(cellVisibilityFilter);
m_cellVisibilityFilters.push_back( cellVisibilityFilter );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool StructGridGeometryGenerator::isCellFaceVisible(size_t i, size_t j, size_t k, StructGridInterface::FaceType face) const
bool StructGridGeometryGenerator::isCellFaceVisible( size_t i, size_t j, size_t k, StructGridInterface::FaceType face ) const
{
size_t idx;
for (idx = 0; idx < m_cellVisibilityFilters.size(); idx++)
for ( idx = 0; idx < m_cellVisibilityFilters.size(); idx++ )
{
const cvf::CellFaceVisibilityFilter* cellFilter = m_cellVisibilityFilters[idx];
if (cellFilter->isFaceVisible(i, j, k, face, m_cellVisibility.p()))
if ( cellFilter->isFaceVisible( i, j, k, face, m_cellVisibility.p() ) )
{
return true;
}
@ -386,56 +380,62 @@ void StructGridGeometryGenerator::computeArrays()
cvf::Vec3d offset = m_grid->displayModelOffset();
#pragma omp parallel for schedule(dynamic) if (m_useOpenMP)
for (int k = 0; k < static_cast<int>(m_grid->cellCountK()); k++)
#pragma omp parallel for schedule( dynamic ) if ( m_useOpenMP )
for ( int k = 0; k < static_cast<int>( m_grid->cellCountK() ); k++ )
{
size_t j;
for (j = 0; j < m_grid->cellCountJ(); j++)
for ( j = 0; j < m_grid->cellCountJ(); j++ )
{
size_t i;
for (i = 0; i < m_grid->cellCountI(); i++)
for ( i = 0; i < m_grid->cellCountI(); i++ )
{
size_t cellIndex = m_grid->cellIndexFromIJK(i, j, k);
if (m_cellVisibility.notNull() && !(*m_cellVisibility)[cellIndex])
size_t cellIndex = m_grid->cellIndexFromIJK( i, j, k );
if ( m_cellVisibility.notNull() && !( *m_cellVisibility )[cellIndex] )
{
continue;
}
std::vector<StructGridInterface::FaceType> visibleFaces;
visibleFaces.reserve(6);
visibleFaces.reserve( 6 );
if (isCellFaceVisible(i, j, k, StructGridInterface::NEG_I)) visibleFaces.push_back(cvf::StructGridInterface::NEG_I);
if (isCellFaceVisible(i, j, k, StructGridInterface::POS_I)) visibleFaces.push_back(cvf::StructGridInterface::POS_I);
if (isCellFaceVisible(i, j, k, StructGridInterface::NEG_J)) visibleFaces.push_back(cvf::StructGridInterface::NEG_J);
if (isCellFaceVisible(i, j, k, StructGridInterface::POS_J)) visibleFaces.push_back(cvf::StructGridInterface::POS_J);
if (isCellFaceVisible(i, j, k, StructGridInterface::NEG_K)) visibleFaces.push_back(cvf::StructGridInterface::NEG_K);
if (isCellFaceVisible(i, j, k, StructGridInterface::POS_K)) visibleFaces.push_back(cvf::StructGridInterface::POS_K);
if ( isCellFaceVisible( i, j, k, StructGridInterface::NEG_I ) )
visibleFaces.push_back( cvf::StructGridInterface::NEG_I );
if ( isCellFaceVisible( i, j, k, StructGridInterface::POS_I ) )
visibleFaces.push_back( cvf::StructGridInterface::POS_I );
if ( isCellFaceVisible( i, j, k, StructGridInterface::NEG_J ) )
visibleFaces.push_back( cvf::StructGridInterface::NEG_J );
if ( isCellFaceVisible( i, j, k, StructGridInterface::POS_J ) )
visibleFaces.push_back( cvf::StructGridInterface::POS_J );
if ( isCellFaceVisible( i, j, k, StructGridInterface::NEG_K ) )
visibleFaces.push_back( cvf::StructGridInterface::NEG_K );
if ( isCellFaceVisible( i, j, k, StructGridInterface::POS_K ) )
visibleFaces.push_back( cvf::StructGridInterface::POS_K );
if (visibleFaces.size() > 0)
if ( visibleFaces.size() > 0 )
{
cvf::Vec3d cornerVerts[8];
m_grid->cellCornerVertices(cellIndex, cornerVerts);
m_grid->cellCornerVertices( cellIndex, cornerVerts );
size_t idx;
for (idx = 0; idx < visibleFaces.size(); idx++)
for ( idx = 0; idx < visibleFaces.size(); idx++ )
{
cvf::StructGridInterface::FaceType face = visibleFaces[idx];
ubyte faceConn[4];
m_grid->cellFaceVertexIndices(face, faceConn);
m_grid->cellFaceVertexIndices( face, faceConn );
// Critical section to avoid two threads accessing the arrays at the same time.
#pragma omp critical(critical_section_StructGridGeometryGenerator_computeArrays)
// Critical section to avoid two threads accessing the arrays at the same time.
#pragma omp critical( critical_section_StructGridGeometryGenerator_computeArrays )
{
int n;
for (n = 0; n < 4; n++)
for ( n = 0; n < 4; n++ )
{
vertices.push_back(cvf::Vec3f(cornerVerts[faceConn[n]] - offset));
vertices.push_back( cvf::Vec3f( cornerVerts[faceConn[n]] - offset ) );
}
// Keep track of the source cell index per quad
m_quadMapper->quadToCellIndexMap().push_back(cellIndex);
m_quadMapper->quadToCellFaceMap().push_back(face);
m_quadMapper->quadToCellIndexMap().push_back( cellIndex );
m_quadMapper->quadToCellFaceMap().push_back( face );
}
}
}
@ -444,41 +444,41 @@ void StructGridGeometryGenerator::computeArrays()
}
m_vertices = new cvf::Vec3fArray;
m_vertices->assign(vertices);
m_vertices->assign( vertices );
}
//--------------------------------------------------------------------------------------------------
/// Calculates the texture coordinates in a "nearly" one dimentional texture.
/// Undefined values are coded with a y-texturecoordinate value of 1.0 instead of the normal 0.5
//--------------------------------------------------------------------------------------------------
void StructGridGeometryGenerator::textureCoordinates(Vec2fArray* textureCoords, const StructGridScalarDataAccess* resultAccessor, const ScalarMapper* mapper) const
void StructGridGeometryGenerator::textureCoordinates( Vec2fArray* textureCoords,
const StructGridScalarDataAccess* resultAccessor,
const ScalarMapper* mapper ) const
{
if (!resultAccessor) return;
if ( !resultAccessor ) return;
size_t numVertices = m_quadMapper->quadCount()*4;
size_t numVertices = m_quadMapper->quadCount() * 4;
textureCoords->resize(numVertices);
textureCoords->resize( numVertices );
cvf::Vec2f* rawPtr = textureCoords->ptr();
double cellScalarValue;
cvf::Vec2f texCoord;
#pragma omp parallel for private(texCoord, cellScalarValue)
for (int i = 0; i < static_cast<int>(m_quadMapper->quadCount()); i++)
#pragma omp parallel for private( texCoord, cellScalarValue )
for ( int i = 0; i < static_cast<int>( m_quadMapper->quadCount() ); i++ )
{
cellScalarValue = resultAccessor->cellScalar(m_quadMapper->cellIndex(i));
texCoord = mapper->mapToTextureCoord(cellScalarValue);
if (cellScalarValue == HUGE_VAL || cellScalarValue != cellScalarValue) // a != a is true for NAN's
cellScalarValue = resultAccessor->cellScalar( m_quadMapper->cellIndex( i ) );
texCoord = mapper->mapToTextureCoord( cellScalarValue );
if ( cellScalarValue == HUGE_VAL || cellScalarValue != cellScalarValue ) // a != a is true for NAN's
{
texCoord[1] = 1.0f;
}
size_t j;
for (j = 0; j < 4; j++)
for ( j = 0; j < 4; j++ )
{
rawPtr[i*4 + j] = texCoord;
rawPtr[i * 4 + j] = texCoord;
}
}
}
@ -500,7 +500,7 @@ void StructGridGeometryGenerator::textureCoordinatesFromSingleFaceValues(Vec2fAr
cvf::Vec2f texCoord;
int quadCount = static_cast<int>(m_quadMapper->quadCount());
#pragma omp parallel for private(texCoord, cellFaceValue)
#pragma omp parallel for private( texCoord, cellFaceValue )
for (int qIdx = 0; qIdx < quadCount; qIdx++)
{
cellFaceValue = resultAccessor->cellFaceScalar(m_quadMapper->cellIndex(qIdx), m_quadMapper->faceType(qIdx));
@ -524,10 +524,9 @@ void StructGridGeometryGenerator::textureCoordinatesFromSingleFaceValues(Vec2fAr
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void StructGridGeometryGenerator::setCellVisibility(const UByteArray* cellVisibility)
void StructGridGeometryGenerator::setCellVisibility( const UByteArray* cellVisibility )
{
m_cellVisibility = cellVisibility;
}
} // namespace cvf

View File

@ -34,16 +34,15 @@
//
//##################################################################################################
#pragma once
#include "cvfObject.h"
#include "cvfArray.h"
#include "cvfStructGrid.h"
#include "cvfCollection.h"
#include "cvfObject.h"
#include "cvfStructGrid.h"
namespace cvf {
namespace cvf
{
class DrawableGeo;
class ScalarMapper;
class StructGridScalarDataAccess;
@ -56,14 +55,14 @@ class CellRangeFilter
public:
CellRangeFilter();
void addCellIncludeRange(size_t minI, size_t minJ, size_t minK, size_t maxI, size_t maxJ, size_t maxK, bool applyToSubGridAreas);
void addCellInclude(size_t i, size_t j, size_t k, bool applyToSubGridAreas);
void addCellIncludeRange( size_t minI, size_t minJ, size_t minK, size_t maxI, size_t maxJ, size_t maxK, bool applyToSubGridAreas );
void addCellInclude( size_t i, size_t j, size_t k, bool applyToSubGridAreas );
void addCellExcludeRange(size_t minI, size_t minJ, size_t minK, size_t maxI, size_t maxJ, size_t maxK, bool applyToSubGridAreas);
void addCellExclude(size_t i, size_t j, size_t k, bool applyToSubGridAreas);
void addCellExcludeRange( size_t minI, size_t minJ, size_t minK, size_t maxI, size_t maxJ, size_t maxK, bool applyToSubGridAreas );
void addCellExclude( size_t i, size_t j, size_t k, bool applyToSubGridAreas );
bool isCellVisible(size_t i, size_t j, size_t k, bool isInSubGridArea) const;
bool isCellExcluded(size_t i, size_t j, size_t k, bool isInSubGridArea) const;
bool isCellVisible( size_t i, size_t j, size_t k, bool isInSubGridArea ) const;
bool isCellExcluded( size_t i, size_t j, size_t k, bool isInSubGridArea ) const;
bool hasIncludeRanges() const;
@ -72,28 +71,28 @@ private:
{
public:
CellRange()
: m_min(cvf::Vec3st::ZERO),
m_max(UNDEFINED_SIZE_T, UNDEFINED_SIZE_T, UNDEFINED_SIZE_T),
m_applyToSubGridAreas(true)
: m_min( cvf::Vec3st::ZERO )
, m_max( UNDEFINED_SIZE_T, UNDEFINED_SIZE_T, UNDEFINED_SIZE_T )
, m_applyToSubGridAreas( true )
{
}
CellRange(size_t minI, size_t minJ, size_t minK, size_t maxI, size_t maxJ, size_t maxK, bool applyToSubGridAreas)
: m_min(minI, minJ, minK),
m_max(maxI, maxJ, maxK),
m_applyToSubGridAreas(applyToSubGridAreas)
CellRange( size_t minI, size_t minJ, size_t minK, size_t maxI, size_t maxJ, size_t maxK, bool applyToSubGridAreas )
: m_min( minI, minJ, minK )
, m_max( maxI, maxJ, maxK )
, m_applyToSubGridAreas( applyToSubGridAreas )
{
}
bool isInRange(size_t i, size_t j, size_t k, bool isInSubGridArea) const
bool isInRange( size_t i, size_t j, size_t k, bool isInSubGridArea ) const
{
if (isInSubGridArea && !m_applyToSubGridAreas) return false;
cvf::Vec3st test(i, j, k);
if ( isInSubGridArea && !m_applyToSubGridAreas ) return false;
cvf::Vec3st test( i, j, k );
int idx;
for (idx = 0; idx < 3; idx++)
for ( idx = 0; idx < 3; idx++ )
{
if (test[idx] < m_min[idx] || m_max[idx] <= test[idx])
if ( test[idx] < m_min[idx] || m_max[idx] <= test[idx] )
{
return false;
}
@ -113,24 +112,26 @@ private:
std::vector<CellRange> m_excludeRanges;
};
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
class CellFaceVisibilityFilter
{
public:
virtual bool isFaceVisible(size_t i, size_t j, size_t k, StructGridInterface::FaceType face, const UByteArray* cellVisibility) const = 0;
virtual bool isFaceVisible( size_t i,
size_t j,
size_t k,
StructGridInterface::FaceType face,
const UByteArray* cellVisibility ) const = 0;
};
class StructGridQuadToCellFaceMapper : public Object
{
public:
size_t quadCount() const { return m_quadsToCells.size();}
size_t quadCount() const { return m_quadsToCells.size(); }
size_t cellIndex(size_t quadIdx) const {return m_quadsToCells[quadIdx]; }
StructGridInterface::FaceType cellFace(size_t quadIdx) const {return m_quadsToFace[quadIdx]; }
size_t cellIndex( size_t quadIdx ) const { return m_quadsToCells[quadIdx]; }
StructGridInterface::FaceType cellFace( size_t quadIdx ) const { return m_quadsToFace[quadIdx]; }
// Interface for building the mappings
std::vector<size_t>& quadToCellIndexMap() { return m_quadsToCells; }
@ -141,21 +142,25 @@ private:
std::vector<StructGridInterface::FaceType> m_quadsToFace;
};
class StuctGridTriangleToCellFaceMapper : public Object
{
public:
explicit StuctGridTriangleToCellFaceMapper(const StructGridQuadToCellFaceMapper* quadMapper) { m_quadMapper = quadMapper; }
size_t triangleCount() const { return 2* m_quadMapper->quadCount();}
explicit StuctGridTriangleToCellFaceMapper( const StructGridQuadToCellFaceMapper* quadMapper )
{
m_quadMapper = quadMapper;
}
size_t triangleCount() const { return 2 * m_quadMapper->quadCount(); }
size_t cellIndex(size_t triangleIdx) const {return m_quadMapper->cellIndex(triangleIdx/2); }
StructGridInterface::FaceType cellFace(size_t triangleIdx) const {return m_quadMapper->cellFace(triangleIdx/2); }
size_t cellIndex( size_t triangleIdx ) const { return m_quadMapper->cellIndex( triangleIdx / 2 ); }
StructGridInterface::FaceType cellFace( size_t triangleIdx ) const
{
return m_quadMapper->cellFace( triangleIdx / 2 );
}
private:
cref<StructGridQuadToCellFaceMapper> m_quadMapper;
};
//==================================================================================================
//
//
@ -164,41 +169,41 @@ private:
class StructGridGeometryGenerator : public Object
{
public:
explicit StructGridGeometryGenerator(const StructGridInterface* grid, bool useOpenMP);
explicit StructGridGeometryGenerator( const StructGridInterface* grid, bool useOpenMP );
~StructGridGeometryGenerator() override;
// Setup methods
void setCellVisibility(const UByteArray* cellVisibility);
void addFaceVisibilityFilter(const CellFaceVisibilityFilter* cellVisibilityFilter);
void setCellVisibility( const UByteArray* cellVisibility );
void addFaceVisibilityFilter( const CellFaceVisibilityFilter* cellVisibilityFilter );
// Access, valid after generation is done
const StructGridInterface* activeGrid() { return m_grid.p(); }
void textureCoordinates(Vec2fArray* textureCoords, const StructGridScalarDataAccess* resultAccessor, const ScalarMapper* mapper) const;
void textureCoordinates( Vec2fArray* textureCoords,
const StructGridScalarDataAccess* resultAccessor,
const ScalarMapper* mapper ) const;
// Mapping between cells and geometry
const StructGridQuadToCellFaceMapper * quadToCellFaceMapper() { return m_quadMapper.p(); }
const StuctGridTriangleToCellFaceMapper * triangleToCellFaceMapper() { return m_triangleMapper.p(); }
const StructGridQuadToCellFaceMapper* quadToCellFaceMapper() { return m_quadMapper.p(); }
const StuctGridTriangleToCellFaceMapper* triangleToCellFaceMapper() { return m_triangleMapper.p(); }
// Generated geometry
ref<DrawableGeo> generateSurface();
ref<DrawableGeo> createMeshDrawable();
ref<DrawableGeo> createOutlineMeshDrawable(double creaseAngle);
ref<DrawableGeo> createOutlineMeshDrawable( double creaseAngle );
static ref<DrawableGeo> createMeshDrawableFromSingleCell(const StructGridInterface* grid,
size_t cellIndex);
static ref<DrawableGeo> createMeshDrawableFromSingleCell( const StructGridInterface* grid, size_t cellIndex );
static ref<DrawableGeo> createMeshDrawableFromSingleCell(const StructGridInterface* grid,
static ref<DrawableGeo> createMeshDrawableFromSingleCell( const StructGridInterface* grid,
size_t cellIndex,
const cvf::Vec3d& displayModelOffset);
const cvf::Vec3d& displayModelOffset );
private:
static ref<UIntArray>
lineIndicesFromQuadVertexArray(const Vec3fArray* vertexArray);
bool isCellFaceVisible(size_t i, size_t j, size_t k, StructGridInterface::FaceType face) const;
static ref<UIntArray> lineIndicesFromQuadVertexArray( const Vec3fArray* vertexArray );
bool isCellFaceVisible( size_t i, size_t j, size_t k, StructGridInterface::FaceType face ) const;
void computeArrays();
@ -221,4 +226,4 @@ private:
bool m_useOpenMP;
};
}
} // namespace cvf

View File

@ -34,23 +34,19 @@
//
//##################################################################################################
#pragma once
#include "cvfBase.h"
#include "cvfObject.h"
#include "cvfVector3.h"
namespace cvf {
namespace cvf
{
class StructGridScalarDataAccess : public Object
{
public:
virtual double cellScalar(size_t cellIndex) const = 0;
virtual void setCellScalar(size_t cellIndex, double value) = 0;
virtual double cellScalar( size_t cellIndex ) const = 0;
virtual void setCellScalar( size_t cellIndex, double value ) = 0;
};
} // namespace cvf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#include "cafAnimationToolBar.h"
#include "cafPopupMenuButton.h"
@ -47,24 +46,23 @@
namespace caf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
AnimationToolBar::AnimationToolBar(QWidget *parent /*= 0*/)
: QToolBar (parent)
AnimationToolBar::AnimationToolBar( QWidget* parent /*= 0*/ )
: QToolBar( parent )
{
setObjectName("AnimationToolBar");
setObjectName( "AnimationToolBar" );
init();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
AnimationToolBar::AnimationToolBar(const QString &title, QWidget *parent /*= 0*/)
: QToolBar(title, parent)
AnimationToolBar::AnimationToolBar( const QString& title, QWidget* parent /*= 0*/ )
: QToolBar( title, parent )
{
setObjectName(title);
setObjectName( title );
init();
}
@ -78,71 +76,72 @@ void AnimationToolBar::init()
m_fastFrameRate = 20;
// Create actions and widgets
m_animSkipToStartAction = new QAction(QIcon(":/cafAnimControl/SkipToStart.png"), tr("Skip to Start"), this);
m_animStepBackwardAction = new QAction(QIcon(":/cafAnimControl/StepBwd.png"), tr("Step Backward"), this);
m_animPauseAction = new QAction(QIcon(":/cafAnimControl/Pause.png"), tr("Pause"), this);
m_animPlayAction = new QAction(QIcon(":/cafAnimControl/Play.png"), tr("Play"), this);
m_animPlayPauseButton = new QToolButton(this);
m_animPlayPauseButton->setIcon(m_animPlayAction->icon());
m_animPlayPauseButton->setToolTip(m_animPlayAction->toolTip());
QObject::connect(m_animPlayPauseButton, SIGNAL(clicked()), this, SLOT(playPauseChanged()));
m_animSkipToStartAction = new QAction( QIcon( ":/cafAnimControl/SkipToStart.png" ), tr( "Skip to Start" ), this );
m_animStepBackwardAction = new QAction( QIcon( ":/cafAnimControl/StepBwd.png" ), tr( "Step Backward" ), this );
m_animPauseAction = new QAction( QIcon( ":/cafAnimControl/Pause.png" ), tr( "Pause" ), this );
m_animPlayAction = new QAction( QIcon( ":/cafAnimControl/Play.png" ), tr( "Play" ), this );
m_animPlayPauseButton = new QToolButton( this );
m_animPlayPauseButton->setIcon( m_animPlayAction->icon() );
m_animPlayPauseButton->setToolTip( m_animPlayAction->toolTip() );
QObject::connect( m_animPlayPauseButton, SIGNAL( clicked() ), this, SLOT( playPauseChanged() ) );
m_animStepForwardAction = new QAction(QIcon(":/cafAnimControl/StepFwd.png"), tr("Step Forward"), this);
m_animSkipToEndAction = new QAction(QIcon(":/cafAnimControl/SkipToEnd.png"), tr("Skip to End"), this);
m_animStepForwardAction = new QAction( QIcon( ":/cafAnimControl/StepFwd.png" ), tr( "Step Forward" ), this );
m_animSkipToEndAction = new QAction( QIcon( ":/cafAnimControl/SkipToEnd.png" ), tr( "Skip to End" ), this );
m_animRepeatFromStartAction = new QAction(QIcon(":/cafAnimControl/RepeatFromStart.png"), tr("Repeat From start"), this);
m_animRepeatFromStartAction->setCheckable(true);
m_animRepeatFromStartAction =
new QAction( QIcon( ":/cafAnimControl/RepeatFromStart.png" ), tr( "Repeat From start" ), this );
m_animRepeatFromStartAction->setCheckable( true );
m_animSpeedButton = new PopupMenuButton(this);
m_animSpeedButton->setIcon(QIcon(":/cafAnimControl/Speed.png"));
m_animSpeedButton->setToolTip("Adjust Animation Speed");
m_animSpeedButton = new PopupMenuButton( this );
m_animSpeedButton->setIcon( QIcon( ":/cafAnimControl/Speed.png" ) );
m_animSpeedButton->setToolTip( "Adjust Animation Speed" );
m_frameRateSlowLabel = new QLabel(this);
m_frameRateSlowLabel->setPixmap(QPixmap(":/cafAnimControl/SlowHorizontal.png"));
m_frameRateSlowLabel->setToolTip(tr("Slow"));
m_frameRateSlowLabel = new QLabel( this );
m_frameRateSlowLabel->setPixmap( QPixmap( ":/cafAnimControl/SlowHorizontal.png" ) );
m_frameRateSlowLabel->setToolTip( tr( "Slow" ) );
m_frameRateFastLabel = new QLabel(this);
m_frameRateFastLabel->setPixmap(QPixmap(":/cafAnimControl/FastHorizontal.png"));
m_frameRateFastLabel->setToolTip(tr("Fast"));
m_frameRateFastLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
m_frameRateFastLabel = new QLabel( this );
m_frameRateFastLabel->setPixmap( QPixmap( ":/cafAnimControl/FastHorizontal.png" ) );
m_frameRateFastLabel->setToolTip( tr( "Fast" ) );
m_frameRateFastLabel->setAlignment( Qt::AlignRight | Qt::AlignVCenter );
m_frameRateSlider = new QSlider(Qt::Horizontal, this);
m_frameRateSlider->setToolTip(tr("Animation speed"));
m_frameRateSlider->setMinimumWidth(100);
m_frameRateSlider = new QSlider( Qt::Horizontal, this );
m_frameRateSlider->setToolTip( tr( "Animation speed" ) );
m_frameRateSlider->setMinimumWidth( 100 );
m_animSpeedButton->addWidget(m_frameRateSlowLabel);
m_animSpeedButton->addWidget(m_frameRateSlider);
m_animSpeedButton->addWidget(m_frameRateFastLabel);
m_animSpeedButton->addWidget( m_frameRateSlowLabel );
m_animSpeedButton->addWidget( m_frameRateSlider );
m_animSpeedButton->addWidget( m_frameRateFastLabel );
m_timestepCombo = new QComboBox(this);
m_timestepCombo->setSizeAdjustPolicy(QComboBox::AdjustToContents);
m_timestepCombo->setToolTip(tr("Current Time Step"));
m_timestepCombo = new QComboBox( this );
m_timestepCombo->setSizeAdjustPolicy( QComboBox::AdjustToContents );
m_timestepCombo->setToolTip( tr( "Current Time Step" ) );
QAction* separator1 = new QAction(this);
separator1->setSeparator(true);
QAction* separator2 = new QAction(this);
separator2->setSeparator(true);
QAction* separator3 = new QAction(this);
separator3->setSeparator(true);
QAction* separator1 = new QAction( this );
separator1->setSeparator( true );
QAction* separator2 = new QAction( this );
separator2->setSeparator( true );
QAction* separator3 = new QAction( this );
separator3->setSeparator( true );
// Add actions and widgets to animation toolbar
addAction(m_animSkipToStartAction);
addAction(m_animStepBackwardAction);
addWidget(m_animPlayPauseButton);
addAction(m_animStepForwardAction);
addAction(m_animSkipToEndAction);
addAction( m_animSkipToStartAction );
addAction( m_animStepBackwardAction );
addWidget( m_animPlayPauseButton );
addAction( m_animStepForwardAction );
addAction( m_animSkipToEndAction );
addAction(separator1);
addAction( separator1 );
addAction(m_animRepeatFromStartAction );
addAction( m_animRepeatFromStartAction );
addAction(separator2);
addAction( separator2 );
addWidget(m_animSpeedButton);
addWidget( m_animSpeedButton );
addAction(separator3);
addAction( separator3 );
addWidget(m_timestepCombo);
addWidget( m_timestepCombo );
updateAnimationButtons();
}
@ -154,44 +153,43 @@ void AnimationToolBar::updateAnimationButtons()
{
bool isPlaying = m_activeAnimationControl && m_activeAnimationControl->isActive();
if (isPlaying)
if ( isPlaying )
{
m_animPlayPauseButton->setIcon(m_animPauseAction->icon());
m_animPlayPauseButton->setToolTip(m_animPauseAction->toolTip());
m_animPlayPauseButton->setIcon( m_animPauseAction->icon() );
m_animPlayPauseButton->setToolTip( m_animPauseAction->toolTip() );
}
else
{
m_animPlayPauseButton->setIcon(m_animPlayAction->icon());
m_animPlayPauseButton->setToolTip(m_animPlayAction->toolTip());
m_animPlayPauseButton->setIcon( m_animPlayAction->icon() );
m_animPlayPauseButton->setToolTip( m_animPlayAction->toolTip() );
}
bool isAtStart = m_timestepCombo->count() == 0 || m_timestepCombo->currentIndex() == 0;
bool isAtEnd = m_timestepCombo->count() > 0 && m_timestepCombo->currentIndex() == m_timestepCombo->count() - 1;
// Going backwards actions disabled when we're stopped at the start
m_animSkipToStartAction->setEnabled(isPlaying || !isAtStart);
m_animStepBackwardAction->setEnabled(isPlaying || !isAtStart);
m_animSkipToStartAction->setEnabled( isPlaying || !isAtStart );
m_animStepBackwardAction->setEnabled( isPlaying || !isAtStart );
bool isRepeat = m_activeAnimationControl &&
m_activeAnimationControl->isRepeatingFromStart();
bool isRepeat = m_activeAnimationControl && m_activeAnimationControl->isRepeatingFromStart();
// Going forwards actions disabled when we're stopped at the end
m_animStepForwardAction->setEnabled(isPlaying || !isAtEnd);
m_animSkipToEndAction->setEnabled(isPlaying || !isAtEnd);
m_animStepForwardAction->setEnabled( isPlaying || !isAtEnd );
m_animSkipToEndAction->setEnabled( isPlaying || !isAtEnd );
// ... however we allow playing if we have repeat on
m_animPlayPauseButton->setEnabled(isPlaying || isRepeat || !isAtEnd);
m_animPlayPauseButton->setEnabled( isPlaying || isRepeat || !isAtEnd );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void AnimationToolBar::connectAnimationControl(caf::FrameAnimationControl* animationControl)
void AnimationToolBar::connectAnimationControl( caf::FrameAnimationControl* animationControl )
{
// Animation action connections
if (m_activeAnimationControl)
if ( m_activeAnimationControl )
{
m_activeAnimationControl->disconnect(this, SLOT(slotUpdateAnimationGuiFromFrameIndex(int)));
m_activeAnimationControl->disconnect(this, SLOT(slotUpdateTimestepList(int)));
m_activeAnimationControl->disconnect( this, SLOT( slotUpdateAnimationGuiFromFrameIndex( int ) ) );
m_activeAnimationControl->disconnect( this, SLOT( slotUpdateTimestepList( int ) ) );
}
m_activeAnimationControl = animationControl;
@ -208,55 +206,57 @@ void AnimationToolBar::connectAnimationControl(caf::FrameAnimationControl* anima
m_timestepCombo->disconnect();
m_frameRateSlider->disconnect();
if (animationControl)
if ( animationControl )
{
connect(m_animSkipToStartAction, SIGNAL(triggered()), animationControl, SLOT(slotSkipToStart()));
connect(m_animStepBackwardAction, SIGNAL(triggered()), animationControl, SLOT(slotStepBackward()));
connect(m_animPauseAction, SIGNAL(triggered()), animationControl, SLOT(slotPause()));
connect(m_animPlayAction, SIGNAL(triggered()), animationControl, SLOT(slotPlayFwd()));
connect(m_animStepForwardAction, SIGNAL(triggered()), animationControl, SLOT(slotStepForward()));
connect(m_animSkipToEndAction, SIGNAL(triggered()), animationControl, SLOT(slotSkipToEnd()));
connect( m_animSkipToStartAction, SIGNAL( triggered() ), animationControl, SLOT( slotSkipToStart() ) );
connect( m_animStepBackwardAction, SIGNAL( triggered() ), animationControl, SLOT( slotStepBackward() ) );
connect( m_animPauseAction, SIGNAL( triggered() ), animationControl, SLOT( slotPause() ) );
connect( m_animPlayAction, SIGNAL( triggered() ), animationControl, SLOT( slotPlayFwd() ) );
connect( m_animStepForwardAction, SIGNAL( triggered() ), animationControl, SLOT( slotStepForward() ) );
connect( m_animSkipToEndAction, SIGNAL( triggered() ), animationControl, SLOT( slotSkipToEnd() ) );
m_animRepeatFromStartAction->setChecked(animationControl->isRepeatingFromStart());
m_animRepeatFromStartAction->setChecked( animationControl->isRepeatingFromStart() );
connect(m_animRepeatFromStartAction,SIGNAL(triggered(bool)), animationControl, SLOT(slotRepeatFromStart(bool)));
connect( m_animRepeatFromStartAction,
SIGNAL( triggered( bool ) ),
animationControl,
SLOT( slotRepeatFromStart( bool ) ) );
connect(m_timestepCombo, SIGNAL(currentIndexChanged(int)), animationControl, SLOT(setCurrentFrame(int)));
connect(m_frameRateSlider, SIGNAL(valueChanged(int)), this, SLOT(slotFrameRateSliderChanged(int)));
connect( m_timestepCombo, SIGNAL( currentIndexChanged( int ) ), animationControl, SLOT( setCurrentFrame( int ) ) );
connect( m_frameRateSlider, SIGNAL( valueChanged( int ) ), this, SLOT( slotFrameRateSliderChanged( int ) ) );
connect(animationControl, SIGNAL(changeFrame(int)), this, SLOT(slotUpdateAnimationGuiFromFrameIndex(int)));
connect(animationControl, SIGNAL(frameCountChanged(int)), this, SLOT(slotUpdateTimestepList(int)));
connect( animationControl, SIGNAL( changeFrame( int ) ), this, SLOT( slotUpdateAnimationGuiFromFrameIndex( int ) ) );
connect( animationControl, SIGNAL( frameCountChanged( int ) ), this, SLOT( slotUpdateTimestepList( int ) ) );
int timeout = animationControl->timeout();
double initialFrameRate = 1000;
if (timeout > 0) initialFrameRate = 1000.0/timeout;
setFrameRate(initialFrameRate);
if ( timeout > 0 ) initialFrameRate = 1000.0 / timeout;
setFrameRate( initialFrameRate );
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void AnimationToolBar::setFrameRate(double frameRate)
void AnimationToolBar::setFrameRate( double frameRate )
{
float sliderRange = m_frameRateSlider->maximum() - m_frameRateSlider->minimum();
float frameRateRange = m_fastFrameRate - m_slowFrameRate;
float normalizedSliderPosition = (frameRate - m_slowFrameRate )/ frameRateRange ;
float sliderTickValue = sliderRange* normalizedSliderPosition ;
float normalizedSliderPosition = ( frameRate - m_slowFrameRate ) / frameRateRange;
float sliderTickValue = sliderRange * normalizedSliderPosition;
m_frameRateSlider->blockSignals(true);
m_frameRateSlider->setValue(static_cast<int>(sliderTickValue));
m_frameRateSlider->blockSignals(false);
m_frameRateSlider->blockSignals( true );
m_frameRateSlider->setValue( static_cast<int>( sliderTickValue ) );
m_frameRateSlider->blockSignals( false );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void AnimationToolBar::setTimeStepStrings(const QStringList& timeStepStrings)
void AnimationToolBar::setTimeStepStrings( const QStringList& timeStepStrings )
{
if (timeStepStrings.empty())
if ( timeStepStrings.empty() )
{
m_hasAutoTimeStepStrings = true;
}
@ -265,29 +265,29 @@ void AnimationToolBar::setTimeStepStrings(const QStringList& timeStepStrings)
m_hasAutoTimeStepStrings = false;
}
m_timestepCombo->blockSignals(true);
m_timestepCombo->blockSignals( true );
m_timestepCombo->clear();
m_timestepCombo->addItems(timeStepStrings);
m_timestepCombo->addItems( timeStepStrings );
m_timestepCombo->blockSignals(false);
m_timestepCombo->blockSignals( false );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void AnimationToolBar::setCurrentTimeStepIndex(int index)
void AnimationToolBar::setCurrentTimeStepIndex( int index )
{
m_timestepCombo->blockSignals(true);
m_timestepCombo->setCurrentIndex(index);
m_timestepCombo->blockSignals( true );
m_timestepCombo->setCurrentIndex( index );
updateAnimationButtons();
m_timestepCombo->blockSignals(false);
m_timestepCombo->blockSignals( false );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void AnimationToolBar::slotFrameRateSliderChanged(int sliderTickValue)
void AnimationToolBar::slotFrameRateSliderChanged( int sliderTickValue )
{
float sliderRange = m_frameRateSlider->maximum() - m_frameRateSlider->minimum();
float normalizedSliderPosition = sliderTickValue / sliderRange;
@ -295,26 +295,26 @@ void AnimationToolBar::slotFrameRateSliderChanged(int sliderTickValue)
float frameRateRange = m_fastFrameRate - m_slowFrameRate;
float newFrameRate = m_slowFrameRate + frameRateRange * normalizedSliderPosition;
if (newFrameRate > m_fastFrameRate)
if ( newFrameRate > m_fastFrameRate )
{
newFrameRate = m_fastFrameRate;
}
if (newFrameRate < m_slowFrameRate)
if ( newFrameRate < m_slowFrameRate )
{
newFrameRate = m_slowFrameRate;
}
setFrameRate(newFrameRate);
setFrameRate( newFrameRate );
if(!m_activeAnimationControl.isNull()) m_activeAnimationControl->setTimeout((int)(1.0/newFrameRate * 1000));
if ( !m_activeAnimationControl.isNull() )
m_activeAnimationControl->setTimeout( (int)( 1.0 / newFrameRate * 1000 ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void AnimationToolBar::setSlowFrameRate(float frameRate)
void AnimationToolBar::setSlowFrameRate( float frameRate )
{
m_slowFrameRate = frameRate;
}
@ -322,28 +322,27 @@ void AnimationToolBar::setSlowFrameRate(float frameRate)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void AnimationToolBar::setFastFrameRate(float frameRate)
void AnimationToolBar::setFastFrameRate( float frameRate )
{
m_fastFrameRate = frameRate;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void AnimationToolBar::slotUpdateTimestepList(int frameCount)
void AnimationToolBar::slotUpdateTimestepList( int frameCount )
{
QStringList timeStepNames;
for (int vIdx = 0; vIdx < frameCount; ++vIdx)
for ( int vIdx = 0; vIdx < frameCount; ++vIdx )
{
timeStepNames.append(QString().setNum(vIdx));
timeStepNames.append( QString().setNum( vIdx ) );
}
m_timestepCombo->blockSignals(true);
m_timestepCombo->blockSignals( true );
m_timestepCombo->clear();
m_timestepCombo->addItems(timeStepNames);
m_timestepCombo->addItems( timeStepNames );
updateAnimationButtons();
m_timestepCombo->blockSignals(false);
m_timestepCombo->blockSignals( false );
}
//--------------------------------------------------------------------------------------------------
@ -351,7 +350,7 @@ void AnimationToolBar::slotUpdateTimestepList(int frameCount)
//--------------------------------------------------------------------------------------------------
void AnimationToolBar::playPauseChanged()
{
if (m_activeAnimationControl->isActive())
if ( m_activeAnimationControl->isActive() )
{
m_animPauseAction->trigger();
updateAnimationButtons();
@ -366,15 +365,18 @@ void AnimationToolBar::playPauseChanged()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void AnimationToolBar::slotUpdateAnimationGuiFromFrameIndex(int value)
void AnimationToolBar::slotUpdateAnimationGuiFromFrameIndex( int value )
{
// Update only the combo box index, but do not set current frame
// Disconnect the signal temporarily when updating UI
disconnect(m_timestepCombo, SIGNAL(currentIndexChanged(int)), m_activeAnimationControl, SLOT(setCurrentFrame(int)));
m_timestepCombo->setCurrentIndex(value);
disconnect( m_timestepCombo,
SIGNAL( currentIndexChanged( int ) ),
m_activeAnimationControl,
SLOT( setCurrentFrame( int ) ) );
m_timestepCombo->setCurrentIndex( value );
updateAnimationButtons();
connect(m_timestepCombo, SIGNAL(currentIndexChanged(int)), m_activeAnimationControl, SLOT(setCurrentFrame(int)));
connect( m_timestepCombo, SIGNAL( currentIndexChanged( int ) ), m_activeAnimationControl, SLOT( setCurrentFrame( int ) ) );
}
} // End namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#pragma once
#include <QPointer>
@ -60,30 +59,31 @@ class AnimationToolBar : public QToolBar
Q_OBJECT
public:
explicit AnimationToolBar(QWidget *parent = nullptr);
AnimationToolBar(const QString &title, QWidget *parent = nullptr);
explicit AnimationToolBar( QWidget* parent = nullptr );
AnimationToolBar( const QString& title, QWidget* parent = nullptr );
void connectAnimationControl(caf::FrameAnimationControl* animationControl);
void connectAnimationControl( caf::FrameAnimationControl* animationControl );
void setTimeStepStrings(const QStringList& timeStepStrings);
void setTimeStepStrings( const QStringList& timeStepStrings );
void setFrameRate(double frameRate);
void setSlowFrameRate(float frameRate);
void setFastFrameRate(float frameRate);
void setFrameRate( double frameRate );
void setSlowFrameRate( float frameRate );
void setFastFrameRate( float frameRate );
void setCurrentTimeStepIndex(int index);
void setCurrentTimeStepIndex( int index );
public slots:
void slotUpdateTimestepList(int frameCount);
void slotUpdateTimestepList( int frameCount );
void playPauseChanged();
private slots:
void slotFrameRateSliderChanged(int value);
void slotUpdateAnimationGuiFromFrameIndex(int value);
void slotFrameRateSliderChanged( int value );
void slotUpdateAnimationGuiFromFrameIndex( int value );
private:
void init();
void updateAnimationButtons();
private:
QAction* m_animSkipToStartAction;
QAction* m_animStepBackwardAction;
@ -109,5 +109,4 @@ private:
bool m_hasAutoTimeStepStrings;
};
} // End namespace caf

View File

@ -34,15 +34,12 @@
//
//##################################################################################################
#include "cafFrameAnimationControl.h"
#include <QTimer>
namespace caf
{
//==================================================================================================
///
/// \class RIAnimationControl
@ -57,11 +54,11 @@ static const int TIMEOUT_DEFAULT = 100;
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
FrameAnimationControl::FrameAnimationControl(QObject* parent)
: QObject(parent)
FrameAnimationControl::FrameAnimationControl( QObject* parent )
: QObject( parent )
{
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), SLOT(slotTimerTriggered()));
m_timer = new QTimer( this );
connect( m_timer, SIGNAL( timeout() ), SLOT( slotTimerTriggered() ) );
setDefault();
}
@ -71,12 +68,12 @@ FrameAnimationControl::FrameAnimationControl(QObject* parent)
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::setDefault()
{
setCurrentFrame(0);
setNumFrames(0);
setTimeout(TIMEOUT_DEFAULT);
setForward(true);
setRepeatFromStart(false);
setRepeatFwdBwd(false);
setCurrentFrame( 0 );
setNumFrames( 0 );
setTimeout( TIMEOUT_DEFAULT );
setForward( true );
setRepeatFromStart( false );
setRepeatFwdBwd( false );
// m_lastTimeStamp = 0;
}
@ -85,7 +82,7 @@ void FrameAnimationControl::setDefault()
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::start()
{
m_timer->start(m_timeout);
m_timer->start( m_timeout );
}
//--------------------------------------------------------------------------------------------------
@ -110,10 +107,10 @@ void FrameAnimationControl::pause()
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::stepForward()
{
if (m_currentFrame < m_numFrames - 1)
if ( m_currentFrame < m_numFrames - 1 )
{
m_timer->stop();
setCurrentFrame(m_currentFrame + 1);
setCurrentFrame( m_currentFrame + 1 );
}
}
@ -122,10 +119,10 @@ void FrameAnimationControl::stepForward()
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::stepBackward()
{
if (m_currentFrame >= 1)
if ( m_currentFrame >= 1 )
{
m_timer->stop();
setCurrentFrame(m_currentFrame - 1);
setCurrentFrame( m_currentFrame - 1 );
}
}
@ -140,12 +137,12 @@ bool FrameAnimationControl::isActive() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::setCurrentFrame(int frameIndex)
void FrameAnimationControl::setCurrentFrame( int frameIndex )
{
if (frameIndex >= 0)
if ( frameIndex >= 0 )
{
m_currentFrame = frameIndex;
emit changeFrame(m_currentFrame);
emit changeFrame( m_currentFrame );
}
}
@ -162,9 +159,9 @@ int FrameAnimationControl::currentFrame() const
/// Used when views are linked and need to update current frame without emitting a signal
/// Emitting a signal will cause infinite recursion
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::setCurrentFrameOnly(int frameIndex)
void FrameAnimationControl::setCurrentFrameOnly( int frameIndex )
{
if (frameIndex >= 0)
if ( frameIndex >= 0 )
{
m_currentFrame = frameIndex;
}
@ -173,14 +170,13 @@ void FrameAnimationControl::setCurrentFrameOnly(int frameIndex)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::setNumFrames(int numFrames)
void FrameAnimationControl::setNumFrames( int numFrames )
{
m_numFrames = numFrames < 0 ? 0 : numFrames;
emit frameCountChanged(m_numFrames);
if (m_currentFrame >= numFrames ) m_currentFrame = 0; // Should we emit frameChanged ?
emit frameCountChanged( m_numFrames );
if ( m_currentFrame >= numFrames ) m_currentFrame = 0; // Should we emit frameChanged ?
}
//--------------------------------------------------------------------------------------------------
@ -194,10 +190,10 @@ int FrameAnimationControl::numFrames() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::setTimeout(int milliSeconds)
void FrameAnimationControl::setTimeout( int milliSeconds )
{
m_timeout = milliSeconds < 0 ? 0 : milliSeconds;
if (isActive()) start();
if ( isActive() ) start();
}
//--------------------------------------------------------------------------------------------------
@ -211,7 +207,7 @@ int FrameAnimationControl::timeout() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::setForward(bool forward)
void FrameAnimationControl::setForward( bool forward )
{
m_forward = forward;
}
@ -227,10 +223,10 @@ bool FrameAnimationControl::forward() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::setRepeatFromStart(bool turnRepeatOn)
void FrameAnimationControl::setRepeatFromStart( bool turnRepeatOn )
{
m_repeatFromStart = turnRepeatOn;
if (turnRepeatOn) m_repeatFwdBwd = false;
if ( turnRepeatOn ) m_repeatFwdBwd = false;
}
//--------------------------------------------------------------------------------------------------
@ -244,10 +240,10 @@ bool FrameAnimationControl::isRepeatingFromStart() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::setRepeatFwdBwd(bool turnRepeatOn)
void FrameAnimationControl::setRepeatFwdBwd( bool turnRepeatOn )
{
m_repeatFwdBwd = turnRepeatOn;
if (turnRepeatOn) m_repeatFromStart = false;
if ( turnRepeatOn ) m_repeatFromStart = false;
}
//--------------------------------------------------------------------------------------------------
@ -263,7 +259,7 @@ bool FrameAnimationControl::isRepeatingFwdBwd() const
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::slotPlayFwd()
{
setForward(true);
setForward( true );
start();
}
//--------------------------------------------------------------------------------------------------
@ -271,7 +267,7 @@ void FrameAnimationControl::slotPlayFwd()
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::slotPlayBwd()
{
setForward(false);
setForward( false );
start();
}
//--------------------------------------------------------------------------------------------------
@ -312,17 +308,17 @@ void FrameAnimationControl::slotStepBackward()
void FrameAnimationControl::slotTimerTriggered()
{
// Update current frame according to settings
if (m_forward)
if ( m_forward )
{
if (m_currentFrame + 1 >= m_numFrames)
if ( m_currentFrame + 1 >= m_numFrames )
{
if (m_repeatFromStart)
if ( m_repeatFromStart )
{
m_currentFrame = 0;
}
else if (m_repeatFwdBwd)
else if ( m_repeatFwdBwd )
{
setForward(false);
setForward( false );
m_currentFrame--;
}
else
@ -338,15 +334,15 @@ void FrameAnimationControl::slotTimerTriggered()
}
else
{
if (m_currentFrame - 1 < 0)
if ( m_currentFrame - 1 < 0 )
{
if (m_repeatFromStart)
if ( m_repeatFromStart )
{
m_currentFrame = m_numFrames - 1;
}
else if (m_repeatFwdBwd)
else if ( m_repeatFwdBwd )
{
setForward(true);
setForward( true );
m_currentFrame++; // Ends up as 1 (second frame) makes 2 1 0 1 2 and not 2 1 0 0 1 2
}
else
@ -362,7 +358,7 @@ void FrameAnimationControl::slotTimerTriggered()
}
// Emit signal with updated frame index
emit changeFrame(m_currentFrame);
emit changeFrame( m_currentFrame );
}
//--------------------------------------------------------------------------------------------------
@ -371,7 +367,7 @@ void FrameAnimationControl::slotTimerTriggered()
void FrameAnimationControl::skipToEnd()
{
m_timer->stop();
setCurrentFrame(m_numFrames-1);
setCurrentFrame( m_numFrames - 1 );
}
//--------------------------------------------------------------------------------------------------
@ -380,7 +376,7 @@ void FrameAnimationControl::skipToEnd()
void FrameAnimationControl::skipToStart()
{
m_timer->stop();
setCurrentFrame(0);
setCurrentFrame( 0 );
}
//--------------------------------------------------------------------------------------------------
@ -402,19 +398,17 @@ void FrameAnimationControl::slotSkipToStart()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::slotRepeatFromStart(bool turnRepeatOn)
void FrameAnimationControl::slotRepeatFromStart( bool turnRepeatOn )
{
setRepeatFromStart(turnRepeatOn);
setRepeatFromStart( turnRepeatOn );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FrameAnimationControl::slotRepeatFwdBwd(bool turnRepeatOn)
void FrameAnimationControl::slotRepeatFwdBwd( bool turnRepeatOn )
{
setRepeatFwdBwd(turnRepeatOn);
setRepeatFwdBwd( turnRepeatOn );
}
} // End namespace caf

View File

@ -34,17 +34,14 @@
//
//##################################################################################################
#pragma once
#include <QObject>
class QTimer;
namespace caf
{
//==================================================================================================
///
//==================================================================================================
@ -53,16 +50,16 @@ class FrameAnimationControl : public QObject
Q_OBJECT
public:
explicit FrameAnimationControl(QObject* parent = nullptr);
explicit FrameAnimationControl( QObject* parent = nullptr );
void setNumFrames(int numFrames);
void setNumFrames( int numFrames );
int numFrames() const;
int currentFrame() const;
void setCurrentFrameOnly(int frameIndex);
void setCurrentFrameOnly( int frameIndex );
bool isActive() const;
void setTimeout(int milliSeconds);
void setTimeout( int milliSeconds );
int timeout() const;
bool isRepeatingFromStart() const;
@ -75,16 +72,16 @@ public slots:
void slotPause();
void slotStepForward();
void slotStepBackward();
void setCurrentFrame(int frameIndex);
void setCurrentFrame( int frameIndex );
void slotSkipToEnd();
void slotSkipToStart();
void slotRepeatFromStart(bool turnRepeatOn);
void slotRepeatFwdBwd(bool turnRepeatOn);
void slotRepeatFromStart( bool turnRepeatOn );
void slotRepeatFwdBwd( bool turnRepeatOn );
signals:
void changeFrame(int frameIndex);
void changeFrame( int frameIndex );
void endAnimation();
void frameCountChanged(int frameCount);
void frameCountChanged( int frameCount );
private slots:
void slotTimerTriggered();
@ -98,12 +95,12 @@ private:
void skipToEnd();
void skipToStart();
void setForward(bool forward);
void setForward( bool forward );
bool forward() const;
void setRepeatFromStart(bool repeat);
void setRepeatFromStart( bool repeat );
void setRepeatFwdBwd(bool repeat);
void setRepeatFwdBwd( bool repeat );
void setDefault();
@ -119,5 +116,4 @@ private:
bool m_repeatFwdBwd;
};
} // End namespace caf

View File

@ -44,33 +44,33 @@ using namespace caf;
///
//--------------------------------------------------------------------------------------------------
PopupMenuButton::PopupMenuButton(QWidget* parentWidget,
PopupMenuButton::PopupMenuButton( QWidget* parentWidget,
Qt::Orientation orientation /*= Qt::Horizontal*/,
ToolButtonPopupMode popupMode /*=InstantPopup*/)
: QToolButton(parentWidget)
ToolButtonPopupMode popupMode /*=InstantPopup*/ )
: QToolButton( parentWidget )
{
if (orientation == Qt::Horizontal)
if ( orientation == Qt::Horizontal )
{
m_layout = new QHBoxLayout(this);
m_layout = new QHBoxLayout( this );
}
else
{
m_layout = new QVBoxLayout(this);
m_layout = new QVBoxLayout( this );
}
m_layout->setContentsMargins(QMargins(2, 2, 2, 2));
m_layout->setContentsMargins( QMargins( 2, 2, 2, 2 ) );
QMenu* menu = new QMenu(this);
menu->setLayout(m_layout);
setMenu(menu);
QMenu* menu = new QMenu( this );
menu->setLayout( m_layout );
setMenu( menu );
setCheckable(true);
setPopupMode(popupMode);
setCheckable( true );
setPopupMode( popupMode );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void caf::PopupMenuButton::addWidget(QWidget* widget, int stretch, Qt::Alignment alignment)
void caf::PopupMenuButton::addWidget( QWidget* widget, int stretch, Qt::Alignment alignment )
{
m_layout->addWidget(widget, stretch, alignment);
m_layout->addWidget( widget, stretch, alignment );
}

View File

@ -50,14 +50,14 @@ class PopupMenuButton : public QToolButton
Q_OBJECT
public:
PopupMenuButton(QWidget* parentWidget,
PopupMenuButton( QWidget* parentWidget,
Qt::Orientation orientation = Qt::Horizontal,
ToolButtonPopupMode popupMode = InstantPopup);
ToolButtonPopupMode popupMode = InstantPopup );
void addWidget(QWidget* widget, int stretch = 0, Qt::Alignment alignment = Qt::Alignment());
void addWidget( QWidget* widget, int stretch = 0, Qt::Alignment alignment = Qt::Alignment() );
private:
QPointer<QBoxLayout> m_layout;
};
}
} // namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#include "cafCmdExecCommandManager.h"
#include "cafCmdExecuteCommand.h"
@ -50,43 +49,31 @@
class UndoRedoWrapper : public QUndoCommand
{
public:
explicit UndoRedoWrapper(caf::CmdExecuteCommand* executeCommand)
explicit UndoRedoWrapper( caf::CmdExecuteCommand* executeCommand )
{
m_executeCommand = executeCommand;
setText(m_executeCommand->name());
setText( m_executeCommand->name() );
}
~UndoRedoWrapper() override
{
delete m_executeCommand;
}
~UndoRedoWrapper() override { delete m_executeCommand; }
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void undo() override
{
m_executeCommand->undo();
}
void undo() override { m_executeCommand->undo(); }
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void redo() override
{
m_executeCommand->redo();
}
void redo() override { m_executeCommand->redo(); }
private:
caf::CmdExecuteCommand* m_executeCommand;
};
namespace caf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@ -111,12 +98,12 @@ CmdExecCommandManager* CmdExecCommandManager::instance()
//--------------------------------------------------------------------------------------------------
void CmdExecCommandManager::activateCommandSystem()
{
if (!m_commandFeatureInterface)
if ( !m_commandFeatureInterface )
{
m_commandFeatureInterface = new CmdUiCommandSystemImpl;
}
PdmUiCommandSystemProxy::instance()->setCommandInterface(m_commandFeatureInterface);
PdmUiCommandSystemProxy::instance()->setCommandInterface( m_commandFeatureInterface );
}
//--------------------------------------------------------------------------------------------------
@ -124,17 +111,17 @@ void CmdExecCommandManager::activateCommandSystem()
//--------------------------------------------------------------------------------------------------
void CmdExecCommandManager::deactivateCommandSystem()
{
PdmUiCommandSystemProxy::instance()->setCommandInterface(nullptr);
PdmUiCommandSystemProxy::instance()->setCommandInterface( nullptr );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdExecCommandManager::enableUndoCommandSystem(bool enable)
void CmdExecCommandManager::enableUndoCommandSystem( bool enable )
{
this->activateCommandSystem();
m_commandFeatureInterface->enableUndoFeature(enable);
m_commandFeatureInterface->enableUndoFeature( enable );
}
//--------------------------------------------------------------------------------------------------
@ -148,14 +135,14 @@ QUndoStack* CmdExecCommandManager::undoStack()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdExecCommandManager::processExecuteCommand(CmdExecuteCommand* executeCommand)
void CmdExecCommandManager::processExecuteCommand( CmdExecuteCommand* executeCommand )
{
if (isUndoEnabledForCurrentCommand(executeCommand))
if ( isUndoEnabledForCurrentCommand( executeCommand ) )
{
// Transfer ownership of execute command to wrapper object
UndoRedoWrapper* undoRedoWrapper = new UndoRedoWrapper(executeCommand);
UndoRedoWrapper* undoRedoWrapper = new UndoRedoWrapper( executeCommand );
m_undoStack->push(undoRedoWrapper);
m_undoStack->push( undoRedoWrapper );
}
else
{
@ -169,29 +156,30 @@ void CmdExecCommandManager::processExecuteCommand(CmdExecuteCommand* executeComm
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdExecCommandManager::processExecuteCommandsAsMacro(const QString& macroName, std::vector<CmdExecuteCommand*>& commands)
void CmdExecCommandManager::processExecuteCommandsAsMacro( const QString& macroName,
std::vector<CmdExecuteCommand*>& commands )
{
if (commands.size() == 0)
if ( commands.size() == 0 )
{
return;
}
if (isUndoEnabledForCurrentCommand(commands[0]))
if ( isUndoEnabledForCurrentCommand( commands[0] ) )
{
m_undoStack->beginMacro(macroName);
for (size_t i = 0; i < commands.size(); i++)
m_undoStack->beginMacro( macroName );
for ( size_t i = 0; i < commands.size(); i++ )
{
UndoRedoWrapper* undoRedoWrapper = new UndoRedoWrapper(commands[i]);
m_undoStack->push(undoRedoWrapper);
UndoRedoWrapper* undoRedoWrapper = new UndoRedoWrapper( commands[i] );
m_undoStack->push( undoRedoWrapper );
}
m_undoStack->endMacro();
}
else
{
for (size_t i = 0; i < commands.size(); i++)
for ( size_t i = 0; i < commands.size(); i++ )
{
CmdExecuteCommand* executeCommand = commands[i];
if (executeCommand)
if ( executeCommand )
{
executeCommand->redo();
delete executeCommand;
@ -203,15 +191,15 @@ void CmdExecCommandManager::processExecuteCommandsAsMacro(const QString& macroNa
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool CmdExecCommandManager::isUndoEnabledForCurrentCommand(CmdExecuteCommand* command)
bool CmdExecCommandManager::isUndoEnabledForCurrentCommand( CmdExecuteCommand* command )
{
bool useUndo = false;
if (dynamic_cast<CmdFieldChangeExec*>(command) && m_commandFeatureInterface->disableUndoForFieldChange())
if ( dynamic_cast<CmdFieldChangeExec*>( command ) && m_commandFeatureInterface->disableUndoForFieldChange() )
{
useUndo = false;
}
else if (m_commandFeatureInterface && m_commandFeatureInterface->isUndoEnabled())
else if ( m_commandFeatureInterface && m_commandFeatureInterface->isUndoEnabled() )
{
useUndo = true;
}
@ -219,5 +207,4 @@ bool CmdExecCommandManager::isUndoEnabledForCurrentCommand(CmdExecuteCommand* co
return useUndo;
}
} // end namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#pragma once
#include <QPointer>
@ -46,7 +45,6 @@ class QString;
namespace caf
{
class CmdExecuteCommand;
class CmdUiCommandSystemImpl;
@ -58,31 +56,31 @@ class CmdExecCommandManager
public:
static CmdExecCommandManager* instance();
CmdExecCommandManager(const CmdExecCommandManager&) = delete;
CmdExecCommandManager& operator=(const CmdExecCommandManager&) = delete;
CmdExecCommandManager( const CmdExecCommandManager& ) = delete;
CmdExecCommandManager& operator=( const CmdExecCommandManager& ) = delete;
// When the undoFeature is enabled, execute commands are inserted in the undo stack
// The application can use the QUndoStack to display/modify execute commands wrapped in QUndoCommand objects
void enableUndoCommandSystem(bool enable);
void enableUndoCommandSystem( bool enable );
QUndoStack* undoStack();
// If undo system is enabled, the PdmExecuteCommand is wrapped in a QUndoCommand and inserted in the QUndoStack.
// If undo is not possible (undo system not enabled, or pdm object has disabled undo),
// the PdmExecuteCommand is executed and deleted
void processExecuteCommand(CmdExecuteCommand* executeCommand);
void processExecuteCommandsAsMacro(const QString& macroName, std::vector<CmdExecuteCommand*>& commands);
void processExecuteCommand( CmdExecuteCommand* executeCommand );
void processExecuteCommandsAsMacro( const QString& macroName, std::vector<CmdExecuteCommand*>& commands );
private:
CmdExecCommandManager();
// Creates the object (CmdUiCommandSystemImpl) used to communicate from UI editors to advanced parts of the command system
// This includes support for undo system and default command features for add/delete of items in PdmChildArrayFieldHandle
// and creation of field changed commands so a change in an editor can be put into undo/redo
// CmdUiCommandSystemImpl is a requirement for using the undo system
// Creates the object (CmdUiCommandSystemImpl) used to communicate from UI editors to advanced parts of the command
// system This includes support for undo system and default command features for add/delete of items in
// PdmChildArrayFieldHandle and creation of field changed commands so a change in an editor can be put into
// undo/redo CmdUiCommandSystemImpl is a requirement for using the undo system
void activateCommandSystem();
void deactivateCommandSystem();
bool isUndoEnabledForCurrentCommand(CmdExecuteCommand* command);
bool isUndoEnabledForCurrentCommand( CmdExecuteCommand* command );
friend class CmdExecCommandSystemActivator;
friend class CmdExecCommandSystemDeactivator;
@ -99,15 +97,9 @@ private:
class CmdExecCommandSystemDeactivator
{
public:
CmdExecCommandSystemDeactivator()
{
CmdExecCommandManager::instance()->deactivateCommandSystem();
}
CmdExecCommandSystemDeactivator() { CmdExecCommandManager::instance()->deactivateCommandSystem(); }
~CmdExecCommandSystemDeactivator()
{
CmdExecCommandManager::instance()->activateCommandSystem();
}
~CmdExecCommandSystemDeactivator() { CmdExecCommandManager::instance()->activateCommandSystem(); }
};
//==================================================================================================
@ -116,15 +108,9 @@ public:
class CmdExecCommandSystemActivator
{
public:
CmdExecCommandSystemActivator()
{
CmdExecCommandManager::instance()->activateCommandSystem();
}
CmdExecCommandSystemActivator() { CmdExecCommandManager::instance()->activateCommandSystem(); }
~CmdExecCommandSystemActivator()
{
CmdExecCommandManager::instance()->deactivateCommandSystem();
}
~CmdExecCommandSystemActivator() { CmdExecCommandManager::instance()->deactivateCommandSystem(); }
};
} // end namespace caf

View File

@ -34,14 +34,12 @@
//
//##################################################################################################
#pragma once
#include <QString>
namespace caf
{
class NotificationCenter;
class PdmObjectHandle;
@ -51,12 +49,9 @@ class PdmObjectHandle;
class CmdExecuteCommand
{
public:
explicit CmdExecuteCommand(NotificationCenter* notificationCenter)
{
m_notificationCenter = notificationCenter;
}
explicit CmdExecuteCommand( NotificationCenter* notificationCenter ) { m_notificationCenter = notificationCenter; }
virtual ~CmdExecuteCommand() { };
virtual ~CmdExecuteCommand(){};
virtual QString name() = 0;
virtual void redo() = 0;
@ -66,6 +61,4 @@ protected:
NotificationCenter* m_notificationCenter;
};
} // end namespace caf

View File

@ -46,12 +46,11 @@
namespace caf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdFeature::CmdFeature()
: m_triggerModelChange(true)
: m_triggerModelChange( true )
{
}
@ -60,7 +59,6 @@ CmdFeature::CmdFeature()
//--------------------------------------------------------------------------------------------------
CmdFeature::~CmdFeature()
{
}
//--------------------------------------------------------------------------------------------------
@ -68,51 +66,51 @@ CmdFeature::~CmdFeature()
//--------------------------------------------------------------------------------------------------
QAction* CmdFeature::action()
{
return this->actionWithCustomText(QString(""));
return this->actionWithCustomText( QString( "" ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QAction* CmdFeature::actionWithCustomText(const QString& customText)
QAction* CmdFeature::actionWithCustomText( const QString& customText )
{
return actionWithUserData(customText, QVariant());
return actionWithUserData( customText, QVariant() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QAction* CmdFeature::actionWithUserData(const QString& customText, const QVariant& userData)
QAction* CmdFeature::actionWithUserData( const QString& customText, const QVariant& userData )
{
QAction* action = nullptr;
std::map<QString, QAction*>::iterator it;
it = m_customTextToActionMap.find(customText);
it = m_customTextToActionMap.find( customText );
if (it != m_customTextToActionMap.end() && it->second != NULL)
if ( it != m_customTextToActionMap.end() && it->second != NULL )
{
action = it->second;
}
else
{
action = new QAction(this);
action = new QAction( this );
connect(action, SIGNAL(triggered(bool)), SLOT(actionTriggered(bool)));
m_customTextToActionMap[customText]= action;
connect( action, SIGNAL( triggered( bool ) ), SLOT( actionTriggered( bool ) ) );
m_customTextToActionMap[customText] = action;
}
if (!userData.isNull())
if ( !userData.isNull() )
{
action->setData(userData);
action->setData( userData );
}
if (dynamic_cast<QApplication*>(QCoreApplication::instance()))
if ( dynamic_cast<QApplication*>( QCoreApplication::instance() ) )
{
this->setupActionLook(action);
this->setupActionLook( action );
}
if (!customText.isEmpty())
if ( !customText.isEmpty() )
{
action->setText(customText);
action->setText( customText );
}
return action;
@ -126,9 +124,9 @@ void CmdFeature::refreshEnabledState()
std::map<QString, QAction*>::iterator it;
bool isEnabled = this->isCommandEnabled();
for (it = m_customTextToActionMap.begin(); it != m_customTextToActionMap.end(); ++it)
for ( it = m_customTextToActionMap.begin(); it != m_customTextToActionMap.end(); ++it )
{
it->second->setEnabled(isEnabled);
it->second->setEnabled( isEnabled );
}
}
@ -140,12 +138,12 @@ void CmdFeature::refreshCheckedState()
std::map<QString, QAction*>::iterator it;
bool isChecked = this->isCommandChecked();
for (it = m_customTextToActionMap.begin(); it != m_customTextToActionMap.end(); ++it)
for ( it = m_customTextToActionMap.begin(); it != m_customTextToActionMap.end(); ++it )
{
QAction* act = it->second;
if (act->isCheckable())
if ( act->isCheckable() )
{
it->second->setChecked(isChecked);
it->second->setChecked( isChecked );
}
}
}
@ -161,25 +159,25 @@ bool CmdFeature::canFeatureBeExecuted()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdFeature::applyShortcutWithHintToAction(QAction* action, const QKeySequence& keySequence)
void CmdFeature::applyShortcutWithHintToAction( QAction* action, const QKeySequence& keySequence )
{
action->setShortcut(keySequence);
action->setShortcut( keySequence );
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
#if ( QT_VERSION >= QT_VERSION_CHECK( 5, 10, 0 ) )
// Qt made keyboard shortcuts in context menus platform dependent in Qt 5.10
// With no global way of removing it.
action->setShortcutVisibleInContextMenu(true);
action->setShortcutVisibleInContextMenu( true );
#endif
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdFeature::actionTriggered(bool isChecked)
void CmdFeature::actionTriggered( bool isChecked )
{
this->onActionTriggered(isChecked);
this->onActionTriggered( isChecked );
if (m_triggerModelChange)
if ( m_triggerModelChange )
{
caf::PdmUiModelChangeDetector::instance()->setModelChanged();
}
@ -207,8 +205,8 @@ void CmdFeature::disableModelChangeContribution()
//--------------------------------------------------------------------------------------------------
const QVariant CmdFeature::userData() const
{
QAction* action = qobject_cast<QAction*>(sender());
CAF_ASSERT(action);
QAction* action = qobject_cast<QAction*>( sender() );
CAF_ASSERT( action );
return action->data();
}

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#pragma once
#include "cafFactory.h"
@ -50,17 +49,19 @@ class QKeySequence;
class QString;
#define CAF_CMD_HEADER_INIT \
public: \
public: \
static const std::string& idNameStatic()
#define CAF_CMD_SOURCE_INIT(ClassName, CommandIdName)\
const std::string& ClassName::idNameStatic() { static std::string id = CommandIdName; return id;} \
CAF_FACTORY_REGISTER(caf::CmdFeature, ClassName, std::string, ClassName::idNameStatic())
#define CAF_CMD_SOURCE_INIT( ClassName, CommandIdName ) \
const std::string& ClassName::idNameStatic() \
{ \
static std::string id = CommandIdName; \
return id; \
} \
CAF_FACTORY_REGISTER( caf::CmdFeature, ClassName, std::string, ClassName::idNameStatic() )
namespace caf
{
class CmdExecuteCommand;
//==================================================================================================
@ -78,21 +79,21 @@ public:
~CmdFeature() override;
QAction* action();
QAction* actionWithCustomText(const QString& customText);
QAction* actionWithUserData(const QString& customText, const QVariant& userData);
QAction* actionWithCustomText( const QString& customText );
QAction* actionWithUserData( const QString& customText, const QVariant& userData );
void refreshEnabledState();
void refreshCheckedState();
bool canFeatureBeExecuted();
static void applyShortcutWithHintToAction(QAction* action, const QKeySequence& keySequence);
static void applyShortcutWithHintToAction( QAction* action, const QKeySequence& keySequence );
public slots:
void actionTriggered(bool isChecked);
void actionTriggered( bool isChecked );
protected:
virtual void onActionTriggered(bool isChecked) = 0;
virtual void setupActionLook(QAction* actionToSetup) = 0;
virtual void onActionTriggered( bool isChecked ) = 0;
virtual void setupActionLook( QAction* actionToSetup ) = 0;
virtual bool isCommandEnabled() = 0;
virtual bool isCommandChecked();
@ -104,6 +105,4 @@ private:
bool m_triggerModelChange;
};
} // end namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#include "cafCmdFeatureManager.h"
#include "cafCmdFeature.h"
@ -46,8 +45,7 @@
namespace caf
{
typedef Factory<CmdFeature, std::string> CommandFeatureFactory;
typedef Factory<CmdFeature, std::string> CommandFeatureFactory;
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@ -58,9 +56,9 @@ CmdFeatureManager::CmdFeatureManager()
// of searching through all command features instead of having to use the string keys to
// be sure all command features are present.
std::vector<std::string> keys = CommandFeatureFactory::instance()->allKeys();
for (size_t i = 0; i < keys.size(); i++)
for ( size_t i = 0; i < keys.size(); i++ )
{
createFeature(keys[i]);
createFeature( keys[i] );
}
}
@ -69,7 +67,6 @@ CmdFeatureManager::CmdFeatureManager()
//--------------------------------------------------------------------------------------------------
CmdFeatureManager::~CmdFeatureManager()
{
}
//--------------------------------------------------------------------------------------------------
@ -85,9 +82,9 @@ CmdFeatureManager* CmdFeatureManager::instance()
/// Get action for the specified command.
/// The action is owned by the PdmCommandItemManager
//--------------------------------------------------------------------------------------------------
QAction* CmdFeatureManager::action(const QString& commandId)
QAction* CmdFeatureManager::action( const QString& commandId )
{
std::pair<CmdFeature*, size_t> featurePair = createFeature(commandId.toStdString());
std::pair<CmdFeature*, size_t> featurePair = createFeature( commandId.toStdString() );
QAction* act = featurePair.first->action();
m_actionToFeatureIdxMap[act] = featurePair.second;
@ -99,11 +96,11 @@ QAction* CmdFeatureManager::action(const QString& commandId)
/// Get action for the specified command, with custom action text
/// The action is owned by the PdmCommandItemManager
//--------------------------------------------------------------------------------------------------
QAction* CmdFeatureManager::action(const QString& commandId, const QString& customActionText)
QAction* CmdFeatureManager::action( const QString& commandId, const QString& customActionText )
{
std::pair<CmdFeature*, size_t> featurePair = createFeature(commandId.toStdString());
std::pair<CmdFeature*, size_t> featurePair = createFeature( commandId.toStdString() );
QAction* act = featurePair.first->actionWithCustomText(customActionText);
QAction* act = featurePair.first->actionWithCustomText( customActionText );
m_actionToFeatureIdxMap[act] = featurePair.second;
return act;
@ -113,11 +110,13 @@ QAction* CmdFeatureManager::action(const QString& commandId, const QString& cust
/// Get action for the specified command, with custom action text
/// The action is owned by the PdmCommandItemManager
//--------------------------------------------------------------------------------------------------
QAction* CmdFeatureManager::actionWithUserData(const QString& commandId, const QString& customActionText, const QVariant& userData)
QAction* CmdFeatureManager::actionWithUserData( const QString& commandId,
const QString& customActionText,
const QVariant& userData )
{
std::pair<CmdFeature*, size_t> featurePair = createFeature(commandId.toStdString());
std::pair<CmdFeature*, size_t> featurePair = createFeature( commandId.toStdString() );
QAction* act = featurePair.first->actionWithUserData(customActionText, userData);
QAction* act = featurePair.first->actionWithUserData( customActionText, userData );
m_actionToFeatureIdxMap[act] = featurePair.second;
return act;
@ -126,58 +125,58 @@ QAction* CmdFeatureManager::actionWithUserData(const QString& commandId, const Q
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::pair<CmdFeature*, size_t> CmdFeatureManager::createFeature(const std::string& commandId)
std::pair<CmdFeature*, size_t> CmdFeatureManager::createFeature( const std::string& commandId )
{
std::pair<CmdFeature*, size_t> featurePair = this->findExistingCmdFeature(commandId);
std::pair<CmdFeature*, size_t> featurePair = this->findExistingCmdFeature( commandId );
if (featurePair.first)
if ( featurePair.first )
{
return featurePair;
}
CmdFeature* feature = CommandFeatureFactory::instance()->create(commandId);
CAF_ASSERT(feature); // The command ID is not known in the factory
CmdFeature* feature = CommandFeatureFactory::instance()->create( commandId );
CAF_ASSERT( feature ); // The command ID is not known in the factory
feature->setParent(this);
feature->setParent( this );
size_t index = m_commandFeatures.size();
m_commandFeatures.push_back(feature);
m_commandFeatures.push_back( feature );
m_commandIdToFeatureIdxMap[commandId] = index;
return std::make_pair(feature, index);
return std::make_pair( feature, index );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::pair<CmdFeature*, size_t> CmdFeatureManager::findExistingCmdFeature(const std::string& commandId)
std::pair<CmdFeature*, size_t> CmdFeatureManager::findExistingCmdFeature( const std::string& commandId )
{
std::map<std::string, size_t>::const_iterator it;
it = m_commandIdToFeatureIdxMap.find(commandId);
it = m_commandIdToFeatureIdxMap.find( commandId );
if (it != m_commandIdToFeatureIdxMap.end())
if ( it != m_commandIdToFeatureIdxMap.end() )
{
size_t itemIndex = it->second;
CmdFeature* item = m_commandFeatures[itemIndex];
item->refreshEnabledState();
return std::make_pair(item, itemIndex);
return std::make_pair( item, itemIndex );
}
else
{
return std::make_pair(static_cast<CmdFeature*>(nullptr), -1);
return std::make_pair( static_cast<CmdFeature*>( nullptr ), -1 );
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::CmdFeature* CmdFeatureManager::commandFeature(const std::string& commandId) const
caf::CmdFeature* CmdFeatureManager::commandFeature( const std::string& commandId ) const
{
std::map<std::string, size_t>::const_iterator it;
it = m_commandIdToFeatureIdxMap.find(commandId);
it = m_commandIdToFeatureIdxMap.find( commandId );
if (it != m_commandIdToFeatureIdxMap.end())
if ( it != m_commandIdToFeatureIdxMap.end() )
{
size_t itemIndex = it->second;
@ -192,15 +191,15 @@ caf::CmdFeature* CmdFeatureManager::commandFeature(const std::string& commandId)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdFeatureManager::refreshStates(const QStringList& commandIdList)
void CmdFeatureManager::refreshStates( const QStringList& commandIdList )
{
if (commandIdList.size() == 0)
if ( commandIdList.size() == 0 )
{
for (size_t i = 0; i < m_commandFeatures.size(); i++)
for ( size_t i = 0; i < m_commandFeatures.size(); i++ )
{
CmdFeature* cmdFeature = m_commandFeatures[i];
if (cmdFeature)
if ( cmdFeature )
{
cmdFeature->refreshEnabledState();
cmdFeature->refreshCheckedState();
@ -209,11 +208,11 @@ void CmdFeatureManager::refreshStates(const QStringList& commandIdList)
}
else
{
for (int i = 0; i < commandIdList.size(); i++)
for ( int i = 0; i < commandIdList.size(); i++ )
{
std::pair<CmdFeature*, size_t> featurePair = findExistingCmdFeature(commandIdList.at(i).toStdString());
std::pair<CmdFeature*, size_t> featurePair = findExistingCmdFeature( commandIdList.at( i ).toStdString() );
if (featurePair.first)
if ( featurePair.first )
{
featurePair.first->refreshEnabledState();
featurePair.first->refreshCheckedState();
@ -225,22 +224,22 @@ void CmdFeatureManager::refreshStates(const QStringList& commandIdList)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdFeatureManager::refreshEnabledState(const QStringList& commandIdList)
void CmdFeatureManager::refreshEnabledState( const QStringList& commandIdList )
{
if (commandIdList.size() == 0)
if ( commandIdList.size() == 0 )
{
for (size_t i = 0; i < m_commandFeatures.size(); i++)
for ( size_t i = 0; i < m_commandFeatures.size(); i++ )
{
m_commandFeatures[i]->refreshEnabledState();
}
}
else
{
for (int i = 0; i < commandIdList.size(); i++)
for ( int i = 0; i < commandIdList.size(); i++ )
{
std::pair<CmdFeature*, size_t> featurePair = findExistingCmdFeature(commandIdList.at(i).toStdString());
std::pair<CmdFeature*, size_t> featurePair = findExistingCmdFeature( commandIdList.at( i ).toStdString() );
if (featurePair.first)
if ( featurePair.first )
{
featurePair.first->refreshEnabledState();
}
@ -251,22 +250,22 @@ void CmdFeatureManager::refreshEnabledState(const QStringList& commandIdList)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdFeatureManager::refreshCheckedState(const QStringList& commandIdList)
void CmdFeatureManager::refreshCheckedState( const QStringList& commandIdList )
{
if (commandIdList.size() == 0)
if ( commandIdList.size() == 0 )
{
for (size_t i = 0; i < m_commandFeatures.size(); i++)
for ( size_t i = 0; i < m_commandFeatures.size(); i++ )
{
m_commandFeatures[i]->refreshCheckedState();
}
}
else
{
for (int i = 0; i < commandIdList.size(); i++)
for ( int i = 0; i < commandIdList.size(); i++ )
{
std::pair<CmdFeature*, size_t> featurePair = findExistingCmdFeature(commandIdList.at(i).toStdString());
std::pair<CmdFeature*, size_t> featurePair = findExistingCmdFeature( commandIdList.at( i ).toStdString() );
if (featurePair.first)
if ( featurePair.first )
{
featurePair.first->refreshCheckedState();
}
@ -277,30 +276,29 @@ void CmdFeatureManager::refreshCheckedState(const QStringList& commandIdList)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdFeature* CmdFeatureManager::getCommandFeature(const std::string& commandId)
CmdFeature* CmdFeatureManager::getCommandFeature( const std::string& commandId )
{
std::pair<CmdFeature*, size_t> featurePair = createFeature(commandId);
std::pair<CmdFeature*, size_t> featurePair = createFeature( commandId );
return featurePair.first;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<CmdFeature*> CmdFeatureManager::commandFeaturesMatchingSubString(const std::string& subString) const
std::vector<CmdFeature*> CmdFeatureManager::commandFeaturesMatchingSubString( const std::string& subString ) const
{
std::vector<CmdFeature*> matches;
std::vector<std::string> keys = CommandFeatureFactory::instance()->allKeys();
for (size_t i = 0; i < keys.size(); i++)
for ( size_t i = 0; i < keys.size(); i++ )
{
if (keys[i].find(subString) != std::string::npos)
if ( keys[i].find( subString ) != std::string::npos )
{
caf::CmdFeature* cmdFeature = commandFeature(keys[i]);
if (cmdFeature)
caf::CmdFeature* cmdFeature = commandFeature( keys[i] );
if ( cmdFeature )
{
matches.push_back(cmdFeature);
matches.push_back( cmdFeature );
}
}
}
@ -311,19 +309,19 @@ std::vector<CmdFeature*> CmdFeatureManager::commandFeaturesMatchingSubString(con
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<CmdFeature*> CmdFeatureManager::commandFeaturesMatchingKeyboardShortcut(const QKeySequence& keySequence) const
std::vector<CmdFeature*> CmdFeatureManager::commandFeaturesMatchingKeyboardShortcut( const QKeySequence& keySequence ) const
{
std::vector<CmdFeature*> matches;
std::vector<std::string> keys = CommandFeatureFactory::instance()->allKeys();
for (size_t i = 0; i < keys.size(); i++)
for ( size_t i = 0; i < keys.size(); i++ )
{
caf::CmdFeature* cmdFeature = commandFeature(keys[i]);
if (cmdFeature)
caf::CmdFeature* cmdFeature = commandFeature( keys[i] );
if ( cmdFeature )
{
if (cmdFeature->action()->shortcut().matches(keySequence) == QKeySequence::ExactMatch)
if ( cmdFeature->action()->shortcut().matches( keySequence ) == QKeySequence::ExactMatch )
{
matches.push_back(cmdFeature);
matches.push_back( cmdFeature );
}
}
}
@ -334,7 +332,7 @@ std::vector<CmdFeature*> CmdFeatureManager::commandFeaturesMatchingKeyboardShort
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdFeatureManager::setCurrentContextMenuTargetWidget(QWidget * targetWidget)
void CmdFeatureManager::setCurrentContextMenuTargetWidget( QWidget* targetWidget )
{
m_currentContextMenuTargetWidget = targetWidget;
}

View File

@ -34,16 +34,15 @@
//
//##################################################################################################
#pragma once
#include <vector>
#include <map>
#include <set>
#include <vector>
#include <QObject>
#include <QStringList>
#include <QPointer>
#include <QStringList>
class QAction;
class QKeySequence;
@ -51,7 +50,6 @@ class QWidget;
namespace caf
{
class CmdFeature;
//==================================================================================================
@ -65,37 +63,35 @@ public:
static CmdFeatureManager* instance();
~CmdFeatureManager() override;
QAction* action(const QString& commandId);
QAction* action(const QString& commandId, const QString& customActionText);
QAction* actionWithUserData(const QString& commandId, const QString& customActionText, const QVariant& userData);
QAction* action( const QString& commandId );
QAction* action( const QString& commandId, const QString& customActionText );
QAction* actionWithUserData( const QString& commandId, const QString& customActionText, const QVariant& userData );
void refreshStates(const QStringList& commandIdList = QStringList());
void refreshEnabledState(const QStringList& commandIdList = QStringList());
void refreshCheckedState(const QStringList& commandIdList = QStringList());
void refreshStates( const QStringList& commandIdList = QStringList() );
void refreshEnabledState( const QStringList& commandIdList = QStringList() );
void refreshCheckedState( const QStringList& commandIdList = QStringList() );
CmdFeature* getCommandFeature(const std::string& commandId);
std::vector<CmdFeature*> commandFeaturesMatchingSubString(const std::string& subString) const;
std::vector<CmdFeature*> commandFeaturesMatchingKeyboardShortcut(const QKeySequence& keySequence) const;
CmdFeature* getCommandFeature( const std::string& commandId );
std::vector<CmdFeature*> commandFeaturesMatchingSubString( const std::string& subString ) const;
std::vector<CmdFeature*> commandFeaturesMatchingKeyboardShortcut( const QKeySequence& keySequence ) const;
void setCurrentContextMenuTargetWidget(QWidget * targetWidget);
void setCurrentContextMenuTargetWidget( QWidget* targetWidget );
QWidget* currentContextMenuTargetWidget();
private:
CmdFeatureManager();
std::pair<CmdFeature*, size_t> createFeature(const std::string& commandId);
std::pair<CmdFeature*, size_t> findExistingCmdFeature(const std::string& commandId);
std::pair<CmdFeature*, size_t> createFeature( const std::string& commandId );
std::pair<CmdFeature*, size_t> findExistingCmdFeature( const std::string& commandId );
CmdFeature* commandFeature(const std::string& commandId) const;
CmdFeature* commandFeature( const std::string& commandId ) const;
private:
std::vector<CmdFeature*> m_commandFeatures;
std::map<std::string , size_t > m_commandIdToFeatureIdxMap;
std::map<QAction*, size_t > m_actionToFeatureIdxMap;
std::map<std::string, size_t> m_commandIdToFeatureIdxMap;
std::map<QAction*, size_t> m_actionToFeatureIdxMap;
QPointer<QWidget> m_currentContextMenuTargetWidget;
};
} // end namespace caf

View File

@ -49,25 +49,29 @@ namespace caf
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdFeatureMenuBuilder::CmdFeatureMenuBuilder() {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdFeatureMenuBuilder::~CmdFeatureMenuBuilder() {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::operator<<(const QString& commandId)
CmdFeatureMenuBuilder::CmdFeatureMenuBuilder()
{
if (commandId == "Separator")
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdFeatureMenuBuilder::~CmdFeatureMenuBuilder()
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::operator<<( const QString& commandId )
{
if ( commandId == "Separator" )
{
addSeparator();
}
else
{
addCmdFeature(commandId);
addCmdFeature( commandId );
}
return *this;
@ -76,13 +80,13 @@ CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::operator<<(const QString& commandI
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::addCmdFeature(const QString commandId, const QString& uiText)
CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::addCmdFeature( const QString commandId, const QString& uiText )
{
MenuItem i;
i.itemType = MenuItem::COMMAND;
i.itemName = commandId;
i.uiText = uiText;
m_items.push_back(i);
m_items.push_back( i );
return *this;
}
@ -90,15 +94,16 @@ CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::addCmdFeature(const QString comman
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::addCmdFeatureWithUserData(const QString commandId, const QString& uiText,
const QVariant& userData)
CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::addCmdFeatureWithUserData( const QString commandId,
const QString& uiText,
const QVariant& userData )
{
MenuItem i;
i.itemType = MenuItem::COMMAND;
i.itemName = commandId;
i.uiText = uiText;
i.userData = userData;
m_items.push_back(i);
m_items.push_back( i );
return *this;
}
@ -110,7 +115,7 @@ CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::addSeparator()
{
MenuItem i;
i.itemType = MenuItem::SEPARATOR;
m_items.push_back(i);
m_items.push_back( i );
return *this;
}
@ -118,13 +123,13 @@ CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::addSeparator()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::subMenuStart(const QString& menuName, const QIcon& menuIcon)
CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::subMenuStart( const QString& menuName, const QIcon& menuIcon )
{
MenuItem i;
i.itemType = MenuItem::SUBMENU_START;
i.itemName = menuName;
i.icon = menuIcon;
m_items.push_back(i);
m_items.push_back( i );
return *this;
}
@ -136,7 +141,7 @@ CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::subMenuEnd()
{
MenuItem i;
i.itemType = MenuItem::SUBMENU_END;
m_items.push_back(i);
m_items.push_back( i );
return *this;
}
@ -144,39 +149,39 @@ CmdFeatureMenuBuilder& CmdFeatureMenuBuilder::subMenuEnd()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdFeatureMenuBuilder::appendToMenu(QMenu* menu)
void CmdFeatureMenuBuilder::appendToMenu( QMenu* menu )
{
CAF_ASSERT(menu);
CAF_ASSERT( menu );
std::vector<QMenu*> menus = {menu};
for (size_t i = 0; i < m_items.size(); i++)
for ( size_t i = 0; i < m_items.size(); i++ )
{
if (m_items[i].itemType == MenuItem::SEPARATOR)
if ( m_items[i].itemType == MenuItem::SEPARATOR )
{
menus.back()->addSeparator();
}
else if (m_items[i].itemType == MenuItem::SUBMENU_START)
else if ( m_items[i].itemType == MenuItem::SUBMENU_START )
{
QMenu* subMenu = menus.back()->addMenu(m_items[i].icon, m_items[i].itemName);
menus.push_back(subMenu);
QMenu* subMenu = menus.back()->addMenu( m_items[i].icon, m_items[i].itemName );
menus.push_back( subMenu );
}
else if (m_items[i].itemType == MenuItem::SUBMENU_END)
else if ( m_items[i].itemType == MenuItem::SUBMENU_END )
{
if (menus.size() > 1)
if ( menus.size() > 1 )
{
QMenu* completeSubMenu = menus.back();
menus.pop_back();
if (!menus.empty())
if ( !menus.empty() )
{
// Remove the sub menu action if no (sub) actions are present in the sub menu
if (completeSubMenu->actions().isEmpty())
if ( completeSubMenu->actions().isEmpty() )
{
QMenu* menuWithEmptySubMenu = menus.back();
QAction* subMenuAction = completeSubMenu->menuAction();
menuWithEmptySubMenu->removeAction(subMenuAction);
menuWithEmptySubMenu->removeAction( subMenuAction );
}
}
}
@ -185,37 +190,37 @@ void CmdFeatureMenuBuilder::appendToMenu(QMenu* menu)
{
CmdFeatureManager* commandManager = CmdFeatureManager::instance();
QMenu* currentMenu = menus.back();
caf::CmdFeature* feature = commandManager->getCommandFeature(m_items[i].itemName.toStdString());
CAF_ASSERT(feature);
caf::CmdFeature* feature = commandManager->getCommandFeature( m_items[i].itemName.toStdString() );
CAF_ASSERT( feature );
if (feature->canFeatureBeExecuted())
if ( feature->canFeatureBeExecuted() )
{
const QAction* act;
if (!m_items[i].userData.isNull())
if ( !m_items[i].userData.isNull() )
{
act = commandManager->actionWithUserData(m_items[i].itemName, m_items[i].uiText, m_items[i].userData);
act = commandManager->actionWithUserData( m_items[i].itemName, m_items[i].uiText, m_items[i].userData );
}
else
{
act = commandManager->action(m_items[i].itemName);
act = commandManager->action( m_items[i].itemName );
}
CAF_ASSERT(act);
CAF_ASSERT( act );
bool duplicateAct = false;
for (QAction* existingAct : currentMenu->actions())
for ( QAction* existingAct : currentMenu->actions() )
{
// If action exist, continue to make sure the action is positioned at the first
// location of a command ID
if (existingAct == act)
if ( existingAct == act )
{
duplicateAct = true;
break;
}
}
if (duplicateAct) continue;
if ( duplicateAct ) continue;
currentMenu->addAction(const_cast<QAction*>(act));
currentMenu->addAction( const_cast<QAction*>( act ) );
}
}
}
@ -224,11 +229,11 @@ void CmdFeatureMenuBuilder::appendToMenu(QMenu* menu)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool CmdFeatureMenuBuilder::isCmdFeatureAdded(const QString &commandId)
bool CmdFeatureMenuBuilder::isCmdFeatureAdded( const QString& commandId )
{
for (const MenuItem &item : m_items)
for ( const MenuItem& item : m_items )
{
if (item.itemType == MenuItem::COMMAND && item.itemName == commandId)
if ( item.itemType == MenuItem::COMMAND && item.itemName == commandId )
{
return true;
}

View File

@ -57,20 +57,21 @@ public:
CmdFeatureMenuBuilder();
virtual ~CmdFeatureMenuBuilder();
CmdFeatureMenuBuilder& operator<<(const QString& commandIdOrSeparator);
CmdFeatureMenuBuilder& addCmdFeature(const QString commandId, const QString& customUiText = "");
CmdFeatureMenuBuilder& addCmdFeatureWithUserData(const QString commandId, const QString& customUiText,
const QVariant& userData);
CmdFeatureMenuBuilder& operator<<( const QString& commandIdOrSeparator );
CmdFeatureMenuBuilder& addCmdFeature( const QString commandId, const QString& customUiText = "" );
CmdFeatureMenuBuilder&
addCmdFeatureWithUserData( const QString commandId, const QString& customUiText, const QVariant& userData );
CmdFeatureMenuBuilder& addSeparator();
CmdFeatureMenuBuilder& subMenuStart(const QString& menuName, const QIcon& menuIcon = QIcon());
CmdFeatureMenuBuilder& subMenuStart( const QString& menuName, const QIcon& menuIcon = QIcon() );
CmdFeatureMenuBuilder& subMenuEnd();
void appendToMenu(QMenu* menu);
void appendToMenu( QMenu* menu );
bool isCmdFeatureAdded(const QString &commandId);
bool isCmdFeatureAdded( const QString& commandId );
size_t itemCount() const;
private:
struct MenuItem
{

View File

@ -34,41 +34,38 @@
//
//##################################################################################################
#include "cafCmdFieldChangeExec.h"
#include "cafPdmReferenceHelper.h"
#include "cafNotificationCenter.h"
#include "cafPdmReferenceHelper.h"
namespace caf
{
CAF_PDM_SOURCE_INIT(CmdFieldChangeExecData, "CmdFieldChangeExecData");
CAF_PDM_SOURCE_INIT( CmdFieldChangeExecData, "CmdFieldChangeExecData" );
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString CmdFieldChangeExec::name()
{
PdmFieldHandle* field = PdmReferenceHelper::fieldFromReference(m_commandData->m_rootObject, m_commandData->m_pathToField);
if (field)
PdmFieldHandle* field =
PdmReferenceHelper::fieldFromReference( m_commandData->m_rootObject, m_commandData->m_pathToField );
if ( field )
{
QString fieldText;
PdmUiFieldHandle* uiFieldHandle = field->uiCapability();
if (uiFieldHandle)
if ( uiFieldHandle )
{
fieldText = QString("Change field '%1'").arg(uiFieldHandle->uiName());
fieldText = QString( "Change field '%1'" ).arg( uiFieldHandle->uiName() );
}
if (field->ownerObject())
if ( field->ownerObject() )
{
PdmUiObjectHandle* uiObjHandle = uiObj(field->ownerObject());
if (uiObjHandle)
PdmUiObjectHandle* uiObjHandle = uiObj( field->ownerObject() );
if ( uiObjHandle )
{
fieldText += QString(" in '%1'").arg(uiObjHandle->uiName());
fieldText += QString( " in '%1'" ).arg( uiObjHandle->uiName() );
}
}
return fieldText;
@ -84,52 +81,53 @@ QString CmdFieldChangeExec::name()
//--------------------------------------------------------------------------------------------------
void CmdFieldChangeExec::redo()
{
PdmFieldHandle* field = PdmReferenceHelper::fieldFromReference(m_commandData->m_rootObject, m_commandData->m_pathToField);
if (!field)
PdmFieldHandle* field =
PdmReferenceHelper::fieldFromReference( m_commandData->m_rootObject, m_commandData->m_pathToField );
if ( !field )
{
CAF_ASSERT(false);
CAF_ASSERT( false );
return;
}
PdmUiFieldHandle* uiFieldHandle = field->uiCapability();
PdmXmlFieldHandle* xmlFieldHandle = field->xmlCapability();
if (uiFieldHandle && xmlFieldHandle)
if ( uiFieldHandle && xmlFieldHandle )
{
if (m_commandData->m_redoFieldValueSerialized.isEmpty())
if ( m_commandData->m_redoFieldValueSerialized.isEmpty() )
{
// We end up here only when the user actually has done something in the actual living Gui editor.
{
QXmlStreamWriter xmlStream(&m_commandData->m_undoFieldValueSerialized);
writeFieldDataToValidXmlDocument(xmlStream, xmlFieldHandle);
QXmlStreamWriter xmlStream( &m_commandData->m_undoFieldValueSerialized );
writeFieldDataToValidXmlDocument( xmlStream, xmlFieldHandle );
}
// This function will notify field change, no need to explicitly call notification
// The ui value might be an index into the option entry cache, so we need to set the value
// and be aware of the option entries, and then serialize the actual field value we ended up with.
uiFieldHandle->setValueFromUiEditor(m_commandData->m_newUiValue);
uiFieldHandle->setValueFromUiEditor( m_commandData->m_newUiValue );
{
QXmlStreamWriter xmlStream(&m_commandData->m_redoFieldValueSerialized);
writeFieldDataToValidXmlDocument(xmlStream, xmlFieldHandle);
QXmlStreamWriter xmlStream( &m_commandData->m_redoFieldValueSerialized );
writeFieldDataToValidXmlDocument( xmlStream, xmlFieldHandle );
}
}
else
{
QVariant oldFieldData = uiFieldHandle->toUiBasedQVariant();
QXmlStreamReader xmlStream(m_commandData->m_redoFieldValueSerialized);
QXmlStreamReader xmlStream( m_commandData->m_redoFieldValueSerialized );
readFieldValueFromValidXmlDocument(xmlStream, xmlFieldHandle);
readFieldValueFromValidXmlDocument( xmlStream, xmlFieldHandle );
QVariant newFieldData = uiFieldHandle->toUiBasedQVariant();
// New data is present in field, notify data changed
uiFieldHandle->notifyFieldChanged(oldFieldData, newFieldData);
uiFieldHandle->notifyFieldChanged( oldFieldData, newFieldData );
}
}
if (m_notificationCenter) m_notificationCenter->notifyObserversOfDataChange(field->ownerObject());
if ( m_notificationCenter ) m_notificationCenter->notifyObserversOfDataChange( field->ownerObject() );
}
//--------------------------------------------------------------------------------------------------
@ -137,47 +135,46 @@ void CmdFieldChangeExec::redo()
//--------------------------------------------------------------------------------------------------
void CmdFieldChangeExec::undo()
{
PdmFieldHandle* field = PdmReferenceHelper::fieldFromReference(m_commandData->m_rootObject, m_commandData->m_pathToField);
if (!field)
PdmFieldHandle* field =
PdmReferenceHelper::fieldFromReference( m_commandData->m_rootObject, m_commandData->m_pathToField );
if ( !field )
{
CAF_ASSERT(false);
CAF_ASSERT( false );
return;
}
PdmUiFieldHandle* uiFieldHandle = field->uiCapability();
PdmXmlFieldHandle* xmlFieldHandle = field->xmlCapability();
if (uiFieldHandle && xmlFieldHandle)
if ( uiFieldHandle && xmlFieldHandle )
{
QXmlStreamReader xmlStream(m_commandData->m_undoFieldValueSerialized);
QXmlStreamReader xmlStream( m_commandData->m_undoFieldValueSerialized );
QVariant oldFieldData = uiFieldHandle->toUiBasedQVariant();
readFieldValueFromValidXmlDocument(xmlStream, xmlFieldHandle);
readFieldValueFromValidXmlDocument( xmlStream, xmlFieldHandle );
QVariant newFieldData = uiFieldHandle->toUiBasedQVariant();
// New data is present in field, notify data changed
uiFieldHandle->notifyFieldChanged(oldFieldData, newFieldData);
uiFieldHandle->notifyFieldChanged( oldFieldData, newFieldData );
}
if (m_notificationCenter) m_notificationCenter->notifyObserversOfDataChange(field->ownerObject());
if ( m_notificationCenter ) m_notificationCenter->notifyObserversOfDataChange( field->ownerObject() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdFieldChangeExec::CmdFieldChangeExec(NotificationCenter* notificationCenter)
: CmdExecuteCommand(notificationCenter)
CmdFieldChangeExec::CmdFieldChangeExec( NotificationCenter* notificationCenter )
: CmdExecuteCommand( notificationCenter )
{
m_commandData = new CmdFieldChangeExecData;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdFieldChangeExec::~CmdFieldChangeExec()
{
}
//--------------------------------------------------------------------------------------------------
@ -191,12 +188,12 @@ CmdFieldChangeExecData* CmdFieldChangeExec::commandData()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdFieldChangeExec::writeFieldDataToValidXmlDocument(QXmlStreamWriter &xmlStream, PdmXmlFieldHandle* xmlFieldHandle)
void CmdFieldChangeExec::writeFieldDataToValidXmlDocument( QXmlStreamWriter& xmlStream, PdmXmlFieldHandle* xmlFieldHandle )
{
xmlStream.setAutoFormatting(true);
xmlStream.setAutoFormatting( true );
xmlStream.writeStartDocument();
xmlStream.writeStartElement("", "d");
xmlFieldHandle->writeFieldData(xmlStream);
xmlStream.writeStartElement( "", "d" );
xmlFieldHandle->writeFieldData( xmlStream );
xmlStream.writeEndElement();
xmlStream.writeEndDocument();
}
@ -204,17 +201,17 @@ void CmdFieldChangeExec::writeFieldDataToValidXmlDocument(QXmlStreamWriter &xmlS
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdFieldChangeExec::readFieldValueFromValidXmlDocument(QXmlStreamReader &xmlStream, PdmXmlFieldHandle* xmlFieldHandle)
void CmdFieldChangeExec::readFieldValueFromValidXmlDocument( QXmlStreamReader& xmlStream, PdmXmlFieldHandle* xmlFieldHandle )
{
// See PdmObject::readFields and friends to match token count for reading field values
// The stream is supposed to be pointing at the first token of field content when calling readFieldData()
QXmlStreamReader::TokenType tt;
int tokenCount = 3;
for (int i = 0; i < tokenCount; i++)
for ( int i = 0; i < tokenCount; i++ )
{
tt = xmlStream.readNext();
}
xmlFieldHandle->readFieldData(xmlStream, PdmDefaultObjectFactory::instance());
xmlFieldHandle->readFieldData( xmlStream, PdmDefaultObjectFactory::instance() );
}
} // end namespace caf

View File

@ -42,7 +42,6 @@
namespace caf
{
class PdmChildArrayFieldHandle;
//==================================================================================================
@ -55,9 +54,12 @@ class CmdFieldChangeExecData : public PdmObject
public:
CmdFieldChangeExecData()
{
CAF_PDM_InitObject("CmdFieldChangeExecData uiName", "", "CmdFieldChangeExecData tooltip", "CmdFieldChangeExecData whatsthis");
CAF_PDM_InitObject( "CmdFieldChangeExecData uiName",
"",
"CmdFieldChangeExecData tooltip",
"CmdFieldChangeExecData whatsthis" );
CAF_PDM_InitField(&m_pathToField, "PathToField", QString(), "PathToField", "", "PathToField tooltip", "PathToField whatsthis");
CAF_PDM_InitField( &m_pathToField, "PathToField", QString(), "PathToField", "", "PathToField tooltip", "PathToField whatsthis" );
}
caf::PdmPointer<PdmObjectHandle> m_rootObject;
@ -69,17 +71,15 @@ public:
QString m_redoFieldValueSerialized;
};
//==================================================================================================
///
//==================================================================================================
class CmdFieldChangeExec : public CmdExecuteCommand
{
public:
explicit CmdFieldChangeExec(NotificationCenter* notificationCenter);
explicit CmdFieldChangeExec( NotificationCenter* notificationCenter );
~CmdFieldChangeExec() override;
CmdFieldChangeExecData* commandData();
QString name() override;
@ -87,13 +87,11 @@ public:
void undo() override;
private:
void readFieldValueFromValidXmlDocument(QXmlStreamReader& xmlStream, PdmXmlFieldHandle* xmlFieldHandle);
void writeFieldDataToValidXmlDocument(QXmlStreamWriter& xmlStream, PdmXmlFieldHandle* xmlFieldHandle);
void readFieldValueFromValidXmlDocument( QXmlStreamReader& xmlStream, PdmXmlFieldHandle* xmlFieldHandle );
void writeFieldDataToValidXmlDocument( QXmlStreamWriter& xmlStream, PdmXmlFieldHandle* xmlFieldHandle );
private:
CmdFieldChangeExecData* m_commandData;
};
} // end namespace caf

View File

@ -34,16 +34,13 @@
//
//##################################################################################################
#include "cafCmdSelectionChangeExec.h"
#include "cafPdmReferenceHelper.h"
#include "cafSelectionManager.h"
namespace caf
{
CAF_PDM_SOURCE_INIT(CmdSelectionChangeExecData, "CmdSelectionChangeExecData");
CAF_PDM_SOURCE_INIT( CmdSelectionChangeExecData, "CmdSelectionChangeExecData" );
//--------------------------------------------------------------------------------------------------
///
@ -58,7 +55,8 @@ QString CmdSelectionChangeExec::name()
//--------------------------------------------------------------------------------------------------
void CmdSelectionChangeExec::redo()
{
SelectionManager::instance()->setSelectionAtLevelFromReferences(m_commandData->m_newSelection.v(), m_commandData->m_selectionLevel.v());
SelectionManager::instance()->setSelectionAtLevelFromReferences( m_commandData->m_newSelection.v(),
m_commandData->m_selectionLevel.v() );
}
//--------------------------------------------------------------------------------------------------
@ -66,25 +64,24 @@ void CmdSelectionChangeExec::redo()
//--------------------------------------------------------------------------------------------------
void CmdSelectionChangeExec::undo()
{
SelectionManager::instance()->setSelectionAtLevelFromReferences(m_commandData->m_previousSelection.v(), m_commandData->m_selectionLevel.v());
SelectionManager::instance()->setSelectionAtLevelFromReferences( m_commandData->m_previousSelection.v(),
m_commandData->m_selectionLevel.v() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdSelectionChangeExec::CmdSelectionChangeExec(NotificationCenter* notificationCenter)
: CmdExecuteCommand(notificationCenter)
CmdSelectionChangeExec::CmdSelectionChangeExec( NotificationCenter* notificationCenter )
: CmdExecuteCommand( notificationCenter )
{
m_commandData = new CmdSelectionChangeExecData;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdSelectionChangeExec::~CmdSelectionChangeExec()
{
}
//--------------------------------------------------------------------------------------------------

View File

@ -38,16 +38,12 @@
#include "cafCmdExecuteCommand.h"
#include "cafAppEnum.h"
#include "cafPdmField.h"
#include "cafPdmObject.h"
#include "cafAppEnum.h"
namespace caf
{
//==================================================================================================
///
//==================================================================================================
@ -58,27 +54,30 @@ class CmdSelectionChangeExecData : public PdmObject
public:
CmdSelectionChangeExecData()
{
CAF_PDM_InitObject("CmdSelectionChangeExecData uiName", "", "CmdSelectionChangeExecData tooltip", "CmdSelectionChangeExecData whatsthis");
CAF_PDM_InitObject( "CmdSelectionChangeExecData uiName",
"",
"CmdSelectionChangeExecData tooltip",
"CmdSelectionChangeExecData whatsthis" );
CAF_PDM_InitFieldNoDefault(&m_selectionLevel, "selectionLevel", "selectionLevel", "", "", "");
CAF_PDM_InitField(&m_previousSelection, "previousSelection", std::vector<QString>(), "previousSelection", "", "", "");
CAF_PDM_InitField(&m_newSelection, "newSelection", std::vector<QString>(), "newSelection", "", "", "");
CAF_PDM_InitFieldNoDefault( &m_selectionLevel, "selectionLevel", "selectionLevel", "", "", "" );
CAF_PDM_InitField( &m_previousSelection, "previousSelection", std::vector<QString>(), "previousSelection", "", "", "" );
CAF_PDM_InitField( &m_newSelection, "newSelection", std::vector<QString>(), "newSelection", "", "", "" );
}
PdmField< int > m_selectionLevel;
PdmField< std::vector<QString> > m_previousSelection;
PdmField< std::vector<QString> > m_newSelection;
PdmField<int> m_selectionLevel;
PdmField<std::vector<QString>> m_previousSelection;
PdmField<std::vector<QString>> m_newSelection;
};
//==================================================================================================
///
//==================================================================================================
class CmdSelectionChangeExec : public CmdExecuteCommand
{
public:
explicit CmdSelectionChangeExec(NotificationCenter* notificationCenter);
~CmdSelectionChangeExec() override;;
explicit CmdSelectionChangeExec( NotificationCenter* notificationCenter );
~CmdSelectionChangeExec() override;
;
CmdSelectionChangeExecData* commandData();
@ -90,6 +89,4 @@ private:
CmdSelectionChangeExecData* m_commandData;
};
} // end namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#include "cafCmdSelectionHelper.h"
#include "cafCmdExecCommandManager.h"
@ -42,38 +41,39 @@
#include "cafSelectionManager.h"
namespace caf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdSelectionHelper::executeSelectionCommand(const std::vector<PdmObjectHandle*>& selection, int selectionLevel)
void CmdSelectionHelper::executeSelectionCommand( const std::vector<PdmObjectHandle*>& selection, int selectionLevel )
{
CmdSelectionChangeExec* selectionChangeExec = createSelectionCommand(selection, selectionLevel);
CmdSelectionChangeExec* selectionChangeExec = createSelectionCommand( selection, selectionLevel );
CmdExecCommandManager::instance()->processExecuteCommand(selectionChangeExec);
CmdExecCommandManager::instance()->processExecuteCommand( selectionChangeExec );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdSelectionChangeExec* CmdSelectionHelper::createSelectionCommand(const std::vector<PdmObjectHandle*>& selection, int selectionLevel)
CmdSelectionChangeExec* CmdSelectionHelper::createSelectionCommand( const std::vector<PdmObjectHandle*>& selection,
int selectionLevel )
{
CmdSelectionChangeExec* selectionChangeExec = new CmdSelectionChangeExec(SelectionManager::instance()->notificationCenter());
CmdSelectionChangeExec* selectionChangeExec =
new CmdSelectionChangeExec( SelectionManager::instance()->notificationCenter() );
selectionChangeExec->commandData()->m_selectionLevel.v() = selectionLevel;
SelectionManager::instance()->selectionAsReferences(selectionChangeExec->commandData()->m_previousSelection.v(), selectionLevel);
SelectionManager::instance()->selectionAsReferences( selectionChangeExec->commandData()->m_previousSelection.v(),
selectionLevel );
for (size_t i = 0; i < selection.size(); i++)
for ( size_t i = 0; i < selection.size(); i++ )
{
QString itemRef = PdmReferenceHelper::referenceFromRootToObject(PdmReferenceHelper::findRoot(selection[i]), selection[i]);
selectionChangeExec->commandData()->m_newSelection.v().push_back(itemRef);
QString itemRef =
PdmReferenceHelper::referenceFromRootToObject( PdmReferenceHelper::findRoot( selection[i] ), selection[i] );
selectionChangeExec->commandData()->m_newSelection.v().push_back( itemRef );
}
return selectionChangeExec;
}
} // end namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#pragma once
#include <vector>
@ -47,10 +46,9 @@ class PdmObjectHandle;
class CmdSelectionHelper
{
public:
static void executeSelectionCommand(const std::vector<PdmObjectHandle*>& selection, int selectionLevel);
static CmdSelectionChangeExec* createSelectionCommand(const std::vector<PdmObjectHandle*>& selection, int selectionLevel);
static void executeSelectionCommand( const std::vector<PdmObjectHandle*>& selection, int selectionLevel );
static CmdSelectionChangeExec* createSelectionCommand( const std::vector<PdmObjectHandle*>& selection,
int selectionLevel );
};
} // end namespace caf

View File

@ -34,13 +34,12 @@
//
//##################################################################################################
#include "cafCmdUiCommandSystemImpl.h"
#include "cafCmdExecCommandManager.h"
#include "cafCmdExecuteCommand.h"
#include "cafCmdFieldChangeExec.h"
#include "cafCmdFeatureManager.h"
#include "cafCmdFieldChangeExec.h"
#include "cafPdmFieldHandle.h"
#include "cafPdmUiObjectHandle.h"
@ -53,7 +52,6 @@
namespace caf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@ -66,59 +64,61 @@ CmdUiCommandSystemImpl::CmdUiCommandSystemImpl()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdUiCommandSystemImpl::fieldChangedCommand( const std::vector<PdmFieldHandle*>& fieldsToUpdate, const QVariant& newUiValue)
void CmdUiCommandSystemImpl::fieldChangedCommand( const std::vector<PdmFieldHandle*>& fieldsToUpdate,
const QVariant& newUiValue )
{
if ( fieldsToUpdate.empty() ) return;
std::vector<CmdExecuteCommand*> commands;
for (size_t i = 0; i < fieldsToUpdate.size(); i++)
for ( size_t i = 0; i < fieldsToUpdate.size(); i++ )
{
PdmFieldHandle* field = fieldsToUpdate[i];
PdmUiFieldHandle* uiFieldHandle = field->uiCapability();
if (uiFieldHandle)
if ( uiFieldHandle )
{
QVariant fieldCurrentUiValue = uiFieldHandle->uiValue();
if (fieldCurrentUiValue != newUiValue)
if ( fieldCurrentUiValue != newUiValue )
{
PdmObjectHandle* rootObjHandle = PdmReferenceHelper::findRoot(field);
PdmObjectHandle* rootObjHandle = PdmReferenceHelper::findRoot( field );
QString reference = PdmReferenceHelper::referenceFromRootToField(rootObjHandle, field);
if (reference.isEmpty())
QString reference = PdmReferenceHelper::referenceFromRootToField( rootObjHandle, field );
if ( reference.isEmpty() )
{
CAF_ASSERT(false);
CAF_ASSERT( false );
return;
}
CmdFieldChangeExec* fieldChangeExec = new CmdFieldChangeExec(SelectionManager::instance()->notificationCenter());
CmdFieldChangeExec* fieldChangeExec =
new CmdFieldChangeExec( SelectionManager::instance()->notificationCenter() );
fieldChangeExec->commandData()->m_newUiValue = newUiValue;
fieldChangeExec->commandData()->m_pathToField = reference;
fieldChangeExec->commandData()->m_rootObject = rootObjHandle;
commands.push_back(fieldChangeExec);
commands.push_back( fieldChangeExec );
}
}
}
caf::PdmUiObjectHandle* uiOwnerObjectHandle = uiObj(fieldsToUpdate[0]->ownerObject());
if (uiOwnerObjectHandle && !uiOwnerObjectHandle->useUndoRedoForFieldChanged())
caf::PdmUiObjectHandle* uiOwnerObjectHandle = uiObj( fieldsToUpdate[0]->ownerObject() );
if ( uiOwnerObjectHandle && !uiOwnerObjectHandle->useUndoRedoForFieldChanged() )
{
// Temporarily disable undo framework as requested by the PdmUiObjectHandle
m_disableUndoForFieldChange = true;
}
if (commands.size() == 1)
if ( commands.size() == 1 )
{
CmdExecCommandManager::instance()->processExecuteCommand(commands[0]);
CmdExecCommandManager::instance()->processExecuteCommand( commands[0] );
}
else
{
CmdExecCommandManager::instance()->processExecuteCommandsAsMacro("Multiple Field Change", commands);
CmdExecCommandManager::instance()->processExecuteCommandsAsMacro( "Multiple Field Change", commands );
}
if (uiOwnerObjectHandle && !uiOwnerObjectHandle->useUndoRedoForFieldChanged())
if ( uiOwnerObjectHandle && !uiOwnerObjectHandle->useUndoRedoForFieldChanged() )
{
// Restore undo feature to normal operation
m_disableUndoForFieldChange = false;
@ -128,19 +128,19 @@ void CmdUiCommandSystemImpl::fieldChangedCommand( const std::vector<PdmFieldHand
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdUiCommandSystemImpl::populateMenuWithDefaultCommands(const QString& uiConfigName, QMenu* menu)
void CmdUiCommandSystemImpl::populateMenuWithDefaultCommands( const QString& uiConfigName, QMenu* menu )
{
if (uiConfigName == "PdmUiTreeViewEditor" ||
uiConfigName == "PdmUiTableViewEditor")
if ( uiConfigName == "PdmUiTreeViewEditor" || uiConfigName == "PdmUiTableViewEditor" )
{
caf::CmdFeatureManager* commandManager = caf::CmdFeatureManager::instance();
menu->addAction(commandManager->action("PdmListField_AddItem"));
menu->addAction(commandManager->action("PdmListField_DeleteItem"));
menu->addAction( commandManager->action( "PdmListField_AddItem" ) );
menu->addAction( commandManager->action( "PdmListField_DeleteItem" ) );
QStringList commandIdList;
commandIdList << "PdmListField_AddItem" << "PdmListField_DeleteItem";
commandManager->refreshStates(commandIdList);
commandIdList << "PdmListField_AddItem"
<< "PdmListField_DeleteItem";
commandManager->refreshStates( commandIdList );
}
}
@ -155,7 +155,7 @@ bool CmdUiCommandSystemImpl::isUndoEnabled()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdUiCommandSystemImpl::enableUndoFeature(bool enable)
void CmdUiCommandSystemImpl::enableUndoFeature( bool enable )
{
m_undoFeatureEnabled = enable;
}
@ -171,9 +171,9 @@ bool CmdUiCommandSystemImpl::disableUndoForFieldChange()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdUiCommandSystemImpl::setCurrentContextMenuTargetWidget(QWidget* targetWidget)
void CmdUiCommandSystemImpl::setCurrentContextMenuTargetWidget( QWidget* targetWidget )
{
caf::CmdFeatureManager::instance()->setCurrentContextMenuTargetWidget(targetWidget);
caf::CmdFeatureManager::instance()->setCurrentContextMenuTargetWidget( targetWidget );
}
} // end namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#pragma once
#include "cafInternalPdmUiCommandSystemInterface.h"
@ -42,7 +41,6 @@
namespace caf
{
class PdmFieldHandle;
class CmdUiCommandSystemImpl : public PdmUiCommandSystemInterface
@ -50,12 +48,12 @@ class CmdUiCommandSystemImpl : public PdmUiCommandSystemInterface
public:
CmdUiCommandSystemImpl();
void fieldChangedCommand(const std::vector<PdmFieldHandle*>& fieldsToUpdate, const QVariant& newUiValue) override;
void setCurrentContextMenuTargetWidget(QWidget* targetWidget) override;
void populateMenuWithDefaultCommands(const QString& uiConfigName, QMenu* menu) override;
void fieldChangedCommand( const std::vector<PdmFieldHandle*>& fieldsToUpdate, const QVariant& newUiValue ) override;
void setCurrentContextMenuTargetWidget( QWidget* targetWidget ) override;
void populateMenuWithDefaultCommands( const QString& uiConfigName, QMenu* menu ) override;
bool isUndoEnabled();
void enableUndoFeature(bool enable);
void enableUndoFeature( bool enable );
bool disableUndoForFieldChange();
@ -64,5 +62,4 @@ private:
bool m_disableUndoForFieldChange;
};
} // end namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#include "cafCmdAddItemExec.h"
#include "cafCmdAddItemExecData.h"
@ -45,28 +44,26 @@
#include "cafPdmChildArrayField.h"
namespace caf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString CmdAddItemExec::name()
{
PdmFieldHandle* field = PdmReferenceHelper::fieldFromReference(m_commandData->m_rootObject, m_commandData->m_pathToField);
PdmFieldHandle* field =
PdmReferenceHelper::fieldFromReference( m_commandData->m_rootObject, m_commandData->m_pathToField );
QString containedObjectType = "object";
PdmChildArrayFieldHandle* listField = dynamic_cast<PdmChildArrayFieldHandle*>(field);
if (listField)
PdmChildArrayFieldHandle* listField = dynamic_cast<PdmChildArrayFieldHandle*>( field );
if ( listField )
{
PdmXmlFieldHandle* xfh = listField->xmlCapability();
containedObjectType = xfh->dataTypeName();
}
return QString("Create new '%1'").arg(containedObjectType);
return QString( "Create new '%1'" ).arg( containedObjectType );
}
//--------------------------------------------------------------------------------------------------
@ -74,40 +71,41 @@ QString CmdAddItemExec::name()
//--------------------------------------------------------------------------------------------------
void CmdAddItemExec::redo()
{
PdmFieldHandle* field = PdmReferenceHelper::fieldFromReference(m_commandData->m_rootObject, m_commandData->m_pathToField);
PdmFieldHandle* field =
PdmReferenceHelper::fieldFromReference( m_commandData->m_rootObject, m_commandData->m_pathToField );
PdmChildArrayFieldHandle* listField = dynamic_cast<PdmChildArrayFieldHandle*>(field);
if (listField && field->xmlCapability())
PdmChildArrayFieldHandle* listField = dynamic_cast<PdmChildArrayFieldHandle*>( field );
if ( listField && field->xmlCapability() )
{
QString classKeyword = field->xmlCapability()->dataTypeName();
if (classKeyword.isEmpty()) return;
if ( classKeyword.isEmpty() ) return;
caf::PdmObjectHandle* obj = PdmDefaultObjectFactory::instance()->create(classKeyword);
caf::PdmObjectHandle* obj = PdmDefaultObjectFactory::instance()->create( classKeyword );
if (!obj) return;
if ( !obj ) return;
listField->insertAt(m_commandData->m_indexAfter, obj);
listField->insertAt( m_commandData->m_indexAfter, obj );
if (m_commandData->m_indexAfter == -1)
if ( m_commandData->m_indexAfter == -1 )
{
m_commandData->m_createdItemIndex = static_cast<int>(listField->size() - 1);
m_commandData->m_createdItemIndex = static_cast<int>( listField->size() - 1 );
}
else
{
m_commandData->m_createdItemIndex = m_commandData->m_indexAfter;
}
if (m_notificationCenter) m_notificationCenter->notifyObserversOfDataChange(obj);
if ( m_notificationCenter ) m_notificationCenter->notifyObserversOfDataChange( obj );
listField->uiCapability()->updateConnectedEditors();
if (listField->ownerObject())
if ( listField->ownerObject() )
{
caf::PdmUiObjectHandle* ownerUiObject = uiObj(listField->ownerObject());
if (ownerUiObject)
caf::PdmUiObjectHandle* ownerUiObject = uiObj( listField->ownerObject() );
if ( ownerUiObject )
{
ownerUiObject->fieldChangedByUi(listField, QVariant(), QVariant());
ownerUiObject->fieldChangedByUi( listField, QVariant(), QVariant() );
}
}
}
@ -118,29 +116,30 @@ void CmdAddItemExec::redo()
//--------------------------------------------------------------------------------------------------
void CmdAddItemExec::undo()
{
PdmFieldHandle* field = PdmReferenceHelper::fieldFromReference(m_commandData->m_rootObject, m_commandData->m_pathToField);
PdmFieldHandle* field =
PdmReferenceHelper::fieldFromReference( m_commandData->m_rootObject, m_commandData->m_pathToField );
PdmChildArrayFieldHandle* listField = dynamic_cast<PdmChildArrayFieldHandle*>(field);
if (listField && m_commandData->m_createdItemIndex >= 0)
PdmChildArrayFieldHandle* listField = dynamic_cast<PdmChildArrayFieldHandle*>( field );
if ( listField && m_commandData->m_createdItemIndex >= 0 )
{
std::vector<caf::PdmObjectHandle*> children;
listField->childObjects(&children);
listField->childObjects( &children );
caf::PdmObjectHandle* obj = children[m_commandData->m_createdItemIndex];
caf::SelectionManager::instance()->removeObjectFromAllSelections(obj);
caf::SelectionManager::instance()->removeObjectFromAllSelections( obj );
listField->erase(m_commandData->m_createdItemIndex);
listField->erase( m_commandData->m_createdItemIndex );
listField->uiCapability()->updateConnectedEditors();
if (m_notificationCenter) m_notificationCenter->notifyObservers();
if ( m_notificationCenter ) m_notificationCenter->notifyObservers();
if (listField->ownerObject())
if ( listField->ownerObject() )
{
caf::PdmUiObjectHandle* ownerUiObject = uiObj(listField->ownerObject());
if (ownerUiObject)
caf::PdmUiObjectHandle* ownerUiObject = uiObj( listField->ownerObject() );
if ( ownerUiObject )
{
ownerUiObject->fieldChangedByUi(listField, QVariant(), QVariant());
ownerUiObject->fieldChangedByUi( listField, QVariant(), QVariant() );
}
}
@ -151,19 +150,17 @@ void CmdAddItemExec::undo()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdAddItemExec::CmdAddItemExec(NotificationCenter* notificationCenter)
: CmdExecuteCommand(notificationCenter)
CmdAddItemExec::CmdAddItemExec( NotificationCenter* notificationCenter )
: CmdExecuteCommand( notificationCenter )
{
m_commandData = new CmdAddItemExecData;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdAddItemExec::~CmdAddItemExec()
{
}
//--------------------------------------------------------------------------------------------------

View File

@ -34,14 +34,12 @@
//
//##################################################################################################
#pragma once
#include "cafCmdExecuteCommand.h"
namespace caf
{
class PdmChildArrayFieldHandle;
class CmdAddItemExecData;
@ -51,8 +49,9 @@ class CmdAddItemExecData;
class CmdAddItemExec : public CmdExecuteCommand
{
public:
explicit CmdAddItemExec(NotificationCenter* notificationCenter);
~CmdAddItemExec() override;;
explicit CmdAddItemExec( NotificationCenter* notificationCenter );
~CmdAddItemExec() override;
;
CmdAddItemExecData* commandData();
@ -64,6 +63,4 @@ private:
CmdAddItemExecData* m_commandData;
};
} // end namespace caf

View File

@ -34,13 +34,10 @@
//
//##################################################################################################
#include "cafCmdAddItemExecData.h"
namespace caf
{
CAF_PDM_SOURCE_INIT(CmdAddItemExecData, "CmdAddItemExecData");
CAF_PDM_SOURCE_INIT( CmdAddItemExecData, "CmdAddItemExecData" );
} // end namespace caf

View File

@ -34,16 +34,13 @@
//
//##################################################################################################
#pragma once
#include "cafPdmObject.h"
#include "cafPdmField.h"
#include "cafPdmObject.h"
namespace caf
{
//==================================================================================================
///
//==================================================================================================
@ -54,11 +51,17 @@ class CmdAddItemExecData : public PdmObject
public:
CmdAddItemExecData()
{
CAF_PDM_InitObject("CmdAddItemExecData uiName", "", "CmdAddItemExecData tooltip", "CmdAddItemExecData whatsthis");
CAF_PDM_InitObject( "CmdAddItemExecData uiName", "", "CmdAddItemExecData tooltip", "CmdAddItemExecData whatsthis" );
CAF_PDM_InitField(&m_pathToField, "PathToField", QString(), "PathToField", "", "PathToField tooltip", "PathToField whatsthis");
CAF_PDM_InitField(&m_indexAfter, "indexAfter", -1, "indexAfter", "", "indexAfter tooltip", "indexAfter whatsthis");
CAF_PDM_InitField(&m_createdItemIndex, "createdItemIndex", -1, "createdItemIndex", "", "createdItemIndex tooltip", "createdItemIndex whatsthis");
CAF_PDM_InitField( &m_pathToField, "PathToField", QString(), "PathToField", "", "PathToField tooltip", "PathToField whatsthis" );
CAF_PDM_InitField( &m_indexAfter, "indexAfter", -1, "indexAfter", "", "indexAfter tooltip", "indexAfter whatsthis" );
CAF_PDM_InitField( &m_createdItemIndex,
"createdItemIndex",
-1,
"createdItemIndex",
"",
"createdItemIndex tooltip",
"createdItemIndex whatsthis" );
}
caf::PdmPointer<PdmObjectHandle> m_rootObject;
@ -68,6 +71,4 @@ public:
caf::PdmField<int> m_createdItemIndex;
};
} // end namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#include "cafCmdAddItemFeature.h"
#include "cafCmdAddItemExec.h"
@ -52,12 +51,9 @@
#include <QAction>
namespace caf
{
CAF_CMD_SOURCE_INIT(CmdAddItemFeature, "PdmListField_AddItem");
CAF_CMD_SOURCE_INIT( CmdAddItemFeature, "PdmListField_AddItem" );
//--------------------------------------------------------------------------------------------------
///
@ -65,14 +61,14 @@ namespace caf
CmdExecuteCommand* CmdAddItemFeature::createExecuteCommand()
{
caf::PdmChildArrayFieldHandle* childArrayFieldHandle = SelectionManager::instance()->activeChildArrayFieldHandle();
if (!childArrayFieldHandle) return nullptr;
if ( !childArrayFieldHandle ) return nullptr;
int indexAfter = -1;
CmdAddItemExec* addItemExec = new CmdAddItemExec(SelectionManager::instance()->notificationCenter());
CmdAddItemExec* addItemExec = new CmdAddItemExec( SelectionManager::instance()->notificationCenter() );
CmdAddItemExecData* data = addItemExec->commandData();
data->m_rootObject = PdmReferenceHelper::findRoot(childArrayFieldHandle);
data->m_pathToField = PdmReferenceHelper::referenceFromRootToField(data->m_rootObject, childArrayFieldHandle);
data->m_rootObject = PdmReferenceHelper::findRoot( childArrayFieldHandle );
data->m_pathToField = PdmReferenceHelper::referenceFromRootToField( data->m_rootObject, childArrayFieldHandle );
data->m_indexAfter = indexAfter;
return addItemExec;
@ -85,7 +81,7 @@ bool CmdAddItemFeature::isCommandEnabled()
{
caf::PdmChildArrayFieldHandle* childArrayFieldHandle = SelectionManager::instance()->activeChildArrayFieldHandle();
if (childArrayFieldHandle)
if ( childArrayFieldHandle )
{
return true;
}
@ -98,18 +94,18 @@ bool CmdAddItemFeature::isCommandEnabled()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdAddItemFeature::onActionTriggered(bool isChecked)
void CmdAddItemFeature::onActionTriggered( bool isChecked )
{
if (isCommandEnabled())
if ( isCommandEnabled() )
{
CmdExecuteCommand* exeCmd = createExecuteCommand();
if (exeCmd)
if ( exeCmd )
{
CmdExecCommandManager::instance()->processExecuteCommand(exeCmd);
CmdExecCommandManager::instance()->processExecuteCommand( exeCmd );
}
else
{
CAF_ASSERT(0);
CAF_ASSERT( 0 );
}
}
}
@ -117,9 +113,9 @@ void CmdAddItemFeature::onActionTriggered(bool isChecked)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdAddItemFeature::setupActionLook(QAction* actionToSetup)
void CmdAddItemFeature::setupActionLook( QAction* actionToSetup )
{
actionToSetup->setText("Add new object");
actionToSetup->setText( "Add new object" );
}
} // end namespace caf

View File

@ -34,14 +34,12 @@
//
//##################################################################################################
#pragma once
#include "cafCmdFeature.h"
namespace caf
{
class CmdExecuteCommand;
//==================================================================================================
@ -50,15 +48,13 @@ class CmdExecuteCommand;
class CmdAddItemFeature : public CmdFeature
{
CAF_CMD_HEADER_INIT;
protected:
CmdExecuteCommand* createExecuteCommand();
bool isCommandEnabled() override;
void onActionTriggered( bool isChecked ) override;
void setupActionLook( QAction* actionToSetup ) override;
};
} // end namespace caf

View File

@ -34,7 +34,6 @@
//
//##################################################################################################
#include "cafCmdDeleteItemExec.h"
#include "cafCmdDeleteItemExecData.h"
@ -45,10 +44,8 @@
#include "cafNotificationCenter.h"
#include "cafSelectionManager.h"
namespace caf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@ -62,40 +59,40 @@ QString CmdDeleteItemExec::name()
//--------------------------------------------------------------------------------------------------
void CmdDeleteItemExec::redo()
{
PdmFieldHandle* field = PdmReferenceHelper::fieldFromReference(m_commandData->m_rootObject, m_commandData->m_pathToField);
PdmFieldHandle* field =
PdmReferenceHelper::fieldFromReference( m_commandData->m_rootObject, m_commandData->m_pathToField );
PdmChildArrayFieldHandle* listField = dynamic_cast<PdmChildArrayFieldHandle*>(field);
if (listField)
PdmChildArrayFieldHandle* listField = dynamic_cast<PdmChildArrayFieldHandle*>( field );
if ( listField )
{
std::vector<PdmObjectHandle*> children;
listField->childObjects(&children);
listField->childObjects( &children );
PdmObjectHandle* obj = children[m_commandData->m_indexToObject];
caf::SelectionManager::instance()->removeObjectFromAllSelections(obj);
caf::SelectionManager::instance()->removeObjectFromAllSelections( obj );
if (m_commandData->m_deletedObjectAsXml().isEmpty())
if ( m_commandData->m_deletedObjectAsXml().isEmpty() )
{
QString encodedXml;
{
m_commandData->m_deletedObjectAsXml = xmlObj(obj)->writeObjectToXmlString();
m_commandData->m_deletedObjectAsXml = xmlObj( obj )->writeObjectToXmlString();
}
}
listField->erase(m_commandData->m_indexToObject);
listField->erase( m_commandData->m_indexToObject );
// TODO: The notification here could possibly be changed to
// PdmUiFieldHandle::notifyDataChange() similar to void CmdFieldChangeExec::redo()
caf::PdmUiObjectHandle* ownerUiObject = uiObj(listField->ownerObject());
if (ownerUiObject)
caf::PdmUiObjectHandle* ownerUiObject = uiObj( listField->ownerObject() );
if ( ownerUiObject )
{
ownerUiObject->fieldChangedByUi(field, QVariant(), QVariant());
ownerUiObject->fieldChangedByUi( field, QVariant(), QVariant() );
}
listField->uiCapability()->updateConnectedEditors();
if (m_notificationCenter) m_notificationCenter->notifyObservers();
if ( m_notificationCenter ) m_notificationCenter->notifyObservers();
delete obj;
}
@ -106,35 +103,38 @@ void CmdDeleteItemExec::redo()
//--------------------------------------------------------------------------------------------------
void CmdDeleteItemExec::undo()
{
PdmFieldHandle* field = PdmReferenceHelper::fieldFromReference(m_commandData->m_rootObject, m_commandData->m_pathToField);
PdmFieldHandle* field =
PdmReferenceHelper::fieldFromReference( m_commandData->m_rootObject, m_commandData->m_pathToField );
PdmChildArrayFieldHandle* listField = dynamic_cast<PdmChildArrayFieldHandle*>(field);
if (listField)
PdmChildArrayFieldHandle* listField = dynamic_cast<PdmChildArrayFieldHandle*>( field );
if ( listField )
{
PdmObjectHandle* obj = PdmXmlObjectHandle::readUnknownObjectFromXmlString(m_commandData->m_deletedObjectAsXml(), PdmDefaultObjectFactory::instance(), false);
PdmObjectHandle* obj = PdmXmlObjectHandle::readUnknownObjectFromXmlString( m_commandData->m_deletedObjectAsXml(),
PdmDefaultObjectFactory::instance(),
false );
listField->insertAt(m_commandData->m_indexToObject, obj);
listField->insertAt( m_commandData->m_indexToObject, obj );
// TODO: The notification here could possibly be changed to
// PdmUiFieldHandle::notifyDataChange() similar to void CmdFieldChangeExec::redo()
caf::PdmUiObjectHandle* ownerUiObject = uiObj(listField->ownerObject());
if (ownerUiObject)
caf::PdmUiObjectHandle* ownerUiObject = uiObj( listField->ownerObject() );
if ( ownerUiObject )
{
ownerUiObject->fieldChangedByUi(field, QVariant(), QVariant());
ownerUiObject->fieldChangedByUi( field, QVariant(), QVariant() );
}
listField->uiCapability()->updateConnectedEditors();
if (m_notificationCenter) m_notificationCenter->notifyObservers();
if ( m_notificationCenter ) m_notificationCenter->notifyObservers();
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
CmdDeleteItemExec::CmdDeleteItemExec(NotificationCenter* notificationCenter)
: CmdExecuteCommand(notificationCenter)
CmdDeleteItemExec::CmdDeleteItemExec( NotificationCenter* notificationCenter )
: CmdExecuteCommand( notificationCenter )
{
m_commandData = new CmdDeleteItemExecData;
}

View File

@ -34,14 +34,12 @@
//
//##################################################################################################
#pragma once
#include "cafCmdExecuteCommand.h"
namespace caf
{
class PdmChildArrayFieldHandle;
class CmdDeleteItemExecData;
@ -51,9 +49,8 @@ class CmdDeleteItemExecData;
class CmdDeleteItemExec : public CmdExecuteCommand
{
public:
explicit CmdDeleteItemExec(NotificationCenter* notificationCenter);
~CmdDeleteItemExec() override {};
explicit CmdDeleteItemExec( NotificationCenter* notificationCenter );
~CmdDeleteItemExec() override{};
CmdDeleteItemExecData* commandData();
@ -65,6 +62,4 @@ private:
CmdDeleteItemExecData* m_commandData;
};
} // end namespace caf

View File

@ -34,13 +34,10 @@
//
//##################################################################################################
#include "cafCmdDeleteItemExecData.h"
namespace caf
{
CAF_PDM_SOURCE_INIT(CmdDeleteItemExecData, "CmdDeleteItemExecData");
CAF_PDM_SOURCE_INIT( CmdDeleteItemExecData, "CmdDeleteItemExecData" );
} // end namespace caf

View File

@ -34,16 +34,13 @@
//
//##################################################################################################
#pragma once
#include "cafPdmObject.h"
#include "cafPdmField.h"
#include "cafPdmObject.h"
namespace caf
{
//==================================================================================================
///
//==================================================================================================
@ -54,11 +51,26 @@ class CmdDeleteItemExecData : public PdmObject
public:
CmdDeleteItemExecData()
{
CAF_PDM_InitObject("CmdDeleteItemExecData uiName", "", "CmdDeleteItemExecData tooltip", "CmdDeleteItemExecData whatsthis");
CAF_PDM_InitObject( "CmdDeleteItemExecData uiName",
"",
"CmdDeleteItemExecData tooltip",
"CmdDeleteItemExecData whatsthis" );
CAF_PDM_InitField(&m_pathToField, "PathToField", QString(), "PathToField", "", "PathToField tooltip", "PathToField whatsthis");
CAF_PDM_InitField(&m_indexToObject, "indexToObject", -1, "indexToObject", "", "indexToObject tooltip", "indexToObject whatsthis");
CAF_PDM_InitField(&m_deletedObjectAsXml, "deletedObjectAsXml", QString(), "deletedObjectAsXml", "", "deletedObjectAsXml tooltip", "deletedObjectAsXml whatsthis");
CAF_PDM_InitField( &m_pathToField, "PathToField", QString(), "PathToField", "", "PathToField tooltip", "PathToField whatsthis" );
CAF_PDM_InitField( &m_indexToObject,
"indexToObject",
-1,
"indexToObject",
"",
"indexToObject tooltip",
"indexToObject whatsthis" );
CAF_PDM_InitField( &m_deletedObjectAsXml,
"deletedObjectAsXml",
QString(),
"deletedObjectAsXml",
"",
"deletedObjectAsXml tooltip",
"deletedObjectAsXml whatsthis" );
}
caf::PdmPointer<PdmObjectHandle> m_rootObject;
@ -68,6 +80,4 @@ public:
caf::PdmField<QString> m_deletedObjectAsXml;
};
} // end namespace caf

View File

@ -36,9 +36,9 @@
#include "cafCmdDeleteItemFeature.h"
#include "cafCmdExecCommandManager.h"
#include "cafCmdDeleteItemExec.h"
#include "cafCmdDeleteItemExecData.h"
#include "cafCmdExecCommandManager.h"
#include "cafCmdSelectionHelper.h"
#include "cafPdmReferenceHelper.h"
#include "cafSelectionManager.h"
@ -50,7 +50,7 @@
namespace caf
{
CAF_CMD_SOURCE_INIT(CmdDeleteItemFeature, "PdmListField_DeleteItem");
CAF_CMD_SOURCE_INIT( CmdDeleteItemFeature, "PdmListField_DeleteItem" );
//--------------------------------------------------------------------------------------------------
///
@ -58,44 +58,45 @@ namespace caf
CmdExecuteCommand* CmdDeleteItemFeature::createExecuteCommand()
{
std::vector<PdmUiItem*> items;
SelectionManager::instance()->selectedItems(items, SelectionManager::FIRST_LEVEL);
SelectionManager::instance()->selectedItems( items, SelectionManager::FIRST_LEVEL );
caf::PdmChildArrayFieldHandle* childArrayFieldHandle = caf::SelectionManager::instance()->activeChildArrayFieldHandle();
if (!childArrayFieldHandle) return nullptr;
caf::PdmChildArrayFieldHandle* childArrayFieldHandle =
caf::SelectionManager::instance()->activeChildArrayFieldHandle();
if ( !childArrayFieldHandle ) return nullptr;
caf::PdmObjectHandle* currentPdmObject = nullptr;
for (size_t i = 0; i < items.size(); i++)
for ( size_t i = 0; i < items.size(); i++ )
{
if (dynamic_cast<caf::PdmUiObjectHandle*>(items[i]))
if ( dynamic_cast<caf::PdmUiObjectHandle*>( items[i] ) )
{
currentPdmObject = dynamic_cast<caf::PdmUiObjectHandle*>(items[i])->objectHandle();
currentPdmObject = dynamic_cast<caf::PdmUiObjectHandle*>( items[i] )->objectHandle();
}
}
if (!currentPdmObject) return nullptr;
if ( !currentPdmObject ) return nullptr;
int indexAfter = -1;
std::vector<PdmObjectHandle*> childObjects;
childArrayFieldHandle->childObjects(&childObjects);
childArrayFieldHandle->childObjects( &childObjects );
for (size_t i = 0; i < childObjects.size(); i++)
for ( size_t i = 0; i < childObjects.size(); i++ )
{
if (childObjects[i] == currentPdmObject)
if ( childObjects[i] == currentPdmObject )
{
indexAfter = static_cast<int>(i);
indexAfter = static_cast<int>( i );
}
}
// Did not find currently selected pdm object in the current list field
CAF_ASSERT(indexAfter != -1);
CAF_ASSERT( indexAfter != -1 );
CmdDeleteItemExec* executeCmd = new CmdDeleteItemExec(SelectionManager::instance()->notificationCenter());
CmdDeleteItemExec* executeCmd = new CmdDeleteItemExec( SelectionManager::instance()->notificationCenter() );
CmdDeleteItemExecData* data = executeCmd->commandData();
data->m_rootObject = PdmReferenceHelper::findRoot(childArrayFieldHandle);
data->m_pathToField = PdmReferenceHelper::referenceFromRootToField(data->m_rootObject, childArrayFieldHandle);
data->m_rootObject = PdmReferenceHelper::findRoot( childArrayFieldHandle );
data->m_pathToField = PdmReferenceHelper::referenceFromRootToField( data->m_rootObject, childArrayFieldHandle );
data->m_indexToObject = indexAfter;
return executeCmd;
@ -106,11 +107,13 @@ CmdExecuteCommand* CmdDeleteItemFeature::createExecuteCommand()
//--------------------------------------------------------------------------------------------------
bool CmdDeleteItemFeature::isCommandEnabled()
{
caf::PdmObject* currentPdmObject = dynamic_cast<caf::PdmObject*>(caf::SelectionManager::instance()->selectedItem(caf::SelectionManager::FIRST_LEVEL));
if (!currentPdmObject) return false;
caf::PdmObject* currentPdmObject = dynamic_cast<caf::PdmObject*>(
caf::SelectionManager::instance()->selectedItem( caf::SelectionManager::FIRST_LEVEL ) );
if ( !currentPdmObject ) return false;
caf::PdmChildArrayFieldHandle* childArrayFieldHandle = caf::SelectionManager::instance()->activeChildArrayFieldHandle();
if (!childArrayFieldHandle) return false;
caf::PdmChildArrayFieldHandle* childArrayFieldHandle =
caf::SelectionManager::instance()->activeChildArrayFieldHandle();
if ( !childArrayFieldHandle ) return false;
return true;
}
@ -118,18 +121,18 @@ bool CmdDeleteItemFeature::isCommandEnabled()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdDeleteItemFeature::onActionTriggered(bool isChecked)
void CmdDeleteItemFeature::onActionTriggered( bool isChecked )
{
if (isCommandEnabled())
if ( isCommandEnabled() )
{
CmdExecuteCommand* exeCmd = createExecuteCommand();
if (exeCmd)
if ( exeCmd )
{
CmdExecCommandManager::instance()->processExecuteCommand(exeCmd);
CmdExecCommandManager::instance()->processExecuteCommand( exeCmd );
}
else
{
CAF_ASSERT(0);
CAF_ASSERT( 0 );
}
}
}
@ -137,10 +140,10 @@ void CmdDeleteItemFeature::onActionTriggered(bool isChecked)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void CmdDeleteItemFeature::setupActionLook(QAction* actionToSetup)
void CmdDeleteItemFeature::setupActionLook( QAction* actionToSetup )
{
actionToSetup->setText("Delete object");
applyShortcutWithHintToAction(actionToSetup, QKeySequence::Delete);
actionToSetup->setText( "Delete object" );
applyShortcutWithHintToAction( actionToSetup, QKeySequence::Delete );
}
} // end namespace caf

View File

@ -34,20 +34,19 @@
//
//##################################################################################################
#pragma once
#include "cafCmdFeature.h"
namespace caf
{
//==================================================================================================
///
//==================================================================================================
class CmdDeleteItemFeature : public CmdFeature
{
CAF_CMD_HEADER_INIT;
protected:
CmdExecuteCommand* createExecuteCommand();
@ -57,6 +56,4 @@ protected:
void setupActionLook( QAction* actionToSetup ) override;
};
} // end namespace caf

View File

@ -44,8 +44,7 @@
namespace caf
{
CAF_CMD_SOURCE_INIT(ToggleItemsFeature, "cafToggleItemsFeature");
CAF_CMD_SOURCE_INIT( ToggleItemsFeature, "cafToggleItemsFeature" );
//--------------------------------------------------------------------------------------------------
///
@ -58,22 +57,22 @@ bool ToggleItemsFeature::isCommandEnabled()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void ToggleItemsFeature::onActionTriggered(bool isChecked)
void ToggleItemsFeature::onActionTriggered( bool isChecked )
{
ToggleItemsFeatureImpl::setObjectToggleStateForSelection(ToggleItemsFeatureImpl::TOGGLE_SUBITEMS);
ToggleItemsFeatureImpl::setObjectToggleStateForSelection( ToggleItemsFeatureImpl::TOGGLE_SUBITEMS );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void ToggleItemsFeature::setupActionLook(QAction* actionToSetup)
void ToggleItemsFeature::setupActionLook( QAction* actionToSetup )
{
if (ToggleItemsFeatureImpl::isToggleCommandsForSubItems())
actionToSetup->setText("Toggle Sub Items");
if ( ToggleItemsFeatureImpl::isToggleCommandsForSubItems() )
actionToSetup->setText( "Toggle Sub Items" );
else
actionToSetup->setText("Toggle");
actionToSetup->setText( "Toggle" );
actionToSetup->setIcon(QIcon(":/cafCommandFeatures/ToggleOnOffL16x16.png"));
actionToSetup->setIcon( QIcon( ":/cafCommandFeatures/ToggleOnOffL16x16.png" ) );
}
}
} // namespace caf

View File

@ -46,12 +46,12 @@ namespace caf
class ToggleItemsFeature : public caf::CmdFeature
{
CAF_CMD_HEADER_INIT;
protected:
protected:
// Overrides
bool isCommandEnabled() override;
void onActionTriggered( bool isChecked ) override;
void setupActionLook( QAction* actionToSetup ) override;
};
}
} // namespace caf

View File

@ -50,38 +50,36 @@
#include <QModelIndex>
#include <vector>
#include "cafCmdFeatureManager.h"
#include <vector>
namespace caf
{
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool ToggleItemsFeatureImpl::isToggleCommandsAvailable()
{
std::vector<caf::PdmUiItem*> selectedItems;
caf::SelectionManager::instance()->selectedItems(selectedItems);
caf::SelectionManager::instance()->selectedItems( selectedItems );
if (selectedItems.size() == 1)
if ( selectedItems.size() == 1 )
{
caf::PdmUiTreeOrdering* treeItem = findTreeItemFromSelectedUiItem(selectedItems[0]);
caf::PdmUiTreeOrdering* treeItem = findTreeItemFromSelectedUiItem( selectedItems[0] );
if (!treeItem) return false;
if ( !treeItem ) return false;
for (int cIdx = 0; cIdx < treeItem->childCount(); ++ cIdx)
for ( int cIdx = 0; cIdx < treeItem->childCount(); ++cIdx )
{
caf::PdmUiTreeOrdering* child = treeItem->child(cIdx);
if (!child) continue;
if (!child->isRepresentingObject()) continue;
caf::PdmUiTreeOrdering* child = treeItem->child( cIdx );
if ( !child ) continue;
if ( !child->isRepresentingObject() ) continue;
caf::PdmObjectHandle* childObj = child->object();
caf::PdmUiObjectHandle* uiObjectHandleChild = uiObj(childObj);
caf::PdmUiObjectHandle* uiObjectHandleChild = uiObj( childObj );
if (uiObjectHandleChild &&
uiObjectHandleChild->objectToggleField() &&
!uiObjectHandleChild->objectToggleField()->uiCapability()->isUiReadOnly())
if ( uiObjectHandleChild && uiObjectHandleChild->objectToggleField() &&
!uiObjectHandleChild->objectToggleField()->uiCapability()->isUiReadOnly() )
{
return true;
}
@ -89,11 +87,11 @@ bool ToggleItemsFeatureImpl::isToggleCommandsAvailable()
}
else
{
for (size_t i = 0; i < selectedItems.size(); ++i)
for ( size_t i = 0; i < selectedItems.size(); ++i )
{
caf::PdmUiObjectHandle* uiObjectHandle = dynamic_cast<caf::PdmUiObjectHandle*>(selectedItems[i]);
caf::PdmUiObjectHandle* uiObjectHandle = dynamic_cast<caf::PdmUiObjectHandle*>( selectedItems[i] );
if (uiObjectHandle && uiObjectHandle->objectToggleField())
if ( uiObjectHandle && uiObjectHandle->objectToggleField() )
{
return true;
}
@ -109,8 +107,8 @@ bool ToggleItemsFeatureImpl::isToggleCommandsAvailable()
bool ToggleItemsFeatureImpl::isToggleCommandsForSubItems()
{
std::vector<caf::PdmUiItem*> selectedItems;
caf::SelectionManager::instance()->selectedItems(selectedItems);
if (isToggleCommandsAvailable() && selectedItems.size() == 1)
caf::SelectionManager::instance()->selectedItems( selectedItems );
if ( isToggleCommandsAvailable() && selectedItems.size() == 1 )
{
return true;
}
@ -120,55 +118,55 @@ bool ToggleItemsFeatureImpl::isToggleCommandsForSubItems()
//--------------------------------------------------------------------------------------------------
/// Set toggle state for list of model indices.
//--------------------------------------------------------------------------------------------------
void ToggleItemsFeatureImpl::setObjectToggleStateForSelection(SelectionToggleType state)
void ToggleItemsFeatureImpl::setObjectToggleStateForSelection( SelectionToggleType state )
{
std::vector<caf::PdmUiItem*> selectedItems;
caf::SelectionManager::instance()->selectedItems(selectedItems);
if (state != TOGGLE && selectedItems.size() == 1)
caf::SelectionManager::instance()->selectedItems( selectedItems );
if ( state != TOGGLE && selectedItems.size() == 1 )
{
// If only one item is selected, loop over its children, and toggle them instead of the
// selected item directly
// We need to get the children through the tree view, because that is where the actually shown children is
caf::PdmUiTreeOrdering* treeItem = findTreeItemFromSelectedUiItem(selectedItems[0]);
caf::PdmUiTreeOrdering* treeItem = findTreeItemFromSelectedUiItem( selectedItems[0] );
if (!treeItem) return;
if ( !treeItem ) return;
for (int cIdx = 0; cIdx < treeItem->childCount(); ++ cIdx)
for ( int cIdx = 0; cIdx < treeItem->childCount(); ++cIdx )
{
caf::PdmUiTreeOrdering* child = treeItem->child(cIdx);
if (!child) continue;
if (!child->isRepresentingObject()) continue;
caf::PdmUiTreeOrdering* child = treeItem->child( cIdx );
if ( !child ) continue;
if ( !child->isRepresentingObject() ) continue;
caf::PdmObjectHandle* childObj = child->object();
caf::PdmUiObjectHandle* uiObjectHandleChild = uiObj(childObj);
caf::PdmUiObjectHandle* uiObjectHandleChild = uiObj( childObj );
if (uiObjectHandleChild && uiObjectHandleChild->objectToggleField())
if ( uiObjectHandleChild && uiObjectHandleChild->objectToggleField() )
{
caf::PdmField<bool>* field = dynamic_cast<caf::PdmField<bool>*>(uiObjectHandleChild->objectToggleField());
caf::PdmField<bool>* field = dynamic_cast<caf::PdmField<bool>*>( uiObjectHandleChild->objectToggleField() );
if (state == TOGGLE_ON) field->setValueWithFieldChanged(true);
if (state == TOGGLE_OFF) field->setValueWithFieldChanged(false);
if (state == TOGGLE_SUBITEMS) field->setValueWithFieldChanged(!(field->v()));
if ( state == TOGGLE_ON ) field->setValueWithFieldChanged( true );
if ( state == TOGGLE_OFF ) field->setValueWithFieldChanged( false );
if ( state == TOGGLE_SUBITEMS ) field->setValueWithFieldChanged( !( field->v() ) );
}
}
}
else
{
for (size_t i = 0; i < selectedItems.size(); ++i)
for ( size_t i = 0; i < selectedItems.size(); ++i )
{
caf::PdmUiObjectHandle* uiObjectHandle = dynamic_cast< caf::PdmUiObjectHandle*>(selectedItems[i]);
caf::PdmUiObjectHandle* uiObjectHandle = dynamic_cast<caf::PdmUiObjectHandle*>( selectedItems[i] );
if (uiObjectHandle && uiObjectHandle->objectToggleField())
if ( uiObjectHandle && uiObjectHandle->objectToggleField() )
{
caf::PdmField<bool>* field = dynamic_cast<caf::PdmField<bool>* >(uiObjectHandle->objectToggleField());
caf::PdmField<bool>* field = dynamic_cast<caf::PdmField<bool>*>( uiObjectHandle->objectToggleField() );
if (state == TOGGLE_ON) field->setValueWithFieldChanged(true);
if (state == TOGGLE_OFF) field->setValueWithFieldChanged(false);
if (state == TOGGLE_SUBITEMS || state == TOGGLE)
if ( state == TOGGLE_ON ) field->setValueWithFieldChanged( true );
if ( state == TOGGLE_OFF ) field->setValueWithFieldChanged( false );
if ( state == TOGGLE_SUBITEMS || state == TOGGLE )
{
field->setValueWithFieldChanged(!(field->v()));
field->setValueWithFieldChanged( !( field->v() ) );
}
}
}
@ -178,9 +176,10 @@ void ToggleItemsFeatureImpl::setObjectToggleStateForSelection(SelectionToggleTyp
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::PdmUiTreeView* ToggleItemsFeatureImpl::findTreeView(const caf::PdmUiItem* uiItem)
caf::PdmUiTreeView* ToggleItemsFeatureImpl::findTreeView( const caf::PdmUiItem* uiItem )
{
caf::PdmUiTreeView* customActiveTreeView = dynamic_cast<caf::PdmUiTreeView*>(CmdFeatureManager::instance()->currentContextMenuTargetWidget());
caf::PdmUiTreeView* customActiveTreeView =
dynamic_cast<caf::PdmUiTreeView*>( CmdFeatureManager::instance()->currentContextMenuTargetWidget() );
return customActiveTreeView;
}
@ -188,17 +187,17 @@ caf::PdmUiTreeView* ToggleItemsFeatureImpl::findTreeView(const caf::PdmUiItem* u
//--------------------------------------------------------------------------------------------------
/// Finds the tree item in either the 3D main window or plot main window project tree view
//--------------------------------------------------------------------------------------------------
caf::PdmUiTreeOrdering* ToggleItemsFeatureImpl::findTreeItemFromSelectedUiItem(const caf::PdmUiItem* uiItem)
caf::PdmUiTreeOrdering* ToggleItemsFeatureImpl::findTreeItemFromSelectedUiItem( const caf::PdmUiItem* uiItem )
{
caf::PdmUiTreeView* pdmUiTreeView = findTreeView(uiItem);
caf::PdmUiTreeView* pdmUiTreeView = findTreeView( uiItem );
if (pdmUiTreeView)
if ( pdmUiTreeView )
{
QModelIndex modIndex = pdmUiTreeView->findModelIndex(uiItem);
return static_cast<caf::PdmUiTreeOrdering*>(modIndex.internalPointer());
QModelIndex modIndex = pdmUiTreeView->findModelIndex( uiItem );
return static_cast<caf::PdmUiTreeOrdering*>( modIndex.internalPointer() );
}
return nullptr;
}
}
} // namespace caf

View File

@ -38,10 +38,9 @@
namespace caf
{
class PdmUiItem;
class PdmUiTreeOrdering;
class PdmUiTreeView;
class PdmUiItem;
class PdmUiTreeOrdering;
class PdmUiTreeView;
//==================================================================================================
///
@ -60,11 +59,11 @@ public:
static bool isToggleCommandsAvailable();
static bool isToggleCommandsForSubItems();
static void setObjectToggleStateForSelection(SelectionToggleType state);
static void setObjectToggleStateForSelection( SelectionToggleType state );
private:
static caf::PdmUiTreeView* findTreeView(const caf::PdmUiItem* uiItem);
static caf::PdmUiTreeOrdering* findTreeItemFromSelectedUiItem(const caf::PdmUiItem* uiItem);
static caf::PdmUiTreeView* findTreeView( const caf::PdmUiItem* uiItem );
static caf::PdmUiTreeOrdering* findTreeItemFromSelectedUiItem( const caf::PdmUiItem* uiItem );
};
};
}; // namespace caf

View File

@ -44,8 +44,7 @@
namespace caf
{
CAF_CMD_SOURCE_INIT(ToggleItemsOffFeature, "cafToggleItemsOffFeature");
CAF_CMD_SOURCE_INIT( ToggleItemsOffFeature, "cafToggleItemsOffFeature" );
//--------------------------------------------------------------------------------------------------
///
@ -58,23 +57,22 @@ bool ToggleItemsOffFeature::isCommandEnabled()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void ToggleItemsOffFeature::onActionTriggered(bool isChecked)
void ToggleItemsOffFeature::onActionTriggered( bool isChecked )
{
ToggleItemsFeatureImpl::setObjectToggleStateForSelection(ToggleItemsFeatureImpl::TOGGLE_OFF);
ToggleItemsFeatureImpl::setObjectToggleStateForSelection( ToggleItemsFeatureImpl::TOGGLE_OFF );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void ToggleItemsOffFeature::setupActionLook(QAction* actionToSetup)
void ToggleItemsOffFeature::setupActionLook( QAction* actionToSetup )
{
if (ToggleItemsFeatureImpl::isToggleCommandsForSubItems())
actionToSetup->setText("Sub Items Off");
if ( ToggleItemsFeatureImpl::isToggleCommandsForSubItems() )
actionToSetup->setText( "Sub Items Off" );
else
actionToSetup->setText("Off");
actionToSetup->setIcon(QIcon(":/cafCommandFeatures/ToggleOffL16x16.png"));
actionToSetup->setText( "Off" );
actionToSetup->setIcon( QIcon( ":/cafCommandFeatures/ToggleOffL16x16.png" ) );
}
}
} // namespace caf

View File

@ -46,12 +46,12 @@ namespace caf
class ToggleItemsOffFeature : public caf::CmdFeature
{
CAF_CMD_HEADER_INIT;
protected:
protected:
// Overrides
bool isCommandEnabled() override;
void onActionTriggered( bool isChecked ) override;
void setupActionLook( QAction* actionToSetup ) override;
};
}
} // namespace caf

View File

@ -44,8 +44,7 @@
namespace caf
{
CAF_CMD_SOURCE_INIT(ToggleItemsOnFeature, "cafToggleItemsOnFeature");
CAF_CMD_SOURCE_INIT( ToggleItemsOnFeature, "cafToggleItemsOnFeature" );
//--------------------------------------------------------------------------------------------------
///
@ -58,23 +57,22 @@ bool ToggleItemsOnFeature::isCommandEnabled()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void ToggleItemsOnFeature::onActionTriggered(bool isChecked)
void ToggleItemsOnFeature::onActionTriggered( bool isChecked )
{
ToggleItemsFeatureImpl::setObjectToggleStateForSelection(ToggleItemsFeatureImpl::TOGGLE_ON);
ToggleItemsFeatureImpl::setObjectToggleStateForSelection( ToggleItemsFeatureImpl::TOGGLE_ON );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void ToggleItemsOnFeature::setupActionLook(QAction* actionToSetup)
void ToggleItemsOnFeature::setupActionLook( QAction* actionToSetup )
{
if (ToggleItemsFeatureImpl::isToggleCommandsForSubItems())
actionToSetup->setText("Sub Items On");
if ( ToggleItemsFeatureImpl::isToggleCommandsForSubItems() )
actionToSetup->setText( "Sub Items On" );
else
actionToSetup->setText("On");
actionToSetup->setIcon(QIcon(":/cafCommandFeatures/ToggleOnL16x16.png"));
actionToSetup->setText( "On" );
actionToSetup->setIcon( QIcon( ":/cafCommandFeatures/ToggleOnL16x16.png" ) );
}
}
} // namespace caf

View File

@ -40,19 +40,18 @@
namespace caf
{
//==================================================================================================
///
//==================================================================================================
class ToggleItemsOnFeature : public caf::CmdFeature
{
CAF_CMD_HEADER_INIT;
protected:
protected:
// Overrides
bool isCommandEnabled() override;
void onActionTriggered( bool isChecked ) override;
void setupActionLook( QAction* actionToSetup ) override;
};
}
} // namespace caf

View File

@ -40,15 +40,14 @@
#include "cafSelectionManager.h"
#include <QAction>
#include "cafPdmObjectHandle.h"
#include "cafPdmObject.h"
#include "cafPdmObjectHandle.h"
#include "cafPdmUiItem.h"
#include <QAction>
namespace caf
{
CAF_CMD_SOURCE_INIT(ToggleItemsOnOthersOffFeature, "cafToggleItemsOnOthersOffFeature");
CAF_CMD_SOURCE_INIT( ToggleItemsOnOthersOffFeature, "cafToggleItemsOnOthersOffFeature" );
//--------------------------------------------------------------------------------------------------
///
@ -56,63 +55,61 @@ CAF_CMD_SOURCE_INIT(ToggleItemsOnOthersOffFeature, "cafToggleItemsOnOthersOffFea
bool ToggleItemsOnOthersOffFeature::isCommandEnabled()
{
std::vector<caf::PdmObject*> selectedObjects;
caf::SelectionManager::instance()->objectsByType(&selectedObjects);
caf::SelectionManager::instance()->objectsByType( &selectedObjects );
caf::PdmFieldHandle* commonParent = verifySameParentForSelection(selectedObjects);
std::vector<caf::PdmObjectHandle*> children = childObjects(commonParent);
caf::PdmFieldHandle* commonParent = verifySameParentForSelection( selectedObjects );
std::vector<caf::PdmObjectHandle*> children = childObjects( commonParent );
return commonParent != nullptr
&& children.size() > 0
&& objectToggleField(children.front())
&& children.size() > selectedObjects.size();
return commonParent != nullptr && children.size() > 0 && objectToggleField( children.front() ) &&
children.size() > selectedObjects.size();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void ToggleItemsOnOthersOffFeature::onActionTriggered(bool isChecked)
void ToggleItemsOnOthersOffFeature::onActionTriggered( bool isChecked )
{
std::vector<caf::PdmObject*> selectedObjects;
caf::SelectionManager::instance()->objectsByType(&selectedObjects);
caf::SelectionManager::instance()->objectsByType( &selectedObjects );
// First toggle off all siblings
caf::PdmFieldHandle* commonParent = verifySameParentForSelection(selectedObjects);
caf::PdmFieldHandle* commonParent = verifySameParentForSelection( selectedObjects );
for (caf::PdmObjectHandle* child : childObjects(commonParent))
for ( caf::PdmObjectHandle* child : childObjects( commonParent ) )
{
caf::PdmField<bool>* field = objectToggleField(child);
caf::PdmField<bool>* field = objectToggleField( child );
if (field)
if ( field )
{
field->setValueWithFieldChanged(false);
field->setValueWithFieldChanged( false );
}
}
// Then toggle on the selected item(s)
for (caf::PdmObject* selectedObject : selectedObjects)
for ( caf::PdmObject* selectedObject : selectedObjects )
{
caf::PdmField<bool>* field = dynamic_cast<caf::PdmField<bool>*>(selectedObject->objectToggleField());
caf::PdmField<bool>* field = dynamic_cast<caf::PdmField<bool>*>( selectedObject->objectToggleField() );
field->setValueWithFieldChanged(true);
field->setValueWithFieldChanged( true );
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void ToggleItemsOnOthersOffFeature::setupActionLook(QAction* actionToSetup)
void ToggleItemsOnOthersOffFeature::setupActionLook( QAction* actionToSetup )
{
actionToSetup->setText("On - Others Off");
actionToSetup->setIcon(QIcon(":/cafCommandFeatures/ToggleOnOthersOffL16x16.png"));
actionToSetup->setText( "On - Others Off" );
actionToSetup->setIcon( QIcon( ":/cafCommandFeatures/ToggleOnOthersOffL16x16.png" ) );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::PdmFieldHandle* ToggleItemsOnOthersOffFeature::verifySameParentForSelection(const std::vector<caf::PdmObject*>& selection)
caf::PdmFieldHandle*
ToggleItemsOnOthersOffFeature::verifySameParentForSelection( const std::vector<caf::PdmObject*>& selection )
{
caf::PdmFieldHandle* sameParent = nullptr;
@ -139,12 +136,12 @@ caf::PdmFieldHandle* ToggleItemsOnOthersOffFeature::verifySameParentForSelection
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<caf::PdmObjectHandle*> ToggleItemsOnOthersOffFeature::childObjects(caf::PdmFieldHandle* parent)
std::vector<caf::PdmObjectHandle*> ToggleItemsOnOthersOffFeature::childObjects( caf::PdmFieldHandle* parent )
{
std::vector<caf::PdmObjectHandle*> children;
if ( parent )
{
parent->childObjects(&children);
parent->childObjects( &children );
}
return children;
}
@ -152,14 +149,14 @@ std::vector<caf::PdmObjectHandle*> ToggleItemsOnOthersOffFeature::childObjects(c
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::PdmField<bool>* ToggleItemsOnOthersOffFeature::objectToggleField(caf::PdmObjectHandle* objectHandle)
caf::PdmField<bool>* ToggleItemsOnOthersOffFeature::objectToggleField( caf::PdmObjectHandle* objectHandle )
{
caf::PdmUiObjectHandle* childUiObject = uiObj(objectHandle);
caf::PdmUiObjectHandle* childUiObject = uiObj( objectHandle );
if ( childUiObject && childUiObject->objectToggleField() )
{
return dynamic_cast<caf::PdmField<bool>*>(childUiObject->objectToggleField());
return dynamic_cast<caf::PdmField<bool>*>( childUiObject->objectToggleField() );
}
return nullptr;
}
}
} // namespace caf

View File

@ -41,10 +41,9 @@
namespace caf
{
class PdmFieldHandle;
class PdmObject;
class PdmObjectHandle;
class PdmFieldHandle;
class PdmObject;
class PdmObjectHandle;
//==================================================================================================
///
@ -52,17 +51,17 @@ namespace caf
class ToggleItemsOnOthersOffFeature : public caf::CmdFeature
{
CAF_CMD_HEADER_INIT;
protected:
protected:
// Overrides
bool isCommandEnabled() override;
void onActionTriggered( bool isChecked ) override;
void setupActionLook( QAction* actionToSetup ) override;
private:
caf::PdmFieldHandle* verifySameParentForSelection(const std::vector<caf::PdmObject*>& selectedObjects);
std::vector<caf::PdmObjectHandle*> childObjects(caf::PdmFieldHandle* parent);
caf::PdmField<bool>* objectToggleField(caf::PdmObjectHandle* objectHandle);
caf::PdmFieldHandle* verifySameParentForSelection( const std::vector<caf::PdmObject*>& selectedObjects );
std::vector<caf::PdmObjectHandle*> childObjects( caf::PdmFieldHandle* parent );
caf::PdmField<bool>* objectToggleField( caf::PdmObjectHandle* objectHandle );
};
}
} // namespace caf

View File

@ -1,3 +1,6 @@
// clang-format off
//##################################################################################################
//
// Custom Visualization Core library
@ -59,6 +62,10 @@ Normalized coordinates i, j, k
Normalized origo in center of element
Normalized cell corners NCn in :
[NC0] = {-1,-1,-1}
[NC1] = { 1,-1,-1}
[NC2] = { 1, 1,-1}
@ -84,7 +91,8 @@ we use i,j,k to calculate all Nn, and then :
R = sum_n(Nn * Vn)
A point [P] = {x,y,z} inside a general element can then be calculated by the {i,j,k} coordinates correponding to the point and the corner positions Cn = {Cx_n, Cy_n, Cz_n} (n = 0..7) of the general hex as:
A point [P] = {x,y,z} inside a general element can then be calculated by the {i,j,k} coordinates correponding to the
point and the corner positions Cn = {Cx_n, Cy_n, Cz_n} (n = 0..7) of the general hex as:
x = sum_n(Nn * Cn_x)
y = sum_n(Nn * Cn_y)
@ -107,8 +115,8 @@ it can be written
[P] = [Cn]*[Nn]
As seen, we need to know the { i, j, k} position of the point. This can only be calculated using some sort of iterative solution, eg. Newton-Rapson.
Using m as iteration number we can use { im, jm, km } to evaluate [Nn] and name it [Nnm].
As seen, we need to know the { i, j, k} position of the point. This can only be calculated using some sort of iterative
solution, eg. Newton-Rapson. Using m as iteration number we can use { im, jm, km } to evaluate [Nn] and name it [Nnm].
We use an initial guess of {im,jm,km} = { 0.5, 0.5, 0.5} // But why ? the element origo is at 0,0,0 !
[Pm] = {xm, ym, zm} = sum_n(Nnm * Cn_x), sum_n(Nnm * Cn_y), sum_n(Nnm * Cn_z) } When using im,jm,km to evaluate Nnm
@ -131,6 +139,10 @@ The Jacobian is the partially derived x, y, z with respect to i, j, k as follows
J = | dx/dj dy/dj dz/dj |
| dx/dk dy/dk dz/dk |
The partial derivatives are calculated by deriving the function [F(i,j,k)] = [Pm(i,j,k)] - [P]
Since [P] is constant, this is the same as deriving [Pm(i,j,k)] = [Cn]*[Nnm]
Explicitly:
@ -195,33 +207,31 @@ dN7/dk = 1/8 * ( + 1 - i + j - ij )
The inverse Jacobian can be calculated by inverting the resulting Jacobian matrix for a specifically chosen set of i,j,k
*/
#include "cvfVector3.h"
#include "cvfMatrix3.h"
#include "cvfVector3.h"
#include <array>
namespace caf {
namespace caf
{
class HexInterpolator
{
public:
static double interpolateHex(const std::array<cvf::Vec3d, 8>& hexCorners,
static double interpolateHex( const std::array<cvf::Vec3d, 8>& hexCorners,
const std::array<double, 8>& values,
const cvf::Vec3d& point)
{
cvf::Vec3d pointInNormElm = findNormalizedCoords(hexCorners, point);
return interpolateInNormElm( pointInNormElm, values);
}
static std::array<double, 8> vertexWeights(const std::array<cvf::Vec3d, 8>& hexCorners,
const cvf::Vec3d& point )
{
cvf::Vec3d pointInNormElm = findNormalizedCoords(hexCorners, point);
return interpolationCoeffs(pointInNormElm);
cvf::Vec3d pointInNormElm = findNormalizedCoords( hexCorners, point );
return interpolateInNormElm( pointInNormElm, values );
}
static std::array<double, 8> vertexWeights( const std::array<cvf::Vec3d, 8>& hexCorners, const cvf::Vec3d& point )
{
cvf::Vec3d pointInNormElm = findNormalizedCoords( hexCorners, point );
return interpolationCoeffs( pointInNormElm );
}
static cvf::Mat3d jacobi(const std::array<cvf::Vec3d, 8>& hexCorners, const cvf::Vec3d & pointInNormalizedElement)
static cvf::Mat3d jacobi( const std::array<cvf::Vec3d, 8>& hexCorners, const cvf::Vec3d& pointInNormalizedElement )
{
const double k_1_8 = 0.125;
@ -229,45 +239,63 @@ public:
double j = pointInNormalizedElement[1];
double k = pointInNormalizedElement[2];
double ij = i*j;
double ik = i*k;
double jk = j*k;
double ij = i * j;
double ik = i * k;
double jk = j * k;
double C0_x = hexCorners[0][0]; double C0_y = hexCorners[0][1]; double C0_z = hexCorners[0][2];
double C1_x = hexCorners[1][0]; double C1_y = hexCorners[1][1]; double C1_z = hexCorners[1][2];
double C2_x = hexCorners[2][0]; double C2_y = hexCorners[2][1]; double C2_z = hexCorners[2][2];
double C3_x = hexCorners[3][0]; double C3_y = hexCorners[3][1]; double C3_z = hexCorners[3][2];
double C4_x = hexCorners[4][0]; double C4_y = hexCorners[4][1]; double C4_z = hexCorners[4][2];
double C5_x = hexCorners[5][0]; double C5_y = hexCorners[5][1]; double C5_z = hexCorners[5][2];
double C6_x = hexCorners[6][0]; double C6_y = hexCorners[6][1]; double C6_z = hexCorners[6][2];
double C7_x = hexCorners[7][0]; double C7_y = hexCorners[7][1]; double C7_z = hexCorners[7][2];
double C0_x = hexCorners[0][0];
double C0_y = hexCorners[0][1];
double C0_z = hexCorners[0][2];
double C1_x = hexCorners[1][0];
double C1_y = hexCorners[1][1];
double C1_z = hexCorners[1][2];
double C2_x = hexCorners[2][0];
double C2_y = hexCorners[2][1];
double C2_z = hexCorners[2][2];
double C3_x = hexCorners[3][0];
double C3_y = hexCorners[3][1];
double C3_z = hexCorners[3][2];
double C4_x = hexCorners[4][0];
double C4_y = hexCorners[4][1];
double C4_z = hexCorners[4][2];
double C5_x = hexCorners[5][0];
double C5_y = hexCorners[5][1];
double C5_z = hexCorners[5][2];
double C6_x = hexCorners[6][0];
double C6_y = hexCorners[6][1];
double C6_z = hexCorners[6][2];
double C7_x = hexCorners[7][0];
double C7_y = hexCorners[7][1];
double C7_z = hexCorners[7][2];
double dN0_di = (- 1 + j + k - jk);
double dN1_di = (+ 1 - j - k + jk);
double dN2_di = (+ 1 + j - k - jk);
double dN3_di = (- 1 - j + k + jk);
double dN4_di = (- 1 + j - k + jk);
double dN5_di = (+ 1 - j + k - jk);
double dN6_di = (+ 1 + j + k + jk);
double dN7_di = (- 1 - j - k - jk);
double dN0_di = ( -1 + j + k - jk );
double dN1_di = ( +1 - j - k + jk );
double dN2_di = ( +1 + j - k - jk );
double dN3_di = ( -1 - j + k + jk );
double dN4_di = ( -1 + j - k + jk );
double dN5_di = ( +1 - j + k - jk );
double dN6_di = ( +1 + j + k + jk );
double dN7_di = ( -1 - j - k - jk );
double dN0_dj = (- 1 + i + k - ik);
double dN1_dj = (- 1 - i + k + ik);
double dN2_dj = (+ 1 + i - k - ik);
double dN3_dj = (+ 1 - i - k + ik);
double dN4_dj = (- 1 + i - k + ik);
double dN5_dj = (- 1 - i - k - ik);
double dN6_dj = (+ 1 + i + k + ik);
double dN7_dj = (+ 1 - i + k - ik);
double dN0_dj = ( -1 + i + k - ik );
double dN1_dj = ( -1 - i + k + ik );
double dN2_dj = ( +1 + i - k - ik );
double dN3_dj = ( +1 - i - k + ik );
double dN4_dj = ( -1 + i - k + ik );
double dN5_dj = ( -1 - i - k - ik );
double dN6_dj = ( +1 + i + k + ik );
double dN7_dj = ( +1 - i + k - ik );
double dN0_dk = (- 1 + i + j - ij);
double dN1_dk = (- 1 - i + j + ij);
double dN2_dk = (- 1 - i - j - ij);
double dN3_dk = (- 1 + i - j + ij);
double dN4_dk = (+ 1 - i - j + ij);
double dN5_dk = (+ 1 + i - j - ij);
double dN6_dk = (+ 1 + i + j + ij);
double dN7_dk = (+ 1 - i + j - ij);
double dN0_dk = ( -1 + i + j - ij );
double dN1_dk = ( -1 - i + j + ij );
double dN2_dk = ( -1 - i - j - ij );
double dN3_dk = ( -1 + i - j + ij );
double dN4_dk = ( +1 - i - j + ij );
double dN5_dk = ( +1 + i - j - ij );
double dN6_dk = ( +1 + i + j + ij );
double dN7_dk = ( +1 - i + j - ij );
// clang-format off
double dx_di = k_1_8 * ( (dN0_di) * C0_x + (dN1_di) * C1_x + (dN2_di) * C2_x + (dN3_di) * C3_x + (dN4_di) * C4_x + (dN5_di) * C5_x + (dN6_di) * C6_x + (dN7_di) * C7_x );
double dx_dj = k_1_8 * ( (dN0_dj) * C0_x + (dN1_dj) * C1_x + (dN2_dj) * C2_x + (dN3_dj) * C3_x + (dN4_dj) * C4_x + (dN5_dj) * C5_x + (dN6_dj) * C6_x + (dN7_dj) * C7_x );
@ -296,40 +324,40 @@ public:
dx_dk, dy_dk, dz_dk
);
#endif
// clang-format on
}
private:
static double interpolateInNormElm( const cvf::Vec3d & pointInNormElm, const std::array<double, 8>& values)
static double interpolateInNormElm( const cvf::Vec3d& pointInNormElm, const std::array<double, 8>& values )
{
std::array<double, 8> Ni = interpolationCoeffs(pointInNormElm);
std::array<double, 8> Ni = interpolationCoeffs( pointInNormElm );
double result = 0.0;
for (int i = 0 ; i < 8 ; ++i )
for ( int i = 0; i < 8; ++i )
{
result += values[i]*Ni[i];
result += values[i] * Ni[i];
}
return result;
}
static cvf::Vec3d interpolateInNormElm( const cvf::Vec3d & pointInNormElm, const std::array<cvf::Vec3d, 8>& values)
static cvf::Vec3d interpolateInNormElm( const cvf::Vec3d& pointInNormElm, const std::array<cvf::Vec3d, 8>& values )
{
std::array<double, 8> Ni = interpolationCoeffs(pointInNormElm);
std::array<double, 8> Ni = interpolationCoeffs( pointInNormElm );
cvf::Vec3d result(cvf::Vec3d::ZERO);
cvf::Vec3d result( cvf::Vec3d::ZERO );
for (int i = 0 ; i < 8 ; ++i )
for ( int i = 0; i < 8; ++i )
{
result += values[i]*Ni[i];
result += values[i] * Ni[i];
}
return result;
}
static std::array<double, 8> interpolationCoeffs( const cvf::Vec3d & pointInNormalizedElement)
static std::array<double, 8> interpolationCoeffs( const cvf::Vec3d& pointInNormalizedElement )
{
const double k_1_8 = 0.125;
@ -344,33 +372,31 @@ private:
// could use as optimization ... >> double onk = 1 - k;
// could use as optimization ... >> double opk = 1 + k;
return {
k_1_8 *(1-i)*(1-j)*(1-k),
k_1_8 *(1+i)*(1-j)*(1-k),
k_1_8 *(1+i)*(1+j)*(1-k),
k_1_8 *(1-i)*(1+j)*(1-k),
k_1_8 *(1-i)*(1-j)*(1+k),
k_1_8 *(1+i)*(1-j)*(1+k),
k_1_8 *(1+i)*(1+j)*(1+k),
k_1_8 *(1-i)*(1+j)*(1+k)
};
return {k_1_8 * ( 1 - i ) * ( 1 - j ) * ( 1 - k ),
k_1_8 * ( 1 + i ) * ( 1 - j ) * ( 1 - k ),
k_1_8 * ( 1 + i ) * ( 1 + j ) * ( 1 - k ),
k_1_8 * ( 1 - i ) * ( 1 + j ) * ( 1 - k ),
k_1_8 * ( 1 - i ) * ( 1 - j ) * ( 1 + k ),
k_1_8 * ( 1 + i ) * ( 1 - j ) * ( 1 + k ),
k_1_8 * ( 1 + i ) * ( 1 + j ) * ( 1 + k ),
k_1_8 * ( 1 - i ) * ( 1 + j ) * ( 1 + k )};
}
static cvf::Vec3d findNormalizedCoords(const std::array<cvf::Vec3d, 8>& hexCorners, const cvf::Vec3d& P)
static cvf::Vec3d findNormalizedCoords( const std::array<cvf::Vec3d, 8>& hexCorners, const cvf::Vec3d& P )
{
cvf::Vec3d normPoint = {0.0, 0.0, 0.0}; // Start value
int m = 0;
while ( m < 5 )
{
cvf::Vec3d Pm = interpolateInNormElm(normPoint, hexCorners);
cvf::Vec3d Pm = interpolateInNormElm( normPoint, hexCorners );
cvf::Vec3d Pdiff = Pm - P;
if (Pdiff.lengthSquared() < 1e-3) break;
if ( Pdiff.lengthSquared() < 1e-3 ) break;
cvf::Mat3d J_inv = jacobi(hexCorners, normPoint) ;
cvf::Mat3d J_inv = jacobi( hexCorners, normPoint );
bool inversionOk = J_inv.invert();
if ( !inversionOk ) break;
cvf::Vec3d ijkStep = Pdiff.getTransformedVector(J_inv);
cvf::Vec3d ijkStep = Pdiff.getTransformedVector( J_inv );
normPoint = normPoint - ijkStep;
@ -381,4 +407,6 @@ private:
}
};
}
} // namespace caf
// clang-format on

View File

@ -34,283 +34,280 @@
//
//##################################################################################################
#include <iostream>
#include "gtest/gtest.h"
#include <iostream>
#include "../cafHexInterpolator.h"
#include "cvfMatrix4.h"
namespace caf {
namespace caf
{
class HexInterpolatorTester
{
};
}
} // namespace caf
void testHex(const std::array<cvf::Vec3d, 8>& hexCorners, double tolerance = 1e-4)
void testHex( const std::array<cvf::Vec3d, 8>& hexCorners, double tolerance = 1e-4 )
{
double result = 0.0;
result = caf::HexInterpolator::interpolateHex(hexCorners, {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0 }, hexCorners[0]);
EXPECT_NEAR(result, 0.0, tolerance);
result = caf::HexInterpolator::interpolateHex(hexCorners, {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0 }, hexCorners[1]);
EXPECT_NEAR(result, 1.0, tolerance);
result = caf::HexInterpolator::interpolateHex(hexCorners, {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0 }, hexCorners[2]);
EXPECT_NEAR(result, 2.0, tolerance);
result = caf::HexInterpolator::interpolateHex(hexCorners, {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0 }, hexCorners[3]);
EXPECT_NEAR(result, 3.0, tolerance);
result = caf::HexInterpolator::interpolateHex(hexCorners, {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0 }, hexCorners[4]);
EXPECT_NEAR(result, 4.0, tolerance);
result = caf::HexInterpolator::interpolateHex(hexCorners, {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0 }, hexCorners[5]);
EXPECT_NEAR(result, 5.0, tolerance);
result = caf::HexInterpolator::interpolateHex(hexCorners, {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0 }, hexCorners[6]);
EXPECT_NEAR(result, 6.0, tolerance);
result = caf::HexInterpolator::interpolateHex(hexCorners, {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0 }, hexCorners[7]);
EXPECT_NEAR(result, 7.0, tolerance);
result = caf::HexInterpolator::interpolateHex( hexCorners, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}, hexCorners[0] );
EXPECT_NEAR( result, 0.0, tolerance );
result = caf::HexInterpolator::interpolateHex( hexCorners, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}, hexCorners[1] );
EXPECT_NEAR( result, 1.0, tolerance );
result = caf::HexInterpolator::interpolateHex( hexCorners, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}, hexCorners[2] );
EXPECT_NEAR( result, 2.0, tolerance );
result = caf::HexInterpolator::interpolateHex( hexCorners, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}, hexCorners[3] );
EXPECT_NEAR( result, 3.0, tolerance );
result = caf::HexInterpolator::interpolateHex( hexCorners, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}, hexCorners[4] );
EXPECT_NEAR( result, 4.0, tolerance );
result = caf::HexInterpolator::interpolateHex( hexCorners, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}, hexCorners[5] );
EXPECT_NEAR( result, 5.0, tolerance );
result = caf::HexInterpolator::interpolateHex( hexCorners, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}, hexCorners[6] );
EXPECT_NEAR( result, 6.0, tolerance );
result = caf::HexInterpolator::interpolateHex( hexCorners, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}, hexCorners[7] );
EXPECT_NEAR( result, 7.0, tolerance );
cvf::Vec3d avg = cvf::Vec3d::ZERO;
for ( const auto & v : hexCorners) avg += v;
for ( const auto& v : hexCorners )
avg += v;
avg *= 0.125;
result = caf::HexInterpolator::interpolateHex(hexCorners, {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0 }, avg);
EXPECT_NEAR(result, 3.5, tolerance);
result = caf::HexInterpolator::interpolateHex( hexCorners, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}, avg );
EXPECT_NEAR( result, 3.5, tolerance );
}
TEST(InterpolationTest, UnitElement)
TEST( InterpolationTest, UnitElement )
{
// Identity element
std::array<cvf::Vec3d, 8> hexCorners = {
cvf::Vec3d(-1.0,-1.0,-1.0),
cvf::Vec3d( 1.0,-1.0,-1.0),
cvf::Vec3d( 1.0, 1.0,-1.0),
cvf::Vec3d(-1.0, 1.0,-1.0),
cvf::Vec3d(-1.0,-1.0, 1.0),
cvf::Vec3d( 1.0,-1.0, 1.0),
cvf::Vec3d( 1.0, 1.0, 1.0),
cvf::Vec3d(-1.0, 1.0, 1.0)
};
std::array<cvf::Vec3d, 8> hexCorners = {cvf::Vec3d( -1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, 1.0, 1.0 ),
cvf::Vec3d( -1.0, 1.0, 1.0 )};
testHex(hexCorners);
testHex( hexCorners );
}
TEST(InterpolationTest, ScaledElement)
TEST( InterpolationTest, ScaledElement )
{
// Identity element
std::array<cvf::Vec3d, 8> hexCorners = {
cvf::Vec3d(-1.0,-1.0,-1.0),
cvf::Vec3d( 1.0,-1.0,-1.0),
cvf::Vec3d( 1.0, 1.0,-1.0),
cvf::Vec3d(-1.0, 1.0,-1.0),
cvf::Vec3d(-1.0,-1.0, 1.0),
cvf::Vec3d( 1.0,-1.0, 1.0),
cvf::Vec3d( 1.0, 1.0, 1.0),
cvf::Vec3d(-1.0, 1.0, 1.0)
};
std::array<cvf::Vec3d, 8> hexCorners = {cvf::Vec3d( -1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, 1.0, 1.0 ),
cvf::Vec3d( -1.0, 1.0, 1.0 )};
for ( auto & v : hexCorners) v *= 2;
for ( auto& v : hexCorners )
v *= 2;
testHex(hexCorners);
testHex( hexCorners );
}
TEST(InterpolationTest, TranslatedElement)
TEST( InterpolationTest, TranslatedElement )
{
// Identity element
std::array<cvf::Vec3d, 8> hexCorners = {
cvf::Vec3d(-1.0,-1.0,-1.0),
cvf::Vec3d( 1.0,-1.0,-1.0),
cvf::Vec3d( 1.0, 1.0,-1.0),
cvf::Vec3d(-1.0, 1.0,-1.0),
cvf::Vec3d(-1.0,-1.0, 1.0),
cvf::Vec3d( 1.0,-1.0, 1.0),
cvf::Vec3d( 1.0, 1.0, 1.0),
cvf::Vec3d(-1.0, 1.0, 1.0)
};
std::array<cvf::Vec3d, 8> hexCorners = {cvf::Vec3d( -1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, 1.0, 1.0 ),
cvf::Vec3d( -1.0, 1.0, 1.0 )};
for ( auto & v : hexCorners) v += {2.2, 4.4, -7.6};
for ( auto& v : hexCorners )
v += {2.2, 4.4, -7.6};
testHex(hexCorners);
testHex( hexCorners );
}
TEST(InterpolationTest, RotatedElement)
TEST( InterpolationTest, RotatedElement )
{
// Identity element
std::array<cvf::Vec3d, 8> hexCorners = {
cvf::Vec3d(-1.0,-1.0,-1.0),
cvf::Vec3d( 1.0,-1.0,-1.0),
cvf::Vec3d( 1.0, 1.0,-1.0),
cvf::Vec3d(-1.0, 1.0,-1.0),
cvf::Vec3d(-1.0,-1.0, 1.0),
cvf::Vec3d( 1.0,-1.0, 1.0),
cvf::Vec3d( 1.0, 1.0, 1.0),
cvf::Vec3d(-1.0, 1.0, 1.0)
};
std::array<cvf::Vec3d, 8> hexCorners = {cvf::Vec3d( -1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, 1.0, 1.0 ),
cvf::Vec3d( -1.0, 1.0, 1.0 )};
cvf::Mat4d rot = cvf::Mat4d::fromRotation({1,1, 0}, 3.14159);
cvf::Mat4d rot = cvf::Mat4d::fromRotation( {1, 1, 0}, 3.14159 );
for ( auto & v : hexCorners) v.transformPoint(rot);
for ( auto& v : hexCorners )
v.transformPoint( rot );
testHex(hexCorners);
testHex( hexCorners );
}
TEST(InterpolationTest, CombinedUndeformed)
TEST( InterpolationTest, CombinedUndeformed )
{
// Identity element
std::array<cvf::Vec3d, 8> hexCorners = {
cvf::Vec3d(-1.0,-1.0,-1.0),
cvf::Vec3d( 1.0,-1.0,-1.0),
cvf::Vec3d( 1.0, 1.0,-1.0),
cvf::Vec3d(-1.0, 1.0,-1.0),
cvf::Vec3d(-1.0,-1.0, 1.0),
cvf::Vec3d( 1.0,-1.0, 1.0),
cvf::Vec3d( 1.0, 1.0, 1.0),
cvf::Vec3d(-1.0, 1.0, 1.0)
};
std::array<cvf::Vec3d, 8> hexCorners = {cvf::Vec3d( -1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, 1.0, 1.0 ),
cvf::Vec3d( -1.0, 1.0, 1.0 )};
for ( auto & v : hexCorners) v *= 2;
for ( auto& v : hexCorners )
v *= 2;
for ( auto & v : hexCorners) v += {2.2, 4.4, -7.6};
for ( auto& v : hexCorners )
v += {2.2, 4.4, -7.6};
cvf::Mat4d rot = cvf::Mat4d::fromRotation({1,1, 0}, 3.14159);
cvf::Mat4d rot = cvf::Mat4d::fromRotation( {1, 1, 0}, 3.14159 );
for ( auto & v : hexCorners) v.transformPoint(rot);
for ( auto& v : hexCorners )
v.transformPoint( rot );
testHex(hexCorners);
testHex( hexCorners );
}
TEST(InterpolationTest, Compressed)
TEST( InterpolationTest, Compressed )
{
// Identity element
std::array<cvf::Vec3d, 8> hexCorners = {
cvf::Vec3d(-1.0,-1.0,-1.0),
cvf::Vec3d( 1.0,-1.0,-1.0),
cvf::Vec3d( 1.0, 1.0,-1.0),
cvf::Vec3d(-1.0, 1.0,-1.0),
cvf::Vec3d(-1.0,-1.0, 1.0),
cvf::Vec3d( 1.0,-1.0, 1.0),
cvf::Vec3d( 1.0, 1.0, 1.0),
cvf::Vec3d(-1.0, 1.0, 1.0)
};
std::array<cvf::Vec3d, 8> hexCorners = {cvf::Vec3d( -1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, 1.0, 1.0 ),
cvf::Vec3d( -1.0, 1.0, 1.0 )};
for ( auto & v : hexCorners) v[0] *= 0.1;
for ( auto& v : hexCorners )
v[0] *= 0.1;
testHex(hexCorners);
testHex( hexCorners );
for ( auto & v : hexCorners) v[0] *= 10.0;
for ( auto & v : hexCorners) v[1] *= 0.1;
for ( auto& v : hexCorners )
v[0] *= 10.0;
for ( auto& v : hexCorners )
v[1] *= 0.1;
testHex(hexCorners);
testHex( hexCorners );
for ( auto & v : hexCorners) v[1] *= 10.0;
for ( auto & v : hexCorners) v[2] *= 0.1;
for ( auto& v : hexCorners )
v[1] *= 10.0;
for ( auto& v : hexCorners )
v[2] *= 0.1;
testHex(hexCorners);
testHex( hexCorners );
}
TEST(InterpolationTest, Scewed)
TEST( InterpolationTest, Scewed )
{
// Identity element
std::array<cvf::Vec3d, 8> hexCorners = {
cvf::Vec3d(-1.0,-1.0,-1.0),
cvf::Vec3d( 1.0,-1.0,-1.0),
cvf::Vec3d( 1.0, 1.0,-1.0),
cvf::Vec3d(-1.0, 1.0,-1.0),
cvf::Vec3d(-1.0,-1.0, 1.0),
cvf::Vec3d( 1.0,-1.0, 1.0),
cvf::Vec3d( 1.0, 1.0, 1.0),
cvf::Vec3d(-1.0, 1.0, 1.0)
};
std::array<cvf::Vec3d, 8> hexCorners = {cvf::Vec3d( -1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, 1.0, 1.0 ),
cvf::Vec3d( -1.0, 1.0, 1.0 )};
for ( int i = 4 ; i< 8 ; ++i) hexCorners[i] += {1.0, 0.0, 0.0};
for ( int i = 4; i < 8; ++i )
hexCorners[i] += {1.0, 0.0, 0.0};
testHex(hexCorners);
testHex( hexCorners );
}
TEST(InterpolationTest, Screwed)
TEST( InterpolationTest, Screwed )
{
// Identity element
std::array<cvf::Vec3d, 8> hexCorners = {
cvf::Vec3d(-1.0,-1.0,-1.0),
cvf::Vec3d( 1.0,-1.0,-1.0),
cvf::Vec3d( 1.0, 1.0,-1.0),
cvf::Vec3d(-1.0, 1.0,-1.0),
cvf::Vec3d(-1.0,-1.0, 1.0),
cvf::Vec3d( 1.0,-1.0, 1.0),
cvf::Vec3d( 1.0, 1.0, 1.0),
cvf::Vec3d(-1.0, 1.0, 1.0)
};
std::array<cvf::Vec3d, 8> hexCorners = {cvf::Vec3d( -1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, 1.0, 1.0 ),
cvf::Vec3d( -1.0, 1.0, 1.0 )};
cvf::Mat4d rot = cvf::Mat4d::fromRotation({0, 0, 1}, 1.0*0.25*3.14159);
cvf::Mat4d rot = cvf::Mat4d::fromRotation( {0, 0, 1}, 1.0 * 0.25 * 3.14159 );
for ( int i = 4 ; i< 8 ; ++i) hexCorners[i].transformPoint(rot);
for ( int i = 4; i < 8; ++i )
hexCorners[i].transformPoint( rot );
testHex(hexCorners);
testHex( hexCorners );
}
TEST(InterpolationTest, Warp)
TEST( InterpolationTest, Warp )
{
// Identity element
std::array<cvf::Vec3d, 8> hexCorners = {
cvf::Vec3d(-1.0,-1.0,-1.0),
cvf::Vec3d( 1.0,-1.0,-1.0),
cvf::Vec3d( 1.0, 1.0,-1.0),
cvf::Vec3d(-1.0, 1.0,-1.0),
cvf::Vec3d(-1.0,-1.0, 1.0),
cvf::Vec3d( 1.0,-1.0, 1.0),
cvf::Vec3d( 1.0, 1.0, 1.0),
cvf::Vec3d(-1.0, 1.0, 1.0)
};
std::array<cvf::Vec3d, 8> hexCorners = {cvf::Vec3d( -1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, 1.0, 1.0 ),
cvf::Vec3d( -1.0, 1.0, 1.0 )};
{
std::array<cvf::Vec3d, 8> cornerCopy = hexCorners;
// Compress x
for ( auto & v : cornerCopy ) v[0] *= 0.1;
for ( auto& v : cornerCopy )
v[0] *= 0.1;
cornerCopy[0][0] += 0.25;
cornerCopy[1][0] += 0.20;
cornerCopy[7][0] += 0.25;
cornerCopy[6][0] += 0.4;
testHex(cornerCopy);
testHex( cornerCopy );
}
{
std::array<cvf::Vec3d, 8> cornerCopy = hexCorners;
// Compress z
for ( auto & v : cornerCopy ) v[2] *= 0.1;
for ( auto& v : cornerCopy )
v[2] *= 0.1;
cornerCopy[0][2] += 0.25;
cornerCopy[2][2] += 0.25;
cornerCopy[4][2] += 0.2;
cornerCopy[6][2] += 0.4;
testHex(cornerCopy);
testHex( cornerCopy );
}
}
TEST(InterpolationTest, TotalCombined)
TEST( InterpolationTest, TotalCombined )
{
// Identity element
std::array<cvf::Vec3d, 8> hexCorners = {
cvf::Vec3d(-1.0,-1.0,-1.0),
cvf::Vec3d( 1.0,-1.0,-1.0),
cvf::Vec3d( 1.0, 1.0,-1.0),
cvf::Vec3d(-1.0, 1.0,-1.0),
cvf::Vec3d(-1.0,-1.0, 1.0),
cvf::Vec3d( 1.0,-1.0, 1.0),
cvf::Vec3d( 1.0, 1.0, 1.0),
cvf::Vec3d(-1.0, 1.0, 1.0)
};
std::array<cvf::Vec3d, 8> hexCorners = {cvf::Vec3d( -1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, -1.0, -1.0 ),
cvf::Vec3d( 1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, 1.0, -1.0 ),
cvf::Vec3d( -1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, -1.0, 1.0 ),
cvf::Vec3d( 1.0, 1.0, 1.0 ),
cvf::Vec3d( -1.0, 1.0, 1.0 )};
cvf::Mat4d rot = cvf::Mat4d::fromRotation({0, 0, 1}, 1.0*0.25*3.14159);
cvf::Mat4d rot = cvf::Mat4d::fromRotation( {0, 0, 1}, 1.0 * 0.25 * 3.14159 );
for ( int i = 4 ; i< 8 ; ++i) hexCorners[i].transformPoint(rot);
for ( int i = 4 ; i< 8 ; ++i) hexCorners[i] += {0.2, 0.0, 0.0};
for ( int i = 4; i < 8; ++i )
hexCorners[i].transformPoint( rot );
for ( int i = 4; i < 8; ++i )
hexCorners[i] += {0.2, 0.0, 0.0};
{
std::array<cvf::Vec3d, 8> cornerCopy = hexCorners;
// Compress z
for ( auto & v : hexCorners ) v[2] *= 0.3;
for ( auto& v : hexCorners )
v[2] *= 0.3;
hexCorners[0][2] += 0.25;
hexCorners[2][2] += 0.25;
@ -318,14 +315,16 @@ TEST(InterpolationTest, TotalCombined)
hexCorners[6][2] += 0.4;
}
for ( auto & v : hexCorners) v *= 200;
for ( auto& v : hexCorners )
v *= 200;
for ( auto & v : hexCorners) v += {2.3e5, 4.7e6, -2000};
for ( auto& v : hexCorners )
v += {2.3e5, 4.7e6, -2000};
cvf::Mat4d rot2 = cvf::Mat4d::fromRotation({1,1, 0}, 3.14159);
cvf::Mat4d rot2 = cvf::Mat4d::fromRotation( {1, 1, 0}, 3.14159 );
for ( auto & v : hexCorners) v.transformPoint(rot2);
for ( auto& v : hexCorners )
v.transformPoint( rot2 );
testHex(hexCorners);
testHex( hexCorners );
}

View File

@ -34,23 +34,21 @@
//
//##################################################################################################
#include "gtest/gtest.h"
#include <stdio.h>
#include <iostream>
#include <stdio.h>
#include <string>
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
int main(int argc, char **argv)
int main( int argc, char** argv )
{
testing::InitGoogleTest(&argc, argv);
testing::InitGoogleTest( &argc, argv );
int result = RUN_ALL_TESTS();
char text[5];
std::cin.getline(text, 5);
std::cin.getline( text, 5 );
return result;
}

View File

@ -1,9 +1,7 @@
namespace cvftest {
namespace cvftest
{
//==================================================================================================
//
//
@ -11,33 +9,32 @@ namespace cvftest {
class Utils
{
public:
static cvf::String getTestDataDir(const cvf::String& unitTestFolder)
static cvf::String getTestDataDir( const cvf::String& unitTestFolder )
{
#ifdef WIN32
std::string exe = std::string(testing::internal::GetArgvs()[0]);
std::string exe = std::string( testing::internal::GetArgvs()[0] );
#else
std::string dir = std::string(testing::internal::FilePath::GetCurrentDir().ToString());
std::string exe = dir + std::string("/") + std::string(testing::internal::GetArgvs()[0]);
std::string dir = std::string( testing::internal::FilePath::GetCurrentDir().ToString() );
std::string exe = dir + std::string( "/" ) + std::string( testing::internal::GetArgvs()[0] );
#endif
std::string testPath = exe.substr(0, exe.find(unitTestFolder.toStdString())) + std::string("TestData/");
std::string testPath = exe.substr( 0, exe.find( unitTestFolder.toStdString() ) ) + std::string( "TestData/" );
return testPath;
}
static cvf::String getGLSLDir(const cvf::String& unitTestFolder)
static cvf::String getGLSLDir( const cvf::String& unitTestFolder )
{
#ifdef WIN32
std::string exe = std::string(testing::internal::GetArgvs()[0]);
std::string exe = std::string( testing::internal::GetArgvs()[0] );
#else
std::string dir = std::string(testing::internal::FilePath::GetCurrentDir().ToString());
std::string exe = dir + std::string("/") + std::string(testing::internal::GetArgvs()[0]);
std::string dir = std::string( testing::internal::FilePath::GetCurrentDir().ToString() );
std::string exe = dir + std::string( "/" ) + std::string( testing::internal::GetArgvs()[0] );
#endif
std::string glslPath = exe.substr(0, exe.find(unitTestFolder.toStdString())) + std::string("../LibRender/glsl/");
std::string glslPath = exe.substr( 0, exe.find( unitTestFolder.toStdString() ) ) +
std::string( "../LibRender/glsl/" );
return glslPath;
}
};
}
} // namespace cvftest

View File

@ -46,7 +46,6 @@
namespace caf
{
//==================================================================================================
/// Partial specialization for PdmValueFieldSpecialization< cvf::Color3f >
//==================================================================================================
@ -55,26 +54,25 @@ template <>
class PdmValueFieldSpecialization<cvf::Color3f>
{
public:
static QVariant convert(const cvf::Color3f& value)
static QVariant convert( const cvf::Color3f& value )
{
QColor col;
col.setRgbF(value.r(), value.g(), value.b());
col.setRgbF( value.r(), value.g(), value.b() );
return col;
}
static void setFromVariant(const QVariant& variantValue, cvf::Color3f& value)
static void setFromVariant( const QVariant& variantValue, cvf::Color3f& value )
{
QColor col = variantValue.value<QColor>();
value.set(col.redF(), col.greenF(), col.blueF());
value.set( col.redF(), col.greenF(), col.blueF() );
}
static bool isEqual(const QVariant& variantValue, const QVariant& variantValue2)
static bool isEqual( const QVariant& variantValue, const QVariant& variantValue2 )
{
return variantValue == variantValue2;
}
};
} // end namespace caf

View File

@ -43,40 +43,37 @@
#include "cafPdmXmlMat4d.h"
namespace caf
{
template <>
class PdmValueFieldSpecialization < cvf::Mat4d >
class PdmValueFieldSpecialization<cvf::Mat4d>
{
public:
/// Convert the field value into a QVariant
static QVariant convert(const cvf::Mat4d& value)
static QVariant convert( const cvf::Mat4d& value )
{
QString str;
QTextStream textStream(&str);
QTextStream textStream( &str );
textStream << value;
return QVariant(str);
return QVariant( str );
}
/// Set the field value from a QVariant
static void setFromVariant(const QVariant& variantValue, cvf::Mat4d& value)
static void setFromVariant( const QVariant& variantValue, cvf::Mat4d& value )
{
QString str = variantValue.toString();
QTextStream textStream(&str);
QTextStream textStream( &str );
textStream >> value;
}
static bool isEqual(const QVariant& variantValue, const QVariant& variantValue2)
static bool isEqual( const QVariant& variantValue, const QVariant& variantValue2 )
{
return variantValue == variantValue2;
}
};
} // end namespace caf

View File

@ -43,42 +43,39 @@
#include "cafPdmXmlVec3d.h"
Q_DECLARE_METATYPE(cvf::Vec3d);
Q_DECLARE_METATYPE( cvf::Vec3d );
namespace caf
{
template <>
class PdmValueFieldSpecialization < cvf::Vec3d >
class PdmValueFieldSpecialization<cvf::Vec3d>
{
public:
/// Convert the field value into a QVariant
static QVariant convert(const cvf::Vec3d& value)
static QVariant convert( const cvf::Vec3d& value )
{
QString str;
QTextStream textStream(&str);
QTextStream textStream( &str );
textStream << value;
return QVariant(str);
return QVariant( str );
}
/// Set the field value from a QVariant
static void setFromVariant(const QVariant& variantValue, cvf::Vec3d& value)
static void setFromVariant( const QVariant& variantValue, cvf::Vec3d& value )
{
QString str = variantValue.toString();
QTextStream textStream(&str);
QTextStream textStream( &str );
textStream >> value;
}
static bool isEqual(const QVariant& variantValue, const QVariant& variantValue2)
static bool isEqual( const QVariant& variantValue, const QVariant& variantValue2 )
{
return variantValue == variantValue2;
}
};
} // end namespace caf

View File

@ -2,58 +2,57 @@
#include "gtest/gtest.h"
TEST(SerializeTest, PdmCoreColor3f)
TEST( SerializeTest, PdmCoreColor3f )
{
float r = 0.4f;
float g = 0.2f;
float b = 0.18f;
cvf::Color3f myColor(r, g, b);
cvf::Color3f myColor( r, g, b );
QString textString;
{
QTextStream out(&textString);
QTextStream out( &textString );
out << myColor;
EXPECT_EQ(0, textString.compare("0.4 0.2 0.18"));
EXPECT_EQ( 0, textString.compare( "0.4 0.2 0.18" ) );
}
{
cvf::Color3f decoded;
QTextStream out(&textString);
QTextStream out( &textString );
out >> decoded;
EXPECT_TRUE(decoded == myColor);
EXPECT_TRUE( decoded == myColor );
}
}
TEST(VariantTest, PdmCoreColor3f)
TEST( VariantTest, PdmCoreColor3f )
{
float r = 0.4f;
float g = 0.2f;
float b = 0.18f;
cvf::Color3f myColor(r, g, b);
cvf::Color3f myColor( r, g, b );
QVariant myVariant = caf::PdmValueFieldSpecialization<cvf::Color3f>::convert(myColor);
QVariant myVariant = caf::PdmValueFieldSpecialization<cvf::Color3f>::convert( myColor );
cvf::Color3f decoded;
caf::PdmValueFieldSpecialization<cvf::Color3f>::setFromVariant(myVariant, decoded);
caf::PdmValueFieldSpecialization<cvf::Color3f>::setFromVariant( myVariant, decoded );
EXPECT_FLOAT_EQ(myColor.r(), decoded.r());
EXPECT_FLOAT_EQ(myColor.g(), decoded.g());
EXPECT_NEAR(myColor.b(), decoded.b(), 0.01); // For some reason, 0.18 is not close enough to use EXPECT_FLOAT_EQ
EXPECT_FLOAT_EQ( myColor.r(), decoded.r() );
EXPECT_FLOAT_EQ( myColor.g(), decoded.g() );
EXPECT_NEAR( myColor.b(), decoded.b(), 0.01 ); // For some reason, 0.18 is not close enough to use EXPECT_FLOAT_EQ
}
TEST(SerializeSeveralTest, PdmCoreColor3f)
TEST( SerializeSeveralTest, PdmCoreColor3f )
{
float r = 0.4f;
float g = 0.2f;
float b = 0.18f;
cvf::Color3f myColor(r, g, b);
cvf::Color3f myColor( r, g, b );
QString textString;
{
QTextStream out(&textString);
QTextStream out( &textString );
out << myColor << " " << myColor;
}
}

View File

@ -23,51 +23,51 @@ cvf::Mat4d createMatrix()
double m32 = 0.32;
double m33 = 0.33;
cvf::Mat4d myVector(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33);
cvf::Mat4d myVector( m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33 );
return myVector;
}
TEST(SerializeTest, PdmCoreMat4d)
TEST( SerializeTest, PdmCoreMat4d )
{
cvf::Mat4d myMatrix = createMatrix();
QString textString;
{
QTextStream out(&textString);
QTextStream out( &textString );
out << myMatrix;
EXPECT_EQ(0, textString.compare("0 0.01 0.02 0.03 0.1 0.11 0.12 0.13 0.2 0.21 0.22 0.23 0.3 0.31 0.32 0.33"));
EXPECT_EQ( 0, textString.compare( "0 0.01 0.02 0.03 0.1 0.11 0.12 0.13 0.2 0.21 0.22 0.23 0.3 0.31 0.32 0.33" ) );
}
{
cvf::Mat4d decoded;
QTextStream out(&textString);
QTextStream out( &textString );
out >> decoded;
EXPECT_TRUE(decoded.equals(myMatrix));
EXPECT_TRUE( decoded.equals( myMatrix ) );
}
}
TEST(VariantTest, PdmCoreMat4d)
TEST( VariantTest, PdmCoreMat4d )
{
cvf::Mat4d myMatrix = createMatrix();
QVariant myVariant = caf::PdmValueFieldSpecialization<cvf::Mat4d>::convert(myMatrix);
QVariant myVariant = caf::PdmValueFieldSpecialization<cvf::Mat4d>::convert( myMatrix );
cvf::Mat4d decoded;
caf::PdmValueFieldSpecialization<cvf::Mat4d>::setFromVariant(myVariant, decoded);
caf::PdmValueFieldSpecialization<cvf::Mat4d>::setFromVariant( myVariant, decoded );
EXPECT_TRUE(decoded.equals(myMatrix));
EXPECT_TRUE( decoded.equals( myMatrix ) );
}
TEST(SerializeSeveralTest, PdmCoreMat4d)
TEST( SerializeSeveralTest, PdmCoreMat4d )
{
cvf::Mat4d myMatrix = createMatrix();
QString textString;
{
QTextStream out(&textString);
QTextStream out( &textString );
out << myMatrix << " " << myMatrix;
}
}

View File

@ -4,58 +4,58 @@
#include "cvfVector3.h"
TEST(SerializeTest, PdmCoreVec3d)
TEST( SerializeTest, PdmCoreVec3d )
{
double a = 2.4;
double b = 12.4;
double c = 232.778;
cvf::Vec3d myVector(a, b, c);
cvf::Vec3d myVector( a, b, c );
QString textString;
{
QTextStream out(&textString);
QTextStream out( &textString );
out << myVector;
EXPECT_EQ(0, textString.compare("2.4 12.4 232.778"));
EXPECT_EQ( 0, textString.compare( "2.4 12.4 232.778" ) );
}
{
cvf::Vec3d decoded;
QTextStream out(&textString);
QTextStream out( &textString );
out >> decoded;
EXPECT_TRUE(decoded.equals(myVector));
EXPECT_TRUE( decoded.equals( myVector ) );
}
}
TEST(VariantTest, PdmCoreVec3d)
TEST( VariantTest, PdmCoreVec3d )
{
double a = 2.4;
double b = 12.4;
double c = 232.778;
cvf::Vec3d myVector(a, b, c);
cvf::Vec3d myVector( a, b, c );
QVariant myVariant = caf::PdmValueFieldSpecialization<cvf::Vec3d>::convert(myVector);
QVariant myVariant = caf::PdmValueFieldSpecialization<cvf::Vec3d>::convert( myVector );
cvf::Vec3d decoded;
caf::PdmValueFieldSpecialization<cvf::Vec3d>::setFromVariant(myVariant, decoded);
caf::PdmValueFieldSpecialization<cvf::Vec3d>::setFromVariant( myVariant, decoded );
EXPECT_TRUE(decoded.equals(myVector));
EXPECT_TRUE( decoded.equals( myVector ) );
}
TEST(SerializeSeveralTest, PdmCoreVec3d)
TEST( SerializeSeveralTest, PdmCoreVec3d )
{
double a = 2.4;
double b = 12.4;
double c = 232.778;
cvf::Vec3d myVector(a, b, c);
cvf::Vec3d myVector( a, b, c );
QString textString;
{
QTextStream out(&textString);
QTextStream out( &textString );
out << myVector << " " << myVector;
}
}

View File

@ -34,23 +34,21 @@
//
//##################################################################################################
#include "gtest/gtest.h"
#include <stdio.h>
#include <iostream>
#include <stdio.h>
#include <string>
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
int main(int argc, char **argv)
int main( int argc, char** argv )
{
testing::InitGoogleTest(&argc, argv);
testing::InitGoogleTest( &argc, argv );
int result = RUN_ALL_TESTS();
char text[5];
std::cin.getline(text, 5);
std::cin.getline( text, 5 );
return result;
}

View File

@ -34,10 +34,8 @@
//
//##################################################################################################
#pragma once
#include "cafPdmCoreColor3f.h"
#include "cafPdmXmlColor3f.h"
#include "cafPdmUiCoreColor3f.h"
#include "cafPdmXmlColor3f.h"

View File

@ -37,5 +37,5 @@
#pragma once
#include "cafPdmCoreMat4d.h"
#include "cafPdmXmlMat4d.h"
#include "cafPdmUiCoreMat4d.h"
#include "cafPdmXmlMat4d.h"

View File

@ -34,9 +34,8 @@
//
//##################################################################################################
#pragma once
#include "cafPdmCoreVec3d.h"
#include "cafPdmXmlVec3d.h"
#include "cafPdmUiCoreVec3d.h"
#include "cafPdmXmlVec3d.h"

View File

@ -42,36 +42,33 @@ using namespace caf;
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void PdmFieldScriptabilityIOHandler<cvf::Color3f>::writeToField(cvf::Color3f& fieldValue,
void PdmFieldScriptabilityIOHandler<cvf::Color3f>::writeToField( cvf::Color3f& fieldValue,
QTextStream& inputStream,
caf::PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted)
bool stringsAreQuoted )
{
QString fieldStringValue;
PdmFieldScriptabilityIOHandler<QString>::writeToField(fieldStringValue,
PdmFieldScriptabilityIOHandler<QString>::writeToField( fieldStringValue,
inputStream,
errorMessageContainer,
stringsAreQuoted);
stringsAreQuoted );
QColor qColor(fieldStringValue);
if (qColor.isValid())
QColor qColor( fieldStringValue );
if ( qColor.isValid() )
{
fieldValue = cvf::Color3f(qColor.redF(), qColor.greenF(), qColor.blueF());
fieldValue = cvf::Color3f( qColor.redF(), qColor.greenF(), qColor.blueF() );
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void PdmFieldScriptabilityIOHandler<cvf::Color3f>::readFromField(const cvf::Color3f& fieldValue,
void PdmFieldScriptabilityIOHandler<cvf::Color3f>::readFromField( const cvf::Color3f& fieldValue,
QTextStream& outputStream,
bool quoteStrings,
bool quoteNonBuiltin)
bool quoteNonBuiltin )
{
QColor qColor(fieldValue.rByte(), fieldValue.gByte(), fieldValue.bByte());
QColor qColor( fieldValue.rByte(), fieldValue.gByte(), fieldValue.bByte() );
QString fieldStringValue = qColor.name();
PdmFieldScriptabilityIOHandler<QString>::readFromField(fieldStringValue, outputStream, quoteStrings);
PdmFieldScriptabilityIOHandler<QString>::readFromField( fieldStringValue, outputStream, quoteStrings );
}

View File

@ -37,19 +37,18 @@
#include "cvfColor3.h"
namespace caf
{
template <>
struct PdmFieldScriptabilityIOHandler<cvf::Color3f>
{
static void writeToField(cvf::Color3f& fieldValue,
static void writeToField( cvf::Color3f& fieldValue,
QTextStream& inputStream,
PdmScriptIOMessages* errorMessageContainer,
bool stringsAreQuoted = true);
static void readFromField(const cvf::Color3f& fieldValue,
bool stringsAreQuoted = true );
static void readFromField( const cvf::Color3f& fieldValue,
QTextStream& outputStream,
bool quoteStrings = true,
bool quoteNonBuiltins = false);
bool quoteNonBuiltins = false );
};
}
} // namespace caf

View File

@ -43,40 +43,37 @@
#include "cafPdmXmlMat3d.h"
namespace caf
{
template <>
class PdmValueFieldSpecialization < cvf::Mat3d >
class PdmValueFieldSpecialization<cvf::Mat3d>
{
public:
/// Convert the field value into a QVariant
static QVariant convert(const cvf::Mat3d& value)
static QVariant convert( const cvf::Mat3d& value )
{
QString str;
QTextStream textStream(&str);
QTextStream textStream( &str );
textStream << value;
return QVariant(str);
return QVariant( str );
}
/// Set the field value from a QVariant
static void setFromVariant(const QVariant& variantValue, cvf::Mat3d& value)
static void setFromVariant( const QVariant& variantValue, cvf::Mat3d& value )
{
QString str = variantValue.toString();
QTextStream textStream(&str);
QTextStream textStream( &str );
textStream >> value;
}
static bool isEqual(const QVariant& variantValue, const QVariant& variantValue2)
static bool isEqual( const QVariant& variantValue, const QVariant& variantValue2 )
{
return variantValue == variantValue2;
}
};
} // end namespace caf

View File

@ -37,5 +37,5 @@
#pragma once
#include "cafPdmCoreMat3d.h"
#include "cafPdmXmlMat3d.h"
#include "cafPdmUiCoreMat3d.h"
#include "cafPdmXmlMat3d.h"

View File

@ -47,39 +47,35 @@
namespace caf
{
template <>
class PdmUiFieldSpecialization < cvf::Mat3d >
class PdmUiFieldSpecialization<cvf::Mat3d>
{
public:
/// Convert the field value into a QVariant
static QVariant convert(const cvf::Mat3d& value)
static QVariant convert( const cvf::Mat3d& value )
{
return PdmValueFieldSpecialization< cvf::Mat3d >::convert(value);
return PdmValueFieldSpecialization<cvf::Mat3d>::convert( value );
}
/// Set the field value from a QVariant
static void setFromVariant(const QVariant& variantValue, cvf::Mat3d& value)
static void setFromVariant( const QVariant& variantValue, cvf::Mat3d& value )
{
PdmValueFieldSpecialization< cvf::Mat3d >::setFromVariant(variantValue, value);
PdmValueFieldSpecialization<cvf::Mat3d>::setFromVariant( variantValue, value );
}
static bool isDataElementEqual(const QVariant& variantValue, const QVariant& variantValue2)
static bool isDataElementEqual( const QVariant& variantValue, const QVariant& variantValue2 )
{
return PdmValueFieldSpecialization< cvf::Mat3d >::isEqual(variantValue, variantValue2);
return PdmValueFieldSpecialization<cvf::Mat3d>::isEqual( variantValue, variantValue2 );
}
/// Methods to get a list of options for a field, specialized for AppEnum
static QList<PdmOptionItemInfo> valueOptions(bool* useOptionsOnly, const cvf::Mat3d&)
static QList<PdmOptionItemInfo> valueOptions( bool* useOptionsOnly, const cvf::Mat3d& )
{
return QList<PdmOptionItemInfo>();
}
/// Methods to retrieve the possible PdmObject pointed to by a field
static void childObjects(const PdmDataValueField< cvf::Mat3d >&, std::vector<PdmObjectHandle*>*)
{ }
static void childObjects( const PdmDataValueField<cvf::Mat3d>&, std::vector<PdmObjectHandle*>* ) {}
};
} // end namespace caf

View File

@ -38,28 +38,28 @@
#include <QTextStream>
QTextStream& operator >> (QTextStream& str, cvf::Mat3d& value)
QTextStream& operator>>( QTextStream& str, cvf::Mat3d& value )
{
for (int r = 0; r < 3; ++r)
for ( int r = 0; r < 3; ++r )
{
for (int c = 0; c < 3; ++c)
for ( int c = 0; c < 3; ++c )
{
str >> value(r, c);
str >> value( r, c );
}
}
return str;
}
QTextStream& operator << (QTextStream& str, const cvf::Mat3d& value)
QTextStream& operator<<( QTextStream& str, const cvf::Mat3d& value )
{
for (int r = 0; r < 3; ++r)
for ( int r = 0; r < 3; ++r )
{
for (int c = 0; c < 3; ++c)
for ( int c = 0; c < 3; ++c )
{
str << value(r, c);
str << value( r, c );
if (r * c < 9)
if ( r * c < 9 )
{
str << " ";
}

View File

@ -41,5 +41,5 @@
class QTextStream;
QTextStream& operator >> (QTextStream& str, cvf::Mat3d& value);
QTextStream& operator << (QTextStream& str, const cvf::Mat3d& value);
QTextStream& operator>>( QTextStream& str, cvf::Mat3d& value );
QTextStream& operator<<( QTextStream& str, const cvf::Mat3d& value );

View File

@ -40,8 +40,9 @@
#include "cafPdmProxyValueField.h"
#include "cafPdmUiColorEditor.h"
namespace caf {
CAF_PDM_UI_REGISTER_DEFAULT_FIELD_EDITOR(PdmUiColorEditor, cvf::Color3f);
namespace caf
{
CAF_PDM_UI_REGISTER_DEFAULT_FIELD_EDITOR( PdmUiColorEditor, cvf::Color3f );
}
//--------------------------------------------------------------------------------------------------
@ -51,5 +52,4 @@ namespace caf {
//--------------------------------------------------------------------------------------------------
PdmColor3fInitializer::PdmColor3fInitializer()
{
}

View File

@ -45,47 +45,41 @@
#include "cafPdmCoreColor3f.h"
namespace caf
{
template <>
class PdmUiFieldSpecialization < cvf::Color3f >
class PdmUiFieldSpecialization<cvf::Color3f>
{
public:
/// Convert the field value into a QVariant
static QVariant convert(const cvf::Color3f& value)
static QVariant convert( const cvf::Color3f& value )
{
return PdmValueFieldSpecialization< cvf::Color3f >::convert(value);
return PdmValueFieldSpecialization<cvf::Color3f>::convert( value );
}
/// Set the field value from a QVariant
static void setFromVariant(const QVariant& variantValue, cvf::Color3f& value)
static void setFromVariant( const QVariant& variantValue, cvf::Color3f& value )
{
PdmValueFieldSpecialization< cvf::Color3f >::setFromVariant(variantValue, value);
PdmValueFieldSpecialization<cvf::Color3f>::setFromVariant( variantValue, value );
}
static bool isDataElementEqual(const QVariant& variantValue, const QVariant& variantValue2)
static bool isDataElementEqual( const QVariant& variantValue, const QVariant& variantValue2 )
{
return PdmValueFieldSpecialization< cvf::Color3f >::isEqual(variantValue, variantValue2);
return PdmValueFieldSpecialization<cvf::Color3f>::isEqual( variantValue, variantValue2 );
}
/// Methods to get a list of options for a field, specialized for AppEnum
static QList<PdmOptionItemInfo> valueOptions(bool* useOptionsOnly, const cvf::Color3f&)
static QList<PdmOptionItemInfo> valueOptions( bool* useOptionsOnly, const cvf::Color3f& )
{
return QList<PdmOptionItemInfo>();
}
/// Methods to retrieve the possible PdmObject pointed to by a field
static void childObjects(const PdmDataValueField< cvf::Color3f >&, std::vector<PdmObjectHandle*>*)
{ }
static void childObjects( const PdmDataValueField<cvf::Color3f>&, std::vector<PdmObjectHandle*>* ) {}
};
} // end namespace caf
//--------------------------------------------------------------------------------------------------
// If the macro for registering the editor is put as the single statement
// in a cpp file, a dummy static class must be used to make sure the compile unit

View File

@ -47,39 +47,35 @@
namespace caf
{
template <>
class PdmUiFieldSpecialization < cvf::Mat4d >
class PdmUiFieldSpecialization<cvf::Mat4d>
{
public:
/// Convert the field value into a QVariant
static QVariant convert(const cvf::Mat4d& value)
static QVariant convert( const cvf::Mat4d& value )
{
return PdmValueFieldSpecialization< cvf::Mat4d >::convert(value);
return PdmValueFieldSpecialization<cvf::Mat4d>::convert( value );
}
/// Set the field value from a QVariant
static void setFromVariant(const QVariant& variantValue, cvf::Mat4d& value)
static void setFromVariant( const QVariant& variantValue, cvf::Mat4d& value )
{
PdmValueFieldSpecialization< cvf::Mat4d >::setFromVariant(variantValue, value);
PdmValueFieldSpecialization<cvf::Mat4d>::setFromVariant( variantValue, value );
}
static bool isDataElementEqual(const QVariant& variantValue, const QVariant& variantValue2)
static bool isDataElementEqual( const QVariant& variantValue, const QVariant& variantValue2 )
{
return PdmValueFieldSpecialization< cvf::Mat4d >::isEqual(variantValue, variantValue2);
return PdmValueFieldSpecialization<cvf::Mat4d>::isEqual( variantValue, variantValue2 );
}
/// Methods to get a list of options for a field, specialized for AppEnum
static QList<PdmOptionItemInfo> valueOptions(bool* useOptionsOnly, const cvf::Mat4d&)
static QList<PdmOptionItemInfo> valueOptions( bool* useOptionsOnly, const cvf::Mat4d& )
{
return QList<PdmOptionItemInfo>();
}
/// Methods to retrieve the possible PdmObject pointed to by a field
static void childObjects(const PdmDataValueField< cvf::Mat4d >&, std::vector<PdmObjectHandle*>*)
{ }
static void childObjects( const PdmDataValueField<cvf::Mat4d>&, std::vector<PdmObjectHandle*>* ) {}
};
} // end namespace caf

View File

@ -41,10 +41,11 @@
#include "cafPdmUiLineEditor.h"
#include "cafPdmUiListEditor.h"
namespace caf {
CAF_PDM_UI_REGISTER_DEFAULT_FIELD_EDITOR(PdmUiLineEditor, cvf::Vec3d);
CAF_PDM_UI_REGISTER_DEFAULT_FIELD_EDITOR(PdmUiListEditor, std::vector<cvf::Vec3d>);
}
namespace caf
{
CAF_PDM_UI_REGISTER_DEFAULT_FIELD_EDITOR( PdmUiLineEditor, cvf::Vec3d );
CAF_PDM_UI_REGISTER_DEFAULT_FIELD_EDITOR( PdmUiListEditor, std::vector<cvf::Vec3d> );
} // namespace caf
//--------------------------------------------------------------------------------------------------
// If the macro for registering the editor is put as the single statement

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