1
0
mirror of https://git.dev.opencascade.org/repos/occt.git synced 2025-08-14 13:30:48 +03:00

Compare commits

..

9 Commits

Author SHA1 Message Date
sshutina
d979d19715 fix error 2025-04-11 11:02:51 +01:00
sshutina
f2f107d6f7 Add stream to json parser to read lines and points 2025-04-11 08:55:15 +01:00
Pasukhin Dmitry
7c8a432c8e Data Exchange, Step - Vis Material support #447
- Introduced STEPConstruct_RenderingProperties class to handle rendering properties in STEP format.
- Implemented constructors for initializing rendering properties from various sources including STEP entities, RGBA colors, and XCAF materials.
- Added methods to set and retrieve ambient, diffuse, and specular reflectance values, along with transparency and rendering method.
- Integrated functionality to create corresponding STEP and XCAF material entities.
2025-04-09 12:46:48 +01:00
Pasukhin Dmitry
74176f3b21 Data Exchange - Step Direction optimization #479
Refactor direction handling in STEP files for improved clarity and performance.
Moved to use array instead of vector
2025-04-06 16:48:09 +01:00
Pasukhin Dmitry
a897fd5942 Testing - Reorganize GitHub actions by actions #480
Refactor test workflow to be based on reusable actions.
2025-04-06 15:14:23 +01:00
Pasukhin Dmitry
5e5e7f1238 Testing - Units Tests for NCollection package #481
- Introduced tests for NCollection_Map, verifying constructors, addition, removal, and iteration functionalities.
- Added comprehensive tests for NCollection_Sequence, covering basic operations, iterator functionality, and complex type handling.
- Implemented tests for NCollection_SparseArray, including basic operations, iterator functionality, and data map interface.
- Created tests for NCollection_Vector, ensuring functionality for appending, resizing, and custom allocator usage.
2025-04-06 12:40:14 +01:00
Pasukhin Dmitry
638b0bfc40 Foundation Classes - HashUtils NoExcept optimization #473
Refactor hash functions in Standard_HashUtils for improved performanceю
Optimized load_bytes functionality.
Making all hash function noexcept
2025-04-04 16:38:56 +01:00
Dmitrii Kulikov
81efe3d3ed Data Exchange, Step Export - Decreasing file size #475
Functionality to remove duplicate entities from Step graph is added.
Class MergeSTEPEntities_Merger is main entry point.
Class MergeSTEPEntities_EntityProcessor implements the basic replacement
logic.
Children of MergeSTEPEntities_EntityProcessor implement the logic for
the replacement of particular step entity.
2025-04-03 17:23:10 +01:00
Pasukhin Dmitry
00ef3523af Testing - Inspector build error on latest CMake #477
Add CMAKE_POLICY_VERSION_MINIMUM to TInspector configuration for Windows and Linux
2025-04-03 13:25:40 +01:00
64 changed files with 7815 additions and 1851 deletions

221
.github/actions/build-occt/action.yml vendored Normal file
View File

@@ -0,0 +1,221 @@
name: 'Build OCCT'
description: 'Prepare and build OCCT on a specific platform'
inputs:
platform:
description: 'Platform (windows, macos, linux)'
required: true
compiler:
description: 'Compiler (msvc, clang, gcc)'
required: true
artifact-name:
description: 'Name of the artifact to store build results'
required: true
additional-cmake-flags:
description: 'Additional CMake flags'
required: false
default: ''
use-vtk:
description: 'Enable VTK'
required: false
default: 'true'
runs:
using: "composite"
steps:
- name: Download and extract 3rdparty dependencies (Windows)
if: ${{ inputs.platform == 'windows' }}
run: |
Invoke-WebRequest -Uri https://github.com/Open-Cascade-SAS/OCCT/releases/download/V7_9_0_beta1/3rdparty-vc14-64.zip -OutFile 3rdparty-vc14-64.zip
Expand-Archive -Path 3rdparty-vc14-64.zip -DestinationPath .
Remove-Item 3rdparty-vc14-64.zip
shell: pwsh
- name: Download and extract Mesa3D (Windows)
if: ${{ inputs.platform == 'windows' }}
run: |
curl -L -o mesa3d.7z https://github.com/pal1000/mesa-dist-win/releases/download/24.3.2/mesa3d-24.3.2-release-mingw.7z
7z x mesa3d.7z -omesa3d
shell: pwsh
- name: Run system-wide deployment (Windows)
if: ${{ inputs.platform == 'windows' }}
run: |
cd mesa3d
.\systemwidedeploy.cmd 1
.\systemwidedeploy.cmd 5
shell: cmd
- name: Install Ninja (Windows Clang)
if: ${{ inputs.platform == 'windows' && inputs.compiler == 'clang' }}
run: |
choco install ninja -y
ninja --version
shell: pwsh
- name: Install dependencies (macOS)
if: ${{ inputs.platform == 'macos' }}
run: |
brew update
brew install tcl-tk tbb gl2ps xerces-c \
libxmu libxi libxft libxpm \
glew freeimage draco glfw
shell: bash
- name: Install dependencies (Linux)
if: ${{ inputs.platform == 'linux' }}
run: sudo apt-get update && sudo apt-get install -y tcl-dev tk-dev cmake ${{ inputs.compiler == 'clang' && 'clang' || 'gcc g++' }} make libbtbb-dev libx11-dev libglu1-mesa-dev tcllib tcl-thread tcl libvtk9-dev libopenvr-dev libdraco-dev libfreeimage-dev libegl1-mesa-dev libgles2-mesa-dev libfreetype-dev
shell: bash
- name: Install rapidjson (macOS/Linux)
if: ${{ inputs.platform == 'macos' || inputs.platform == 'linux' }}
run: |
wget https://github.com/Tencent/rapidjson/archive/858451e5b7d1c56cf8f6d58f88cf958351837e53.zip -O rapidjson.zip
unzip rapidjson.zip
shell: bash
- name: Configure OCCT (Windows MSVC)
if: ${{ inputs.platform == 'windows' && inputs.compiler == 'msvc' }}
run: |
mkdir build
cd build
cmake -T host=x64 `
-D USE_FREETYPE=ON `
-D USE_TK=OFF `
-D BUILD_USE_PCH=ON `
-D BUILD_OPT_PROFILE=Production `
-D BUILD_INCLUDE_SYMLINK=ON `
-D CMAKE_BUILD_TYPE=Release `
-D 3RDPARTY_DIR=${{ github.workspace }}/3rdparty-vc14-64 `
-D INSTALL_DIR=${{ github.workspace }}/install `
-D USE_D3D=ON `
-D USE_DRACO=ON `
-D USE_FFMPEG=ON `
-D USE_FREEIMAGE=ON `
-D USE_GLES2=ON `
-D USE_OPENVR=ON `
-D USE_VTK=${{ inputs.use-vtk }} `
-D USE_TBB=ON `
-D USE_RAPIDJSON=ON `
-D USE_OPENGL=ON `
-D BUILD_GTEST=ON `
-D BUILD_CPP_STANDARD=C++14 `
-D INSTALL_GTEST=ON ${{ inputs.additional-cmake-flags }} ..
shell: pwsh
- name: Configure OCCT (Windows Clang)
if: ${{ inputs.platform == 'windows' && inputs.compiler == 'clang' }}
run: |
mkdir build
cd build
cmake -G "Ninja" `
-D CMAKE_C_COMPILER=clang `
-D CMAKE_CXX_COMPILER=clang++ `
-D USE_FREETYPE=ON `
-D USE_TK=OFF `
-D BUILD_USE_PCH=ON `
-D BUILD_OPT_PROFILE=Production `
-D BUILD_INCLUDE_SYMLINK=ON `
-D CMAKE_BUILD_TYPE=Release `
-D 3RDPARTY_DIR=${{ github.workspace }}/3rdparty-vc14-64 `
-D INSTALL_DIR=${{ github.workspace }}/install `
-D USE_D3D=ON `
-D USE_DRACO=ON `
-D USE_FFMPEG=ON `
-D USE_FREEIMAGE=ON `
-D USE_GLES2=ON `
-D USE_OPENVR=ON `
-D USE_VTK=${{ inputs.use-vtk }} `
-D USE_TBB=ON `
-D USE_RAPIDJSON=ON `
-D USE_OPENGL=ON `
-D BUILD_GTEST=ON `
-D BUILD_CPP_STANDARD=C++14 `
-D INSTALL_GTEST=ON `
-D CMAKE_CXX_FLAGS="-Werror -Wall -Wextra -Wno-unknown-warning-option" `
-D CMAKE_C_FLAGS="-Werror -Wall -Wextra -Wno-unknown-warning-option" ${{ inputs.additional-cmake-flags }} ..
shell: pwsh
- name: Configure OCCT (macOS)
if: ${{ inputs.platform == 'macos' }}
run: |
mkdir -p build
cd build
cmake -G "Unix Makefiles" \
-D CMAKE_C_COMPILER=${{ inputs.compiler == 'clang' && 'clang' || 'gcc' }} \
-D CMAKE_CXX_COMPILER=${{ inputs.compiler == 'clang' && 'clang++' || 'g++' }} \
-D BUILD_USE_PCH=ON \
-D BUILD_INCLUDE_SYMLINK=ON \
-D CMAKE_BUILD_TYPE=Release \
-D INSTALL_DIR=${{ github.workspace }}/install \
-D 3RDPARTY_RAPIDJSON_DIR=${{ github.workspace }}/rapidjson-858451e5b7d1c56cf8f6d58f88cf958351837e53 \
-D USE_RAPIDJSON=ON \
-D USE_DRACO=ON \
-D USE_FREETYPE=ON \
-D USE_OPENGL=ON \
-D USE_FREEIMAGE=ON \
-D BUILD_GTEST=ON \
-D BUILD_CPP_STANDARD=C++14 \
-D INSTALL_GTEST=ON \
-D CMAKE_CXX_FLAGS="-Werror -Wall -Wextra" \
-D CMAKE_C_FLAGS="-Werror -Wall -Wextra" ${{ inputs.additional-cmake-flags }} ..
shell: bash
- name: Configure OCCT (Linux)
if: ${{ inputs.platform == 'linux' }}
run: |
mkdir -p build
cd build
cmake -G "Unix Makefiles" \
-D CMAKE_C_COMPILER=${{ inputs.compiler == 'clang' && 'clang' || 'gcc' }} \
-D CMAKE_CXX_COMPILER=${{ inputs.compiler == 'clang' && 'clang++' || 'g++' }} \
-D BUILD_USE_PCH=ON \
-D BUILD_INCLUDE_SYMLINK=ON \
-D BUILD_OPT_PROFILE=Production \
-D USE_TK=OFF \
-D CMAKE_BUILD_TYPE=Release \
-D INSTALL_DIR=${{ github.workspace }}/install \
-D 3RDPARTY_RAPIDJSON_DIR=${{ github.workspace }}/rapidjson-858451e5b7d1c56cf8f6d58f88cf958351837e53 \
-D USE_FREETYPE=ON \
-D USE_DRACO=ON \
-D USE_FFMPEG=OFF \
-D USE_FREEIMAGE=ON \
-D USE_GLES2=ON \
-D USE_OPENVR=ON \
-D USE_VTK=${{ inputs.use-vtk }} \
-D USE_TBB=OFF \
-D USE_RAPIDJSON=ON \
-D USE_OPENGL=ON \
-D BUILD_GTEST=ON \
-D BUILD_CPP_STANDARD=C++14 \
-D INSTALL_GTEST=ON \
${{ inputs.compiler == 'clang' && '-D CMAKE_CXX_FLAGS="-Werror -Wall -Wextra" -D CMAKE_C_FLAGS="-Werror -Wall -Wextra"' || '' }} ${{ inputs.additional-cmake-flags }} ..
shell: bash
- name: Build OCCT (Windows)
if: ${{ inputs.platform == 'windows' }}
run: |
cd build
cmake --build . --target install --config Release
shell: pwsh
- name: Build OCCT (macOS)
if: ${{ inputs.platform == 'macos' }}
run: |
cd build
make install -j$(sysctl -n hw.logicalcpu)
shell: bash
- name: Build OCCT (Linux)
if: ${{ inputs.platform == 'linux' }}
run: |
cd build
cmake --build . --target install --config Release -- -j
shell: bash
- name: Upload install directory
uses: actions/upload-artifact@v4.4.3
with:
name: ${{ inputs.artifact-name }}
path: install
retention-days: 7

View File

@@ -55,6 +55,7 @@ runs:
-D 3RDPARTY_DIR=${{ github.workspace }}//3rdparty-vc14-64 `
-D OpenCASCADE_DIR=${{ github.workspace }}/occt-install `
-D INSTALL_DIR=${{ github.workspace }}/inspector/install `
-D CMAKE_POLICY_VERSION_MINIMUM=3.5 `
..
- name: Configure TInspector - Linux
@@ -69,6 +70,7 @@ runs:
-D BUILD_SHARED_LIBS=ON \
-D OpenCASCADE_DIR=${{ github.workspace }}/occt-install \
-D INSTALL_DIR=${{ github.workspace }}/inspector/install \
-D CMAKE_POLICY_VERSION_MINIMUM=3.5 \
..
- name: Build TInspector - Windows

View File

@@ -0,0 +1,321 @@
name: 'Retest Failures'
description: 'Rerun failed tests and update test results'
inputs:
platform:
description: 'Platform (windows, macos, linux)'
required: true
compiler:
description: 'Compiler (msvc, clang, gcc)'
required: true
install-artifact-name:
description: 'Name of the artifact containing the install directory'
required: true
results-artifact-name:
description: 'Name of the artifact containing the test results'
required: true
test-directory-name:
description: 'Name of the directory containing test results'
required: true
runs:
using: "composite"
steps:
- name: Download previous test results (Windows)
if: ${{ inputs.platform == 'windows' }}
uses: actions/download-artifact@v4.1.7
with:
name: ${{ inputs.results-artifact-name }}
path: install/results
- name: Download previous test results (macOS/Linux)
if: ${{ inputs.platform != 'windows' }}
uses: actions/download-artifact@v4.1.7
with:
name: ${{ inputs.results-artifact-name }}
path: install/bin/results
- name: Check for test failures (Windows)
id: check_failures_windows
if: ${{ inputs.platform == 'windows' }}
shell: pwsh
run: |
$failedCount = 0
if (Test-Path "install/results/${{ inputs.test-directory-name }}/tests.log") {
$content = Get-Content "install/results/${{ inputs.test-directory-name }}/tests.log"
$totalLine = $content | Select-String "Total cases:"
if ($totalLine) {
if ($totalLine -match "FAILED") {
$failedCount = ($totalLine | ForEach-Object { $_.Line -replace '.*?(\d+) FAILED.*','$1' }) -as [int]
}
}
echo "failed_count=$failedCount" >> $env:GITHUB_OUTPUT
if ($failedCount -gt 0) {
echo "Tests failed count: $failedCount"
}
}
- name: Check for test failures (macOS/Linux)
id: check_failures_unix
if: ${{ inputs.platform != 'windows' }}
shell: bash
run: |
failed_count=0
if [ -f "install/bin/results/${{ inputs.test-directory-name }}/tests.log" ]; then
total_line=$(grep "Total cases:" install/bin/results/${{ inputs.test-directory-name }}/tests.log)
if [ ! -z "$total_line" ]; then
if [[ $total_line =~ "FAILED" ]]; then
failed_count=$(echo "$total_line" | grep -o "[0-9]* FAILED" | awk '{print $1}')
fi
fi
echo "failed_count=$failed_count" >> $GITHUB_OUTPUT
if [ "$failed_count" -gt 0 ]; then
echo "Tests failed count: $failed_count"
fi
fi
- name: Set failed count
id: check_failures
shell: ${{ inputs.platform == 'windows' && 'pwsh' || 'bash' }}
run: |
${{ inputs.platform == 'windows' && format('
echo "failed_count={0}" >> $env:GITHUB_OUTPUT
', steps.check_failures_windows.outputs.failed_count) || format('
echo "failed_count={0}" >> $GITHUB_OUTPUT
', steps.check_failures_unix.outputs.failed_count) }}
- name: Download and extract 3rdparty dependencies (Windows)
if: ${{ inputs.platform == 'windows' && steps.check_failures.outputs.failed_count > 0 }}
shell: pwsh
run: |
Invoke-WebRequest -Uri https://github.com/Open-Cascade-SAS/OCCT/releases/download/V7_9_0_beta1/3rdparty-vc14-64.zip -OutFile 3rdparty-vc14-64.zip
Expand-Archive -Path 3rdparty-vc14-64.zip -DestinationPath .
Remove-Item 3rdparty-vc14-64.zip
- name: Install dependencies (macOS)
if: ${{ inputs.platform == 'macos' && steps.check_failures.outputs.failed_count > 0 }}
shell: bash
run: |
brew update
brew install tcl-tk tbb gl2ps xerces-c \
libxmu libxi libxft libxpm \
glew freeimage draco glfw
- name: Install dependencies (Linux)
if: ${{ inputs.platform == 'linux' && steps.check_failures.outputs.failed_count > 0 }}
shell: bash
run: sudo apt-get update && sudo apt-get install -y tcl-dev tk-dev cmake ${{ inputs.compiler == 'clang' && 'clang' || 'gcc g++' }} make libbtbb-dev libx11-dev libglu1-mesa-dev tcllib tcl-thread tcl libvtk9-dev libopenvr-dev libdraco-dev libfreeimage-dev libegl1-mesa-dev libgles2-mesa-dev libfreetype-dev fonts-noto-cjk fonts-liberation fonts-ubuntu fonts-liberation fonts-ubuntu fonts-noto-cjk fonts-ipafont-gothic fonts-ipafont-mincho fonts-unfonts-core
- name: Setup Xvfb and Mesa (Linux)
if: ${{ inputs.platform == 'linux' && steps.check_failures.outputs.failed_count > 0 }}
uses: ./.github/actions/setup-xvfb-mesa
- name: Download test data (Windows)
if: ${{ inputs.platform == 'windows' && steps.check_failures.outputs.failed_count > 0 }}
shell: pwsh
run: |
cd data
Invoke-WebRequest -Uri https://github.com/Open-Cascade-SAS/OCCT/releases/download/V7_9_0_beta1/opencascade-dataset-7.9.0.zip -OutFile opencascade-dataset-7.9.0.zip
Expand-Archive -Path opencascade-dataset-7.9.0.zip -DestinationPath .
Remove-Item opencascade-dataset-7.9.0.zip
- name: Download test data (macOS/Linux)
if: ${{ (inputs.platform == 'macos' || inputs.platform == 'linux') && steps.check_failures.outputs.failed_count > 0 }}
shell: bash
run: |
cd data
curl -L -O https://github.com/Open-Cascade-SAS/OCCT/releases/download/V7_9_0_beta1/opencascade-dataset-7.9.0.${{ inputs.platform == 'macos' && 'tar.xz' || 'tar.xz' }}
tar -xf opencascade-dataset-7.9.0.tar.xz
- name: Download and extract install directory
if: steps.check_failures.outputs.failed_count > 0
uses: actions/download-artifact@v4.1.7
with:
name: ${{ inputs.install-artifact-name }}
path: install
- name: Download and extract Mesa3D (Windows)
if: ${{ inputs.platform == 'windows' && steps.check_failures.outputs.failed_count > 0 }}
shell: pwsh
run: |
curl -L -o mesa3d.7z https://github.com/pal1000/mesa-dist-win/releases/download/24.3.2/mesa3d-24.3.2-release-mingw.7z
7z x mesa3d.7z -omesa3d
- name: Run system-wide deployment (Windows)
if: ${{ inputs.platform == 'windows' && steps.check_failures.outputs.failed_count > 0 }}
shell: cmd
run: |
cd mesa3d
.\systemwidedeploy.cmd 1
.\systemwidedeploy.cmd 5
- name: Install CJK Fonts (Windows)
if: ${{ inputs.platform == 'windows' && steps.check_failures.outputs.failed_count > 0 }}
shell: pwsh
run: |
Invoke-WebRequest -Uri https://noto-website-2.storage.googleapis.com/pkgs/Noto-hinted.zip -OutFile Noto-hinted.zip
Expand-Archive -Path Noto-hinted.zip -DestinationPath $env:windir\Fonts
Remove-Item Noto-hinted.zip
- name: Set execute permissions on DRAWEXE (macOS/Linux)
if: ${{ (inputs.platform == 'macos' || inputs.platform == 'linux') && steps.check_failures.outputs.failed_count > 0 }}
shell: bash
run: chmod +x install/${{ inputs.platform == 'macos' && 'bin' || 'bin' }}/DRAWEXE
- name: Run regression tests (Windows)
if: ${{ inputs.platform == 'windows' && steps.check_failures.outputs.failed_count > 0 }}
shell: cmd
run: |
cd install
call env.bat ${{ inputs.compiler == 'clang' && 'clang' || 'vc14' }} win64 release
DRAWEXE.exe -v -c testgrid -regress results/${{ inputs.test-directory-name }} -outdir results/${{ inputs.test-directory-name }}-retest -parallel 0
env:
LIBGL_ALWAYS_SOFTWARE: 1
CSF_TestScriptsPath: ${{ github.workspace }}/tests
CSF_TestDataPath: ${{ github.workspace }}/data
- name: Run regression tests (macOS/Linux)
if: ${{ (inputs.platform == 'macos' || inputs.platform == 'linux') && steps.check_failures.outputs.failed_count > 0 }}
shell: bash
run: |
cd install
cd bin
source env.sh
./DRAWEXE -v -c testgrid -regress results/${{ inputs.test-directory-name }} -outdir results/${{ inputs.test-directory-name }}-retest -parallel 0
env:
DISPLAY: ${{ inputs.platform == 'linux' && ':99' || '' }}
LIBGL_ALWAYS_SOFTWARE: 1
CSF_TestScriptsPath: ${{ github.workspace }}/tests
CSF_TestDataPath: ${{ github.workspace }}/data
- name: Repeating failed tests (Windows)
if: ${{ inputs.platform == 'windows' && steps.check_failures.outputs.failed_count > 0 && steps.check_failures.outputs.failed_count < 20 }}
shell: cmd
run: |
cd install
call env.bat ${{ inputs.compiler == 'clang' && 'clang' || 'vc14' }} win64 release
# Repeat failed tests for 10 times
for /l %%i in (1,1,10) do (
DRAWEXE.exe -v -c testgrid -regress results/${{ inputs.test-directory-name }}-retest -outdir results/${{ inputs.test-directory-name }}-retest -parallel 0 -overwrite
DRAWEXE.exe -v -c "testsummarize results/${{ inputs.test-directory-name }}-retest"
)
env:
LIBGL_ALWAYS_SOFTWARE: 1
CSF_TestScriptsPath: ${{ github.workspace }}/tests
CSF_TestDataPath: ${{ github.workspace }}/data
- name: Repeating failed tests (macOS/Linux)
if: ${{ inputs.platform != 'windows' && steps.check_failures.outputs.failed_count > 0 && steps.check_failures.outputs.failed_count < 20 }}
shell: bash
run: |
cd install
cd bin
source env.sh
# Repeat failed tests for 10 times
for i in {1..10}; do
./DRAWEXE -v -c testgrid -regress results/${{ inputs.test-directory-name }}-retest -outdir results/${{ inputs.test-directory-name }}-retest -parallel 0 -overwrite
./DRAWEXE -v -c "testsummarize results/${{ inputs.test-directory-name }}-retest"
done
env:
DISPLAY: ${{ inputs.platform == 'linux' && ':99' || '' }}
LIBGL_ALWAYS_SOFTWARE: 1
CSF_TestScriptsPath: ${{ github.workspace }}/tests
CSF_TestDataPath: ${{ github.workspace }}/data
- name: Upload regression test results
if: steps.check_failures.outputs.failed_count > 0
uses: actions/upload-artifact@v4.4.3
with:
name: ${{ inputs.results-artifact-name }}-retest
path: install/${{ (inputs.platform == 'windows') && '' || 'bin/' }}results/${{ inputs.test-directory-name }}-retest
retention-days: 15
overwrite: true
- name: Copy retest results back to original location (Windows)
if: ${{ inputs.platform == 'windows' && steps.check_failures.outputs.failed_count > 0 }}
shell: cmd
run: |
cd install\results\${{ inputs.test-directory-name }}-retest
if exist "*" (
xcopy /s /y /i . "..\${{ inputs.test-directory-name }}"
cd ..\..
call env.bat ${{ inputs.compiler == 'clang' && 'clang' || 'vc14' }} win64 release
DRAWEXE.exe -v -c "testsummarize results/${{ inputs.test-directory-name }}"
) else (
echo No retest results to copy - directory is empty
)
- name: Copy retest results back to original location (macOS/Linux)
if: ${{ inputs.platform != 'windows' && steps.check_failures.outputs.failed_count > 0 }}
shell: bash
run: |
cd install/bin/results/${{ inputs.test-directory-name }}-retest
if [ "$(ls -A)" ]; then
cp -rf * ../${{ inputs.test-directory-name }}/
cd ../../
source env.sh
./DRAWEXE -v -c testsummarize results/${{ inputs.test-directory-name }}
else
echo "No retest results to copy - directory is empty"
fi
- name: Upload updated test results (Windows)
if: ${{ inputs.platform == 'windows' && steps.check_failures.outputs.failed_count > 0 }}
uses: actions/upload-artifact@v4.4.3
with:
name: ${{ inputs.results-artifact-name }}
path: install/results/${{ inputs.test-directory-name }}*
retention-days: 15
overwrite: true
- name: Upload updated test results (macOS/Linux)
if : ${{ inputs.platform != 'windows' && steps.check_failures.outputs.failed_count > 0 }}
uses: actions/upload-artifact@v4.4.3
with:
name: ${{ inputs.results-artifact-name }}
path: install/bin/results/${{ inputs.test-directory-name }}*
retention-days: 15
overwrite: true
- name: Check test failures (Windows)
if: ${{ inputs.platform == 'windows' && steps.check_failures.outputs.failed_count > 0 }}
shell: pwsh
run: |
cd install/results/${{ inputs.test-directory-name }}-retest
$failedCount = 0
if (Test-Path tests.log) {
$content = Get-Content tests.log
$totalLine = $content | Select-String "Total cases:"
if ($totalLine) {
if ($totalLine -match "FAILED") {
$failedCount = ($totalLine | ForEach-Object { $_.Line -replace '.*?(\d+) FAILED.*','$1' }) -as [int]
}
}
if ($failedCount -gt 0) {
Write-Error "Number of FAILED tests ($failedCount) exceeds threshold of 0"
echo "FAILED_COUNT=$failedCount" >> $env:GITHUB_ENV
exit 1
}
Write-Output "Found $failedCount FAILED tests"
}
- name: Check test failures (macOS/Linux)
if: ${{ inputs.platform != 'windows' && steps.check_failures.outputs.failed_count > 0 }}
shell: bash
run: |
cd install/bin/results/${{ inputs.test-directory-name }}-retest
if [ -f tests.log ]; then
TOTAL_LINE=$(grep "Total cases:" tests.log | tail -n1)
echo "Total line: $TOTAL_LINE"
if [[ $TOTAL_LINE =~ ([0-9]+)[[:space:]]FAILED ]]; then
FAILED_COUNT="${BASH_REMATCH[1]}"
if [ $FAILED_COUNT -gt 0 ]; then
echo "Number of FAILED tests ($FAILED_COUNT) exceeds threshold of 0"
echo "::error::Number of FAILED tests ($FAILED_COUNT) exceeds threshold of 0"
echo "FAILED_COUNT=$FAILED_COUNT" >> $GITHUB_ENV
exit 1
fi
fi
echo "Found 0 FAILED tests"
fi

View File

@@ -86,7 +86,7 @@ runs:
run: |
cd install/bin
source env.sh
./OpenCascadeGTest --gtest_output=xml:gtest_results.xml > gtest_output.log 2>&1
./OpenCascadeGTest --gtest_output=xml:gtest_results.xml > gtest_output.log 2>&1 || true
cat gtest_output.log
- name: Upload GTest results

178
.github/actions/run-tests/action.yml vendored Normal file
View File

@@ -0,0 +1,178 @@
name: 'Run Tests'
description: 'Run OCCT tests on a specific platform'
inputs:
platform:
description: 'Platform (windows, macos, linux)'
required: true
compiler:
description: 'Compiler (msvc, clang, gcc)'
required: true
install-artifact-name:
description: 'Name of the artifact containing the install directory'
required: true
test-directory-name:
description: 'Name of the directory to store test results'
required: true
test-script:
description: 'The test script to run'
required: true
runs:
using: "composite"
steps:
- name: Download and extract 3rdparty dependencies (Windows)
if: ${{ inputs.platform == 'windows' }}
run: |
Invoke-WebRequest -Uri https://github.com/Open-Cascade-SAS/OCCT/releases/download/V7_9_0_beta1/3rdparty-vc14-64.zip -OutFile 3rdparty-vc14-64.zip
Expand-Archive -Path 3rdparty-vc14-64.zip -DestinationPath .
Remove-Item 3rdparty-vc14-64.zip
shell: pwsh
- name: Install dependencies (macOS)
if: ${{ inputs.platform == 'macos' }}
run: |
brew update
brew install tcl-tk tbb gl2ps xerces-c \
libxmu libxi libxft libxpm \
glew freeimage draco glfw
shell: bash
- name: Install dependencies (Linux)
if: ${{ inputs.platform == 'linux' }}
run: sudo apt-get update && sudo apt-get install -y tcl-dev tk-dev cmake ${{ inputs.compiler == 'gcc' && 'gcc g++' || 'clang' }} make libbtbb-dev libx11-dev libglu1-mesa-dev tcllib tcl-thread tcl libvtk9-dev libopenvr-dev libdraco-dev libfreeimage-dev libegl1-mesa-dev libgles2-mesa-dev libfreetype-dev fonts-noto-cjk fonts-liberation fonts-ubuntu fonts-liberation fonts-ubuntu fonts-noto-cjk fonts-ipafont-gothic fonts-ipafont-mincho fonts-unfonts-core
shell: bash
- name: Setup Xvfb and Mesa (Linux)
if: ${{ inputs.platform == 'linux' }}
uses: ./.github/actions/setup-xvfb-mesa
- name: Download and extract test data (Windows)
if: ${{ inputs.platform == 'windows' }}
run: |
cd data
Invoke-WebRequest -Uri https://github.com/Open-Cascade-SAS/OCCT/releases/download/V7_9_0_beta1/opencascade-dataset-7.9.0.zip -OutFile opencascade-dataset-7.9.0.zip
Expand-Archive -Path opencascade-dataset-7.9.0.zip -DestinationPath .
Remove-Item opencascade-dataset-7.9.0.zip
shell: pwsh
- name: Download test data (macOS/Linux)
if: ${{ (inputs.platform == 'macos' || inputs.platform == 'linux') }}
run: |
cd data
wget -q https://github.com/Open-Cascade-SAS/OCCT/releases/download/V7_9_0_beta1/opencascade-dataset-7.9.0.tar.xz
tar -xf opencascade-dataset-7.9.0.tar.xz
shell: bash
- name: Download and extract install directory
uses: actions/download-artifact@v4.1.7
with:
name: ${{ inputs.install-artifact-name }}
path: install
- name: Download and extract Mesa3D (Windows)
if: ${{ inputs.platform == 'windows' }}
run: |
curl -L -o mesa3d.7z https://github.com/pal1000/mesa-dist-win/releases/download/24.3.2/mesa3d-24.3.2-release-mingw.7z
7z x mesa3d.7z -omesa3d
shell: pwsh
- name: Run system-wide deployment (Windows)
if: ${{ inputs.platform == 'windows' }}
run: |
cd mesa3d
.\systemwidedeploy.cmd 1
.\systemwidedeploy.cmd 5
shell: cmd
- name: Install CJK Fonts (Windows)
if: ${{ inputs.platform == 'windows' }}
run: |
Invoke-WebRequest -Uri https://noto-website-2.storage.googleapis.com/pkgs/Noto-hinted.zip -OutFile Noto-hinted.zip
Expand-Archive -Path Noto-hinted.zip -DestinationPath $env:windir\Fonts
Remove-Item Noto-hinted.zip
shell: pwsh
- name: Set LIBGL_ALWAYS_SOFTWARE environment variable (macOS)
if: ${{ inputs.platform == 'macos' }}
run: echo "LIBGL_ALWAYS_SOFTWARE=1" >> $GITHUB_ENV
shell: bash
- name: Set execute permissions on DRAWEXE (macOS/Linux)
if: ${{ inputs.platform == 'macos' || inputs.platform == 'linux' }}
run: chmod +x install/bin/DRAWEXE
shell: bash
- name: Run tests (Windows)
if: ${{ inputs.platform == 'windows' }}
run: |
cd install
call env.bat ${{ inputs.compiler == 'msvc' && 'vc14' || 'clang' }} win64 release
DRAWEXE.exe -v -f ${{ github.workspace }}/${{ inputs.test-script }}
shell: cmd
env:
LIBGL_ALWAYS_SOFTWARE: 1
CSF_TestScriptsPath: ${{ github.workspace }}/tests
CSF_TestDataPath: ${{ github.workspace }}/data
- name: Run tests (macOS/Linux)
if: ${{ inputs.platform == 'macos' || inputs.platform == 'linux' }}
run: |
cd install
cd bin
source env.sh
./DRAWEXE -v -f ${{ github.workspace }}/${{ inputs.test-script }}
shell: bash
env:
DISPLAY: ${{ inputs.platform == 'linux' && ':99' || '' }}
LIBGL_ALWAYS_SOFTWARE: 1
CSF_TestScriptsPath: ${{ github.workspace }}/tests
CSF_TestDataPath: ${{ github.workspace }}/data
- name: Clean up test results (Windows)
if: ${{ inputs.platform == 'windows' }}
run: |
cd install
call env.bat ${{ inputs.compiler == 'msvc' && 'vc14' || 'clang' }} win64 release
DRAWEXE.exe -v -c cleanuptest results/${{ inputs.test-directory-name }}
shell: cmd
env:
LIBGL_ALWAYS_SOFTWARE: 1
CSF_TestScriptsPath: ${{ github.workspace }}/tests
CSF_TestDataPath: ${{ github.workspace }}/data
- name: Clean up test results (macOS/Linux)
if: ${{ inputs.platform == 'macos' || inputs.platform == 'linux' }}
run: |
cd install
cd bin
source env.sh
./DRAWEXE -v -c cleanuptest results/${{ inputs.test-directory-name }}
shell: bash
env:
DISPLAY: ${{ inputs.platform == 'linux' && ':99' || '' }}
LIBGL_ALWAYS_SOFTWARE: 1
CSF_TestScriptsPath: ${{ github.workspace }}/tests
CSF_TestDataPath: ${{ github.workspace }}/data
- name: Upload test results (Windows)
if: ${{ inputs.platform == 'windows' }}
uses: actions/upload-artifact@v4.4.3
with:
name: results-${{ inputs.test-directory-name }}
path: |
install/results/**/*.log
install/results/**/*.png
install/results/**/*.html
retention-days: 15
- name: Upload test results (macOS/Linux)
if: ${{ inputs.platform == 'macos' || inputs.platform == 'linux' }}
uses: actions/upload-artifact@v4.4.3
with:
name: results-${{ inputs.test-directory-name }}
path: |
install/bin/results/**/*.log
install/bin/results/**/*.png
install/bin/results/**/*.html
retention-days: 15

94
.github/actions/test-summary/action.yml vendored Normal file
View File

@@ -0,0 +1,94 @@
name: 'Test Summary'
description: 'Compare test results between current branch and master'
runs:
using: "composite"
steps:
- name: Install dependencies
run: sudo apt-get update && sudo apt-get install -y tcl-dev tk-dev cmake gcc g++ make libbtbb-dev libx11-dev libglu1-mesa-dev tcllib tcl-thread tcl libvtk9-dev libopenvr-dev libdraco-dev libfreeimage-dev libegl1-mesa-dev libgles2-mesa-dev libfreetype-dev
shell: bash
- name: Setup Xvfb and Mesa
uses: ./.github/actions/setup-xvfb-mesa
- name: Set environment variables
run: |
echo "DISPLAY=:99" >> $GITHUB_ENV
echo "LIBGL_ALWAYS_SOFTWARE=1" >> $GITHUB_ENV
shell: bash
- name: Download and extract install directory
uses: actions/download-artifact@v4.1.7
with:
name: install-linux-gcc-x64
path: install
- name: Set execute permissions on DRAWEXE
run: chmod +x install/bin/DRAWEXE
shell: bash
- name: Get latest workflow run ID from target branch
id: get_run_id
run: |
response=$(curl -s \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/${{ github.repository }}/actions/runs?branch=${{ github.event.pull_request.base.ref }}&status=success")
latest_run_id=$(echo "$response" | jq -r '.workflow_runs[] | select(.name=="Build and Test OCCT on Multiple Platforms") | .id' | head -n 1)
echo "latest_run_id=$latest_run_id" >> $GITHUB_ENV
shell: bash
- name: Download master branch test results
env:
GH_TOKEN: ${{ github.token }}
run: |
for platform in windows-x64 windows-clang-x64 macos-x64 macos-gcc-x64 linux-clang-x64 linux-gcc-x64; do
echo "Downloading results for $platform"
gh run download ${{ env.latest_run_id }} -n "results-$platform" -D "install/bin/results/master/"
done
shell: bash
- name: Download current branch test results
env:
GH_TOKEN: ${{ github.token }}
run: |
for platform in windows-x64 windows-clang-x64 macos-x64 macos-gcc-x64 linux-clang-x64 linux-gcc-x64; do
echo "Downloading results for $platform"
gh run download -n "results-$platform" -D "install/bin/results/current/"
done
shell: bash
- name: Compare test results
run: |
echo "Comparing test results..."
cd install/bin
source env.sh
for platform in windows-x64 windows-clang-x64 macos-x64 macos-gcc-x64 linux-clang-x64 linux-gcc-x64; do
./DRAWEXE -v -c testdiff "results/current/$platform" "results/master/$platform" &
done
wait
shell: bash
- name: Install BeautifulSoup
run: pip install beautifulsoup4
shell: bash
- name: Clean unused test images
run: |
# copy to the install/bin/results directory
cp ${{ github.workspace }}/.github/actions/scripts/cleanup_test_images.py install/bin/results
cd install/bin/results
python cleanup_test_images.py
shell: bash
- name: Upload comparison results
uses: actions/upload-artifact@v4.4.3
with:
name: test-compare-results
retention-days: 15
overwrite: true
path: |
install/bin/results/**/diff-*.html
install/bin/results/**/diff-*.log
install/bin/results/**/summary.html
install/bin/results/**/tests.log
install/bin/results/**/*.png

File diff suppressed because it is too large Load Diff

View File

@@ -20,6 +20,7 @@
#include <Message_Messenger.hxx>
#include <Message_ProgressScope.hxx>
#include <OSD_File.hxx>
#include <OSD_FileSystem.hxx>
#include <OSD_OpenFile.hxx>
#include <OSD_Path.hxx>
#include <OSD_ThreadPool.hxx>
@@ -1932,10 +1933,7 @@ bool RWGltf_GltfJsonParser::gltfParsePrimArray(TopoDS_Shape& th
{
Message::SendWarning("Deferred loading is available only for triangulations. Other elements "
"will be loaded immediately.");
Handle(RWGltf_TriangulationReader) aReader = new RWGltf_TriangulationReader();
aReader->SetCoordinateSystemConverter(myCSTrsf);
aMeshData->SetReader(aReader);
aMeshData->LoadDeferredData();
fillMeshData(aMeshData);
}
TopoDS_Shape aShape;
@@ -2457,6 +2455,44 @@ void RWGltf_GltfJsonParser::bindNamedShape(TopoDS_Shape& the
}
myShapeMap[theGroup].Bind(theId, theShape);
}
//=================================================================================================
bool RWGltf_GltfJsonParser::fillMeshData(
const Handle(RWGltf_GltfLatePrimitiveArray)& theMeshData) const
{
if (myStream == nullptr)
{
const Handle(OSD_FileSystem)& aFileSystem = OSD_FileSystem::DefaultFileSystem();
myStream = aFileSystem->OpenIStream(myFilePath, std::ios::in | std::ios::binary);
}
if (myStream == nullptr)
{
reportGltfError("Buffer '" + myFilePath + "' isn't defined.");
return false;
}
for (NCollection_Sequence<RWGltf_GltfPrimArrayData>::Iterator aDataIter(theMeshData->Data());
aDataIter.More();
aDataIter.Next())
{
const RWGltf_GltfPrimArrayData& aData = aDataIter.Value();
Handle(RWGltf_TriangulationReader) aReader = new RWGltf_TriangulationReader();
aReader->SetCoordinateSystemConverter(myCSTrsf);
std::shared_ptr<std::istream> aNewStream = myStream;
aNewStream->seekg(aData.StreamOffset);
if (!aReader
->ReadStream(theMeshData, theMeshData, *aNewStream.get(), aData.Accessor, aData.Type))
{
return false;
}
}
return true;
}
#endif
//=================================================================================================

View File

@@ -126,6 +126,9 @@ public:
//! Return face list for loading triangulation.
NCollection_Vector<TopoDS_Face>& FaceList() { return myFaceList; }
//! Set inpit stream.
void SetStream(std::shared_ptr<std::istream>& theStream) { myStream = theStream; }
protected:
#ifdef HAVE_RAPIDJSON
//! Search mandatory root elements in the document.
@@ -421,6 +424,11 @@ private:
const RWGltf_JsonValue* theScaleVal,
const RWGltf_JsonValue* theTranslationVal,
TopLoc_Location& theResult) const;
//! Fill lines and points data not deferred.
//! @param theMeshData source glTF triangulation
Standard_EXPORT bool fillMeshData(const Handle(RWGltf_GltfLatePrimitiveArray)& theMeshData) const;
#endif
protected:
//! Print message about invalid glTF syntax.
@@ -437,6 +445,8 @@ protected:
// clang-format on
TColStd_IndexedDataMapOfStringString* myMetadata; //!< file metadata
mutable std::shared_ptr<std::istream> myStream; //!< input stream
NCollection_DataMap<TCollection_AsciiString, Handle(RWGltf_MaterialMetallicRoughness)>
myMaterialsPbr;
NCollection_DataMap<TCollection_AsciiString, Handle(RWGltf_MaterialCommon)> myMaterialsCommon;

View File

@@ -562,6 +562,19 @@ bool RWGltf_TriangulationReader::readBuffer(
const RWGltf_GltfAccessor& theAccessor,
RWGltf_GltfArrayType theType) const
{
return ReadStream(theSourceMesh, theDestMesh, theStream, theAccessor, theType);
}
//=================================================================================================
bool RWGltf_TriangulationReader::ReadStream(
const Handle(RWGltf_GltfLatePrimitiveArray)& theSourceMesh,
const Handle(Poly_Triangulation)& theDestMesh,
std::istream& theStream,
const RWGltf_GltfAccessor& theAccessor,
RWGltf_GltfArrayType theType) const
{
const TCollection_AsciiString& aName = theSourceMesh->Id();
const RWGltf_GltfPrimitiveMode aPrimMode = theSourceMesh->PrimitiveMode();

View File

@@ -36,6 +36,19 @@ public:
Standard_EXPORT bool LoadStreamData(const Handle(RWMesh_TriangulationSource)& theSourceMesh,
const Handle(Poly_Triangulation)& theDestMesh) const;
//! Fills triangulation, lines and points data.
//! @param theSourceGltfMesh source glTF triangulation
//! @param theDestMesh triangulation to be modified
//! @param theStream input stream to read from
//! @param theAccessor buffer accessor
//! @param theType array type
//! @return FALSE on error
Standard_EXPORT bool ReadStream(const Handle(RWGltf_GltfLatePrimitiveArray)& theSourceMesh,
const Handle(Poly_Triangulation)& theDestMesh,
std::istream& theStream,
const RWGltf_GltfAccessor& theAccessor,
RWGltf_GltfArrayType theType) const;
protected:
//! Reports error.
Standard_EXPORT virtual void reportError(const TCollection_AsciiString& theText) const;

View File

@@ -190,6 +190,10 @@ bool DESTEP_ConfigurationNode::Load(const Handle(DE_ConfigurationContext)& theRe
theResource->BooleanVal("write.layer", InternalParameters.WriteLayer, aScope);
InternalParameters.WriteProps =
theResource->BooleanVal("write.props", InternalParameters.WriteProps, aScope);
InternalParameters.WriteMaterial =
theResource->BooleanVal("write.material", InternalParameters.WriteMaterial, aScope);
InternalParameters.WriteVisMaterial =
theResource->BooleanVal("write.vismaterial", InternalParameters.WriteVisMaterial, aScope);
InternalParameters.WriteModelType =
(STEPControl_StepModelType)theResource->IntegerVal("write.model.type",
InternalParameters.WriteModelType,
@@ -556,6 +560,20 @@ TCollection_AsciiString DESTEP_ConfigurationNode::Save() const
aResult += aScope + "write.props :\t " + InternalParameters.WriteProps + "\n";
aResult += "!\n";
aResult += "!\n";
aResult += "!Setting up the write.material parameter which is used to indicate write "
"Material properties or not\n";
aResult += "!Default value: +. Available values: \"-\", \"+\"\n";
aResult += aScope + "write.material :\t " + InternalParameters.WriteMaterial + "\n";
aResult += "!\n";
aResult += "!\n";
aResult += "!Setting up the write.vismaterial parameter which is used to indicate write "
"Visual Material properties or not\n";
aResult += "!Default value: +. Available values: \"-\", \"+\"\n";
aResult += aScope + "write.vismaterial :\t " + InternalParameters.WriteVisMaterial + "\n";
aResult += "!\n";
aResult += "!\n";
aResult += "!Setting up the Model Type which gives you the choice of translation mode for an "
"Open CASCADE shape that ";

View File

@@ -199,6 +199,8 @@ public:
bool WriteName = true; //<! NameMode is used to indicate write Name or not
bool WriteLayer = true; //<! LayerMode is used to indicate write Layers or not
bool WriteProps = true; //<! PropsMode is used to indicate write Validation properties or not
bool WriteMaterial = true; //<! MaterialMode is used to indicate write Material or not
bool WriteVisMaterial = false; //<! VisMaterialMode is used to indicate write Visual Material or not
STEPControl_StepModelType WriteModelType = STEPControl_AsIs; //<! Gives you the choice of translation mode for an Open CASCADE shape that is being translated to STEP
bool CleanDuplicates = false; //<! Indicates whether to remove duplicate entities from the STEP file
// clang-format on

View File

@@ -116,6 +116,8 @@ bool DESTEP_Provider::Write(const TCollection_AsciiString& thePath,
aWriter.SetLayerMode(aNode->InternalParameters.WriteLayer);
aWriter.SetPropsMode(aNode->InternalParameters.WriteProps);
aWriter.SetShapeFixParameters(aNode->ShapeFixParameters);
aWriter.SetMaterialMode(aNode->InternalParameters.WriteMaterial);
aWriter.SetVisualMaterialMode(aNode->InternalParameters.WriteVisMaterial);
aWriter.SetCleanDuplicates(aNode->InternalParameters.CleanDuplicates);
DESTEP_Parameters aParams = aNode->InternalParameters;
Standard_Real aScaleFactorMM = 1.;

View File

@@ -2,6 +2,7 @@
set(OCCT_TKDESTEP_GTests_FILES_LOCATION "${CMAKE_CURRENT_LIST_DIR}")
set(OCCT_TKDESTEP_GTests_FILES
STEPConstruct_RenderingProperties_Test.cxx
StepTidy_BaseTestFixture.pxx
StepTidy_Axis2Placement3dReducer_Test.cxx
StepTidy_CartesianPointReducer_Test.cxx

View File

@@ -0,0 +1,508 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <STEPConstruct_RenderingProperties.hxx>
#include <STEPConstruct_Styles.hxx>
#include <StepVisual_SurfaceStyleRenderingWithProperties.hxx>
#include <StepVisual_HArray1OfRenderingPropertiesSelect.hxx>
#include <StepVisual_SurfaceStyleTransparent.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular.hxx>
#include <StepVisual_ColourRgb.hxx>
#include <Quantity_Color.hxx>
#include <Quantity_ColorRGBA.hxx>
#include <TCollection_HAsciiString.hxx>
#include <gtest/gtest.h>
// Test fixture for STEPConstruct_RenderingProperties tests
class STEPConstruct_RenderingPropertiesTest : public ::testing::Test
{
protected:
//! Set up function called before each test
void SetUp() override
{
// Create some common colors and values for testing
mySurfaceColor = Quantity_Color(0.8, 0.5, 0.2, Quantity_TOC_RGB);
myTransparency = 0.25;
myAmbientFactor = 0.3;
myDiffuseFactor = 1.0;
mySpecularFactor = 0.8;
mySpecularExponent = 45.0;
mySpecularColor = Quantity_Color(0.9, 0.9, 0.9, Quantity_TOC_RGB);
}
//! Helper function to create a STEP rendering properties object for testing
Handle(StepVisual_SurfaceStyleRenderingWithProperties) CreateStepRenderingProperties()
{
// Create the surface color
Handle(TCollection_HAsciiString) aColorName = new TCollection_HAsciiString("");
Handle(StepVisual_Colour) aSurfaceColor = STEPConstruct_Styles::EncodeColor(mySurfaceColor);
// Create transparency property
Handle(StepVisual_SurfaceStyleTransparent) aTransp = new StepVisual_SurfaceStyleTransparent();
aTransp->Init(myTransparency);
// Create specular color
Handle(StepVisual_Colour) aSpecColor = STEPConstruct_Styles::EncodeColor(mySpecularColor);
// Create reflectance model
Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular) aReflectance =
new StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular();
aReflectance->Init(myAmbientFactor,
myDiffuseFactor,
mySpecularFactor,
mySpecularExponent,
aSpecColor);
// Create the properties array with two entries: transparency and reflectance
Handle(StepVisual_HArray1OfRenderingPropertiesSelect) aProps =
new StepVisual_HArray1OfRenderingPropertiesSelect(1, 2);
StepVisual_RenderingPropertiesSelect aRps1, aRps2;
aRps1.SetValue(aTransp);
aRps2.SetValue(aReflectance);
aProps->SetValue(1, aRps1);
aProps->SetValue(2, aRps2);
// Create and return the final object
Handle(StepVisual_SurfaceStyleRenderingWithProperties) aResult =
new StepVisual_SurfaceStyleRenderingWithProperties();
aResult->Init(StepVisual_ssmNormalShading, aSurfaceColor, aProps);
return aResult;
}
//! Helper function to create a common material for testing
XCAFDoc_VisMaterialCommon CreateMaterial()
{
XCAFDoc_VisMaterialCommon aMaterial;
// Set basic properties
aMaterial.DiffuseColor = mySurfaceColor;
aMaterial.Transparency = myTransparency;
// Calculate ambient color based on ambient factor
aMaterial.AmbientColor = Quantity_Color(mySurfaceColor.Red() * myAmbientFactor,
mySurfaceColor.Green() * myAmbientFactor,
mySurfaceColor.Blue() * myAmbientFactor,
Quantity_TOC_RGB);
// Set specular properties
aMaterial.SpecularColor = mySpecularColor;
aMaterial.Shininess = (Standard_ShortReal)(mySpecularExponent / 128.0);
// Mark as defined
aMaterial.IsDefined = Standard_True;
return aMaterial;
}
//! Compare two colors with tolerance
Standard_Boolean AreColorsEqual(const Quantity_Color& theC1,
const Quantity_Color& theC2,
const Standard_Real theTol = 0.01)
{
return (Abs(theC1.Red() - theC2.Red()) <= theTol)
&& (Abs(theC1.Green() - theC2.Green()) <= theTol)
&& (Abs(theC1.Blue() - theC2.Blue()) <= theTol);
}
// Test member variables
Quantity_Color mySurfaceColor; //!< Surface color for testing
Quantity_Color mySpecularColor; //!< Specular color for testing
Standard_Real myTransparency; //!< Transparency value for testing
Standard_Real myAmbientFactor; //!< Ambient reflectance factor for testing
Standard_Real myDiffuseFactor; //!< Diffuse reflectance factor for testing
Standard_Real mySpecularFactor; //!< Specular reflectance factor for testing
Standard_Real mySpecularExponent; //!< Specular exponent value for testing
};
// Test default constructor
TEST_F(STEPConstruct_RenderingPropertiesTest, DefaultConstructor)
{
STEPConstruct_RenderingProperties aProps;
EXPECT_FALSE(aProps.IsDefined());
EXPECT_FALSE(aProps.IsAmbientReflectanceDefined());
EXPECT_FALSE(aProps.IsDiffuseReflectanceDefined());
EXPECT_FALSE(aProps.IsSpecularReflectanceDefined());
EXPECT_FALSE(aProps.IsSpecularExponentDefined());
EXPECT_FALSE(aProps.IsSpecularColourDefined());
EXPECT_EQ(aProps.Transparency(), 0.0);
EXPECT_EQ(aProps.RenderingMethod(), StepVisual_ssmNormalShading);
}
// Test RGBA color constructor
TEST_F(STEPConstruct_RenderingPropertiesTest, RGBAConstructor)
{
// Create an RGBA color with alpha = 0.75 (transparency = 0.25)
Quantity_ColorRGBA aRgba(mySurfaceColor, 0.75);
// Create rendering properties from RGBA
STEPConstruct_RenderingProperties aProps(aRgba);
EXPECT_TRUE(aProps.IsDefined());
EXPECT_FALSE(aProps.IsAmbientReflectanceDefined());
EXPECT_FALSE(aProps.IsDiffuseReflectanceDefined());
EXPECT_FALSE(aProps.IsSpecularReflectanceDefined());
EXPECT_TRUE(AreColorsEqual(aProps.SurfaceColor(), mySurfaceColor));
EXPECT_NEAR(aProps.Transparency(), 0.25, 0.001);
EXPECT_EQ(aProps.RenderingMethod(), StepVisual_ssmNormalShading);
}
// Test StepVisual_SurfaceStyleRenderingWithProperties constructor
TEST_F(STEPConstruct_RenderingPropertiesTest, StepRenderingPropertiesConstructor)
{
Handle(StepVisual_SurfaceStyleRenderingWithProperties) aStepProps =
CreateStepRenderingProperties();
STEPConstruct_RenderingProperties aProps(aStepProps);
EXPECT_TRUE(aProps.IsDefined());
EXPECT_TRUE(aProps.IsAmbientReflectanceDefined());
EXPECT_TRUE(aProps.IsDiffuseReflectanceDefined());
EXPECT_TRUE(aProps.IsSpecularReflectanceDefined());
EXPECT_TRUE(aProps.IsSpecularExponentDefined());
EXPECT_TRUE(aProps.IsSpecularColourDefined());
EXPECT_TRUE(AreColorsEqual(aProps.SurfaceColor(), mySurfaceColor));
EXPECT_NEAR(aProps.Transparency(), myTransparency, 0.001);
EXPECT_NEAR(aProps.AmbientReflectance(), myAmbientFactor, 0.001);
EXPECT_NEAR(aProps.DiffuseReflectance(), myDiffuseFactor, 0.001);
EXPECT_NEAR(aProps.SpecularReflectance(), mySpecularFactor, 0.001);
EXPECT_NEAR(aProps.SpecularExponent(), mySpecularExponent, 0.001);
EXPECT_TRUE(AreColorsEqual(aProps.SpecularColour(), mySpecularColor));
EXPECT_EQ(aProps.RenderingMethod(), StepVisual_ssmNormalShading);
}
// Test XCAFDoc_VisMaterialCommon constructor
TEST_F(STEPConstruct_RenderingPropertiesTest, MaterialConstructor)
{
XCAFDoc_VisMaterialCommon aMaterial = CreateMaterial();
STEPConstruct_RenderingProperties aProps(aMaterial);
EXPECT_TRUE(aProps.IsDefined());
EXPECT_TRUE(aProps.IsAmbientReflectanceDefined());
EXPECT_TRUE(aProps.IsDiffuseReflectanceDefined());
EXPECT_TRUE(aProps.IsSpecularReflectanceDefined());
EXPECT_TRUE(aProps.IsSpecularExponentDefined());
EXPECT_TRUE(aProps.IsSpecularColourDefined());
EXPECT_TRUE(AreColorsEqual(aProps.SurfaceColor(), mySurfaceColor));
EXPECT_NEAR(aProps.Transparency(), myTransparency, 0.001);
EXPECT_NEAR(aProps.AmbientReflectance(), myAmbientFactor, 0.02); // Slightly larger tolerance
EXPECT_NEAR(aProps.DiffuseReflectance(), 1.0, 0.001);
}
// Test setting reflectance properties
TEST_F(STEPConstruct_RenderingPropertiesTest, SetReflectanceProperties)
{
STEPConstruct_RenderingProperties aProps;
// Initialize with basic color and transparency
aProps.Init(mySurfaceColor, myTransparency);
EXPECT_TRUE(aProps.IsDefined());
// Set ambient reflectance
aProps.SetAmbientReflectance(myAmbientFactor);
EXPECT_TRUE(aProps.IsAmbientReflectanceDefined());
EXPECT_NEAR(aProps.AmbientReflectance(), myAmbientFactor, 0.001);
EXPECT_FALSE(aProps.IsDiffuseReflectanceDefined());
// Set ambient and diffuse reflectance
aProps.SetAmbientAndDiffuseReflectance(myAmbientFactor, myDiffuseFactor);
EXPECT_TRUE(aProps.IsAmbientReflectanceDefined());
EXPECT_TRUE(aProps.IsDiffuseReflectanceDefined());
EXPECT_NEAR(aProps.AmbientReflectance(), myAmbientFactor, 0.001);
EXPECT_NEAR(aProps.DiffuseReflectance(), myDiffuseFactor, 0.001);
EXPECT_FALSE(aProps.IsSpecularReflectanceDefined());
// Set all reflectance properties
aProps.SetAmbientDiffuseAndSpecularReflectance(myAmbientFactor,
myDiffuseFactor,
mySpecularFactor,
mySpecularExponent,
mySpecularColor);
EXPECT_TRUE(aProps.IsAmbientReflectanceDefined());
EXPECT_TRUE(aProps.IsDiffuseReflectanceDefined());
EXPECT_TRUE(aProps.IsSpecularReflectanceDefined());
EXPECT_TRUE(aProps.IsSpecularExponentDefined());
EXPECT_TRUE(aProps.IsSpecularColourDefined());
EXPECT_NEAR(aProps.AmbientReflectance(), myAmbientFactor, 0.001);
EXPECT_NEAR(aProps.DiffuseReflectance(), myDiffuseFactor, 0.001);
EXPECT_NEAR(aProps.SpecularReflectance(), mySpecularFactor, 0.001);
EXPECT_NEAR(aProps.SpecularExponent(), mySpecularExponent, 0.001);
EXPECT_TRUE(AreColorsEqual(aProps.SpecularColour(), mySpecularColor));
}
// Test creating STEP rendering properties
TEST_F(STEPConstruct_RenderingPropertiesTest, CreateRenderingProperties)
{
STEPConstruct_RenderingProperties aProps;
aProps.Init(mySurfaceColor, myTransparency);
aProps.SetAmbientDiffuseAndSpecularReflectance(myAmbientFactor,
myDiffuseFactor,
mySpecularFactor,
mySpecularExponent,
mySpecularColor);
Handle(StepVisual_SurfaceStyleRenderingWithProperties) aStepProps =
aProps.CreateRenderingProperties();
ASSERT_FALSE(aStepProps.IsNull());
EXPECT_EQ(aStepProps->RenderingMethod(), StepVisual_ssmNormalShading);
// Verify properties through re-parsing
STEPConstruct_RenderingProperties aParsedProps(aStepProps);
EXPECT_TRUE(aParsedProps.IsDefined());
EXPECT_TRUE(AreColorsEqual(aParsedProps.SurfaceColor(), mySurfaceColor));
EXPECT_NEAR(aParsedProps.Transparency(), myTransparency, 0.001);
EXPECT_NEAR(aParsedProps.AmbientReflectance(), myAmbientFactor, 0.001);
EXPECT_NEAR(aParsedProps.DiffuseReflectance(), myDiffuseFactor, 0.001);
EXPECT_NEAR(aParsedProps.SpecularReflectance(), mySpecularFactor, 0.001);
EXPECT_NEAR(aParsedProps.SpecularExponent(), mySpecularExponent, 0.001);
EXPECT_TRUE(AreColorsEqual(aParsedProps.SpecularColour(), mySpecularColor));
}
// Test creating XCAFDoc_VisMaterialCommon
TEST_F(STEPConstruct_RenderingPropertiesTest, CreateXCAFMaterial)
{
STEPConstruct_RenderingProperties aProps;
aProps.Init(mySurfaceColor, myTransparency);
aProps.SetAmbientDiffuseAndSpecularReflectance(myAmbientFactor,
myDiffuseFactor,
mySpecularFactor,
mySpecularExponent,
mySpecularColor);
XCAFDoc_VisMaterialCommon aMaterial = aProps.CreateXCAFMaterial();
EXPECT_TRUE(aMaterial.IsDefined);
// Check basic properties
EXPECT_TRUE(AreColorsEqual(aMaterial.DiffuseColor, mySurfaceColor));
EXPECT_NEAR(aMaterial.Transparency, myTransparency, 0.001);
// Check calculated ambient color
Quantity_Color anExpectedAmbient(mySurfaceColor.Red() * myAmbientFactor,
mySurfaceColor.Green() * myAmbientFactor,
mySurfaceColor.Blue() * myAmbientFactor,
Quantity_TOC_RGB);
EXPECT_TRUE(AreColorsEqual(aMaterial.AmbientColor, anExpectedAmbient));
// Check specular properties
EXPECT_TRUE(AreColorsEqual(aMaterial.SpecularColor, mySpecularColor));
EXPECT_NEAR(aMaterial.Shininess, mySpecularExponent / 128.0, 0.01);
}
// Test bidirectional conversion
TEST_F(STEPConstruct_RenderingPropertiesTest, BidirectionalConversion)
{
// Start with an XCAFDoc_VisMaterialCommon
XCAFDoc_VisMaterialCommon aOriginalMaterial = CreateMaterial();
// Convert to rendering properties
STEPConstruct_RenderingProperties aProps(aOriginalMaterial);
// Convert back to material
XCAFDoc_VisMaterialCommon aConvertedMaterial = aProps.CreateXCAFMaterial();
// Verify that the converted material matches the original
EXPECT_TRUE(aConvertedMaterial.IsDefined);
EXPECT_TRUE(AreColorsEqual(aConvertedMaterial.DiffuseColor, aOriginalMaterial.DiffuseColor));
EXPECT_NEAR(aConvertedMaterial.Transparency, aOriginalMaterial.Transparency, 0.001);
EXPECT_TRUE(
AreColorsEqual(aConvertedMaterial.AmbientColor, aOriginalMaterial.AmbientColor, 0.05));
EXPECT_TRUE(
AreColorsEqual(aConvertedMaterial.SpecularColor, aOriginalMaterial.SpecularColor, 0.05));
EXPECT_NEAR(aConvertedMaterial.Shininess, aOriginalMaterial.Shininess, 0.05);
}
// Test Init method with RGBA color
TEST_F(STEPConstruct_RenderingPropertiesTest, InitWithRGBAColor)
{
STEPConstruct_RenderingProperties aProps;
// Create an RGBA color with alpha = 0.6 (transparency = 0.4)
Quantity_ColorRGBA aRgba(Quantity_Color(0.3, 0.6, 0.9, Quantity_TOC_RGB), 0.6);
aProps.Init(aRgba);
EXPECT_TRUE(aProps.IsDefined());
EXPECT_FALSE(aProps.IsAmbientReflectanceDefined());
EXPECT_FALSE(aProps.IsDiffuseReflectanceDefined());
EXPECT_FALSE(aProps.IsSpecularReflectanceDefined());
Quantity_Color expectedColor(0.3, 0.6, 0.9, Quantity_TOC_RGB);
EXPECT_TRUE(AreColorsEqual(aProps.SurfaceColor(), expectedColor));
EXPECT_NEAR(aProps.Transparency(), 0.4, 0.001);
}
// Test Init method with custom rendering method
TEST_F(STEPConstruct_RenderingPropertiesTest, InitWithCustomRenderingMethod)
{
STEPConstruct_RenderingProperties aProps;
// Initialize with phong shading
aProps.Init(mySurfaceColor, myTransparency);
aProps.SetRenderingMethod(StepVisual_ssmDotShading);
EXPECT_TRUE(aProps.IsDefined());
EXPECT_TRUE(AreColorsEqual(aProps.SurfaceColor(), mySurfaceColor));
EXPECT_NEAR(aProps.Transparency(), myTransparency, 0.001);
EXPECT_EQ(aProps.RenderingMethod(), StepVisual_ssmDotShading);
}
// Test the IsMaterialConvertible method
TEST_F(STEPConstruct_RenderingPropertiesTest, MaterialConvertible)
{
STEPConstruct_RenderingProperties aProps;
// Initially shouldn't be convertible
EXPECT_FALSE(aProps.IsMaterialConvertible());
// After setting basic properties, still shouldn't be convertible
aProps.Init(mySurfaceColor, myTransparency);
EXPECT_FALSE(aProps.IsMaterialConvertible());
// After setting all required properties, should be convertible
aProps.SetAmbientDiffuseAndSpecularReflectance(myAmbientFactor,
myDiffuseFactor,
mySpecularFactor,
mySpecularExponent,
mySpecularColor);
EXPECT_TRUE(aProps.IsMaterialConvertible());
}
// Test with null inputs
TEST_F(STEPConstruct_RenderingPropertiesTest, NullInputs)
{
STEPConstruct_RenderingProperties aProps;
// Creating from null STEP rendering properties
Handle(StepVisual_SurfaceStyleRenderingWithProperties) nullProps;
aProps.Init(nullProps);
EXPECT_FALSE(aProps.IsDefined());
// Creating from null XCAF material
XCAFDoc_VisMaterialCommon nullMaterial;
nullMaterial.IsDefined = Standard_False;
STEPConstruct_RenderingProperties propsFromNull(nullMaterial);
EXPECT_FALSE(propsFromNull.IsDefined());
}
// Test creating STEP rendering properties with ambient only
TEST_F(STEPConstruct_RenderingPropertiesTest, CreateAmbientOnlyProperties)
{
STEPConstruct_RenderingProperties aProps;
aProps.Init(mySurfaceColor, myTransparency);
aProps.SetAmbientReflectance(myAmbientFactor);
Handle(StepVisual_SurfaceStyleRenderingWithProperties) aStepProps =
aProps.CreateRenderingProperties();
ASSERT_FALSE(aStepProps.IsNull());
// Verify properties through re-parsing
STEPConstruct_RenderingProperties aParsedProps(aStepProps);
EXPECT_TRUE(aParsedProps.IsDefined());
EXPECT_TRUE(aParsedProps.IsAmbientReflectanceDefined());
EXPECT_FALSE(aParsedProps.IsDiffuseReflectanceDefined());
EXPECT_FALSE(aParsedProps.IsSpecularReflectanceDefined());
EXPECT_TRUE(AreColorsEqual(aParsedProps.SurfaceColor(), mySurfaceColor));
EXPECT_NEAR(aParsedProps.Transparency(), myTransparency, 0.001);
EXPECT_NEAR(aParsedProps.AmbientReflectance(), myAmbientFactor, 0.001);
}
// Test creating STEP rendering properties with ambient and diffuse
TEST_F(STEPConstruct_RenderingPropertiesTest, CreateAmbientAndDiffuseProperties)
{
STEPConstruct_RenderingProperties aProps;
aProps.Init(mySurfaceColor, myTransparency);
aProps.SetAmbientAndDiffuseReflectance(myAmbientFactor, myDiffuseFactor);
Handle(StepVisual_SurfaceStyleRenderingWithProperties) aStepProps =
aProps.CreateRenderingProperties();
ASSERT_FALSE(aStepProps.IsNull());
// Verify properties through re-parsing
STEPConstruct_RenderingProperties aParsedProps(aStepProps);
EXPECT_TRUE(aParsedProps.IsDefined());
EXPECT_TRUE(aParsedProps.IsAmbientReflectanceDefined());
EXPECT_TRUE(aParsedProps.IsDiffuseReflectanceDefined());
EXPECT_FALSE(aParsedProps.IsSpecularReflectanceDefined());
EXPECT_TRUE(AreColorsEqual(aParsedProps.SurfaceColor(), mySurfaceColor));
EXPECT_NEAR(aParsedProps.Transparency(), myTransparency, 0.001);
EXPECT_NEAR(aParsedProps.AmbientReflectance(), myAmbientFactor, 0.001);
EXPECT_NEAR(aParsedProps.DiffuseReflectance(), myDiffuseFactor, 0.001);
}
// Test handling of non-standard specular color
TEST_F(STEPConstruct_RenderingPropertiesTest, NonStandardSpecularColor)
{
// Create a material with custom specular color not matching diffuse
XCAFDoc_VisMaterialCommon aMaterial = CreateMaterial();
Quantity_Color aCustomSpecular(0.1, 0.8, 0.2, Quantity_TOC_RGB); // Very different from diffuse
aMaterial.SpecularColor = aCustomSpecular;
// Convert to rendering properties
STEPConstruct_RenderingProperties aProps(aMaterial);
// Verify specular color is preserved as actual color, not just a factor
EXPECT_TRUE(aProps.IsSpecularColourDefined());
EXPECT_TRUE(AreColorsEqual(aProps.SpecularColour(), aCustomSpecular));
// Verify converting back preserves the special color
XCAFDoc_VisMaterialCommon aReconvertedMaterial = aProps.CreateXCAFMaterial();
EXPECT_TRUE(AreColorsEqual(aReconvertedMaterial.SpecularColor, aCustomSpecular, 0.05));
}
// Test extreme values for properties
TEST_F(STEPConstruct_RenderingPropertiesTest, ExtremeValues)
{
STEPConstruct_RenderingProperties aProps;
// Test with full transparency
aProps.Init(mySurfaceColor, 1.0);
EXPECT_NEAR(aProps.Transparency(), 1.0, 0.001);
// Test with extreme reflectance values
aProps.SetAmbientDiffuseAndSpecularReflectance(0.0, 2.0, 1.0, 256.0, mySpecularColor);
// Values should be clamped when creating material
XCAFDoc_VisMaterialCommon aMaterial = aProps.CreateXCAFMaterial();
// Ambient should be 0
EXPECT_NEAR(aMaterial.AmbientColor.Red(), 0.0, 0.001);
EXPECT_NEAR(aMaterial.AmbientColor.Green(), 0.0, 0.001);
EXPECT_NEAR(aMaterial.AmbientColor.Blue(), 0.0, 0.001);
// Shininess should be reasonable value (256/128 = 2, clamped to 1.0)
EXPECT_NEAR(aMaterial.Shininess, 1.0, 0.1);
}

View File

@@ -511,6 +511,19 @@ TEST_F(StepTidy_CartesianPointReducerTest,
Handle(StepGeom_CartesianPoint) aPt1 = addCartesianPoint();
Handle(StepGeom_CartesianPoint) aPt2 = addCartesianPoint();
// Creating rational BSpline surface to use.
Handle(StepGeom_RationalBSplineSurface) aRationalBSplineSurface =
new StepGeom_RationalBSplineSurface;
aRationalBSplineSurface->Init(new TCollection_HAsciiString,
1,
1,
new StepGeom_HArray2OfCartesianPoint(1, 1, 1, 1),
StepGeom_bssfUnspecified,
StepData_LUnknown,
StepData_LUnknown,
StepData_LUnknown,
new TColStd_HArray2OfReal(1, 1, 1, 1));
// Creating surface containing the first Cartesian point.
Handle(StepGeom_HArray2OfCartesianPoint) aFirstControlPoints =
new StepGeom_HArray2OfCartesianPoint(1, 1, 1, 1);
@@ -541,7 +554,7 @@ TEST_F(StepTidy_CartesianPointReducerTest,
StepData_LUnknown,
StepData_LUnknown,
aFirstBSSWN,
new StepGeom_RationalBSplineSurface);
aRationalBSplineSurface);
addToModel(aFirstSurface);
// Creating surface containing the second Cartesian point.
@@ -573,8 +586,8 @@ TEST_F(StepTidy_CartesianPointReducerTest,
StepData_LUnknown,
StepData_LUnknown,
StepData_LUnknown,
new StepGeom_BSplineSurfaceWithKnots,
new StepGeom_RationalBSplineSurface);
aSecondBSSWN,
aRationalBSplineSurface);
// Performing removal of duplicate Cartesian points.
TColStd_MapOfTransient aRemovedEntities = replaceDuplicateCartesianPoints();

View File

@@ -471,6 +471,8 @@
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleFillArea.pxx"
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleParameterLine.pxx"
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleReflectanceAmbient.pxx"
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse.pxx"
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular.pxx"
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleRendering.pxx"
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleRenderingWithProperties.pxx"
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleSegmentationCurve.pxx"
@@ -969,6 +971,8 @@
#include <StepVisual_SurfaceStyleFillArea.hxx>
#include <StepVisual_SurfaceStyleParameterLine.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbient.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuse.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular.hxx>
#include <StepVisual_SurfaceStyleRenderingWithProperties.hxx>
#include <StepVisual_SurfaceStyleSegmentationCurve.hxx>
#include <StepVisual_SurfaceStyleSilhouette.hxx>
@@ -5284,6 +5288,18 @@ void RWStepAP214_GeneralModule::FillSharedCase(const Standard_Integer
aTool.Share(anEnt, iter);
}
break;
case 825: {
DeclareAndCast(StepVisual_SurfaceStyleReflectanceAmbientDiffuse, anEnt, ent);
RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse aTool;
aTool.Share(anEnt, iter);
}
break;
case 826: {
DeclareAndCast(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular, anEnt, ent);
RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular aTool;
aTool.Share(anEnt, iter);
}
break;
default:
break;
}
@@ -7588,7 +7604,12 @@ Standard_Boolean RWStepAP214_GeneralModule::NewVoid(const Standard_Integer
case 824:
ent = new StepRepr_MechanicalDesignAndDraughtingRelationship;
break;
case 825:
ent = new StepVisual_SurfaceStyleReflectanceAmbientDiffuse;
break;
case 826:
ent = new StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular;
break;
default:
return Standard_False;
}

View File

@@ -436,6 +436,8 @@ IMPLEMENT_STANDARD_RTTIEXT(RWStepAP214_ReadWriteModule, StepData_ReadWriteModule
#include <StepVisual_SurfaceStyleTransparent.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbient.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuse.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular.hxx>
#include <StepVisual_SurfaceStyleRendering.hxx>
#include <StepVisual_SurfaceStyleRenderingWithProperties.hxx>
@@ -1454,6 +1456,8 @@ IMPLEMENT_STANDARD_RTTIEXT(RWStepAP214_ReadWriteModule, StepData_ReadWriteModule
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleTransparent.pxx"
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleReflectanceAmbient.pxx"
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse.pxx"
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular.pxx"
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleRendering.pxx"
#include "../RWStepVisual/RWStepVisual_RWSurfaceStyleRenderingWithProperties.pxx"
@@ -10816,6 +10820,18 @@ void RWStepAP214_ReadWriteModule::ReadStep(const Standard_Integer
aTool.ReadStep(data, num, ach, anent);
}
break;
case 825: {
DeclareAndCast(StepVisual_SurfaceStyleReflectanceAmbientDiffuse, anent, ent);
RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse aTool;
aTool.ReadStep(data, num, ach, anent);
}
break;
case 826: {
DeclareAndCast(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular, anent, ent);
RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular aTool;
aTool.ReadStep(data, num, ach, anent);
}
break;
default:
ach->AddFail("Type Mismatch when reading - Entity");
}

View File

@@ -446,6 +446,16 @@ void RWStepGeom_RWBSplineSurfaceWithKnots::Check(
{
ach->AddFail("ERROR: No.of KnotMultiplicities not equal No.of Knots in V");
}
if (nbMulU == 0)
{
ach->AddWarning("WARNING: No.of KnotMultiplicities in U is zero");
return;
}
if (nbMulV == 0)
{
ach->AddWarning("WARNING: No.of KnotMultiplicities in V is zero");
return;
}
// check in U direction

View File

@@ -40,24 +40,31 @@ void RWStepGeom_RWDirection::ReadStep(const Handle(StepData_StepReaderData)& dat
// --- own field : directionRatios ---
Handle(TColStd_HArray1OfReal) aDirectionRatios;
Standard_Real aDirectionRatiosItem;
Standard_Integer nsub2;
if (data->ReadSubList(num, 2, "direction_ratios", ach, nsub2))
Standard_Real aCoordinatesItem;
Standard_Integer aNSub2, aNbCoord = 0;
Standard_Real aXYZ[3] = {0., 0., 0.};
if (data->ReadSubList(num, 2, "direction_ratios", ach, aNSub2))
{
Standard_Integer nb2 = data->NbParams(nsub2);
aDirectionRatios = new TColStd_HArray1OfReal(1, nb2);
for (Standard_Integer i2 = 1; i2 <= nb2; i2++)
Standard_Integer aNbElements = data->NbParams(aNSub2);
if (aNbElements > 3)
{
// szv#4:S4163:12Mar99 `Standard_Boolean stat2 =` not needed
if (data->ReadReal(nsub2, i2, "direction_ratios", ach, aDirectionRatiosItem))
aDirectionRatios->SetValue(i2, aDirectionRatiosItem);
ach->AddWarning("More than 3 direction ratios, ignored");
}
aNbCoord = Min(aNbElements, 3);
for (Standard_Integer i2 = 0; i2 < aNbCoord; i2++)
{
if (data->ReadReal(aNSub2, i2 + 1, "direction_ratios", ach, aCoordinatesItem))
{
aXYZ[i2] = aCoordinatesItem;
}
}
}
//--- Initialisation of the read entity ---
ent->Init(aName, aDirectionRatios);
if (aNbCoord == 3)
ent->Init3D(aName, aXYZ[0], aXYZ[1], aXYZ[2]);
else
ent->Init2D(aName, aXYZ[0], aXYZ[1]);
}
void RWStepGeom_RWDirection::WriteStep(StepData_StepWriter& SW,

View File

@@ -128,6 +128,10 @@ set(OCCT_RWStepVisual_FILES
RWStepVisual_RWSurfaceStyleParameterLine.pxx
RWStepVisual_RWSurfaceStyleReflectanceAmbient.cxx
RWStepVisual_RWSurfaceStyleReflectanceAmbient.pxx
RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse.cxx
RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse.pxx
RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular.cxx
RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular.pxx
RWStepVisual_RWSurfaceStyleRendering.cxx
RWStepVisual_RWSurfaceStyleRendering.pxx
RWStepVisual_RWSurfaceStyleRenderingWithProperties.cxx

View File

@@ -0,0 +1,72 @@
// Copyright (c) Open CASCADE 2025
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include "RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse.pxx"
#include <Interface_EntityIterator.hxx>
#include <StepData_StepReaderData.hxx>
#include <StepData_StepWriter.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuse.hxx>
#include <Standard_Real.hxx>
//=================================================================================================
RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse::
RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse()
{
}
//=================================================================================================
void RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse::ReadStep(
const Handle(StepData_StepReaderData)& theData,
const Standard_Integer theNum,
Handle(Interface_Check)& theAch,
const Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuse)& theEnt) const
{
// Check number of parameters
if (!theData->CheckNbParams(theNum, 2, theAch, "surface_style_reflectance_ambient_diffuse"))
return;
// Inherited fields of SurfaceStyleReflectanceAmbient
Standard_Real aAmbientReflectance;
theData->ReadReal(theNum, 1, "ambient_reflectance", theAch, aAmbientReflectance);
// Own fields of SurfaceStyleReflectanceAmbientDiffuse
Standard_Real aDiffuseReflectance;
theData->ReadReal(theNum, 2, "diffuse_reflectance", theAch, aDiffuseReflectance);
// Initialize entity
theEnt->Init(aAmbientReflectance, aDiffuseReflectance);
}
//=================================================================================================
void RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse::WriteStep(
StepData_StepWriter& theSW,
const Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuse)& theEnt) const
{
// Inherited fields of SurfaceStyleReflectanceAmbient
theSW.Send(theEnt->AmbientReflectance());
// Own fields of SurfaceStyleReflectanceAmbientDiffuse
theSW.Send(theEnt->DiffuseReflectance());
}
//=================================================================================================
void RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse::Share(
const Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuse)&,
Interface_EntityIterator&) const
{
// Own fields of SurfaceStyleReflectanceAmbientDiffuse
}

View File

@@ -0,0 +1,48 @@
// Copyright (c) Open CASCADE 2025
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse_HeaderFile_
#define _RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse_HeaderFile_
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
class StepData_StepReaderData;
class Interface_Check;
class StepData_StepWriter;
class Interface_EntityIterator;
class StepVisual_SurfaceStyleReflectanceAmbientDiffuse;
//! Read & Write tool for SurfaceStyleReflectanceAmbientDiffuse
class RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse
{
public:
DEFINE_STANDARD_ALLOC
Standard_HIDDEN RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse();
Standard_HIDDEN void ReadStep(
const Handle(StepData_StepReaderData)& theData,
const Standard_Integer theNum,
Handle(Interface_Check)& theAch,
const Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuse)& theEnt) const;
Standard_HIDDEN void WriteStep(
StepData_StepWriter& theSW,
const Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuse)& theEnt) const;
Standard_HIDDEN void Share(const Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuse)& theEnt,
Interface_EntityIterator& theIter) const;
};
#endif // _RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuse_HeaderFile_

View File

@@ -0,0 +1,101 @@
// Copyright (c) Open CASCADE 2025
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include "RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular.pxx"
#include <Interface_EntityIterator.hxx>
#include <StepData_StepReaderData.hxx>
#include <StepData_StepWriter.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular.hxx>
#include <StepVisual_Colour.hxx>
#include <Standard_Real.hxx>
//=================================================================================================
RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular::
RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular()
{
}
//=================================================================================================
void RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular::ReadStep(
const Handle(StepData_StepReaderData)& theData,
const Standard_Integer theNum,
Handle(Interface_Check)& theAch,
const Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular)& theEnt) const
{
// Check number of parameters
if (!theData->CheckNbParams(theNum,
5,
theAch,
"surface_style_reflectance_ambient_diffuse_specular"))
return;
// Inherited fields of SurfaceStyleReflectanceAmbient
Standard_Real aAmbientReflectance;
theData->ReadReal(theNum, 1, "ambient_reflectance", theAch, aAmbientReflectance);
// Inherited fields of SurfaceStyleReflectanceAmbientDiffuse
Standard_Real aDiffuseReflectance;
theData->ReadReal(theNum, 2, "diffuse_reflectance", theAch, aDiffuseReflectance);
// Own fields of SurfaceStyleReflectanceAmbientDiffuseSpecular
Standard_Real aSpecularReflectance;
theData->ReadReal(theNum, 3, "specular_reflectance", theAch, aSpecularReflectance);
Standard_Real aSpecularExponent;
theData->ReadReal(theNum, 4, "specular_exponent", theAch, aSpecularExponent);
Handle(StepVisual_Colour) aSpecularColour;
theData->ReadEntity(theNum,
5,
"specular_colour",
theAch,
STANDARD_TYPE(StepVisual_Colour),
aSpecularColour);
// Initialize entity
theEnt->Init(aAmbientReflectance,
aDiffuseReflectance,
aSpecularReflectance,
aSpecularExponent,
aSpecularColour);
}
//=================================================================================================
void RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular::WriteStep(
StepData_StepWriter& theSW,
const Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular)& theEnt) const
{
// Inherited fields of SurfaceStyleReflectanceAmbient
theSW.Send(theEnt->AmbientReflectance());
// Inherited fields of SurfaceStyleReflectanceAmbientDiffuse
theSW.Send(theEnt->DiffuseReflectance());
// Own fields of SurfaceStyleReflectanceAmbientDiffuseSpecular
theSW.Send(theEnt->SpecularReflectance());
theSW.Send(theEnt->SpecularExponent());
theSW.Send(theEnt->SpecularColour());
}
//=================================================================================================
void RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular::Share(
const Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular)& theEnt,
Interface_EntityIterator& theIter) const
{
// Own fields of SurfaceStyleReflectanceAmbientDiffuseSpecular
theIter.AddItem(theEnt->SpecularColour());
}

View File

@@ -0,0 +1,49 @@
// Copyright (c) Open CASCADE 2025
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular_HeaderFile_
#define _RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular_HeaderFile_
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
class StepData_StepReaderData;
class Interface_Check;
class StepData_StepWriter;
class Interface_EntityIterator;
class StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular;
//! Read & Write tool for SurfaceStyleReflectanceAmbientDiffuseSpecular
class RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular
{
public:
DEFINE_STANDARD_ALLOC
Standard_HIDDEN RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular();
Standard_HIDDEN void ReadStep(
const Handle(StepData_StepReaderData)& theData,
const Standard_Integer theNum,
Handle(Interface_Check)& theAch,
const Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular)& theEnt) const;
Standard_HIDDEN void WriteStep(
StepData_StepWriter& theSW,
const Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular)& theEnt) const;
Standard_HIDDEN void Share(
const Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular)& theEnt,
Interface_EntityIterator& theIter) const;
};
#endif // _RWStepVisual_RWSurfaceStyleReflectanceAmbientDiffuseSpecular_HeaderFile_

View File

@@ -1024,17 +1024,11 @@ static void SetAssemblyComponentStyle(
if (theStyle.IsNull())
return;
Handle(StepVisual_Colour) aSurfCol, aBoundCol, aCurveCol, aRenderCol;
Standard_Real aRenderTransp;
Handle(StepVisual_Colour) aSurfCol, aBoundCol, aCurveCol;
STEPConstruct_RenderingProperties aRenderProps;
// check if it is component style
Standard_Boolean anIsComponent = Standard_False;
if (!theStyles.GetColors(theStyle,
aSurfCol,
aBoundCol,
aCurveCol,
aRenderCol,
aRenderTransp,
anIsComponent))
if (!theStyles.GetColors(theStyle, aSurfCol, aBoundCol, aCurveCol, aRenderProps, anIsComponent))
return;
const Interface_Graph& aGraph = theTP->Graph();
@@ -1103,7 +1097,7 @@ static void SetAssemblyComponentStyle(
aShape.Location(aLoc, Standard_False);
if (!aSurfCol.IsNull() || !aBoundCol.IsNull() || !aCurveCol.IsNull() || !aRenderCol.IsNull())
if (!aSurfCol.IsNull() || !aBoundCol.IsNull() || !aCurveCol.IsNull() || aRenderProps.IsDefined())
{
Quantity_Color aSCol, aBCol, aCCol, aRCol;
Quantity_ColorRGBA aFullSCol;
@@ -1116,13 +1110,12 @@ static void SetAssemblyComponentStyle(
theStyles.DecodeColor(aBoundCol, aBCol);
if (!aCurveCol.IsNull())
theStyles.DecodeColor(aCurveCol, aCCol);
if (!aRenderCol.IsNull())
if (aRenderProps.IsDefined())
{
theStyles.DecodeColor(aRenderCol, aRCol);
aFullSCol = Quantity_ColorRGBA(aRCol, static_cast<float>(1.0f - aRenderTransp));
aFullSCol = aRenderProps.GetRGBAColor();
}
if (!aSurfCol.IsNull() || !aRenderCol.IsNull())
if (!aSurfCol.IsNull() || aRenderProps.IsDefined())
theCTool->SetInstanceColor(aShape, XCAFDoc_ColorSurf, aFullSCol);
if (!aBoundCol.IsNull())
theCTool->SetInstanceColor(aShape, XCAFDoc_ColorCurv, aBCol);
@@ -1182,17 +1175,12 @@ static void SetStyle(const Handle(XSControl_WorkSession)& theWS,
anIsVisible = Standard_False;
break;
}
Handle(StepVisual_Colour) aSurfCol, aBoundCol, aCurveCol, aRenderCol;
Standard_Real aRenderTransp;
Handle(StepVisual_Colour) aSurfCol, aBoundCol, aCurveCol;
// check if it is component style
Standard_Boolean anIsComponent = Standard_False;
if (!theStyles.GetColors(theStyle,
aSurfCol,
aBoundCol,
aCurveCol,
aRenderCol,
aRenderTransp,
anIsComponent)
Standard_Boolean anIsComponent = Standard_False;
STEPConstruct_RenderingProperties aRenderProps;
if (!theStyles.GetColors(theStyle, aSurfCol, aBoundCol, aCurveCol, aRenderProps, anIsComponent)
&& anIsVisible)
return;
@@ -1272,12 +1260,13 @@ static void SetStyle(const Handle(XSControl_WorkSession)& theWS,
if (aS.IsNull())
continue;
if (!aSurfCol.IsNull() || !aBoundCol.IsNull() || !aCurveCol.IsNull() || !aRenderCol.IsNull()
if (!aSurfCol.IsNull() || !aBoundCol.IsNull() || !aCurveCol.IsNull() || aRenderProps.IsDefined()
|| !anIsVisible)
{
TDF_Label aL;
Standard_Boolean isFound = theSTool->SearchUsingMap(aS, aL, Standard_False, Standard_True);
if (!aSurfCol.IsNull() || !aBoundCol.IsNull() || !aCurveCol.IsNull() || !aRenderCol.IsNull())
if (!aSurfCol.IsNull() || !aBoundCol.IsNull() || !aCurveCol.IsNull()
|| aRenderProps.IsDefined())
{
Quantity_Color aSCol, aBCol, aCCol, aRCol;
Quantity_ColorRGBA aFullSCol;
@@ -1290,14 +1279,13 @@ static void SetStyle(const Handle(XSControl_WorkSession)& theWS,
theStyles.DecodeColor(aBoundCol, aBCol);
if (!aCurveCol.IsNull())
theStyles.DecodeColor(aCurveCol, aCCol);
if (!aRenderCol.IsNull())
if (aRenderProps.IsDefined())
{
theStyles.DecodeColor(aRenderCol, aRCol);
aFullSCol = Quantity_ColorRGBA(aRCol, static_cast<float>(1.0f - aRenderTransp));
aFullSCol = aRenderProps.GetRGBAColor();
}
if (isFound)
{
if (!aSurfCol.IsNull() || !aRenderCol.IsNull())
if (!aSurfCol.IsNull() || aRenderProps.IsDefined())
theCTool->SetColor(aL, aFullSCol, XCAFDoc_ColorSurf);
if (!aBoundCol.IsNull())
theCTool->SetColor(aL, aBCol, XCAFDoc_ColorCurv);
@@ -1311,7 +1299,7 @@ static void SetStyle(const Handle(XSControl_WorkSession)& theWS,
TDF_Label aL1;
if (theSTool->SearchUsingMap(it.Value(), aL1, Standard_False, Standard_True))
{
if (!aSurfCol.IsNull() || !aRenderCol.IsNull())
if (!aSurfCol.IsNull() || aRenderProps.IsDefined())
theCTool->SetColor(aL1, aFullSCol, XCAFDoc_ColorSurf);
if (!aBoundCol.IsNull())
theCTool->SetColor(aL1, aBCol, XCAFDoc_ColorCurv);
@@ -2012,11 +2000,11 @@ Standard_Boolean STEPCAFControl_Reader::ReadSHUOs(
break;
}
Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol, RenderCol;
Standard_Real RenderTransp;
Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
// check if it is component style
Standard_Boolean IsComponent = Standard_False;
if (!Styles.GetColors(style, SurfCol, BoundCol, CurveCol, RenderCol, RenderTransp, IsComponent)
Standard_Boolean IsComponent = Standard_False;
STEPConstruct_RenderingProperties aRenderProps;
if (!Styles.GetColors(style, SurfCol, BoundCol, CurveCol, aRenderProps, IsComponent)
&& IsVisible)
continue;
if (!IsComponent)
@@ -2056,7 +2044,7 @@ Standard_Boolean STEPCAFControl_Reader::ReadSHUOs(
continue;
}
// now set the style to the SHUO main label.
if (!SurfCol.IsNull() || !RenderCol.IsNull())
if (!SurfCol.IsNull() || aRenderProps.IsDefined())
{
Quantity_Color col;
Quantity_ColorRGBA colRGBA;
@@ -2065,10 +2053,9 @@ Standard_Boolean STEPCAFControl_Reader::ReadSHUOs(
Styles.DecodeColor(SurfCol, col);
colRGBA = Quantity_ColorRGBA(col);
}
if (!RenderCol.IsNull())
if (aRenderProps.IsDefined())
{
Styles.DecodeColor(RenderCol, col);
colRGBA = Quantity_ColorRGBA(col, static_cast<float>(1.0 - RenderTransp));
colRGBA = aRenderProps.GetRGBAColor();
}
CTool->SetColor(aLabelForStyle, colRGBA, XCAFDoc_ColorSurf);
}
@@ -4393,26 +4380,19 @@ static void setDimObjectToXCAF(const Handle(Standard_Transient)& theEnt,
return;
aDimObj->SetPath(aSh);
}
else if (!anAP.IsNull())
else if (!anAP.IsNull() && !anAP->RefDirection().IsNull() && !anAP->Name().IsNull()
&& !anAP->Axis().IsNull() && anAP->Name()->String().IsEqual("orientation"))
{
if (anAP->Name()->String().IsEqual("orientation") && !anAP->Axis().IsNull())
// for Oriented Dimensional Location
const Handle(StepGeom_Direction)& aRefDirection = anAP->RefDirection();
const std::array<Standard_Real, 3>& aDirArr = aRefDirection->DirectionRatios();
if (aRefDirection->NbDirectionRatios() >= 3)
{
// for Oriented Dimensional Location
Handle(TColStd_HArray1OfReal) aDirArr = anAP->RefDirection()->DirectionRatios();
gp_Dir aDir;
Standard_Integer aDirLower = aDirArr->Lower();
if (!aDirArr.IsNull() && aDirArr->Length() > 2)
{
aDir.SetCoord(aDirArr->Value(aDirLower),
aDirArr->Value(aDirLower + 1),
aDirArr->Value(aDirLower + 2));
aDimObj->SetDirection(aDir);
}
else if (aDirArr->Length() > 1)
{
aDir.SetCoord(aDirArr->Value(aDirLower), aDirArr->Value(aDirLower + 1), 0);
aDimObj->SetDirection(aDir);
}
aDimObj->SetDirection({aDirArr[0], aDirArr[1], aDirArr[2]});
}
else if (aRefDirection->NbDirectionRatios() == 2)
{
aDimObj->SetDirection({aDirArr[0], aDirArr[1], 0.});
}
}
}

View File

@@ -249,7 +249,9 @@ STEPCAFControl_Writer::STEPCAFControl_Writer()
myPropsMode(Standard_True),
mySHUOMode(Standard_True),
myGDTMode(Standard_True),
myMatMode(Standard_True)
myMatMode(Standard_True),
myVisMatMode(Standard_False),
myIsCleanDuplicates(Standard_False)
{
STEPCAFControl_Controller::Init();
Handle(XSControl_WorkSession) aWS = new XSControl_WorkSession;
@@ -266,7 +268,9 @@ STEPCAFControl_Writer::STEPCAFControl_Writer(const Handle(XSControl_WorkSession)
myPropsMode(Standard_True),
mySHUOMode(Standard_True),
myGDTMode(Standard_True),
myMatMode(Standard_True)
myMatMode(Standard_True),
myVisMatMode(Standard_False),
myIsCleanDuplicates(Standard_False)
{
STEPCAFControl_Controller::Init();
Init(theWS, theScratch);
@@ -1190,8 +1194,9 @@ static void MakeSTEPStyles(STEPConstruct_Styles& theStyle
STEPConstruct_DataMapOfAsciiStringTransient& theDPDCs,
STEPConstruct_DataMapOfPointTransient& theColRGBs,
const Handle(XCAFDoc_ShapeTool)& theShTool,
const XCAFPrs_Style* theInherit = 0,
const Standard_Boolean theIsComponent = Standard_False)
const XCAFPrs_Style* theInherit,
const Standard_Boolean theIsComponent,
const Standard_Boolean theVisMaterialMode)
{
// skip already processed shapes
if (!theMap.Add(theShape))
@@ -1210,6 +1215,8 @@ static void MakeSTEPStyles(STEPConstruct_Styles& theStyle
aStyle.SetColorCurv(anOwnStyle.GetColorCurv());
if (anOwnStyle.IsSetColorSurf())
aStyle.SetColorSurf(anOwnStyle.GetColorSurfRGBA());
if (!anOwnStyle.Material().IsNull())
aStyle.SetMaterial(anOwnStyle.Material());
}
// translate colors to STEP
@@ -1249,22 +1256,31 @@ static void MakeSTEPStyles(STEPConstruct_Styles& theStyle
const Handle(StepRepr_RepresentationItem)& anItem =
Handle(StepRepr_RepresentationItem)::DownCast(anEntIter.Value());
Handle(StepVisual_PresentationStyleAssignment) aPSA;
if (aStyle.IsVisible() || !aSurfColor.IsNull() || !aCurvColor.IsNull())
if (aStyle.IsVisible() || !aSurfColor.IsNull() || !aCurvColor.IsNull()
|| (theVisMaterialMode && !aStyle.Material().IsNull() && !aStyle.Material()->IsEmpty()))
{
aPSA = theStyles.MakeColorPSA(anItem,
aSurfColor,
aCurvColor,
aSurfColor,
aRenderTransp,
theIsComponent);
STEPConstruct_RenderingProperties aRenderProps;
if (theVisMaterialMode && !aStyle.Material().IsNull() && !aStyle.Material()->IsEmpty())
{
aRenderProps.Init(aStyle.Material());
}
else if (aRenderTransp > 0.0)
{
aRenderProps.Init(aStyle.GetColorSurfRGBA());
}
aPSA =
theStyles.MakeColorPSA(anItem, aSurfColor, aCurvColor, aRenderProps, theIsComponent);
}
else
{
// default white color
aSurfColor =
theStyles.EncodeColor(Quantity_Color(Quantity_NOC_WHITE), theDPDCs, theColRGBs);
aPSA =
theStyles.MakeColorPSA(anItem, aSurfColor, aCurvColor, aSurfColor, 0.0, theIsComponent);
aPSA = theStyles.MakeColorPSA(anItem,
aSurfColor,
aCurvColor,
STEPConstruct_RenderingProperties(),
theIsComponent);
if (theIsComponent)
setDefaultInstanceColor(theOverride, aPSA);
@@ -1294,7 +1310,9 @@ static void MakeSTEPStyles(STEPConstruct_Styles& theStyle
theDPDCs,
theColRGBs,
theShTool,
(aHasOwn ? &aStyle : 0));
(aHasOwn ? &aStyle : 0),
Standard_False,
theVisMaterialMode);
}
}
@@ -1415,7 +1433,8 @@ Standard_Boolean STEPCAFControl_Writer::writeColors(const Handle(XSControl_WorkS
ColRGBs,
aSTool,
0,
anIsComponent);
anIsComponent,
GetVisualMaterialMode());
const Handle(XSControl_TransferWriter)& aTW = theWS->TransferWriter();
const Handle(Transfer_FinderProcess)& aFP = aTW->FinderProcess();
@@ -2017,8 +2036,13 @@ static Standard_Boolean createSHUOStyledItem(const XCAFPrs_Style& theStyle,
aSurfColor = aStyles.EncodeColor(Quantity_Color(Quantity_NOC_WHITE));
isSetDefaultColor = Standard_True;
}
STEPConstruct_RenderingProperties aRenderProps;
if (aRenderTransp > 0.0)
{
aRenderProps.Init(theStyle.GetColorSurfRGBA());
}
Handle(StepVisual_PresentationStyleAssignment) aPSA =
aStyles.MakeColorPSA(anItem, aSurfColor, aCurvColor, aSurfColor, aRenderTransp, isComponent);
aStyles.MakeColorPSA(anItem, aSurfColor, aCurvColor, aRenderProps, isComponent);
Handle(StepVisual_StyledItem) anOverride; // null styled item
// find the repr item of the shape
@@ -4266,7 +4290,7 @@ Standard_Boolean STEPCAFControl_Writer::writeDGTsAP242(const Handle(XSControl_Wo
Handle(StepRepr_RepresentationItem) anItem = NULL;
myGDTPrsCurveStyle->SetValue(
1,
aStyles.MakeColorPSA(anItem, aCurvColor, aCurvColor, aCurvColor, 0.0));
aStyles.MakeColorPSA(anItem, aCurvColor, aCurvColor, STEPConstruct_RenderingProperties()));
for (Interface_EntityIterator aModelIter = aModel->Entities();
aModelIter.More() && myGDTCommonPDS.IsNull();
aModelIter.Next())

View File

@@ -221,11 +221,19 @@ public:
Standard_Boolean GetDimTolMode() const { return myGDTMode; }
//! Set dimtolmode for indicate write D&GTs or not.
//! Set flag for indicate write material or not.
void SetMaterialMode(const Standard_Boolean theMaterialMode) { myMatMode = theMaterialMode; }
Standard_Boolean GetMaterialMode() const { return myMatMode; }
//! Set flag for indicate write visual material or not.
void SetVisualMaterialMode(const Standard_Boolean theVisualMaterialMode)
{
myVisMatMode = theVisualMaterialMode;
}
Standard_Boolean GetVisualMaterialMode() const { return myVisMatMode; }
//! Set clean duplicates flag.
//! If set to True, duplicates will be removed from the model.
//! @param theCleanDuplicates the flag to set.
@@ -394,6 +402,7 @@ private:
MoniTool_DataMapOfShapeTransient myMapCompMDGPR;
Standard_Boolean myGDTMode;
Standard_Boolean myMatMode;
Standard_Boolean myVisMatMode;
Standard_Boolean myIsCleanDuplicates;
NCollection_Vector<Handle(StepRepr_RepresentationItem)> myGDTAnnotations;
Handle(StepVisual_DraughtingModel) myGDTPresentationDM;

View File

@@ -18,6 +18,8 @@ set(OCCT_STEPConstruct_FILES
STEPConstruct_ExternRefs.hxx
STEPConstruct_Part.cxx
STEPConstruct_Part.hxx
STEPConstruct_RenderingProperties.cxx
STEPConstruct_RenderingProperties.hxx
STEPConstruct_Styles.cxx
STEPConstruct_Styles.hxx
STEPConstruct_Tool.cxx

View File

@@ -0,0 +1,736 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <STEPConstruct_RenderingProperties.hxx>
#include <STEPConstruct_Styles.hxx>
#include <StepVisual_SurfaceStyleRenderingWithProperties.hxx>
#include <StepVisual_SurfaceStyleElementSelect.hxx>
#include <StepVisual_SurfaceStyleTransparent.hxx>
#include <StepVisual_RenderingPropertiesSelect.hxx>
#include <StepVisual_HArray1OfRenderingPropertiesSelect.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular.hxx>
#include <StepVisual_ColourRgb.hxx>
#include <StepVisual_DraughtingPreDefinedColour.hxx>
#include <StepVisual_PreDefinedItem.hxx>
#include <TCollection_HAsciiString.hxx>
#include <XCAFDoc_VisMaterialCommon.hxx>
#include <XCAFDoc_VisMaterial.hxx>
//=================================================================================================
STEPConstruct_RenderingProperties::STEPConstruct_RenderingProperties()
: mySurfaceColor(Quantity_NOC_WHITE),
myTransparency(0.0),
myRenderingMethod(StepVisual_ssmNormalShading),
myIsDefined(Standard_False),
myAmbientReflectance(0.0, Standard_False),
myDiffuseReflectance(0.0, Standard_False),
mySpecularReflectance(0.0, Standard_False),
mySpecularExponent(0.0, Standard_False),
mySpecularColour(Quantity_NOC_WHITE, Standard_False)
{
}
//=================================================================================================
STEPConstruct_RenderingProperties::STEPConstruct_RenderingProperties(
const Handle(StepVisual_SurfaceStyleRenderingWithProperties)& theRenderingProperties)
: mySurfaceColor(Quantity_NOC_WHITE),
myTransparency(0.0),
myRenderingMethod(StepVisual_ssmNormalShading),
myIsDefined(Standard_False),
myAmbientReflectance(0.0, Standard_False),
myDiffuseReflectance(0.0, Standard_False),
mySpecularReflectance(0.0, Standard_False),
mySpecularExponent(0.0, Standard_False),
mySpecularColour(Quantity_NOC_WHITE, Standard_False)
{
Init(theRenderingProperties);
}
//=================================================================================================
STEPConstruct_RenderingProperties::STEPConstruct_RenderingProperties(
const Quantity_ColorRGBA& theRGBAColor)
: mySurfaceColor(Quantity_NOC_WHITE),
myTransparency(0.0),
myRenderingMethod(StepVisual_ssmNormalShading),
myIsDefined(Standard_False),
myAmbientReflectance(0.0, Standard_False),
myDiffuseReflectance(0.0, Standard_False),
mySpecularReflectance(0.0, Standard_False),
mySpecularExponent(0.0, Standard_False),
mySpecularColour(Quantity_NOC_WHITE, Standard_False)
{
Init(theRGBAColor);
}
//=================================================================================================
STEPConstruct_RenderingProperties::STEPConstruct_RenderingProperties(
const Handle(StepVisual_Colour)& theColor,
const Standard_Real theTransparency)
: mySurfaceColor(Quantity_NOC_WHITE),
myTransparency(0.0),
myRenderingMethod(StepVisual_ssmNormalShading),
myIsDefined(Standard_False),
myAmbientReflectance(0.0, Standard_False),
myDiffuseReflectance(0.0, Standard_False),
mySpecularReflectance(0.0, Standard_False),
mySpecularExponent(0.0, Standard_False),
mySpecularColour(Quantity_NOC_WHITE, Standard_False)
{
Init(theColor, theTransparency);
}
//=================================================================================================
STEPConstruct_RenderingProperties::STEPConstruct_RenderingProperties(
const XCAFDoc_VisMaterialCommon& theMaterial)
: mySurfaceColor(Quantity_NOC_WHITE),
myTransparency(0.0),
myRenderingMethod(StepVisual_ssmNormalShading),
myIsDefined(Standard_False),
myAmbientReflectance(0.0, Standard_False),
myDiffuseReflectance(0.0, Standard_False),
mySpecularReflectance(0.0, Standard_False),
mySpecularExponent(0.0, Standard_False),
mySpecularColour(Quantity_NOC_WHITE, Standard_False)
{
Init(theMaterial);
}
//=================================================================================================
STEPConstruct_RenderingProperties::STEPConstruct_RenderingProperties(
const Handle(XCAFDoc_VisMaterial)& theMaterial)
: mySurfaceColor(Quantity_NOC_WHITE),
myTransparency(0.0),
myRenderingMethod(StepVisual_ssmNormalShading),
myIsDefined(Standard_False),
myAmbientReflectance(0.0, Standard_False),
myDiffuseReflectance(0.0, Standard_False),
mySpecularReflectance(0.0, Standard_False),
mySpecularExponent(0.0, Standard_False),
mySpecularColour(Quantity_NOC_WHITE, Standard_False)
{
Init(theMaterial);
}
//=================================================================================================
STEPConstruct_RenderingProperties::STEPConstruct_RenderingProperties(
const Quantity_Color& theSurfaceColor,
const Standard_Real theTransparency)
: mySurfaceColor(Quantity_NOC_WHITE),
myTransparency(0.0),
myRenderingMethod(StepVisual_ssmNormalShading),
myIsDefined(Standard_False),
myAmbientReflectance(0.0, Standard_False),
myDiffuseReflectance(0.0, Standard_False),
mySpecularReflectance(0.0, Standard_False),
mySpecularExponent(0.0, Standard_False),
mySpecularColour(Quantity_NOC_WHITE, Standard_False)
{
Init(theSurfaceColor, theTransparency);
}
//=================================================================================================
void STEPConstruct_RenderingProperties::SetAmbientReflectance(
const Standard_Real theAmbientReflectance)
{
myAmbientReflectance.first = theAmbientReflectance;
myAmbientReflectance.second = Standard_True;
}
//=================================================================================================
void STEPConstruct_RenderingProperties::SetAmbientAndDiffuseReflectance(
const Standard_Real theAmbientReflectance,
const Standard_Real theDiffuseReflectance)
{
myAmbientReflectance.first = theAmbientReflectance;
myAmbientReflectance.second = Standard_True;
myDiffuseReflectance.first = theDiffuseReflectance;
myDiffuseReflectance.second = Standard_True;
}
//=================================================================================================
void STEPConstruct_RenderingProperties::SetAmbientDiffuseAndSpecularReflectance(
const Standard_Real theAmbientReflectance,
const Standard_Real theDiffuseReflectance,
const Standard_Real theSpecularReflectance,
const Standard_Real theSpecularExponent,
const Quantity_Color& theSpecularColour)
{
myAmbientReflectance.first = theAmbientReflectance;
myAmbientReflectance.second = Standard_True;
myDiffuseReflectance.first = theDiffuseReflectance;
myDiffuseReflectance.second = Standard_True;
mySpecularReflectance.first = theSpecularReflectance;
mySpecularReflectance.second = Standard_True;
mySpecularExponent.first = theSpecularExponent;
mySpecularExponent.second = Standard_True;
mySpecularColour.first = theSpecularColour;
mySpecularColour.second = Standard_True;
}
//=================================================================================================
Handle(StepVisual_SurfaceStyleRenderingWithProperties) STEPConstruct_RenderingProperties::
CreateRenderingProperties() const
{
return CreateRenderingProperties(STEPConstruct_Styles::EncodeColor(mySurfaceColor));
}
//=================================================================================================
Handle(StepVisual_SurfaceStyleRenderingWithProperties) STEPConstruct_RenderingProperties::
CreateRenderingProperties(const Handle(StepVisual_Colour)& theRenderColour) const
{
if (!myIsDefined)
{
return nullptr;
}
// Create STEP RGB color or use predefined color using STEPConstruct_Styles utility
Handle(StepVisual_Colour) aStepColor =
!theRenderColour.IsNull() ? theRenderColour : STEPConstruct_Styles::EncodeColor(mySurfaceColor);
// Count and determine which properties to create.
// Transparency is always included.
Standard_Integer aNbProps = 1;
// Determine which reflectance properties to include
const Standard_Boolean hasFullReflectance =
(mySpecularColour.second && mySpecularExponent.second && mySpecularReflectance.second
&& myDiffuseReflectance.second && myAmbientReflectance.second);
const Standard_Boolean hasDiffuseAndAmbient =
(myDiffuseReflectance.second && myAmbientReflectance.second && !mySpecularReflectance.second);
const Standard_Boolean hasAmbientOnly =
(myAmbientReflectance.second && !myDiffuseReflectance.second && !mySpecularReflectance.second);
// Add reflectance property if we have any defined
if (hasFullReflectance || hasDiffuseAndAmbient || hasAmbientOnly)
{
aNbProps++;
}
// Create properties array
Handle(StepVisual_HArray1OfRenderingPropertiesSelect) aProps =
new StepVisual_HArray1OfRenderingPropertiesSelect(1, aNbProps);
Standard_Integer aPropIndex = 1;
// Add transparency
Handle(StepVisual_SurfaceStyleTransparent) aTransparent = new StepVisual_SurfaceStyleTransparent;
aTransparent->Init(myTransparency);
StepVisual_RenderingPropertiesSelect aRPS;
aRPS.SetValue(aTransparent);
aProps->SetValue(aPropIndex++, aRPS);
// Add the appropriate reflectance model based on what we have
if (hasAmbientOnly)
{
// Add ambient reflectance only
Handle(StepVisual_SurfaceStyleReflectanceAmbient) aAmbient =
new StepVisual_SurfaceStyleReflectanceAmbient;
aAmbient->Init(myAmbientReflectance.first);
StepVisual_RenderingPropertiesSelect aRPS;
aRPS.SetValue(aAmbient);
aProps->SetValue(aPropIndex++, aRPS);
}
else if (hasDiffuseAndAmbient)
{
// Add ambient and diffuse reflectance
Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuse) aAmbientDiffuse =
new StepVisual_SurfaceStyleReflectanceAmbientDiffuse;
aAmbientDiffuse->Init(myAmbientReflectance.first, myDiffuseReflectance.first);
StepVisual_RenderingPropertiesSelect aRPS;
aRPS.SetValue(aAmbientDiffuse);
aProps->SetValue(aPropIndex++, aRPS);
}
else if (hasFullReflectance)
{
// Add full PBR reflectance model (ambient, diffuse, specular)
Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular) aFullRefl =
new StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular;
aFullRefl->Init(myAmbientReflectance.first,
myDiffuseReflectance.first,
mySpecularReflectance.first,
mySpecularExponent.first,
STEPConstruct_Styles::EncodeColor(mySpecularColour.first));
StepVisual_RenderingPropertiesSelect aRPS;
aRPS.SetValue(aFullRefl);
aProps->SetValue(aPropIndex++, aRPS);
}
// Create STEP surface style rendering with properties
Handle(StepVisual_SurfaceStyleRenderingWithProperties) aSSRWP =
new StepVisual_SurfaceStyleRenderingWithProperties;
aSSRWP->Init(myRenderingMethod, aStepColor, aProps);
return aSSRWP;
}
//=================================================================================================
XCAFDoc_VisMaterialCommon STEPConstruct_RenderingProperties::CreateXCAFMaterial() const
{
if (!myIsDefined)
{
XCAFDoc_VisMaterialCommon aMaterial;
aMaterial.IsDefined = Standard_False;
return aMaterial;
}
XCAFDoc_VisMaterialCommon aMaterial;
// Use surface color as the base diffuse color
aMaterial.DiffuseColor = mySurfaceColor;
aMaterial.Transparency = myTransparency;
aMaterial.IsDefined = Standard_True;
// Set default values for other properties
aMaterial.AmbientColor = Quantity_Color(0.1, 0.1, 0.1, Quantity_TOC_RGB);
aMaterial.SpecularColor = Quantity_Color(0.2, 0.2, 0.2, Quantity_TOC_RGB);
aMaterial.EmissiveColor = Quantity_Color(0.0, 0.0, 0.0, Quantity_TOC_RGB);
aMaterial.Shininess = 1.0f;
// Handle ambient reflectance - apply factor to diffuse color
if (myAmbientReflectance.second)
{
// Get the reflectance factor, clamped to valid range
const Standard_Real aAmbientFactor = Max(0.0, Min(1.0, myAmbientReflectance.first));
// Apply factor to surface color (RGB components individually)
const Standard_Real aRed = mySurfaceColor.Red() * aAmbientFactor;
const Standard_Real aGreen = mySurfaceColor.Green() * aAmbientFactor;
const Standard_Real aBlue = mySurfaceColor.Blue() * aAmbientFactor;
Quantity_Color aAmbientColor(aRed, aGreen, aBlue, Quantity_TOC_RGB);
aMaterial.AmbientColor = aAmbientColor;
}
// Handle specular properties - apply factor to diffuse color or use explicit color
if (mySpecularColour.second)
{
// Use explicitly defined specular color
aMaterial.SpecularColor = mySpecularColour.first;
}
else if (mySpecularReflectance.second)
{
// Apply specular reflectance factor to surface color
const Standard_Real aSpecularFactor = Max(0.0, Min(1.0, mySpecularReflectance.first));
const Standard_Real aRed = mySurfaceColor.Red() * aSpecularFactor;
const Standard_Real aGreen = mySurfaceColor.Green() * aSpecularFactor;
const Standard_Real aBlue = mySurfaceColor.Blue() * aSpecularFactor;
Quantity_Color aSpecularColor(aRed, aGreen, aBlue, Quantity_TOC_RGB);
aMaterial.SpecularColor = aSpecularColor;
}
// Handle shininess (specular exponent)
if (mySpecularExponent.second)
{
// Convert STEP specular exponent to XCAF shininess using fixed scale factor
const Standard_Real kScaleFactor = 128.0;
const Standard_Real aShininess = mySpecularExponent.first / kScaleFactor;
aMaterial.Shininess = (Standard_ShortReal)Min(1.0, aShininess);
}
return aMaterial;
}
//=================================================================================================
void STEPConstruct_RenderingProperties::Init(
const Handle(StepVisual_SurfaceStyleRenderingWithProperties)& theRenderingProperties)
{
mySurfaceColor = Quantity_NOC_WHITE;
myTransparency = 0.0;
myRenderingMethod = StepVisual_ssmNormalShading;
myIsDefined = Standard_False;
myAmbientReflectance = std::make_pair(0.0, Standard_False);
myDiffuseReflectance = std::make_pair(0.0, Standard_False);
mySpecularReflectance = std::make_pair(0.0, Standard_False);
mySpecularExponent = std::make_pair(0.0, Standard_False);
mySpecularColour = std::make_pair(Quantity_NOC_WHITE, Standard_False);
if (theRenderingProperties.IsNull())
{
return;
}
myRenderingMethod = theRenderingProperties->RenderingMethod();
Handle(StepVisual_Colour) aColor = theRenderingProperties->SurfaceColour();
// Decode surface color using STEPConstruct_Styles utility
if (!aColor.IsNull())
{
Quantity_Color aDecodedColor;
if (STEPConstruct_Styles::DecodeColor(aColor, aDecodedColor))
{
mySurfaceColor = aDecodedColor;
myIsDefined = Standard_True;
}
}
// Process rendering properties
Handle(StepVisual_HArray1OfRenderingPropertiesSelect) aProperties =
theRenderingProperties->Properties();
if (!aProperties.IsNull())
{
for (Standard_Integer i = 1; i <= aProperties->Length(); i++)
{
StepVisual_RenderingPropertiesSelect aPropSelect = aProperties->Value(i);
// Check for transparency
Handle(StepVisual_SurfaceStyleTransparent) aTransparent =
aPropSelect.SurfaceStyleTransparent();
if (!aTransparent.IsNull())
{
myTransparency = aTransparent->Transparency();
myIsDefined = Standard_True;
}
// Check for ambient reflectance
Handle(StepVisual_SurfaceStyleReflectanceAmbient) aAmbient =
aPropSelect.SurfaceStyleReflectanceAmbient();
Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuse) aAmbientDiffuse =
Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuse)::DownCast(aAmbient);
Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular) aFullRefl =
Handle(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular)::DownCast(aAmbient);
if (!aFullRefl.IsNull())
{
myIsDefined = Standard_True;
myAmbientReflectance.first = aFullRefl->AmbientReflectance();
myDiffuseReflectance.first = aFullRefl->DiffuseReflectance();
mySpecularReflectance.first = aFullRefl->SpecularReflectance();
mySpecularExponent.first = aFullRefl->SpecularExponent();
myAmbientReflectance.second = Standard_True;
myDiffuseReflectance.second = Standard_True;
mySpecularReflectance.second = Standard_True;
mySpecularExponent.second = Standard_True;
mySpecularColour.second =
STEPConstruct_Styles::DecodeColor(aFullRefl->SpecularColour(), mySpecularColour.first);
}
else if (!aAmbientDiffuse.IsNull())
{
myAmbientReflectance.first = aAmbientDiffuse->AmbientReflectance();
myAmbientReflectance.second = Standard_True;
myDiffuseReflectance.first = aAmbientDiffuse->DiffuseReflectance();
myDiffuseReflectance.second = Standard_True;
myIsDefined = Standard_True;
}
else if (!aAmbient.IsNull())
{
myAmbientReflectance.first = aAmbient->AmbientReflectance();
myAmbientReflectance.second = Standard_True;
myIsDefined = Standard_True;
}
}
}
}
//=================================================================================================
void STEPConstruct_RenderingProperties::Init(const Quantity_ColorRGBA& theRGBAColor)
{
mySurfaceColor = theRGBAColor.GetRGB();
myTransparency = 1.0 - theRGBAColor.Alpha();
myRenderingMethod = StepVisual_ssmNormalShading;
myIsDefined = Standard_True;
myAmbientReflectance = std::make_pair(0.0, Standard_False);
myDiffuseReflectance = std::make_pair(0.0, Standard_False);
mySpecularReflectance = std::make_pair(0.0, Standard_False);
mySpecularExponent = std::make_pair(0.0, Standard_False);
mySpecularColour = std::make_pair(Quantity_NOC_WHITE, Standard_False);
}
//=================================================================================================
void STEPConstruct_RenderingProperties::Init(const Handle(StepVisual_Colour)& theColor,
const Standard_Real theTransparency)
{
mySurfaceColor = Quantity_NOC_WHITE;
myTransparency = theTransparency;
myRenderingMethod = StepVisual_ssmNormalShading;
myIsDefined = Standard_False;
myAmbientReflectance = std::make_pair(0.0, Standard_False);
myDiffuseReflectance = std::make_pair(0.0, Standard_False);
mySpecularReflectance = std::make_pair(0.0, Standard_False);
mySpecularExponent = std::make_pair(0.0, Standard_False);
mySpecularColour = std::make_pair(Quantity_NOC_WHITE, Standard_False);
if (theColor.IsNull())
{
return;
}
// Decode color using STEPConstruct_Styles utility
Quantity_Color aDecodedColor;
if (STEPConstruct_Styles::DecodeColor(theColor, aDecodedColor))
{
mySurfaceColor = aDecodedColor;
myIsDefined = Standard_True;
}
}
//=================================================================================================
void STEPConstruct_RenderingProperties::Init(const XCAFDoc_VisMaterialCommon& theMaterial)
{
if (!theMaterial.IsDefined)
{
mySurfaceColor = Quantity_NOC_WHITE;
myTransparency = 0.0;
myIsDefined = Standard_False;
return;
}
// Basic properties - use diffuse color as the base surface color
mySurfaceColor = theMaterial.DiffuseColor;
myTransparency = theMaterial.Transparency;
myRenderingMethod = StepVisual_ssmNormalShading;
myIsDefined = Standard_True;
// Reset reflectance properties
myAmbientReflectance = std::make_pair(0.0, Standard_False);
myDiffuseReflectance = std::make_pair(0.0, Standard_False);
mySpecularReflectance = std::make_pair(0.0, Standard_False);
mySpecularExponent = std::make_pair(0.0, Standard_False);
mySpecularColour = std::make_pair(Quantity_NOC_WHITE, Standard_False);
// Extract RGB components from diffuse color
const Standard_Real aDiffRed = theMaterial.DiffuseColor.Red();
const Standard_Real aDiffGreen = theMaterial.DiffuseColor.Green();
const Standard_Real aDiffBlue = theMaterial.DiffuseColor.Blue();
// Find maximum diffuse component to avoid division by zero for dark colors
const Standard_Real aDiffMax = Max(aDiffRed, Max(aDiffGreen, aDiffBlue));
// Check if ambient color is non-default and diffuse color has non-zero components
if (aDiffMax > Precision::Confusion())
{
// Extract RGB components from ambient color
Standard_Real aAmbRed = theMaterial.AmbientColor.Red();
Standard_Real aAmbGreen = theMaterial.AmbientColor.Green();
Standard_Real aAmbBlue = theMaterial.AmbientColor.Blue();
// Calculate per-channel ratios
const Standard_Real aRed = (aDiffRed > Precision::Confusion()) ? aAmbRed / aDiffRed : 0.0;
const Standard_Real aGreen =
(aDiffGreen > Precision::Confusion()) ? aAmbGreen / aDiffGreen : 0.0;
const Standard_Real aBlue = (aDiffBlue > Precision::Confusion()) ? aAmbBlue / aDiffBlue : 0.0;
// Calculate min and max of RGB ratios
const Standard_Real aMin = Min(aRed, Min(aGreen, aBlue));
const Standard_Real aMax = Max(aRed, Max(aGreen, aBlue));
// If ratios are reasonably close, use average as ambient reflectance factor
// otherwise the ambient color isn't a simple multiplier of diffuse
const Standard_Real kMaxRatioDeviation = 0.2; // Max allowed deviation between RGB ratios
if ((aMax - aMin) < kMaxRatioDeviation)
{
// Use average of RGB ratios as the reflectance factor
Standard_Real aAmbientFactor = (aRed + aGreen + aBlue) / 3.0;
// Check if factor is significantly different from default (0.1)
if (Abs(aAmbientFactor - 0.1) > 0.01)
{
// Clamp to valid range
aAmbientFactor = Max(0.0, Min(1.0, aAmbientFactor));
myAmbientReflectance.first = aAmbientFactor;
myAmbientReflectance.second = Standard_True;
}
}
}
// Diffuse reflectance is always 1.0 for the main color
myDiffuseReflectance.first = 1.0;
myDiffuseReflectance.second = Standard_True;
// Calculate specular reflectance factor relative to diffuse color
// Compare specular color to diffuse color directly to get reflectance factor
if (aDiffMax > Precision::Confusion())
{
// Extract RGB components from specular color
const Standard_Real aSpecRed = theMaterial.SpecularColor.Red();
const Standard_Real aSpecGreen = theMaterial.SpecularColor.Green();
const Standard_Real aSpecBlue = theMaterial.SpecularColor.Blue();
// Calculate per-channel ratios
const Standard_Real aRed = (aDiffRed > Precision::Confusion()) ? aSpecRed / aDiffRed : 0.0;
const Standard_Real aGreen =
(aDiffGreen > Precision::Confusion()) ? aSpecGreen / aDiffGreen : 0.0;
const Standard_Real aBlue = (aDiffBlue > Precision::Confusion()) ? aSpecBlue / aDiffBlue : 0.0;
// Calculate min and max of RGB ratios
const Standard_Real aMin = Min(aRed, Min(aGreen, aBlue));
const Standard_Real aMax = Max(aRed, Max(aGreen, aBlue));
// If ratios are reasonably close, use average as specular reflectance factor
const Standard_Real kMaxRatioDeviation = 0.2; // Max allowed deviation between RGB ratios
if ((aMax - aMin) < kMaxRatioDeviation)
{
// Use average of RGB ratios as the reflectance factor
Standard_Real aSpecularFactor = (aRed + aGreen + aBlue) / 3.0;
// Check if factor is significantly different from default (0.2)
if (Abs(aSpecularFactor - 0.2) > 0.01)
{
// Clamp to valid range
aSpecularFactor = Max(0.0, Min(1.0, aSpecularFactor));
mySpecularReflectance.first = aSpecularFactor;
mySpecularReflectance.second = Standard_True;
}
}
else
{
// Ratios differ significantly, specular color isn't a simple multiplier of diffuse
// Store actual specular color
mySpecularColour.first = theMaterial.SpecularColor;
mySpecularColour.second = Standard_True;
// Still compute an average reflectance factor for formats that don't support color
Standard_Real aSpecularFactor = (aSpecRed + aSpecGreen + aSpecBlue) / 3.0;
mySpecularReflectance.first = aSpecularFactor;
mySpecularReflectance.second = Standard_True;
}
}
// Convert shininess to specular exponent using fixed scale factor
if (theMaterial.Shininess >= 0.0f && Abs(theMaterial.Shininess - 1.0f) > 0.01f)
{
const Standard_Real kScaleFactor = 128.0;
mySpecularExponent.first = theMaterial.Shininess * kScaleFactor;
mySpecularExponent.second = Standard_True;
}
}
//=================================================================================================
void STEPConstruct_RenderingProperties::Init(const Handle(XCAFDoc_VisMaterial)& theMaterial)
{
if (theMaterial.IsNull())
{
return;
}
// Use the material to initialize rendering properties
Init(theMaterial->ConvertToCommonMaterial());
}
//=================================================================================================
void STEPConstruct_RenderingProperties::Init(const Quantity_Color& theSurfaceColor,
const Standard_Real theTransparency)
{
mySurfaceColor = theSurfaceColor;
myTransparency = theTransparency;
myRenderingMethod = StepVisual_ssmNormalShading;
myIsDefined = Standard_True;
myAmbientReflectance = std::make_pair(0.0, Standard_False);
myDiffuseReflectance = std::make_pair(0.0, Standard_False);
mySpecularReflectance = std::make_pair(0.0, Standard_False);
mySpecularExponent = std::make_pair(0.0, Standard_False);
mySpecularColour = std::make_pair(Quantity_NOC_WHITE, Standard_False);
}
//=================================================================================================
Standard_Boolean STEPConstruct_RenderingProperties::IsMaterialConvertible() const
{
return myIsDefined && myAmbientReflectance.second && myDiffuseReflectance.second
&& mySpecularReflectance.second && mySpecularExponent.second && mySpecularColour.second;
}
//=================================================================================================
Standard_Real STEPConstruct_RenderingProperties::AmbientReflectance() const
{
return myAmbientReflectance.first;
}
//=================================================================================================
Standard_Boolean STEPConstruct_RenderingProperties::IsAmbientReflectanceDefined() const
{
return myAmbientReflectance.second;
}
//=================================================================================================
Standard_Real STEPConstruct_RenderingProperties::DiffuseReflectance() const
{
return myDiffuseReflectance.first;
}
//=================================================================================================
Standard_Boolean STEPConstruct_RenderingProperties::IsDiffuseReflectanceDefined() const
{
return myDiffuseReflectance.second;
}
//=================================================================================================
Standard_Real STEPConstruct_RenderingProperties::SpecularReflectance() const
{
return mySpecularReflectance.first;
}
//=================================================================================================
Standard_Boolean STEPConstruct_RenderingProperties::IsSpecularReflectanceDefined() const
{
return mySpecularReflectance.second;
}
//=================================================================================================
Standard_Real STEPConstruct_RenderingProperties::SpecularExponent() const
{
return mySpecularExponent.first;
}
//=================================================================================================
Standard_Boolean STEPConstruct_RenderingProperties::IsSpecularExponentDefined() const
{
return mySpecularExponent.second;
}
//=================================================================================================
Quantity_Color STEPConstruct_RenderingProperties::SpecularColour() const
{
return mySpecularColour.first;
}
//=================================================================================================
Standard_Boolean STEPConstruct_RenderingProperties::IsSpecularColourDefined() const
{
return mySpecularColour.second;
}

View File

@@ -0,0 +1,235 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef STEPConstruct_RenderingProperties_HeaderFile
#define STEPConstruct_RenderingProperties_HeaderFile
#include <Quantity_Color.hxx>
#include <Quantity_ColorRGBA.hxx>
#include <StepVisual_ShadingSurfaceMethod.hxx>
#include <StepVisual_SurfaceStyleRenderingWithProperties.hxx>
#include <XCAFDoc_VisMaterialCommon.hxx>
#include <utility>
class StepVisual_SurfaceStyleRenderingWithProperties;
class StepVisual_Colour;
class XCAFDoc_VisMaterial;
//! Class for working with STEP rendering properties.
//! Provides functionality to create and manipulate rendering properties
//! used for specifying visual appearance in STEP format.
//! This class handles both parsing of STEP entities and creation of new ones.
class STEPConstruct_RenderingProperties
{
public:
DEFINE_STANDARD_ALLOC
public:
//! Default constructor creating an empty rendering properties object
Standard_EXPORT STEPConstruct_RenderingProperties();
//! Constructor from STEP rendering properties entity.
//! Extracts color, transparency, and other properties from the STEP entity.
//! @param[in] theRenderingProperties rendering properties entity
Standard_EXPORT STEPConstruct_RenderingProperties(
const Handle(StepVisual_SurfaceStyleRenderingWithProperties)& theRenderingProperties);
//! Constructor from RGBA color.
//! Creates rendering properties with the given color and transparency.
//! @param[in] theRGBAColor color with transparency
Standard_EXPORT STEPConstruct_RenderingProperties(const Quantity_ColorRGBA& theRGBAColor);
//! Constructor from STEP color and transparency value.
//! Creates rendering properties with the given color and transparency.
//! @param[in] theColor color
//! @param[in] theTransparency transparency value
Standard_EXPORT STEPConstruct_RenderingProperties(const Handle(StepVisual_Colour)& theColor,
const Standard_Real theTransparency);
//! Constructor from XCAFDoc_VisMaterialCommon.
//! Creates rendering properties using material properties from the OCCT material.
//! @param[in] theMaterial common visualization material properties
Standard_EXPORT STEPConstruct_RenderingProperties(const XCAFDoc_VisMaterialCommon& theMaterial);
//! Constructor from XCAFDoc_VisMaterial.
//! Creates rendering properties using material properties from the OCCT material.
//! @param[in] theMaterial visualization material properties
Standard_EXPORT STEPConstruct_RenderingProperties(const Handle(XCAFDoc_VisMaterial)& theMaterial);
//! Constructor from surface color, transparency, and rendering method.
//! @param[in] theSurfaceColor surface color
//! @param[in] theTransparency transparency value
Standard_EXPORT STEPConstruct_RenderingProperties(const Quantity_Color& theSurfaceColor,
const Standard_Real theTransparency = 0.0);
//! Initializes from STEP rendering properties entity.
//! Extracts color, transparency, and other properties from the STEP entity.
//! @param[in] theRenderingProperties rendering properties entity
Standard_EXPORT void Init(
const Handle(StepVisual_SurfaceStyleRenderingWithProperties)& theRenderingProperties);
//! Initializes from RGBA color.
//! @param[in] theRGBAColor color with transparency
Standard_EXPORT void Init(const Quantity_ColorRGBA& theRGBAColor);
//! Initializes from STEP color and transparency value.
//! @param[in] theColor STEP color entity
//! @param[in] theTransparency transparency value
Standard_EXPORT void Init(const Handle(StepVisual_Colour)& theColor,
const Standard_Real theTransparency);
//! Initializes from XCAFDoc_VisMaterialCommon.
//! @param[in] theMaterial common visualization material properties
Standard_EXPORT void Init(const XCAFDoc_VisMaterialCommon& theMaterial);
//! Initializes from XCAFDoc_VisMaterial.
//! @param[in] theMaterial visualization material properties
Standard_EXPORT void Init(const Handle(XCAFDoc_VisMaterial)& theMaterial);
//! Initializes from surface color, transparency and rendering method.
//! @param[in] theSurfaceColor surface color
//! @param[in] theTransparency transparency value
Standard_EXPORT void Init(const Quantity_Color& theSurfaceColor,
const Standard_Real theTransparency = 0.0);
//! Sets ambient reflectance value
//! @param[in] theAmbientReflectance ambient reflectance value
Standard_EXPORT void SetAmbientReflectance(const Standard_Real theAmbientReflectance);
//! Sets ambient and diffuse reflectance values
//! @param[in] theAmbientReflectance ambient reflectance value
//! @param[in] theDiffuseReflectance diffuse reflectance value
Standard_EXPORT void SetAmbientAndDiffuseReflectance(const Standard_Real theAmbientReflectance,
const Standard_Real theDiffuseReflectance);
//! Sets ambient, diffuse and specular reflectance values
//! @param[in] theAmbientReflectance ambient reflectance value
//! @param[in] theDiffuseReflectance diffuse reflectance value
//! @param[in] theSpecularReflectance specular reflectance value
//! @param[in] theSpecularExponent specular exponent value
//! @param[in] theSpecularColour specular color
Standard_EXPORT void SetAmbientDiffuseAndSpecularReflectance(
const Standard_Real theAmbientReflectance,
const Standard_Real theDiffuseReflectance,
const Standard_Real theSpecularReflectance,
const Standard_Real theSpecularExponent,
const Quantity_Color& theSpecularColour);
//! Creates and returns rendering properties entity
//! @return created rendering properties entity
Standard_EXPORT Handle(StepVisual_SurfaceStyleRenderingWithProperties) CreateRenderingProperties()
const;
// Creates and returns rendering properties entity with the specified color
//! @param[in] theRenderColour color to be used for rendering
//! @return created rendering properties entity
Standard_EXPORT Handle(StepVisual_SurfaceStyleRenderingWithProperties) CreateRenderingProperties(
const Handle(StepVisual_Colour)& theRenderColour) const;
//! Creates and returns XCAF material entity
//! @return created XCAF material entity
Standard_EXPORT XCAFDoc_VisMaterialCommon CreateXCAFMaterial() const;
//! Creates the ColorRGBA object from the current color and transparency
//! @return ColorRGBA object
Quantity_ColorRGBA GetRGBAColor() const
{
return Quantity_ColorRGBA(mySurfaceColor, 1.0 - myTransparency);
}
//! Returns surface color
//! @return surface color
Quantity_Color SurfaceColor() const { return mySurfaceColor; }
//! Returns transparency value
//! @return transparency value
Standard_Real Transparency() const { return myTransparency; }
//! Returns rendering method
//! @return rendering method
StepVisual_ShadingSurfaceMethod RenderingMethod() const { return myRenderingMethod; }
//! Sets rendering method
//! @param[in] theRenderingMethod rendering method
void SetRenderingMethod(const StepVisual_ShadingSurfaceMethod theRenderingMethod)
{
myRenderingMethod = theRenderingMethod;
}
//! Returns whether the rendering properties are defined
//! @return true if defined, false otherwise
Standard_Boolean IsDefined() const { return myIsDefined; }
//! Returns whether material is convertible to STEP
//! @return true if fully defined for conversion, false otherwise
Standard_EXPORT Standard_Boolean IsMaterialConvertible() const;
//! Returns ambient reflectance value
//! @return ambient reflectance value
Standard_EXPORT Standard_Real AmbientReflectance() const;
//! Returns whether ambient reflectance is defined
//! @return true if defined, false otherwise
Standard_EXPORT Standard_Boolean IsAmbientReflectanceDefined() const;
//! Returns diffuse reflectance value
//! @return diffuse reflectance value
Standard_EXPORT Standard_Real DiffuseReflectance() const;
//! Returns whether diffuse reflectance is defined
//! @return true if defined, false otherwise
Standard_EXPORT Standard_Boolean IsDiffuseReflectanceDefined() const;
//! Returns specular reflectance value
//! @return specular reflectance value
Standard_EXPORT Standard_Real SpecularReflectance() const;
//! Returns whether specular reflectance is defined
//! @return true if defined, false otherwise
Standard_EXPORT Standard_Boolean IsSpecularReflectanceDefined() const;
//! Returns specular exponent value
//! @return specular exponent value
Standard_EXPORT Standard_Real SpecularExponent() const;
//! Returns whether specular exponent is defined
//! @return true if defined, false otherwise
Standard_EXPORT Standard_Boolean IsSpecularExponentDefined() const;
//! Returns specular color
//! @return specular color
Standard_EXPORT Quantity_Color SpecularColour() const;
//! Returns whether specular color is defined
//! @return true if defined, false otherwise
Standard_EXPORT Standard_Boolean IsSpecularColourDefined() const;
private:
Quantity_Color mySurfaceColor; //!< Surface colour used for rendering
Standard_Real myTransparency; //!< Transparency value (0.0 - opaque, 1.0 - fully transparent)
StepVisual_ShadingSurfaceMethod myRenderingMethod; //!< Rendering method used for shading
Standard_Boolean myIsDefined; //!< Flag indicating if rendering properties are defined
//! Ambient reflectance value, applyed on the surface color
std::pair<Standard_Real, Standard_Boolean> myAmbientReflectance;
//! Diffuse reflectance value, applyed on the surface color
std::pair<Standard_Real, Standard_Boolean> myDiffuseReflectance;
//! Specular reflectance value, applyed on the surface color
std::pair<Standard_Real, Standard_Boolean> mySpecularReflectance;
//! Specular exponent value, applyed on the surface color
std::pair<Standard_Real, Standard_Boolean> mySpecularExponent;
//! Specular color, applyed on the surface color
std::pair<Quantity_Color, Standard_Boolean> mySpecularColour;
};
#endif // STEPConstruct_RenderingProperties_HeaderFile

View File

@@ -79,39 +79,23 @@ namespace
// (even if color and transparency data couldn't be extracted
// for some reason), otherwise returns false.
//=======================================================================
Standard_Boolean ProcessAsSurfaceStyleRendering(const StepVisual_SurfaceStyleElementSelect& theSSES,
Handle(StepVisual_Colour)& theRenderColour,
Standard_Real& theRenderTransparency)
Standard_Boolean ProcessAsSurfaceStyleRendering(
const StepVisual_SurfaceStyleElementSelect& theSSES,
STEPConstruct_RenderingProperties& theRenderingProps)
{
const Handle(StepVisual_SurfaceStyleRendering) aSSR = theSSES.SurfaceStyleRendering();
if (aSSR.IsNull())
{
return Standard_False;
}
theRenderColour = aSSR->SurfaceColour();
theRenderTransparency = 0.0;
const Handle(StepVisual_SurfaceStyleRenderingWithProperties) aSSRWP =
Handle(StepVisual_SurfaceStyleRenderingWithProperties)::DownCast(aSSR);
if (aSSRWP.IsNull())
{
return Standard_True;
}
const Handle(StepVisual_HArray1OfRenderingPropertiesSelect) aHARP = aSSRWP->Properties();
if (aHARP.IsNull())
{
return Standard_True;
}
for (Standard_Integer aPropIndex = 1; aPropIndex <= aHARP->Length(); ++aPropIndex)
{
const Handle(StepVisual_SurfaceStyleTransparent) aSST =
aHARP->Value(aPropIndex).SurfaceStyleTransparent();
if (!aSST.IsNull())
{
theRenderTransparency = aSST->Transparency();
}
}
return Standard_True;
theRenderingProps.Init(aSSRWP);
return theRenderingProps.IsDefined();
}
//=======================================================================
@@ -189,10 +173,9 @@ Standard_Boolean ProcessAsSurfaceStyleFillArea(const StepVisual_SurfaceStyleElem
// otherwise returns false.
//=======================================================================
Standard_Boolean ProcessAsSurfaceStyleUsage(const StepVisual_PresentationStyleSelect& thePSS,
Handle(StepVisual_Colour)& theSurfaceColour,
Handle(StepVisual_Colour)& theBoundaryColour,
Handle(StepVisual_Colour)& theRenderColour,
Standard_Real& theRenderTransparency)
Handle(StepVisual_Colour)& theSurfaceColour,
Handle(StepVisual_Colour)& theBoundaryColour,
STEPConstruct_RenderingProperties& theRenderingProps)
{
const Handle(StepVisual_SurfaceStyleUsage) aSSU = thePSS.SurfaceStyleUsage();
if (aSSU.IsNull())
@@ -209,7 +192,7 @@ Standard_Boolean ProcessAsSurfaceStyleUsage(const StepVisual_PresentationStyleSe
// So we're using && operator to stop as soon as this type is processed.
ProcessAsSurfaceStyleFillArea(aSSES, aSSU->Side(), theSurfaceColour)
|| ProcessAsSurfaceStyleBoundary(aSSES, theBoundaryColour)
|| ProcessAsSurfaceStyleRendering(aSSES, theRenderColour, theRenderTransparency);
|| ProcessAsSurfaceStyleRendering(aSSES, theRenderingProps);
}
return Standard_True;
}
@@ -584,11 +567,10 @@ Standard_Boolean STEPConstruct_Styles::LoadInvisStyles(
Handle(StepVisual_PresentationStyleAssignment) STEPConstruct_Styles::MakeColorPSA(
const Handle(StepRepr_RepresentationItem)& /*item*/,
const Handle(StepVisual_Colour)& SurfCol,
const Handle(StepVisual_Colour)& CurveCol,
const Handle(StepVisual_Colour)& RenderCol,
const Standard_Real RenderTransp,
const Standard_Boolean isForNAUO) const
const Handle(StepVisual_Colour)& SurfCol,
const Handle(StepVisual_Colour)& CurveCol,
const STEPConstruct_RenderingProperties& theRenderingProps,
const Standard_Boolean isForNAUO) const
{
Handle(StepVisual_PresentationStyleAssignment) PSA;
TColStd_SequenceOfTransient items;
@@ -617,30 +599,20 @@ Handle(StepVisual_PresentationStyleAssignment) STEPConstruct_Styles::MakeColorPS
StepVisual_SurfaceStyleElementSelect SES;
SES.SetValue(SSFA);
Handle(StepVisual_SurfaceStyleRenderingWithProperties) aSSRWP =
theRenderingProps.CreateRenderingProperties(SurfCol);
Handle(StepVisual_HArray1OfSurfaceStyleElementSelect) SSESs;
if (RenderTransp == 0.0)
if (aSSRWP.IsNull())
{
SSESs = new StepVisual_HArray1OfSurfaceStyleElementSelect(1, 1);
}
else
{
Handle(StepVisual_SurfaceStyleTransparent) SST = new StepVisual_SurfaceStyleTransparent;
SST->Init(RenderTransp);
StepVisual_RenderingPropertiesSelect RPS;
RPS.SetValue(SST);
Handle(StepVisual_HArray1OfRenderingPropertiesSelect) HARP =
new StepVisual_HArray1OfRenderingPropertiesSelect(1, 1);
HARP->SetValue(1, RPS);
Handle(StepVisual_SurfaceStyleRenderingWithProperties) SSRWP =
new StepVisual_SurfaceStyleRenderingWithProperties;
SSRWP->Init(StepVisual_ssmNormalShading, RenderCol, HARP);
StepVisual_SurfaceStyleElementSelect SESR;
SESR.SetValue(SSRWP);
StepVisual_SurfaceStyleElementSelect aSESR;
aSESR.SetValue(aSSRWP);
SSESs = new StepVisual_HArray1OfSurfaceStyleElementSelect(1, 2);
SSESs->SetValue(2, SESR);
SSESs->SetValue(2, aSESR);
}
SSESs->SetValue(1, SES);
@@ -719,7 +691,7 @@ Handle(StepVisual_PresentationStyleAssignment) STEPConstruct_Styles::GetColorPSA
}
else
{
PSA = MakeColorPSA(item, Col, Col, Col, 0.0);
PSA = MakeColorPSA(item, Col, Col, STEPConstruct_RenderingProperties());
myMapOfStyles.Add(Col, PSA);
}
return PSA;
@@ -727,18 +699,18 @@ Handle(StepVisual_PresentationStyleAssignment) STEPConstruct_Styles::GetColorPSA
//=================================================================================================
Standard_Boolean STEPConstruct_Styles::GetColors(const Handle(StepVisual_StyledItem)& theStyle,
Handle(StepVisual_Colour)& theSurfaceColour,
Handle(StepVisual_Colour)& theBoundaryColour,
Handle(StepVisual_Colour)& theCurveColour,
Handle(StepVisual_Colour)& theRenderColour,
Standard_Real& theRenderTransparency,
Standard_Boolean& theIsComponent) const
Standard_Boolean STEPConstruct_Styles::GetColors(
const Handle(StepVisual_StyledItem)& theStyle,
Handle(StepVisual_Colour)& theSurfaceColour,
Handle(StepVisual_Colour)& theBoundaryColour,
Handle(StepVisual_Colour)& theCurveColour,
STEPConstruct_RenderingProperties& theRenderingProps,
Standard_Boolean& theIsComponent) const
{
theSurfaceColour.Nullify();
theBoundaryColour.Nullify();
theCurveColour.Nullify();
theRenderColour.Nullify();
theRenderingProps = STEPConstruct_RenderingProperties();
// parse on styles
for (Standard_Integer aPSAIndex = 1; aPSAIndex <= theStyle->NbStyles(); ++aPSAIndex)
@@ -756,16 +728,12 @@ Standard_Boolean STEPConstruct_Styles::GetColors(const Handle(StepVisual_StyledI
// PresentationStyleSelect can be of only one of the following types:
// SurfaceStyleUsage, CurveStyle.
// So we're using && operator to stop as soon as this type is processed.
ProcessAsSurfaceStyleUsage(aPSS,
theSurfaceColour,
theBoundaryColour,
theRenderColour,
theRenderTransparency)
ProcessAsSurfaceStyleUsage(aPSS, theSurfaceColour, theBoundaryColour, theRenderingProps)
|| ProcessAsCurveStyle(aPSS, theCurveColour);
}
}
return !theSurfaceColour.IsNull() || !theBoundaryColour.IsNull() || !theCurveColour.IsNull()
|| !theRenderColour.IsNull();
|| theRenderingProps.IsDefined();
}
//=================================================================================================

View File

@@ -25,6 +25,7 @@
#include <STEPConstruct_Tool.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_HSequenceOfTransient.hxx>
#include <STEPConstruct_RenderingProperties.hxx>
#include <STEPConstruct_DataMapOfAsciiStringTransient.hxx>
#include <STEPConstruct_DataMapOfPointTransient.hxx>
@@ -35,6 +36,7 @@ class StepVisual_PresentationStyleAssignment;
class TopoDS_Shape;
class StepRepr_RepresentationContext;
class StepVisual_MechanicalDesignGeometricPresentationRepresentation;
class StepData_StepModel;
class StepShape_ContextDependentShapeRepresentation;
class StepRepr_ProductDefinitionShape;
class StepVisual_Colour;
@@ -136,8 +138,7 @@ public:
const Handle(StepRepr_RepresentationItem)& item,
const Handle(StepVisual_Colour)& SurfCol,
const Handle(StepVisual_Colour)& CurveCol,
const Handle(StepVisual_Colour)& RenderCol,
const Standard_Real RenderTransp,
const STEPConstruct_RenderingProperties& theRenderingProps,
const Standard_Boolean isForNAUO = Standard_False) const;
//! Returns a PresentationStyleAssignment entity which defines
@@ -156,8 +157,7 @@ public:
Handle(StepVisual_Colour)& theSurfaceColour,
Handle(StepVisual_Colour)& theBoundaryColour,
Handle(StepVisual_Colour)& theCurveColour,
Handle(StepVisual_Colour)& theRenderColour,
Standard_Real& theRenderTransparency,
STEPConstruct_RenderingProperties& theRenderingProps,
Standard_Boolean& theIsComponent) const;
//! Create STEP color entity by given Quantity_Color

View File

@@ -734,6 +734,8 @@ static Standard_CString schemaAP242DIS =
#include <StepVisual_SurfaceStyleTransparent.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbient.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuse.hxx>
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular.hxx>
#include <StepVisual_SurfaceStyleRenderingWithProperties.hxx>
#include <StepVisual_TessellatedConnectingEdge.hxx>
@@ -1567,6 +1569,8 @@ StepAP214_Protocol::StepAP214_Protocol()
types.Bind(STANDARD_TYPE(StepRepr_BooleanRepresentationItem), 822);
types.Bind(STANDARD_TYPE(StepRepr_RealRepresentationItem), 823);
types.Bind(STANDARD_TYPE(StepRepr_MechanicalDesignAndDraughtingRelationship), 824);
types.Bind(STANDARD_TYPE(StepVisual_SurfaceStyleReflectanceAmbientDiffuse), 825);
types.Bind(STANDARD_TYPE(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular), 826);
}
//=================================================================================================

View File

@@ -19,71 +19,71 @@ IMPLEMENT_STANDARD_RTTIEXT(StepGeom_CartesianPoint, StepGeom_Point)
StepGeom_CartesianPoint::StepGeom_CartesianPoint() {}
void StepGeom_CartesianPoint::Init(const Handle(TCollection_HAsciiString)& aName,
void StepGeom_CartesianPoint::Init(const Handle(TCollection_HAsciiString)& theName,
const Handle(TColStd_HArray1OfReal)& aCoordinates)
{
// --- classe own fields ---
nbcoord = aCoordinates->Length();
coords[0] = aCoordinates->Value(1);
coords[1] = aCoordinates->Value(2);
coords[2] = aCoordinates->Value(3);
// coordinates = aCoordinates;
SetCoordinates(aCoordinates);
// --- classe inherited fields ---
StepRepr_RepresentationItem::Init(aName);
StepRepr_RepresentationItem::Init(theName);
}
void StepGeom_CartesianPoint::Init2D(const Handle(TCollection_HAsciiString)& aName,
const Standard_Real X,
const Standard_Real Y)
void StepGeom_CartesianPoint::Init2D(const Handle(TCollection_HAsciiString)& theName,
const Standard_Real theX,
const Standard_Real theY)
{
nbcoord = 2;
coords[0] = X;
coords[1] = Y;
coords[2] = 0;
myNbCoord = 2;
myCoords[0] = theX;
myCoords[1] = theY;
myCoords[2] = 0;
// --- classe inherited fields ---
StepRepr_RepresentationItem::Init(aName);
StepRepr_RepresentationItem::Init(theName);
}
void StepGeom_CartesianPoint::Init3D(const Handle(TCollection_HAsciiString)& aName,
const Standard_Real X,
const Standard_Real Y,
const Standard_Real Z)
void StepGeom_CartesianPoint::Init3D(const Handle(TCollection_HAsciiString)& theName,
const Standard_Real theX,
const Standard_Real theY,
const Standard_Real theZ)
{
nbcoord = 3;
coords[0] = X;
coords[1] = Y;
coords[2] = Z;
myNbCoord = 3;
myCoords[0] = theX;
myCoords[1] = theY;
myCoords[2] = theZ;
// --- classe inherited fields ---
StepRepr_RepresentationItem::Init(aName);
StepRepr_RepresentationItem::Init(theName);
}
void StepGeom_CartesianPoint::SetCoordinates(const Handle(TColStd_HArray1OfReal)& aCoordinates)
{
nbcoord = aCoordinates->Length();
coords[0] = aCoordinates->Value(1);
coords[1] = aCoordinates->Value(2);
coords[2] = aCoordinates->Value(3);
// coordinates = aCoordinates;
myNbCoord = aCoordinates->Length();
if (myNbCoord > 0)
myCoords[0] = aCoordinates->Value(1);
if (myNbCoord > 1)
myCoords[1] = aCoordinates->Value(2);
if (myNbCoord > 2)
myCoords[2] = aCoordinates->Value(3);
}
void StepGeom_CartesianPoint::SetCoordinates(const std::array<Standard_Real, 3>& theCoordinates)
{
coords = theCoordinates;
myCoords = theCoordinates;
}
const std::array<Standard_Real, 3>& StepGeom_CartesianPoint::Coordinates() const
{
return coords;
return myCoords;
}
Standard_Real StepGeom_CartesianPoint::CoordinatesValue(const Standard_Integer num) const
{
return coords[num - 1];
// return coordinates->Value(num);
return myCoords[num - 1];
}
void StepGeom_CartesianPoint::SetNbCoordinates(const Standard_Integer num)
{
myNbCoord = num;
}
Standard_Integer StepGeom_CartesianPoint::NbCoordinates() const
{
return nbcoord;
// return coordinates->Length();
return myNbCoord;
}

View File

@@ -38,34 +38,35 @@ public:
//! Returns a CartesianPoint
Standard_EXPORT StepGeom_CartesianPoint();
Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& aName,
const Handle(TColStd_HArray1OfReal)& aCoordinates);
Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& theName,
const Handle(TColStd_HArray1OfReal)& theCoordinates);
Standard_EXPORT void Init2D(const Handle(TCollection_HAsciiString)& aName,
const Standard_Real X,
const Standard_Real Y);
Standard_EXPORT void Init2D(const Handle(TCollection_HAsciiString)& theName,
const Standard_Real theX,
const Standard_Real theY);
Standard_EXPORT void Init3D(const Handle(TCollection_HAsciiString)& aName,
const Standard_Real X,
const Standard_Real Y,
const Standard_Real Z);
Standard_EXPORT void Init3D(const Handle(TCollection_HAsciiString)& theName,
const Standard_Real theX,
const Standard_Real theY,
const Standard_Real theZ);
Standard_EXPORT void SetCoordinates(const Handle(TColStd_HArray1OfReal)& aCoordinates);
Standard_EXPORT void SetCoordinates(const Handle(TColStd_HArray1OfReal)& theCoordinates);
Standard_EXPORT void SetCoordinates(const std::array<Standard_Real, 3>& theCoordinates);
Standard_EXPORT const std::array<Standard_Real, 3>& Coordinates() const;
Standard_EXPORT Standard_Real CoordinatesValue(const Standard_Integer num) const;
Standard_EXPORT Standard_Real CoordinatesValue(const Standard_Integer theInd) const;
Standard_EXPORT void SetNbCoordinates(const Standard_Integer theSize);
Standard_EXPORT Standard_Integer NbCoordinates() const;
DEFINE_STANDARD_RTTIEXT(StepGeom_CartesianPoint, StepGeom_Point)
protected:
private:
Standard_Integer nbcoord;
std::array<Standard_Real, 3> coords;
Standard_Integer myNbCoord;
std::array<Standard_Real, 3> myCoords;
};
#endif // _StepGeom_CartesianPoint_HeaderFile

View File

@@ -18,31 +18,74 @@ IMPLEMENT_STANDARD_RTTIEXT(StepGeom_Direction, StepGeom_GeometricRepresentationI
StepGeom_Direction::StepGeom_Direction() {}
void StepGeom_Direction::Init(const Handle(TCollection_HAsciiString)& aName,
const Handle(TColStd_HArray1OfReal)& aDirectionRatios)
void StepGeom_Direction::Init(const Handle(TCollection_HAsciiString)& theName,
const Handle(TColStd_HArray1OfReal)& theDirectionRatios)
{
// --- classe own fields ---
directionRatios = aDirectionRatios;
SetDirectionRatios(theDirectionRatios);
// --- classe inherited fields ---
StepRepr_RepresentationItem::Init(aName);
StepRepr_RepresentationItem::Init(theName);
}
void StepGeom_Direction::SetDirectionRatios(const Handle(TColStd_HArray1OfReal)& aDirectionRatios)
void StepGeom_Direction::Init3D(const Handle(TCollection_HAsciiString)& theName,
const Standard_Real theDirectionRatios1,
const Standard_Real theDirectionRatios2,
const Standard_Real theDirectionRatios3)
{
directionRatios = aDirectionRatios;
myNbCoord = 3;
myCoords[0] = theDirectionRatios1;
myCoords[1] = theDirectionRatios2;
myCoords[2] = theDirectionRatios3;
// --- classe inherited fields ---
StepRepr_RepresentationItem::Init(theName);
}
Handle(TColStd_HArray1OfReal) StepGeom_Direction::DirectionRatios() const
void StepGeom_Direction::Init2D(const Handle(TCollection_HAsciiString)& theName,
const Standard_Real theDirectionRatios1,
const Standard_Real theDirectionRatios2)
{
return directionRatios;
myNbCoord = 2;
myCoords[0] = theDirectionRatios1;
myCoords[1] = theDirectionRatios2;
myCoords[2] = 0.0;
// --- classe inherited fields ---
StepRepr_RepresentationItem::Init(theName);
}
Standard_Real StepGeom_Direction::DirectionRatiosValue(const Standard_Integer num) const
void StepGeom_Direction::SetDirectionRatios(const Handle(TColStd_HArray1OfReal)& theDirectionRatios)
{
return directionRatios->Value(num);
myNbCoord = theDirectionRatios->Length();
if (myNbCoord > 0)
myCoords[0] = theDirectionRatios->Value(1);
if (myNbCoord > 1)
myCoords[1] = theDirectionRatios->Value(2);
if (myNbCoord > 2)
myCoords[2] = theDirectionRatios->Value(3);
}
void StepGeom_Direction::SetDirectionRatios(const std::array<Standard_Real, 3>& theDirectionRatios)
{
myCoords[0] = theDirectionRatios[0];
myCoords[1] = theDirectionRatios[1];
myCoords[2] = theDirectionRatios[2];
}
const std::array<Standard_Real, 3>& StepGeom_Direction::DirectionRatios() const
{
return myCoords;
}
Standard_Real StepGeom_Direction::DirectionRatiosValue(const Standard_Integer theInd) const
{
return myCoords[theInd - 1];
}
void StepGeom_Direction::SetNbDirectionRatios(const Standard_Integer theSize)
{
myNbCoord = theSize;
}
Standard_Integer StepGeom_Direction::NbDirectionRatios() const
{
return directionRatios->Length();
return myNbCoord;
}

View File

@@ -24,6 +24,9 @@
#include <StepGeom_GeometricRepresentationItem.hxx>
#include <Standard_Real.hxx>
#include <Standard_Integer.hxx>
#include <array>
class TCollection_HAsciiString;
class StepGeom_Direction;
@@ -36,22 +39,35 @@ public:
//! Returns a Direction
Standard_EXPORT StepGeom_Direction();
Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& aName,
const Handle(TColStd_HArray1OfReal)& aDirectionRatios);
Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& theName,
const Handle(TColStd_HArray1OfReal)& theDirectionRatios);
Standard_EXPORT void SetDirectionRatios(const Handle(TColStd_HArray1OfReal)& aDirectionRatios);
Standard_EXPORT void Init3D(const Handle(TCollection_HAsciiString)& theName,
const Standard_Real theDirectionRatios1,
const Standard_Real theDirectionRatios2,
const Standard_Real theDirectionRatios3);
Standard_EXPORT Handle(TColStd_HArray1OfReal) DirectionRatios() const;
Standard_EXPORT void Init2D(const Handle(TCollection_HAsciiString)& theName,
const Standard_Real theDirectionRatios1,
const Standard_Real theDirectionRatios2);
Standard_EXPORT Standard_Real DirectionRatiosValue(const Standard_Integer num) const;
Standard_EXPORT void SetDirectionRatios(const Handle(TColStd_HArray1OfReal)& theDirectionRatios);
Standard_EXPORT void SetDirectionRatios(const std::array<Standard_Real, 3>& theDirectionRatios);
Standard_EXPORT const std::array<Standard_Real, 3>& DirectionRatios() const;
Standard_EXPORT Standard_Real DirectionRatiosValue(const Standard_Integer theInd) const;
Standard_EXPORT void SetNbDirectionRatios(const Standard_Integer theSize);
Standard_EXPORT Standard_Integer NbDirectionRatios() const;
DEFINE_STANDARD_RTTIEXT(StepGeom_Direction, StepGeom_GeometricRepresentationItem)
protected:
private:
Handle(TColStd_HArray1OfReal) directionRatios;
Standard_Integer myNbCoord;
std::array<Standard_Real, 3> myCoords;
};
#endif // _StepGeom_Direction_HeaderFile

View File

@@ -56,11 +56,11 @@ struct StepTidy_CartesianPointHasher
constexpr double aTolerance = 1e-12;
const std::array<Standard_Real, 3>& aCoords1 = theCartesianPoint1->Coordinates();
const std::array<Standard_Real, 3>& aCoords2 = theCartesianPoint2->Coordinates();
if (aCoords1.size() != aCoords2.size())
if (theCartesianPoint1->NbCoordinates() != theCartesianPoint2->NbCoordinates())
{
return false;
}
for (size_t anIndex = 0; anIndex < aCoords1.size(); ++anIndex)
for (int anIndex = 0; anIndex < theCartesianPoint1->NbCoordinates(); ++anIndex)
{
if (std::abs(aCoords1[anIndex] - aCoords2[anIndex]) > aTolerance)
{

View File

@@ -24,21 +24,17 @@ struct StepTidy_DirectionHasher
// Hashes the direction by its name and direction ratios.
std::size_t operator()(const Handle(StepGeom_Direction)& theDirection) const noexcept
{
// Prepare an array of direction ratios.
const Handle(TColStd_HArray1OfReal) aCoords = theDirection->DirectionRatios();
int anArray[3]{};
for (int anIndex = aCoords->Lower(); anIndex < aCoords->Upper(); ++anIndex)
{
anArray[anIndex] = static_cast<int>(aCoords->Value(anIndex));
}
// If direction has no name, hash only direction ratios.
const std::array<Standard_Real, 3>& aCoords = theDirection->DirectionRatios();
// If Cartesian point has no name, hash only directional ratios.
if (theDirection->Name().IsNull())
{
return opencascade::hashBytes(anArray, sizeof(anArray));
return opencascade::hashBytes(aCoords.data(), static_cast<int>(aCoords.size()));
}
// Otherwise, hash both direction ratios and name.
const size_t aHashes[2]{opencascade::hashBytes(anArray, sizeof(anArray)),
std::hash<TCollection_AsciiString>{}(theDirection->Name()->String())};
// Otherwise, hash both coordinates and name.
const size_t aHashes[2]{
opencascade::hashBytes(aCoords.data(), static_cast<int>(aCoords.size())),
std::hash<TCollection_AsciiString>{}(theDirection->Name()->String())};
return opencascade::hashBytes(aHashes, sizeof(aHashes));
}
@@ -58,15 +54,15 @@ struct StepTidy_DirectionHasher
// Compare coordinates.
constexpr double aTolerance = 1e-12;
const Handle(TColStd_HArray1OfReal) aCoords1 = theDirection1->DirectionRatios();
const Handle(TColStd_HArray1OfReal) aCoords2 = theDirection2->DirectionRatios();
if (aCoords1->Length() != aCoords2->Length())
const std::array<Standard_Real, 3>& aCoords1 = theDirection1->DirectionRatios();
const std::array<Standard_Real, 3>& aCoords2 = theDirection2->DirectionRatios();
if (theDirection1->NbDirectionRatios() != theDirection2->NbDirectionRatios())
{
return false;
}
for (Standard_Integer i = aCoords1->Lower(); i <= aCoords1->Upper(); ++i)
for (int anIndex = 0; anIndex < theDirection1->NbDirectionRatios(); ++anIndex)
{
if (std::abs(aCoords1->Value(i) - aCoords2->Value(i)) > aTolerance)
if (std::abs(aCoords1[anIndex] - aCoords2[anIndex]) > aTolerance)
{
return false;
}

View File

@@ -2510,7 +2510,7 @@ Handle(TColStd_HArray1OfReal) StepToGeom::MakeYprRotation(
}
if (SR.RotationAboutDirection().IsNull()
|| SR.RotationAboutDirection()->DirectionOfAxis()->DirectionRatios()->Length() != 3
|| SR.RotationAboutDirection()->DirectionOfAxis()->NbDirectionRatios() != 3
|| theCntxt.IsNull())
{
return NULL;

View File

@@ -227,6 +227,10 @@ set(OCCT_StepVisual_FILES
StepVisual_SurfaceStyleParameterLine.hxx
StepVisual_SurfaceStyleReflectanceAmbient.cxx
StepVisual_SurfaceStyleReflectanceAmbient.hxx
StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular.cxx
StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular.hxx
StepVisual_SurfaceStyleReflectanceAmbientDiffuse.cxx
StepVisual_SurfaceStyleReflectanceAmbientDiffuse.hxx
StepVisual_SurfaceStyleRendering.cxx
StepVisual_SurfaceStyleRendering.hxx
StepVisual_SurfaceStyleRenderingWithProperties.cxx

View File

@@ -0,0 +1,48 @@
// Copyright (c) Open CASCADE 2025
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuse.hxx>
IMPLEMENT_STANDARD_RTTIEXT(StepVisual_SurfaceStyleReflectanceAmbientDiffuse,
StepVisual_SurfaceStyleReflectanceAmbient)
//=================================================================================================
StepVisual_SurfaceStyleReflectanceAmbientDiffuse::StepVisual_SurfaceStyleReflectanceAmbientDiffuse()
{
}
//=================================================================================================
void StepVisual_SurfaceStyleReflectanceAmbientDiffuse::Init(
const Standard_Real theAmbientReflectance,
const Standard_Real theDiffuseReflectance)
{
StepVisual_SurfaceStyleReflectanceAmbient::Init(theAmbientReflectance);
myDiffuseReflectance = theDiffuseReflectance;
}
//=================================================================================================
Standard_Real StepVisual_SurfaceStyleReflectanceAmbientDiffuse::DiffuseReflectance() const
{
return myDiffuseReflectance;
}
//=================================================================================================
void StepVisual_SurfaceStyleReflectanceAmbientDiffuse::SetDiffuseReflectance(
const Standard_Real theDiffuseReflectance)
{
myDiffuseReflectance = theDiffuseReflectance;
}

View File

@@ -0,0 +1,43 @@
// Copyright (c) Open CASCADE 2025
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepVisual_SurfaceStyleReflectanceAmbientDiffuse_HeaderFile_
#define _StepVisual_SurfaceStyleReflectanceAmbientDiffuse_HeaderFile_
#include <StepVisual_SurfaceStyleReflectanceAmbient.hxx>
//! Representation of STEP entity SurfaceStyleReflectanceAmbientDiffuse
class StepVisual_SurfaceStyleReflectanceAmbientDiffuse
: public StepVisual_SurfaceStyleReflectanceAmbient
{
public:
//! default constructor
Standard_EXPORT StepVisual_SurfaceStyleReflectanceAmbientDiffuse();
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init(const Standard_Real theAmbientReflectance,
const Standard_Real theDiffuseReflectance);
//! Returns field DiffuseReflectance
Standard_EXPORT Standard_Real DiffuseReflectance() const;
//! Sets field DiffuseReflectance
Standard_EXPORT void SetDiffuseReflectance(const Standard_Real theDiffuseReflectance);
DEFINE_STANDARD_RTTIEXT(StepVisual_SurfaceStyleReflectanceAmbientDiffuse,
StepVisual_SurfaceStyleReflectanceAmbient)
private:
Standard_Real myDiffuseReflectance;
};
#endif // _StepVisual_SurfaceStyleReflectanceAmbientDiffuse_HeaderFile_

View File

@@ -0,0 +1,86 @@
// Copyright (c) Open CASCADE 2025
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular.hxx>
IMPLEMENT_STANDARD_RTTIEXT(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular,
StepVisual_SurfaceStyleReflectanceAmbientDiffuse)
//=================================================================================================
StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular::
StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular()
{
}
//=================================================================================================
void StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular::Init(
const Standard_Real theAmbientReflectance,
const Standard_Real theDiffuseReflectance,
const Standard_Real theSpecularReflectance,
const Standard_Real theSpecularExponent,
const Handle(StepVisual_Colour)& theSpecularColour)
{
StepVisual_SurfaceStyleReflectanceAmbientDiffuse::Init(theAmbientReflectance,
theDiffuseReflectance);
mySpecularReflectance = theSpecularReflectance;
mySpecularExponent = theSpecularExponent;
mySpecularColour = theSpecularColour;
}
//=================================================================================================
Standard_Real StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular::SpecularReflectance() const
{
return mySpecularReflectance;
}
//=================================================================================================
void StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular::SetSpecularReflectance(
const Standard_Real theSpecularReflectance)
{
mySpecularReflectance = theSpecularReflectance;
}
//=================================================================================================
Standard_Real StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular::SpecularExponent() const
{
return mySpecularExponent;
}
//=================================================================================================
void StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular::SetSpecularExponent(
const Standard_Real theSpecularExponent)
{
mySpecularExponent = theSpecularExponent;
}
//=================================================================================================
Handle(StepVisual_Colour) StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular::SpecularColour()
const
{
return mySpecularColour;
}
//=================================================================================================
void StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular::SetSpecularColour(
const Handle(StepVisual_Colour)& theSpecularColour)
{
mySpecularColour = theSpecularColour;
}

View File

@@ -0,0 +1,61 @@
// Copyright (c) Open CASCADE 2025
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular_HeaderFile_
#define _StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular_HeaderFile_
#include <StepVisual_SurfaceStyleReflectanceAmbientDiffuse.hxx>
#include <StepVisual_Colour.hxx>
//! Representation of STEP entity SurfaceStyleReflectanceAmbientDiffuseSpecular
class StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular
: public StepVisual_SurfaceStyleReflectanceAmbientDiffuse
{
public:
//! default constructor
Standard_EXPORT StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular();
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init(const Standard_Real theAmbientReflectance,
const Standard_Real theDiffuseReflectance,
const Standard_Real theSpecularReflectance,
const Standard_Real theSpecularExponent,
const Handle(StepVisual_Colour)& theSpecularColour);
//! Returns field SpecularReflectance
Standard_EXPORT Standard_Real SpecularReflectance() const;
//! Sets field SpecularReflectance
Standard_EXPORT void SetSpecularReflectance(const Standard_Real theSpecularReflectance);
//! Returns field SpecularExponent
Standard_EXPORT Standard_Real SpecularExponent() const;
//! Sets field SpecularExponent
Standard_EXPORT void SetSpecularExponent(const Standard_Real theSpecularExponent);
//! Returns field SpecularColour
Standard_EXPORT Handle(StepVisual_Colour) SpecularColour() const;
//! Sets field SpecularColour
Standard_EXPORT void SetSpecularColour(const Handle(StepVisual_Colour)& theSpecularColour);
DEFINE_STANDARD_RTTIEXT(StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular,
StepVisual_SurfaceStyleReflectanceAmbientDiffuse)
private:
Standard_Real mySpecularReflectance;
Standard_Real mySpecularExponent;
Handle(StepVisual_Colour) mySpecularColour;
};
#endif // _StepVisual_SurfaceStyleReflectanceAmbientDiffuseSpecular_HeaderFile_

View File

@@ -2,6 +2,18 @@
set(OCCT_TKernel_GTests_FILES_LOCATION "${CMAKE_CURRENT_LIST_DIR}")
set(OCCT_TKernel_GTests_FILES
NCollection_Array1_Test.cxx
NCollection_BaseAllocator_Test.cxx
NCollection_DataMap_Test.cxx
NCollection_DoubleMap_Test.cxx
NCollection_IndexedDataMap_Test.cxx
NCollection_IndexedMap_Test.cxx
NCollection_List_Test.cxx
NCollection_LocalArray_Test.cxx
NCollection_Map_Test.cxx
NCollection_Sequence_Test.cxx
NCollection_SparseArray_Test.cxx
NCollection_Vector_Test.cxx
TCollection_AsciiString_Test.cxx
TCollection_ExtendedString_Test.cxx
)

View File

@@ -0,0 +1,354 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <NCollection_Array1.hxx>
#include <Standard_Integer.hxx>
#include <gtest/gtest.h>
// Test fixture for NCollection_Array1 tests
class NCollection_Array1Test : public testing::Test
{
protected:
void SetUp() override {}
void TearDown() override {}
};
TEST_F(NCollection_Array1Test, DefaultConstructor)
{
// Default constructor should not compile as it's explicitly deleted
// NCollection_Array1<Standard_Integer> anArray;
// Instead we need to use the parameterized constructor
NCollection_Array1<Standard_Integer> anArray(1, 10);
EXPECT_EQ(10, anArray.Length());
EXPECT_EQ(1, anArray.Lower());
EXPECT_EQ(10, anArray.Upper());
}
TEST_F(NCollection_Array1Test, ConstructorWithBounds)
{
// Test constructor with explicit bounds
NCollection_Array1<Standard_Integer> anArray(1, 5);
EXPECT_EQ(5, anArray.Size());
EXPECT_EQ(1, anArray.Lower());
EXPECT_EQ(5, anArray.Upper());
}
TEST_F(NCollection_Array1Test, ConstructorWithNegativeBounds)
{
// Test constructor with negative bounds
NCollection_Array1<Standard_Integer> anArray(-3, 2);
EXPECT_EQ(6, anArray.Size());
EXPECT_EQ(-3, anArray.Lower());
EXPECT_EQ(2, anArray.Upper());
}
TEST_F(NCollection_Array1Test, AssignmentValue)
{
NCollection_Array1<Standard_Integer> anArray(1, 5);
// Initialize array
for (Standard_Integer i = anArray.Lower(); i <= anArray.Upper(); i++)
{
anArray(i) = i * 10;
}
// Verify values
for (Standard_Integer i = anArray.Lower(); i <= anArray.Upper(); i++)
{
EXPECT_EQ(i * 10, anArray(i));
}
// Test Value vs operator()
for (Standard_Integer i = anArray.Lower(); i <= anArray.Upper(); i++)
{
EXPECT_EQ(anArray.Value(i), anArray(i));
}
}
TEST_F(NCollection_Array1Test, CopyConstructor)
{
NCollection_Array1<Standard_Integer> anArray1(1, 5);
// Initialize array
for (Standard_Integer i = anArray1.Lower(); i <= anArray1.Upper(); i++)
{
anArray1(i) = i * 10;
}
// Copy construct
NCollection_Array1<Standard_Integer> anArray2(anArray1);
// Verify copy
EXPECT_EQ(anArray1.Length(), anArray2.Length());
EXPECT_EQ(anArray1.Lower(), anArray2.Lower());
EXPECT_EQ(anArray1.Upper(), anArray2.Upper());
for (Standard_Integer i = anArray1.Lower(); i <= anArray1.Upper(); i++)
{
EXPECT_EQ(anArray1(i), anArray2(i));
}
// Modify original to ensure deep copy
anArray1(3) = 999;
EXPECT_NE(anArray1(3), anArray2(3));
}
TEST_F(NCollection_Array1Test, ValueAccess)
{
NCollection_Array1<Standard_Integer> anArray(1, 5);
// Set values
for (Standard_Integer i = 1; i <= 5; i++)
{
anArray.SetValue(i, i * 10);
}
// Check values
for (Standard_Integer i = 1; i <= 5; i++)
{
EXPECT_EQ(i * 10, anArray.Value(i));
EXPECT_EQ(i * 10, anArray(i)); // Using operator()
}
}
TEST_F(NCollection_Array1Test, ChangeValueAccess)
{
NCollection_Array1<Standard_Integer> anArray(1, 5);
// Set values using ChangeValue
for (Standard_Integer i = 1; i <= 5; i++)
{
anArray.ChangeValue(i) = i * 10;
}
// Check values
for (Standard_Integer i = 1; i <= 5; i++)
{
EXPECT_EQ(i * 10, anArray(i));
}
// Modify values through references
for (Standard_Integer i = 1; i <= 5; i++)
{
anArray.ChangeValue(i) += 5;
}
// Check modified values
for (Standard_Integer i = 1; i <= 5; i++)
{
EXPECT_EQ(i * 10 + 5, anArray(i));
}
}
TEST_F(NCollection_Array1Test, AssignmentOperator)
{
NCollection_Array1<Standard_Integer> anArray1(1, 5);
// Initialize array
for (Standard_Integer i = anArray1.Lower(); i <= anArray1.Upper(); i++)
{
anArray1(i) = i * 10;
}
// Test assignment
NCollection_Array1<Standard_Integer> anArray2(11, 15);
anArray2 = anArray1;
anArray2.Resize(1, 5, Standard_True); // Resize to match anArray1
// Verify assignment result
EXPECT_EQ(anArray1.Length(), anArray2.Length());
EXPECT_EQ(anArray1.Lower(), anArray2.Lower());
EXPECT_EQ(anArray1.Upper(), anArray2.Upper());
for (Standard_Integer i = anArray1.Lower(); i <= anArray1.Upper(); i++)
{
EXPECT_EQ(anArray1(i), anArray2(i));
}
}
TEST_F(NCollection_Array1Test, Move)
{
NCollection_Array1<Standard_Integer> anArray1(1, 5);
// Initialize array
for (Standard_Integer i = anArray1.Lower(); i <= anArray1.Upper(); i++)
{
anArray1(i) = i * 10;
}
// Test Move method
NCollection_Array1<Standard_Integer> anArray2(11, 15);
anArray2.Move(anArray1);
anArray2.Resize(1, 5, Standard_True); // Resize to match anArray1
// Verify move result
EXPECT_EQ(5, anArray2.Length());
EXPECT_EQ(1, anArray2.Lower());
EXPECT_EQ(5, anArray2.Upper());
// Original array is keep referecing the same data
EXPECT_EQ(anArray1.Lower(), anArray2.Lower());
EXPECT_EQ(anArray1.Upper(), anArray2.Upper());
EXPECT_EQ(anArray1(1), anArray2(1));
EXPECT_EQ(anArray1(2), anArray2(2));
EXPECT_EQ(5, anArray1.Length());
}
TEST_F(NCollection_Array1Test, Init)
{
NCollection_Array1<Standard_Integer> anArray(1, 5);
// Test Init method
anArray.Init(42);
// Verify all values initialized
for (Standard_Integer i = anArray.Lower(); i <= anArray.Upper(); i++)
{
EXPECT_EQ(42, anArray(i));
}
}
TEST_F(NCollection_Array1Test, SetValue)
{
NCollection_Array1<Standard_Integer> anArray(1, 5);
// Test SetValue method
anArray.SetValue(3, 123);
// Verify value set
EXPECT_EQ(123, anArray(3));
}
TEST_F(NCollection_Array1Test, FirstLast)
{
NCollection_Array1<Standard_Integer> anArray(5, 10);
anArray(5) = 55;
anArray(10) = 1010;
// Test First and Last methods
EXPECT_EQ(55, anArray.First());
EXPECT_EQ(1010, anArray.Last());
// Change First and Last
anArray.ChangeFirst() = 555;
anArray.ChangeLast() = 10101;
EXPECT_EQ(555, anArray.First());
EXPECT_EQ(10101, anArray.Last());
}
TEST_F(NCollection_Array1Test, STLIteration)
{
NCollection_Array1<Standard_Integer> anArray(1, 5);
for (Standard_Integer i = anArray.Lower(); i <= anArray.Upper(); i++)
{
anArray(i) = i * 10;
}
// Test STL-style iteration
Standard_Integer index = 1;
for (const auto& val : anArray)
{
EXPECT_EQ(index * 10, val);
index++;
}
}
TEST_F(NCollection_Array1Test, Resize)
{
NCollection_Array1<Standard_Integer> anArray(1, 5);
for (Standard_Integer i = anArray.Lower(); i <= anArray.Upper(); i++)
{
anArray(i) = i * 10;
}
// Test Resize method - increasing size
anArray.Resize(1, 10, Standard_True);
// Check new size
EXPECT_EQ(10, anArray.Length());
EXPECT_EQ(1, anArray.Lower());
EXPECT_EQ(10, anArray.Upper());
// Verify original data preserved
for (Standard_Integer i = 1; i <= 5; i++)
{
EXPECT_EQ(i * 10, anArray(i));
}
// Test Resize method - decreasing size
NCollection_Array1<Standard_Integer> anArray2(1, 10);
for (Standard_Integer i = anArray2.Lower(); i <= anArray2.Upper(); i++)
{
anArray2(i) = i * 10;
}
anArray2.Resize(1, 5, Standard_True);
// Check new size
EXPECT_EQ(5, anArray2.Length());
EXPECT_EQ(1, anArray2.Lower());
EXPECT_EQ(5, anArray2.Upper());
// Verify original data preserved
for (Standard_Integer i = 1; i <= 5; i++)
{
EXPECT_EQ(i * 10, anArray2(i));
}
}
TEST_F(NCollection_Array1Test, ChangeValue)
{
NCollection_Array1<Standard_Integer> anArray(1, 5);
anArray.Init(42);
// Test ChangeValue method
anArray.ChangeValue(3) = 123;
// Verify value changed
EXPECT_EQ(123, anArray(3));
// Verify other values unchanged
EXPECT_EQ(42, anArray(1));
EXPECT_EQ(42, anArray(2));
EXPECT_EQ(42, anArray(4));
EXPECT_EQ(42, anArray(5));
}
TEST_F(NCollection_Array1Test, IteratorAccess)
{
NCollection_Array1<Standard_Integer> anArray(1, 5);
for (Standard_Integer i = 1; i <= 5; i++)
{
anArray(i) = i * 10;
}
// Test iteration using STL-compatible iterators
int index = 1;
for (auto it = anArray.begin(); it != anArray.end(); ++it, ++index)
{
EXPECT_EQ(index * 10, *it);
}
// Test range-based for loop
index = 1;
for (const auto& value : anArray)
{
EXPECT_EQ(index * 10, value);
index++;
}
}

View File

@@ -0,0 +1,220 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <NCollection_BaseAllocator.hxx>
#include <NCollection_Vector.hxx>
#include <gtest/gtest.h>
// Simple struct to test allocations
struct TestStruct
{
Standard_Integer myValue1;
Standard_Real myValue2;
Standard_Character myChar;
TestStruct(Standard_Integer theVal1 = 0,
Standard_Real theVal2 = 0.0,
Standard_Character theChar = 'A')
: myValue1(theVal1),
myValue2(theVal2),
myChar(theChar)
{
}
bool operator==(const TestStruct& other) const
{
return myValue1 == other.myValue1 && fabs(myValue2 - other.myValue2) < 1e-10
&& myChar == other.myChar;
}
};
TEST(NCollection_BaseAllocatorTest, DefaultInstance)
{
// Get default allocator
Handle(NCollection_BaseAllocator) aDefaultAlloc =
NCollection_BaseAllocator::CommonBaseAllocator();
// Ensure it's not null
EXPECT_FALSE(aDefaultAlloc.IsNull());
// Test that we get the same instance when requesting default allocator again
Handle(NCollection_BaseAllocator) anotherDefaultAlloc =
NCollection_BaseAllocator::CommonBaseAllocator();
EXPECT_EQ(aDefaultAlloc, anotherDefaultAlloc);
}
TEST(NCollection_BaseAllocatorTest, Allocate)
{
Handle(NCollection_BaseAllocator) anAlloc = NCollection_BaseAllocator::CommonBaseAllocator();
// Test allocation of different sizes
void* ptr1 = anAlloc->Allocate(10);
EXPECT_NE(ptr1, nullptr);
void* ptr2 = anAlloc->Allocate(100);
EXPECT_NE(ptr2, nullptr);
void* ptr3 = anAlloc->Allocate(1000);
EXPECT_NE(ptr3, nullptr);
// Allocations should return different pointers
EXPECT_NE(ptr1, ptr2);
EXPECT_NE(ptr1, ptr3);
EXPECT_NE(ptr2, ptr3);
// Free the allocated memory
anAlloc->Free(ptr1);
anAlloc->Free(ptr2);
anAlloc->Free(ptr3);
}
TEST(NCollection_BaseAllocatorTest, AllocateStruct)
{
Handle(NCollection_BaseAllocator) anAlloc = NCollection_BaseAllocator::CommonBaseAllocator();
// Allocate and construct test struct
TestStruct* pStruct = static_cast<TestStruct*>(anAlloc->Allocate(sizeof(TestStruct)));
EXPECT_NE(pStruct, nullptr);
// Use placement new to construct object at allocated memory
new (pStruct) TestStruct(42, 3.14159, 'Z');
// Verify object values
EXPECT_EQ(pStruct->myValue1, 42);
EXPECT_DOUBLE_EQ(pStruct->myValue2, 3.14159);
EXPECT_EQ(pStruct->myChar, 'Z');
// Destruct the object and free memory
pStruct->~TestStruct();
anAlloc->Free(pStruct);
}
TEST(NCollection_BaseAllocatorTest, AllocateArray)
{
Handle(NCollection_BaseAllocator) anAlloc = NCollection_BaseAllocator::CommonBaseAllocator();
const Standard_Integer arraySize = 5;
// Allocate memory for an array of test structs
TestStruct* pArray = static_cast<TestStruct*>(anAlloc->Allocate(arraySize * sizeof(TestStruct)));
EXPECT_NE(pArray, nullptr);
// Construct objects at allocated memory
for (Standard_Integer i = 0; i < arraySize; ++i)
{
new (&pArray[i]) TestStruct(i, i * 1.5, static_cast<Standard_Character>('A' + i));
}
// Verify object values
for (Standard_Integer i = 0; i < arraySize; ++i)
{
EXPECT_EQ(pArray[i].myValue1, i);
EXPECT_DOUBLE_EQ(pArray[i].myValue2, i * 1.5);
EXPECT_EQ(pArray[i].myChar, static_cast<Standard_Character>('A' + i));
}
// Destruct objects and free memory
for (Standard_Integer i = 0; i < arraySize; ++i)
{
pArray[i].~TestStruct();
}
anAlloc->Free(pArray);
}
TEST(NCollection_BaseAllocatorTest, UsageWithVector)
{
// Create a collection using the default allocator
NCollection_Vector<TestStruct> aVector;
// Add elements
aVector.Append(TestStruct(10, 1.0, 'X'));
aVector.Append(TestStruct(20, 2.0, 'Y'));
aVector.Append(TestStruct(30, 3.0, 'Z'));
// Verify elements were stored correctly
EXPECT_EQ(aVector.Length(), 3);
EXPECT_EQ(aVector(0).myValue1, 10);
EXPECT_DOUBLE_EQ(aVector(0).myValue2, 1.0);
EXPECT_EQ(aVector(0).myChar, 'X');
EXPECT_EQ(aVector(1).myValue1, 20);
EXPECT_DOUBLE_EQ(aVector(1).myValue2, 2.0);
EXPECT_EQ(aVector(1).myChar, 'Y');
EXPECT_EQ(aVector(2).myValue1, 30);
EXPECT_DOUBLE_EQ(aVector(2).myValue2, 3.0);
EXPECT_EQ(aVector(2).myChar, 'Z');
// Create a custom allocator
Handle(NCollection_BaseAllocator) aCustomAlloc = NCollection_BaseAllocator::CommonBaseAllocator();
// Create a collection using custom allocator
NCollection_Vector<TestStruct> aVectorWithCustomAlloc(5, aCustomAlloc);
// Add elements
aVectorWithCustomAlloc.Append(TestStruct(40, 4.0, 'P'));
aVectorWithCustomAlloc.Append(TestStruct(50, 5.0, 'Q'));
// Verify elements were stored correctly
EXPECT_EQ(aVectorWithCustomAlloc.Length(), 2);
EXPECT_EQ(aVectorWithCustomAlloc(0).myValue1, 40);
EXPECT_DOUBLE_EQ(aVectorWithCustomAlloc(0).myValue2, 4.0);
EXPECT_EQ(aVectorWithCustomAlloc(0).myChar, 'P');
EXPECT_EQ(aVectorWithCustomAlloc(1).myValue1, 50);
EXPECT_DOUBLE_EQ(aVectorWithCustomAlloc(1).myValue2, 5.0);
EXPECT_EQ(aVectorWithCustomAlloc(1).myChar, 'Q');
}
TEST(NCollection_BaseAllocatorTest, CopyAndMove)
{
Handle(NCollection_BaseAllocator) anAlloc1 = NCollection_BaseAllocator::CommonBaseAllocator();
// Create a collection with allocator
NCollection_Vector<TestStruct> aVector1(5, anAlloc1);
aVector1.Append(TestStruct(10, 1.0, 'A'));
aVector1.Append(TestStruct(20, 2.0, 'B'));
// Copy constructor should preserve the allocator
NCollection_Vector<TestStruct> aVector2(aVector1);
EXPECT_EQ(aVector2.Length(), 2);
EXPECT_EQ(aVector2(0), TestStruct(10, 1.0, 'A'));
EXPECT_EQ(aVector2(1), TestStruct(20, 2.0, 'B'));
// Create a new collection with new allocator
Handle(NCollection_BaseAllocator) anAlloc2 = NCollection_BaseAllocator::CommonBaseAllocator();
NCollection_Vector<TestStruct> aVector3(5, anAlloc2);
// Assignment operator should preserve the destination's allocator
aVector3 = aVector1;
EXPECT_EQ(aVector3.Length(), 2);
EXPECT_EQ(aVector3(0), TestStruct(10, 1.0, 'A'));
EXPECT_EQ(aVector3(1), TestStruct(20, 2.0, 'B'));
}
TEST(NCollection_BaseAllocatorTest, BigAllocation)
{
Handle(NCollection_BaseAllocator) anAlloc = NCollection_BaseAllocator::CommonBaseAllocator();
// Test a large allocation
const size_t largeSize = 1024 * 1024; // 1MB
void* pLarge = anAlloc->Allocate(largeSize);
EXPECT_NE(pLarge, nullptr);
// Write to the allocated memory to verify it's usable
memset(pLarge, 0xAB, largeSize);
// Free the allocated memory
anAlloc->Free(pLarge);
}

View File

@@ -0,0 +1,234 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <NCollection_DataMap.hxx>
#include <Standard_Integer.hxx>
#include <TCollection_AsciiString.hxx>
#include <gtest/gtest.h>
// Test fixture for NCollection_DataMap tests
class NCollection_DataMapTest : public testing::Test
{
protected:
void SetUp() override {}
void TearDown() override {}
};
// Tests with Integer keys and String values
TEST_F(NCollection_DataMapTest, IntegerKeys)
{
// Default constructor should create an empty map
NCollection_DataMap<Standard_Integer, TCollection_AsciiString> aMap;
EXPECT_TRUE(aMap.IsEmpty());
EXPECT_EQ(0, aMap.Size());
EXPECT_EQ(0, aMap.Extent());
}
TEST_F(NCollection_DataMapTest, BindingAndAccess)
{
NCollection_DataMap<Standard_Integer, TCollection_AsciiString> aMap;
// Test Bind method
aMap.Bind(1, "One");
aMap.Bind(2, "Two");
aMap.Bind(3, "Three");
EXPECT_FALSE(aMap.IsEmpty());
EXPECT_EQ(3, aMap.Size());
// Test Find method
EXPECT_STREQ("One", aMap.Find(1).ToCString());
EXPECT_STREQ("Two", aMap.Find(2).ToCString());
EXPECT_STREQ("Three", aMap.Find(3).ToCString());
// Test IsBound
EXPECT_TRUE(aMap.IsBound(1));
EXPECT_TRUE(aMap.IsBound(2));
EXPECT_TRUE(aMap.IsBound(3));
EXPECT_FALSE(aMap.IsBound(4));
}
TEST_F(NCollection_DataMapTest, ChangeFind)
{
NCollection_DataMap<Standard_Integer, TCollection_AsciiString> aMap;
aMap.Bind(1, "One");
// Test ChangeFind for modification
EXPECT_STREQ("One", aMap.Find(1).ToCString());
aMap.ChangeFind(1) = "Modified One";
EXPECT_STREQ("Modified One", aMap.Find(1).ToCString());
}
TEST_F(NCollection_DataMapTest, Rebind)
{
NCollection_DataMap<Standard_Integer, TCollection_AsciiString> aMap;
// First binding
aMap.Bind(1, "One");
EXPECT_STREQ("One", aMap.Find(1).ToCString());
// Re-bind the same key with a different value
aMap.Bind(1, "New One");
EXPECT_STREQ("New One", aMap.Find(1).ToCString());
// Size should still be 1
EXPECT_EQ(1, aMap.Size());
}
TEST_F(NCollection_DataMapTest, UnBind)
{
NCollection_DataMap<Standard_Integer, TCollection_AsciiString> aMap;
aMap.Bind(1, "One");
aMap.Bind(2, "Two");
aMap.Bind(3, "Three");
// Test UnBind
EXPECT_TRUE(aMap.UnBind(2));
EXPECT_EQ(2, aMap.Size());
// Check key 2 is no longer bound
EXPECT_FALSE(aMap.IsBound(2));
// Try to unbind a non-existent key
EXPECT_FALSE(aMap.UnBind(4));
EXPECT_EQ(2, aMap.Size());
}
TEST_F(NCollection_DataMapTest, Clear)
{
NCollection_DataMap<Standard_Integer, TCollection_AsciiString> aMap;
aMap.Bind(1, "One");
aMap.Bind(2, "Two");
// Test Clear
aMap.Clear();
EXPECT_TRUE(aMap.IsEmpty());
EXPECT_EQ(0, aMap.Size());
EXPECT_FALSE(aMap.IsBound(1));
EXPECT_FALSE(aMap.IsBound(2));
}
TEST_F(NCollection_DataMapTest, Assignment)
{
NCollection_DataMap<Standard_Integer, TCollection_AsciiString> aMap1;
aMap1.Bind(1, "One");
aMap1.Bind(2, "Two");
// Test assignment operator
NCollection_DataMap<Standard_Integer, TCollection_AsciiString> aMap2;
aMap2 = aMap1;
// Check both maps have the same content
EXPECT_EQ(aMap1.Size(), aMap2.Size());
EXPECT_STREQ(aMap1.Find(1).ToCString(), aMap2.Find(1).ToCString());
EXPECT_STREQ(aMap1.Find(2).ToCString(), aMap2.Find(2).ToCString());
// Modify original to ensure deep copy
aMap1.ChangeFind(1) = "Modified One";
EXPECT_STREQ("Modified One", aMap1.Find(1).ToCString());
EXPECT_STREQ("One", aMap2.Find(1).ToCString());
}
TEST_F(NCollection_DataMapTest, Find_NonExisting)
{
NCollection_DataMap<Standard_Integer, TCollection_AsciiString> aMap;
aMap.Bind(1, "One");
// Finding non-existent key should throw exception
EXPECT_THROW(aMap.Find(2), Standard_NoSuchObject);
// ChangeFind for non-existent key should throw exception
EXPECT_THROW(aMap.ChangeFind(2), Standard_NoSuchObject);
}
TEST_F(NCollection_DataMapTest, IteratorAccess)
{
NCollection_DataMap<Standard_Integer, TCollection_AsciiString> aMap;
aMap.Bind(1, "One");
aMap.Bind(2, "Two");
aMap.Bind(3, "Three");
// Test iteration using OCCT iterator
NCollection_DataMap<Standard_Integer, TCollection_AsciiString>::Iterator it(aMap);
// Create sets to check all keys and values are visited
std::set<Standard_Integer> foundKeys;
std::set<std::string> foundValues;
for (; it.More(); it.Next())
{
foundKeys.insert(it.Key());
foundValues.insert(it.Value().ToCString());
}
// Check all keys were visited
EXPECT_EQ(3, foundKeys.size());
EXPECT_TRUE(foundKeys.find(1) != foundKeys.end());
EXPECT_TRUE(foundKeys.find(2) != foundKeys.end());
EXPECT_TRUE(foundKeys.find(3) != foundKeys.end());
// Check all values were visited
EXPECT_EQ(3, foundValues.size());
EXPECT_TRUE(foundValues.find("One") != foundValues.end());
EXPECT_TRUE(foundValues.find("Two") != foundValues.end());
EXPECT_TRUE(foundValues.find("Three") != foundValues.end());
}
TEST_F(NCollection_DataMapTest, ChangeValue)
{
NCollection_DataMap<Standard_Integer, TCollection_AsciiString> aMap;
aMap.Bind(1, "One");
// Test Value change through iterator
NCollection_DataMap<Standard_Integer, TCollection_AsciiString>::Iterator it(aMap);
EXPECT_STREQ("One", it.Value().ToCString());
it.ChangeValue() = "Modified via Iterator";
EXPECT_STREQ("Modified via Iterator", it.Value().ToCString());
// Check the change is reflected in the map itself
EXPECT_STREQ("Modified via Iterator", aMap.Find(1).ToCString());
}
TEST_F(NCollection_DataMapTest, ExhaustiveIterator)
{
const int NUM_ELEMENTS = 1000;
// Create a map with many elements to test iterator efficiency
NCollection_DataMap<Standard_Integer, Standard_Integer> aMap;
// Bind many elements
for (int i = 0; i < NUM_ELEMENTS; ++i)
{
aMap.Bind(i, i * 2);
}
EXPECT_EQ(NUM_ELEMENTS, aMap.Size());
// Count elements using iterator
int count = 0;
NCollection_DataMap<Standard_Integer, Standard_Integer>::Iterator it(aMap);
for (; it.More(); it.Next())
{
EXPECT_EQ(it.Key() * 2, it.Value());
count++;
}
EXPECT_EQ(NUM_ELEMENTS, count);
}

View File

@@ -0,0 +1,460 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <NCollection_DoubleMap.hxx>
#include <TCollection_AsciiString.hxx>
#include <gtest/gtest.h>
// Basic test types for the DoubleMap
typedef Standard_Integer Key1Type;
typedef Standard_Real Key2Type;
// Custom key types for testing
class TestKey1
{
public:
TestKey1(int id = 0, const char* name = "")
: myId(id),
myName(name)
{
}
bool operator==(const TestKey1& other) const
{
return myId == other.myId && myName == other.myName;
}
int GetId() const { return myId; }
const std::string& GetName() const { return myName; }
private:
int myId;
std::string myName;
};
class TestKey2
{
public:
TestKey2(double value = 0.0, const char* code = "")
: myValue(value),
myCode(code)
{
}
bool operator==(const TestKey2& other) const
{
return fabs(myValue - other.myValue) < 1e-10 && myCode == other.myCode;
}
double GetValue() const { return myValue; }
const std::string& GetCode() const { return myCode; }
private:
double myValue;
std::string myCode;
};
namespace std
{
template <>
struct hash<TestKey1>
{
size_t operator()(const TestKey1& key) const
{
return static_cast<size_t>(key.GetId() + std::hash<std::string>()(key.GetName()));
}
};
template <>
struct hash<TestKey2>
{
size_t operator()(const TestKey2& key) const
{
return static_cast<size_t>(key.GetValue() * 100 + std::hash<std::string>()(key.GetCode()));
}
};
} // namespace std
TEST(NCollection_DoubleMapTest, DefaultConstructor)
{
// Test default constructor
NCollection_DoubleMap<Key1Type, Key2Type> aMap;
EXPECT_TRUE(aMap.IsEmpty());
EXPECT_EQ(aMap.Extent(), 0);
EXPECT_EQ(aMap.Size(), 0);
}
TEST(NCollection_DoubleMapTest, CustomBuckets)
{
// Test constructor with custom number of buckets
NCollection_DoubleMap<Key1Type, Key2Type> aMap(100);
EXPECT_TRUE(aMap.IsEmpty());
EXPECT_EQ(aMap.Extent(), 0);
EXPECT_EQ(aMap.Size(), 0);
}
TEST(NCollection_DoubleMapTest, BasicBindFind)
{
NCollection_DoubleMap<Key1Type, Key2Type> aMap;
// Test binding elements
aMap.Bind(10, 1.0);
aMap.Bind(20, 2.0);
aMap.Bind(30, 3.0);
EXPECT_EQ(aMap.Extent(), 3);
// Test finding by Key1
EXPECT_TRUE(aMap.IsBound1(10));
EXPECT_TRUE(aMap.IsBound1(20));
EXPECT_TRUE(aMap.IsBound1(30));
EXPECT_FALSE(aMap.IsBound1(40));
// Test finding by Key2
EXPECT_TRUE(aMap.IsBound2(1.0));
EXPECT_TRUE(aMap.IsBound2(2.0));
EXPECT_TRUE(aMap.IsBound2(3.0));
EXPECT_FALSE(aMap.IsBound2(4.0));
// Test finding Key2 by Key1
EXPECT_DOUBLE_EQ(aMap.Find1(10), 1.0);
EXPECT_DOUBLE_EQ(aMap.Find1(20), 2.0);
EXPECT_DOUBLE_EQ(aMap.Find1(30), 3.0);
// Test finding Key1 by Key2
EXPECT_EQ(aMap.Find2(1.0), 10);
EXPECT_EQ(aMap.Find2(2.0), 20);
EXPECT_EQ(aMap.Find2(3.0), 30);
}
TEST(NCollection_DoubleMapTest, BindWithDuplicateKeys)
{
NCollection_DoubleMap<Key1Type, Key2Type> aMap;
// First binding
aMap.Bind(10, 1.0);
EXPECT_EQ(aMap.Extent(), 1);
EXPECT_DOUBLE_EQ(aMap.Find1(10), 1.0);
// Try to bind a duplicate Key1 with a new Key2
// This should fail silently in a production system, but we'll check that the map wasn't modified
EXPECT_ANY_THROW(aMap.Bind(10, 2.0));
EXPECT_EQ(aMap.Extent(), 1); // Size should remain 1
EXPECT_DOUBLE_EQ(aMap.Find1(10), 1.0); // Value should remain unchanged
EXPECT_FALSE(aMap.IsBound2(2.0)); // The new Key2 should not be bound
// Try to bind a new Key1 with duplicate Key2
EXPECT_ANY_THROW(aMap.Bind(20, 1.0));
EXPECT_EQ(aMap.Extent(), 1); // Size should remain 1
EXPECT_FALSE(aMap.IsBound1(20)); // The new Key1 should not be bound
}
TEST(NCollection_DoubleMapTest, UnbindTest)
{
NCollection_DoubleMap<Key1Type, Key2Type> aMap;
// Add elements
aMap.Bind(10, 1.0);
aMap.Bind(20, 2.0);
aMap.Bind(30, 3.0);
EXPECT_EQ(aMap.Extent(), 3);
// Test UnBind1
aMap.UnBind1(20);
EXPECT_EQ(aMap.Extent(), 2);
EXPECT_FALSE(aMap.IsBound1(20));
EXPECT_FALSE(aMap.IsBound2(2.0));
// Test UnBind2
aMap.UnBind2(3.0);
EXPECT_EQ(aMap.Extent(), 1);
EXPECT_FALSE(aMap.IsBound1(30));
EXPECT_FALSE(aMap.IsBound2(3.0));
// Try to unbind non-existent keys
aMap.UnBind1(40); // Should have no effect
EXPECT_EQ(aMap.Extent(), 1);
aMap.UnBind2(4.0); // Should have no effect
EXPECT_EQ(aMap.Extent(), 1);
}
TEST(NCollection_DoubleMapTest, Clear)
{
NCollection_DoubleMap<Key1Type, Key2Type> aMap;
// Add elements
aMap.Bind(10, 1.0);
aMap.Bind(20, 2.0);
aMap.Bind(30, 3.0);
EXPECT_EQ(aMap.Extent(), 3);
// Clear the map
aMap.Clear();
EXPECT_TRUE(aMap.IsEmpty());
EXPECT_EQ(aMap.Extent(), 0);
// Ensure we can add elements again
aMap.Bind(40, 4.0);
EXPECT_EQ(aMap.Extent(), 1);
}
TEST(NCollection_DoubleMapTest, SeekTests)
{
NCollection_DoubleMap<Key1Type, Key2Type> aMap;
// Add elements
aMap.Bind(10, 1.0);
aMap.Bind(20, 2.0);
// Test Seek1
const Key2Type* key2Ptr = aMap.Seek1(10);
EXPECT_TRUE(key2Ptr != nullptr);
EXPECT_DOUBLE_EQ(*key2Ptr, 1.0);
// Test Seek2
const Key1Type* key1Ptr = aMap.Seek2(2.0);
EXPECT_TRUE(key1Ptr != nullptr);
EXPECT_EQ(*key1Ptr, 20);
// Test seeking non-existent keys
EXPECT_TRUE(aMap.Seek1(30) == nullptr);
EXPECT_TRUE(aMap.Seek2(3.0) == nullptr);
}
TEST(NCollection_DoubleMapTest, CopyConstructor)
{
NCollection_DoubleMap<Key1Type, Key2Type> aMap1;
// Add elements to first map
aMap1.Bind(10, 1.0);
aMap1.Bind(20, 2.0);
aMap1.Bind(30, 3.0);
// Create a copy
NCollection_DoubleMap<Key1Type, Key2Type> aMap2(aMap1);
// Check that copy has the same elements
EXPECT_EQ(aMap2.Extent(), 3);
EXPECT_TRUE(aMap2.IsBound1(10));
EXPECT_TRUE(aMap2.IsBound1(20));
EXPECT_TRUE(aMap2.IsBound1(30));
EXPECT_TRUE(aMap2.IsBound2(1.0));
EXPECT_TRUE(aMap2.IsBound2(2.0));
EXPECT_TRUE(aMap2.IsBound2(3.0));
// Modify original to ensure deep copy
aMap1.Bind(40, 4.0);
EXPECT_EQ(aMap1.Extent(), 4);
EXPECT_EQ(aMap2.Extent(), 3);
EXPECT_FALSE(aMap2.IsBound1(40));
EXPECT_FALSE(aMap2.IsBound2(4.0));
}
TEST(NCollection_DoubleMapTest, AssignmentOperator)
{
NCollection_DoubleMap<Key1Type, Key2Type> aMap1;
NCollection_DoubleMap<Key1Type, Key2Type> aMap2;
// Add elements to first map
aMap1.Bind(10, 1.0);
aMap1.Bind(20, 2.0);
// Add different elements to second map
aMap2.Bind(30, 3.0);
aMap2.Bind(40, 4.0);
aMap2.Bind(50, 5.0);
// Assign first to second
aMap2 = aMap1;
// Check that second map now matches first
EXPECT_EQ(aMap2.Extent(), 2);
EXPECT_TRUE(aMap2.IsBound1(10));
EXPECT_TRUE(aMap2.IsBound1(20));
EXPECT_FALSE(aMap2.IsBound1(30));
EXPECT_FALSE(aMap2.IsBound1(40));
EXPECT_FALSE(aMap2.IsBound1(50));
EXPECT_TRUE(aMap2.IsBound2(1.0));
EXPECT_TRUE(aMap2.IsBound2(2.0));
EXPECT_FALSE(aMap2.IsBound2(3.0));
EXPECT_FALSE(aMap2.IsBound2(4.0));
EXPECT_FALSE(aMap2.IsBound2(5.0));
}
TEST(NCollection_DoubleMapTest, ReSize)
{
NCollection_DoubleMap<Key1Type, Key2Type> aMap(3); // Start with small bucket count
// Add many elements to trigger resize
for (Standard_Integer i = 1; i <= 100; ++i)
{
aMap.Bind(i, static_cast<Standard_Real>(i) / 10.0);
}
// Verify all elements are present
EXPECT_EQ(aMap.Extent(), 100);
for (Standard_Integer i = 1; i <= 100; ++i)
{
EXPECT_TRUE(aMap.IsBound1(i));
EXPECT_TRUE(aMap.IsBound2(static_cast<Standard_Real>(i) / 10.0));
EXPECT_DOUBLE_EQ(aMap.Find1(i), static_cast<Standard_Real>(i) / 10.0);
EXPECT_EQ(aMap.Find2(static_cast<Standard_Real>(i) / 10.0), i);
}
}
TEST(NCollection_DoubleMapTest, Exchange)
{
NCollection_DoubleMap<Key1Type, Key2Type> aMap1;
NCollection_DoubleMap<Key1Type, Key2Type> aMap2;
// Add elements to first map
aMap1.Bind(10, 1.0);
aMap1.Bind(20, 2.0);
// Add different elements to second map
aMap2.Bind(30, 3.0);
aMap2.Bind(40, 4.0);
aMap2.Bind(50, 5.0);
// Exchange maps
aMap1.Exchange(aMap2);
// Check that maps are exchanged
EXPECT_EQ(aMap1.Extent(), 3);
EXPECT_TRUE(aMap1.IsBound1(30));
EXPECT_TRUE(aMap1.IsBound1(40));
EXPECT_TRUE(aMap1.IsBound1(50));
EXPECT_TRUE(aMap1.IsBound2(3.0));
EXPECT_TRUE(aMap1.IsBound2(4.0));
EXPECT_TRUE(aMap1.IsBound2(5.0));
EXPECT_EQ(aMap2.Extent(), 2);
EXPECT_TRUE(aMap2.IsBound1(10));
EXPECT_TRUE(aMap2.IsBound1(20));
EXPECT_TRUE(aMap2.IsBound2(1.0));
EXPECT_TRUE(aMap2.IsBound2(2.0));
}
TEST(NCollection_DoubleMapTest, Iterator)
{
NCollection_DoubleMap<Key1Type, Key2Type> aMap;
// Add elements
aMap.Bind(10, 1.0);
aMap.Bind(20, 2.0);
aMap.Bind(30, 3.0);
// Use iterator to check all elements
Standard_Boolean found10 = Standard_False;
Standard_Boolean found20 = Standard_False;
Standard_Boolean found30 = Standard_False;
Standard_Size count = 0;
for (NCollection_DoubleMap<Key1Type, Key2Type>::Iterator it(aMap); it.More(); it.Next(), ++count)
{
const Key1Type& key1 = it.Key1();
const Key2Type& key2 = it.Key2();
if (key1 == 10 && key2 == 1.0)
found10 = Standard_True;
else if (key1 == 20 && key2 == 2.0)
found20 = Standard_True;
else if (key1 == 30 && key2 == 3.0)
found30 = Standard_True;
}
EXPECT_EQ(count, 3);
EXPECT_TRUE(found10);
EXPECT_TRUE(found20);
EXPECT_TRUE(found30);
}
TEST(NCollection_DoubleMapTest, StringKeys)
{
// Test with string keys
NCollection_DoubleMap<TCollection_AsciiString, TCollection_AsciiString> aStringMap;
// Add string pairs
aStringMap.Bind(TCollection_AsciiString("Key1"), TCollection_AsciiString("Value1"));
aStringMap.Bind(TCollection_AsciiString("Key2"), TCollection_AsciiString("Value2"));
aStringMap.Bind(TCollection_AsciiString("Key3"), TCollection_AsciiString("Value3"));
EXPECT_EQ(aStringMap.Extent(), 3);
// Check key-value bindings
EXPECT_TRUE(aStringMap.IsBound1(TCollection_AsciiString("Key1")));
EXPECT_TRUE(aStringMap.IsBound1(TCollection_AsciiString("Key2")));
EXPECT_TRUE(aStringMap.IsBound1(TCollection_AsciiString("Key3")));
EXPECT_TRUE(aStringMap.IsBound2(TCollection_AsciiString("Value1")));
EXPECT_TRUE(aStringMap.IsBound2(TCollection_AsciiString("Value2")));
EXPECT_TRUE(aStringMap.IsBound2(TCollection_AsciiString("Value3")));
// Test finding values by keys
EXPECT_TRUE(aStringMap.Find1(TCollection_AsciiString("Key1")).IsEqual("Value1"));
EXPECT_TRUE(aStringMap.Find1(TCollection_AsciiString("Key2")).IsEqual("Value2"));
EXPECT_TRUE(aStringMap.Find1(TCollection_AsciiString("Key3")).IsEqual("Value3"));
// Test finding keys by values
EXPECT_TRUE(aStringMap.Find2(TCollection_AsciiString("Value1")).IsEqual("Key1"));
EXPECT_TRUE(aStringMap.Find2(TCollection_AsciiString("Value2")).IsEqual("Key2"));
EXPECT_TRUE(aStringMap.Find2(TCollection_AsciiString("Value3")).IsEqual("Key3"));
}
TEST(NCollection_DoubleMapTest, ComplexKeys)
{
// Create map with custom key types and hashers
NCollection_DoubleMap<TestKey1, TestKey2> aComplexMap;
// Add complex key pairs
TestKey1 key1_1(1, "One");
TestKey1 key1_2(2, "Two");
TestKey1 key1_3(3, "Three");
TestKey2 key2_1(1.1, "A");
TestKey2 key2_2(2.2, "B");
TestKey2 key2_3(3.3, "C");
aComplexMap.Bind(key1_1, key2_1);
aComplexMap.Bind(key1_2, key2_2);
aComplexMap.Bind(key1_3, key2_3);
EXPECT_EQ(aComplexMap.Extent(), 3);
// Test IsBound for both key types
EXPECT_TRUE(aComplexMap.IsBound1(TestKey1(1, "One")));
EXPECT_TRUE(aComplexMap.IsBound1(TestKey1(2, "Two")));
EXPECT_TRUE(aComplexMap.IsBound1(TestKey1(3, "Three")));
EXPECT_TRUE(aComplexMap.IsBound2(TestKey2(1.1, "A")));
EXPECT_TRUE(aComplexMap.IsBound2(TestKey2(2.2, "B")));
EXPECT_TRUE(aComplexMap.IsBound2(TestKey2(3.3, "C")));
// Test finding second key by first key
const TestKey2& foundKey2 = aComplexMap.Find1(key1_2);
EXPECT_DOUBLE_EQ(foundKey2.GetValue(), 2.2);
EXPECT_EQ(foundKey2.GetCode(), "B");
// Test finding first key by second key
const TestKey1& foundKey1 = aComplexMap.Find2(key2_3);
EXPECT_EQ(foundKey1.GetId(), 3);
EXPECT_EQ(foundKey1.GetName(), "Three");
}

View File

@@ -0,0 +1,705 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <NCollection_IndexedDataMap.hxx>
#include <TCollection_AsciiString.hxx>
#include <gtest/gtest.h>
// Basic test types for the IndexedDataMap
typedef Standard_Integer KeyType;
typedef Standard_Real ItemType;
// Custom class for testing complex keys
class TestKey
{
public:
TestKey(int id = 0, const char* name = "")
: myId(id),
myName(name)
{
}
bool operator==(const TestKey& other) const
{
return myId == other.myId && myName == other.myName;
}
int GetId() const { return myId; }
const std::string& GetName() const { return myName; }
private:
int myId;
std::string myName;
};
namespace std
{
template <>
struct hash<TestKey>
{
size_t operator()(const TestKey& key) const
{
// Combine the hash
size_t aCombintation[2] = {std::hash<int>()(key.GetId()),
std::hash<std::string>()(key.GetName())};
return opencascade::hashBytes(aCombintation, sizeof(aCombintation));
}
};
} // namespace std
// Custom class for testing complex items
class TestItem
{
public:
TestItem(double value = 0.0, const char* description = "")
: myValue(value),
myDescription(description)
{
}
bool operator==(const TestItem& other) const
{
return fabs(myValue - other.myValue) < 1e-10 && myDescription == other.myDescription;
}
double GetValue() const { return myValue; }
const std::string& GetDescription() const { return myDescription; }
void SetValue(double value) { myValue = value; }
private:
double myValue;
std::string myDescription;
};
TEST(NCollection_IndexedDataMapTest, DefaultConstructor)
{
// Test default constructor
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
EXPECT_TRUE(aMap.IsEmpty());
EXPECT_EQ(aMap.Extent(), 0);
EXPECT_EQ(aMap.Size(), 0);
}
TEST(NCollection_IndexedDataMapTest, BasicAddFind)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
// Test adding elements
Standard_Integer index1 = aMap.Add(10, 1.0);
Standard_Integer index2 = aMap.Add(20, 2.0);
Standard_Integer index3 = aMap.Add(30, 3.0);
EXPECT_EQ(index1, 1);
EXPECT_EQ(index2, 2);
EXPECT_EQ(index3, 3);
EXPECT_EQ(aMap.Extent(), 3);
// Test finding elements by key
EXPECT_EQ(aMap.FindIndex(10), 1);
EXPECT_EQ(aMap.FindIndex(20), 2);
EXPECT_EQ(aMap.FindIndex(30), 3);
// Test finding keys by index
EXPECT_EQ(aMap.FindKey(1), 10);
EXPECT_EQ(aMap.FindKey(2), 20);
EXPECT_EQ(aMap.FindKey(3), 30);
// Test finding items by index
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(1), 1.0);
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(2), 2.0);
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(3), 3.0);
// Test operator()
EXPECT_DOUBLE_EQ(aMap(1), 1.0);
EXPECT_DOUBLE_EQ(aMap(2), 2.0);
EXPECT_DOUBLE_EQ(aMap(3), 3.0);
// Test finding items by key
EXPECT_DOUBLE_EQ(aMap.FindFromKey(10), 1.0);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(20), 2.0);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(30), 3.0);
// Test Contains
EXPECT_TRUE(aMap.Contains(10));
EXPECT_TRUE(aMap.Contains(20));
EXPECT_TRUE(aMap.Contains(30));
EXPECT_FALSE(aMap.Contains(40));
}
TEST(NCollection_IndexedDataMapTest, DuplicateKey)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
// Add initial elements
Standard_Integer index1 = aMap.Add(10, 1.0);
Standard_Integer index2 = aMap.Add(20, 2.0);
EXPECT_EQ(index1, 1);
EXPECT_EQ(index2, 2);
// Try to add a duplicate - should return the existing index and not change the item
Standard_Integer indexDup = aMap.Add(10, 3.0);
EXPECT_EQ(indexDup, 1);
EXPECT_EQ(aMap.Extent(), 2); // Size should not change
EXPECT_DOUBLE_EQ(aMap.FindFromKey(10), 1.0); // Original value should be preserved
}
TEST(NCollection_IndexedDataMapTest, ChangeValues)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
// Add elements
aMap.Add(10, 1.0);
aMap.Add(20, 2.0);
// Change values through ChangeFromIndex
aMap.ChangeFromIndex(1) = 1.5;
aMap.ChangeFromIndex(2) = 2.5;
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(1), 1.5);
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(2), 2.5);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(10), 1.5);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(20), 2.5);
// Change values through ChangeFromKey
aMap.ChangeFromKey(10) = 1.75;
aMap.ChangeFromKey(20) = 2.75;
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(1), 1.75);
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(2), 2.75);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(10), 1.75);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(20), 2.75);
// Change values through operator()
aMap(1) = 1.9;
aMap(2) = 2.9;
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(1), 1.9);
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(2), 2.9);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(10), 1.9);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(20), 2.9);
}
TEST(NCollection_IndexedDataMapTest, SeekTests)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
// Add elements
aMap.Add(10, 1.0);
aMap.Add(20, 2.0);
// Test Seek
const ItemType* item1 = aMap.Seek(10);
const ItemType* item2 = aMap.Seek(20);
const ItemType* item3 = aMap.Seek(30); // Not present
EXPECT_TRUE(item1 != nullptr);
EXPECT_TRUE(item2 != nullptr);
EXPECT_TRUE(item3 == nullptr);
EXPECT_DOUBLE_EQ(*item1, 1.0);
EXPECT_DOUBLE_EQ(*item2, 2.0);
// Test ChangeSeek
ItemType* changeItem1 = aMap.ChangeSeek(10);
ItemType* changeItem2 = aMap.ChangeSeek(20);
ItemType* changeItem3 = aMap.ChangeSeek(30); // Not present
EXPECT_TRUE(changeItem1 != nullptr);
EXPECT_TRUE(changeItem2 != nullptr);
EXPECT_TRUE(changeItem3 == nullptr);
*changeItem1 = 1.5;
*changeItem2 = 2.5;
EXPECT_DOUBLE_EQ(aMap.FindFromKey(10), 1.5);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(20), 2.5);
// Test FindFromKey with copy
ItemType value;
bool found = aMap.FindFromKey(10, value);
EXPECT_TRUE(found);
EXPECT_DOUBLE_EQ(value, 1.5);
found = aMap.FindFromKey(30, value);
EXPECT_FALSE(found);
}
TEST(NCollection_IndexedDataMapTest, RemoveLast)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
// Add elements
aMap.Add(10, 1.0);
aMap.Add(20, 2.0);
aMap.Add(30, 3.0);
// Remove the last element
aMap.RemoveLast();
EXPECT_EQ(aMap.Extent(), 2);
EXPECT_TRUE(aMap.Contains(10));
EXPECT_TRUE(aMap.Contains(20));
EXPECT_FALSE(aMap.Contains(30));
// Check indices - they should still be sequential
EXPECT_EQ(aMap.FindIndex(10), 1);
EXPECT_EQ(aMap.FindIndex(20), 2);
}
TEST(NCollection_IndexedDataMapTest, RemoveFromIndex)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
// Add elements
aMap.Add(10, 1.0);
aMap.Add(20, 2.0);
aMap.Add(30, 3.0);
aMap.Add(40, 4.0);
// Remove element at index 2
aMap.RemoveFromIndex(2);
EXPECT_EQ(aMap.Extent(), 3);
EXPECT_TRUE(aMap.Contains(10));
EXPECT_FALSE(aMap.Contains(20)); // Removed
EXPECT_TRUE(aMap.Contains(30));
EXPECT_TRUE(aMap.Contains(40));
// Test how the indices were rearranged
// Index 2 should now contain what was previously at the last position
EXPECT_EQ(aMap.FindKey(2), 40); // Last element moved to position 2
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(2), 4.0);
EXPECT_EQ(aMap.FindKey(1), 10); // First element unchanged
EXPECT_EQ(aMap.FindKey(3), 30); // Third element unchanged
}
TEST(NCollection_IndexedDataMapTest, RemoveKey)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
// Add elements
aMap.Add(10, 1.0);
aMap.Add(20, 2.0);
aMap.Add(30, 3.0);
// Remove by key
aMap.RemoveKey(20);
EXPECT_EQ(aMap.Extent(), 2);
EXPECT_TRUE(aMap.Contains(10));
EXPECT_FALSE(aMap.Contains(20));
EXPECT_TRUE(aMap.Contains(30));
// Try to remove non-existent key
aMap.RemoveKey(50); // Should have no effect
EXPECT_EQ(aMap.Extent(), 2);
}
TEST(NCollection_IndexedDataMapTest, Substitute)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
// Add elements
aMap.Add(10, 1.0);
aMap.Add(20, 2.0);
aMap.Add(30, 3.0);
// Substitute key and value at index 2
aMap.Substitute(2, 25, 2.5);
EXPECT_EQ(aMap.Extent(), 3);
EXPECT_TRUE(aMap.Contains(10));
EXPECT_FALSE(aMap.Contains(20));
EXPECT_TRUE(aMap.Contains(25));
EXPECT_TRUE(aMap.Contains(30));
// Check indices after substitution
EXPECT_EQ(aMap.FindIndex(10), 1);
EXPECT_EQ(aMap.FindIndex(25), 2);
EXPECT_EQ(aMap.FindIndex(30), 3);
// Check values after substitution
EXPECT_DOUBLE_EQ(aMap.FindFromKey(10), 1.0);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(25), 2.5);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(30), 3.0);
}
TEST(NCollection_IndexedDataMapTest, Swap)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
// Add elements
aMap.Add(10, 1.0);
aMap.Add(20, 2.0);
aMap.Add(30, 3.0);
// Swap elements at indices 1 and 3
aMap.Swap(1, 3);
EXPECT_EQ(aMap.Extent(), 3);
// Check that keys maintained their values
EXPECT_TRUE(aMap.Contains(10));
EXPECT_TRUE(aMap.Contains(20));
EXPECT_TRUE(aMap.Contains(30));
// But indices are swapped
EXPECT_EQ(aMap.FindKey(1), 30);
EXPECT_EQ(aMap.FindKey(2), 20);
EXPECT_EQ(aMap.FindKey(3), 10);
EXPECT_EQ(aMap.FindIndex(10), 3);
EXPECT_EQ(aMap.FindIndex(20), 2);
EXPECT_EQ(aMap.FindIndex(30), 1);
// And values follow their keys
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(1), 3.0);
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(2), 2.0);
EXPECT_DOUBLE_EQ(aMap.FindFromIndex(3), 1.0);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(10), 1.0);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(20), 2.0);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(30), 3.0);
}
TEST(NCollection_IndexedDataMapTest, Clear)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
// Add elements
aMap.Add(10, 1.0);
aMap.Add(20, 2.0);
aMap.Add(30, 3.0);
EXPECT_EQ(aMap.Extent(), 3);
// Clear the map
aMap.Clear();
EXPECT_TRUE(aMap.IsEmpty());
EXPECT_EQ(aMap.Extent(), 0);
// Ensure we can add elements again
Standard_Integer index1 = aMap.Add(40, 4.0);
EXPECT_EQ(index1, 1);
EXPECT_EQ(aMap.Extent(), 1);
}
TEST(NCollection_IndexedDataMapTest, CopyConstructor)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap1;
// Add elements to first map
aMap1.Add(10, 1.0);
aMap1.Add(20, 2.0);
aMap1.Add(30, 3.0);
// Create a copy
NCollection_IndexedDataMap<KeyType, ItemType> aMap2(aMap1);
// Check that copy has the same elements
EXPECT_EQ(aMap2.Extent(), 3);
EXPECT_TRUE(aMap2.Contains(10));
EXPECT_TRUE(aMap2.Contains(20));
EXPECT_TRUE(aMap2.Contains(30));
// Check indices
EXPECT_EQ(aMap2.FindIndex(10), 1);
EXPECT_EQ(aMap2.FindIndex(20), 2);
EXPECT_EQ(aMap2.FindIndex(30), 3);
// Check values
EXPECT_DOUBLE_EQ(aMap2.FindFromKey(10), 1.0);
EXPECT_DOUBLE_EQ(aMap2.FindFromKey(20), 2.0);
EXPECT_DOUBLE_EQ(aMap2.FindFromKey(30), 3.0);
// Modify original to ensure deep copy
aMap1.Add(40, 4.0);
EXPECT_EQ(aMap1.Extent(), 4);
EXPECT_EQ(aMap2.Extent(), 3);
EXPECT_FALSE(aMap2.Contains(40));
}
TEST(NCollection_IndexedDataMapTest, AssignmentOperator)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap1;
NCollection_IndexedDataMap<KeyType, ItemType> aMap2;
// Add elements to first map
aMap1.Add(10, 1.0);
aMap1.Add(20, 2.0);
// Add different elements to second map
aMap2.Add(30, 3.0);
aMap2.Add(40, 4.0);
aMap2.Add(50, 5.0);
// Assign first to second
aMap2 = aMap1;
// Check that second map now matches first
EXPECT_EQ(aMap2.Extent(), 2);
EXPECT_TRUE(aMap2.Contains(10));
EXPECT_TRUE(aMap2.Contains(20));
EXPECT_FALSE(aMap2.Contains(30));
EXPECT_FALSE(aMap2.Contains(40));
EXPECT_FALSE(aMap2.Contains(50));
// Check values
EXPECT_DOUBLE_EQ(aMap2.FindFromKey(10), 1.0);
EXPECT_DOUBLE_EQ(aMap2.FindFromKey(20), 2.0);
}
TEST(NCollection_IndexedDataMapTest, Iterator)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
// Add elements
aMap.Add(10, 1.0);
aMap.Add(20, 2.0);
aMap.Add(30, 3.0);
// Use iterator to check all elements
Standard_Boolean found10 = Standard_False;
Standard_Boolean found20 = Standard_False;
Standard_Boolean found30 = Standard_False;
Standard_Size count = 0;
for (NCollection_IndexedDataMap<KeyType, ItemType>::Iterator it(aMap); it.More();
it.Next(), ++count)
{
const KeyType& key = it.Key();
const ItemType& value = it.Value();
if (key == 10 && value == 1.0)
found10 = Standard_True;
else if (key == 20 && value == 2.0)
found20 = Standard_True;
else if (key == 30 && value == 3.0)
found30 = Standard_True;
}
EXPECT_EQ(count, 3);
EXPECT_TRUE(found10);
EXPECT_TRUE(found20);
EXPECT_TRUE(found30);
// Test modification through iterator
for (NCollection_IndexedDataMap<KeyType, ItemType>::Iterator it(aMap); it.More(); it.Next())
{
it.ChangeValue() *= 2;
}
EXPECT_DOUBLE_EQ(aMap.FindFromKey(10), 2.0);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(20), 4.0);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(30), 6.0);
}
TEST(NCollection_IndexedDataMapTest, StlIterator)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap;
// Add elements
aMap.Add(10, 1.0);
aMap.Add(20, 2.0);
aMap.Add(30, 3.0);
// Use STL-style iterator
Standard_Boolean found1 = Standard_False;
Standard_Boolean found2 = Standard_False;
Standard_Boolean found3 = Standard_False;
Standard_Size count = 0;
for (auto it = aMap.begin(); it != aMap.end(); ++it, ++count)
{
if (*it == 1.0)
found1 = Standard_True;
else if (*it == 2.0)
found2 = Standard_True;
else if (*it == 3.0)
found3 = Standard_True;
}
EXPECT_EQ(count, 3);
EXPECT_TRUE(found1);
EXPECT_TRUE(found2);
EXPECT_TRUE(found3);
// Test const iterator
count = 0;
found1 = Standard_False;
found2 = Standard_False;
found3 = Standard_False;
for (auto it = aMap.cbegin(); it != aMap.cend(); ++it, ++count)
{
if (*it == 1.0)
found1 = Standard_True;
else if (*it == 2.0)
found2 = Standard_True;
else if (*it == 3.0)
found3 = Standard_True;
}
EXPECT_EQ(count, 3);
EXPECT_TRUE(found1);
EXPECT_TRUE(found2);
EXPECT_TRUE(found3);
}
TEST(NCollection_IndexedDataMapTest, StringKeys)
{
// Test with string keys
NCollection_IndexedDataMap<TCollection_AsciiString, ItemType> aStringMap;
// Add string keys
Standard_Integer index1 = aStringMap.Add(TCollection_AsciiString("First"), 1.0);
Standard_Integer index2 = aStringMap.Add(TCollection_AsciiString("Second"), 2.0);
Standard_Integer index3 = aStringMap.Add(TCollection_AsciiString("Third"), 3.0);
EXPECT_EQ(index1, 1);
EXPECT_EQ(index2, 2);
EXPECT_EQ(index3, 3);
// Find by key
EXPECT_EQ(aStringMap.FindIndex(TCollection_AsciiString("First")), 1);
EXPECT_EQ(aStringMap.FindIndex(TCollection_AsciiString("Second")), 2);
EXPECT_EQ(aStringMap.FindIndex(TCollection_AsciiString("Third")), 3);
// Find by index
EXPECT_TRUE(aStringMap.FindKey(1).IsEqual("First"));
EXPECT_TRUE(aStringMap.FindKey(2).IsEqual("Second"));
EXPECT_TRUE(aStringMap.FindKey(3).IsEqual("Third"));
// Find values
EXPECT_DOUBLE_EQ(aStringMap.FindFromKey(TCollection_AsciiString("First")), 1.0);
EXPECT_DOUBLE_EQ(aStringMap.FindFromKey(TCollection_AsciiString("Second")), 2.0);
EXPECT_DOUBLE_EQ(aStringMap.FindFromKey(TCollection_AsciiString("Third")), 3.0);
}
TEST(NCollection_IndexedDataMapTest, ComplexKeyAndValue)
{
// Create map with custom key and hasher
NCollection_IndexedDataMap<TestKey, TestItem> aComplexMap;
// Add complex keys and values
TestKey key1(1, "One");
TestKey key2(2, "Two");
TestKey key3(3, "Three");
TestItem item1(1.1, "Item One");
TestItem item2(2.2, "Item Two");
TestItem item3(3.3, "Item Three");
Standard_Integer index1 = aComplexMap.Add(key1, item1);
Standard_Integer index2 = aComplexMap.Add(key2, item2);
Standard_Integer index3 = aComplexMap.Add(key3, item3);
EXPECT_EQ(index1, 1);
EXPECT_EQ(index2, 2);
EXPECT_EQ(index3, 3);
// Find by key
EXPECT_EQ(aComplexMap.FindIndex(key1), 1);
EXPECT_EQ(aComplexMap.FindIndex(key2), 2);
EXPECT_EQ(aComplexMap.FindIndex(key3), 3);
// Find by index
EXPECT_EQ(aComplexMap.FindKey(1).GetId(), 1);
EXPECT_EQ(aComplexMap.FindKey(2).GetId(), 2);
EXPECT_EQ(aComplexMap.FindKey(3).GetId(), 3);
// Find values
EXPECT_DOUBLE_EQ(aComplexMap.FindFromKey(key1).GetValue(), 1.1);
EXPECT_DOUBLE_EQ(aComplexMap.FindFromKey(key2).GetValue(), 2.2);
EXPECT_DOUBLE_EQ(aComplexMap.FindFromKey(key3).GetValue(), 3.3);
// Test contains
EXPECT_TRUE(aComplexMap.Contains(TestKey(1, "One")));
EXPECT_FALSE(aComplexMap.Contains(TestKey(4, "Four")));
// Test value modification
aComplexMap.ChangeFromKey(key1).SetValue(1.5);
EXPECT_DOUBLE_EQ(aComplexMap.FindFromKey(key1).GetValue(), 1.5);
}
TEST(NCollection_IndexedDataMapTest, Exchange)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap1;
NCollection_IndexedDataMap<KeyType, ItemType> aMap2;
// Add elements to first map
aMap1.Add(10, 1.0);
aMap1.Add(20, 2.0);
// Add different elements to second map
aMap2.Add(30, 3.0);
aMap2.Add(40, 4.0);
aMap2.Add(50, 5.0);
// Exchange maps
aMap1.Exchange(aMap2);
// Check that maps are exchanged
EXPECT_EQ(aMap1.Extent(), 3);
EXPECT_TRUE(aMap1.Contains(30));
EXPECT_TRUE(aMap1.Contains(40));
EXPECT_TRUE(aMap1.Contains(50));
EXPECT_DOUBLE_EQ(aMap1.FindFromKey(30), 3.0);
EXPECT_DOUBLE_EQ(aMap1.FindFromKey(40), 4.0);
EXPECT_DOUBLE_EQ(aMap1.FindFromKey(50), 5.0);
EXPECT_EQ(aMap2.Extent(), 2);
EXPECT_TRUE(aMap2.Contains(10));
EXPECT_TRUE(aMap2.Contains(20));
EXPECT_DOUBLE_EQ(aMap2.FindFromKey(10), 1.0);
EXPECT_DOUBLE_EQ(aMap2.FindFromKey(20), 2.0);
}
TEST(NCollection_IndexedDataMapTest, ReSize)
{
NCollection_IndexedDataMap<KeyType, ItemType> aMap(3); // Start with small bucket count
// Add many elements to trigger resize
for (Standard_Integer i = 1; i <= 100; ++i)
{
aMap.Add(i, static_cast<Standard_Real>(i) / 10.0);
}
// Verify all elements are present
EXPECT_EQ(aMap.Extent(), 100);
for (Standard_Integer i = 1; i <= 100; ++i)
{
EXPECT_TRUE(aMap.Contains(i));
EXPECT_EQ(aMap.FindIndex(i), i);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(i), static_cast<Standard_Real>(i) / 10.0);
}
// Explicitly resize
aMap.ReSize(200);
// Check that elements are still accessible
EXPECT_EQ(aMap.Extent(), 100);
for (Standard_Integer i = 1; i <= 100; ++i)
{
EXPECT_TRUE(aMap.Contains(i));
EXPECT_EQ(aMap.FindIndex(i), i);
EXPECT_DOUBLE_EQ(aMap.FindFromKey(i), static_cast<Standard_Real>(i) / 10.0);
}
}

View File

@@ -0,0 +1,514 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <NCollection_IndexedMap.hxx>
#include <TCollection_AsciiString.hxx>
#include <gtest/gtest.h>
// Basic test type for the IndexedMap
typedef Standard_Integer KeyType;
// Custom class for testing complex keys
class TestKey
{
public:
TestKey(int id = 0, const char* name = "")
: myId(id),
myName(name)
{
}
bool operator==(const TestKey& other) const
{
return myId == other.myId && myName == other.myName;
}
int GetId() const { return myId; }
const std::string& GetName() const { return myName; }
private:
int myId;
std::string myName;
};
// Hasher for TestKey
struct TestKeyHasher
{
size_t operator()(const TestKey& theKey) const
{
// Combine the hash of the id and name
size_t aCombination[2] = {std::hash<int>()(theKey.GetId()),
std::hash<std::string>()(theKey.GetName())};
return opencascade::hashBytes(aCombination, sizeof(aCombination));
}
Standard_Boolean operator()(const TestKey& theKey1, const TestKey& theKey2) const
{
return theKey1 == theKey2;
}
};
TEST(NCollection_IndexedMapTest, DefaultConstructor)
{
// Test default constructor
NCollection_IndexedMap<KeyType> aMap;
EXPECT_TRUE(aMap.IsEmpty());
EXPECT_EQ(aMap.Extent(), 0);
EXPECT_EQ(aMap.Size(), 0);
}
TEST(NCollection_IndexedMapTest, BasicAddFind)
{
NCollection_IndexedMap<KeyType> aMap;
// Test adding elements
Standard_Integer index1 = aMap.Add(10);
Standard_Integer index2 = aMap.Add(20);
Standard_Integer index3 = aMap.Add(30);
EXPECT_EQ(index1, 1);
EXPECT_EQ(index2, 2);
EXPECT_EQ(index3, 3);
EXPECT_EQ(aMap.Extent(), 3);
// Test finding elements by key
EXPECT_EQ(aMap.FindIndex(10), 1);
EXPECT_EQ(aMap.FindIndex(20), 2);
EXPECT_EQ(aMap.FindIndex(30), 3);
// Test finding keys by index
EXPECT_EQ(aMap.FindKey(1), 10);
EXPECT_EQ(aMap.FindKey(2), 20);
EXPECT_EQ(aMap.FindKey(3), 30);
// Test operator()
EXPECT_EQ(aMap(1), 10);
EXPECT_EQ(aMap(2), 20);
EXPECT_EQ(aMap(3), 30);
// Test Contains
EXPECT_TRUE(aMap.Contains(10));
EXPECT_TRUE(aMap.Contains(20));
EXPECT_TRUE(aMap.Contains(30));
EXPECT_FALSE(aMap.Contains(40));
}
TEST(NCollection_IndexedMapTest, DuplicateKey)
{
NCollection_IndexedMap<KeyType> aMap;
// Add initial elements
Standard_Integer index1 = aMap.Add(10);
Standard_Integer index2 = aMap.Add(20);
EXPECT_EQ(index1, 1);
EXPECT_EQ(index2, 2);
// Try to add a duplicate - should return the existing index
Standard_Integer indexDup = aMap.Add(10);
EXPECT_EQ(indexDup, 1);
EXPECT_EQ(aMap.Extent(), 2); // Size should not change
}
TEST(NCollection_IndexedMapTest, RemoveLast)
{
NCollection_IndexedMap<KeyType> aMap;
// Add elements
aMap.Add(10);
aMap.Add(20);
aMap.Add(30);
// Remove the last element
aMap.RemoveLast();
EXPECT_EQ(aMap.Extent(), 2);
EXPECT_TRUE(aMap.Contains(10));
EXPECT_TRUE(aMap.Contains(20));
EXPECT_FALSE(aMap.Contains(30));
// Check indices - they should still be sequential
EXPECT_EQ(aMap.FindIndex(10), 1);
EXPECT_EQ(aMap.FindIndex(20), 2);
}
TEST(NCollection_IndexedMapTest, RemoveFromIndex)
{
NCollection_IndexedMap<KeyType> aMap;
// Add elements
aMap.Add(10);
aMap.Add(20);
aMap.Add(30);
aMap.Add(40);
// Remove element at index 2
aMap.RemoveFromIndex(2);
EXPECT_EQ(aMap.Extent(), 3);
EXPECT_TRUE(aMap.Contains(10));
EXPECT_FALSE(aMap.Contains(20)); // Removed
EXPECT_TRUE(aMap.Contains(30));
EXPECT_TRUE(aMap.Contains(40));
// Test how the indices were rearranged
// Index 2 should now contain what was previously at the last position
EXPECT_EQ(aMap.FindKey(2), 40); // Last element moved to position 2
EXPECT_EQ(aMap.FindKey(1), 10); // First element unchanged
EXPECT_EQ(aMap.FindKey(3), 30); // Third element unchanged
}
TEST(NCollection_IndexedMapTest, RemoveKey)
{
NCollection_IndexedMap<KeyType> aMap;
// Add elements
aMap.Add(10);
aMap.Add(20);
aMap.Add(30);
// Remove by key
bool removed = aMap.RemoveKey(20);
EXPECT_TRUE(removed);
EXPECT_EQ(aMap.Extent(), 2);
EXPECT_TRUE(aMap.Contains(10));
EXPECT_FALSE(aMap.Contains(20));
EXPECT_TRUE(aMap.Contains(30));
// Try to remove non-existent key
removed = aMap.RemoveKey(50);
EXPECT_FALSE(removed);
EXPECT_EQ(aMap.Extent(), 2);
}
TEST(NCollection_IndexedMapTest, Substitute)
{
NCollection_IndexedMap<KeyType> aMap;
// Add elements
aMap.Add(10);
aMap.Add(20);
aMap.Add(30);
// Substitute key at index 2
aMap.Substitute(2, 25);
EXPECT_EQ(aMap.Extent(), 3);
EXPECT_TRUE(aMap.Contains(10));
EXPECT_FALSE(aMap.Contains(20));
EXPECT_TRUE(aMap.Contains(25));
EXPECT_TRUE(aMap.Contains(30));
// Check indices after substitution
EXPECT_EQ(aMap.FindIndex(10), 1);
EXPECT_EQ(aMap.FindIndex(25), 2);
EXPECT_EQ(aMap.FindIndex(30), 3);
// Check keys
EXPECT_EQ(aMap.FindKey(1), 10);
EXPECT_EQ(aMap.FindKey(2), 25);
EXPECT_EQ(aMap.FindKey(3), 30);
}
TEST(NCollection_IndexedMapTest, Swap)
{
NCollection_IndexedMap<KeyType> aMap;
// Add elements
aMap.Add(10);
aMap.Add(20);
aMap.Add(30);
// Swap elements at indices 1 and 3
aMap.Swap(1, 3);
EXPECT_EQ(aMap.Extent(), 3);
// Check that keys maintained their values
EXPECT_TRUE(aMap.Contains(10));
EXPECT_TRUE(aMap.Contains(20));
EXPECT_TRUE(aMap.Contains(30));
// But indices are swapped
EXPECT_EQ(aMap.FindKey(1), 30);
EXPECT_EQ(aMap.FindKey(2), 20);
EXPECT_EQ(aMap.FindKey(3), 10);
EXPECT_EQ(aMap.FindIndex(10), 3);
EXPECT_EQ(aMap.FindIndex(20), 2);
EXPECT_EQ(aMap.FindIndex(30), 1);
}
TEST(NCollection_IndexedMapTest, Clear)
{
NCollection_IndexedMap<KeyType> aMap;
// Add elements
aMap.Add(10);
aMap.Add(20);
aMap.Add(30);
EXPECT_EQ(aMap.Extent(), 3);
// Clear the map
aMap.Clear();
EXPECT_TRUE(aMap.IsEmpty());
EXPECT_EQ(aMap.Extent(), 0);
// Ensure we can add elements again
Standard_Integer index1 = aMap.Add(40);
EXPECT_EQ(index1, 1);
EXPECT_EQ(aMap.Extent(), 1);
}
TEST(NCollection_IndexedMapTest, CopyConstructor)
{
NCollection_IndexedMap<KeyType> aMap1;
// Add elements to first map
aMap1.Add(10);
aMap1.Add(20);
aMap1.Add(30);
// Create a copy
NCollection_IndexedMap<KeyType> aMap2(aMap1);
// Check that copy has the same elements
EXPECT_EQ(aMap2.Extent(), 3);
EXPECT_TRUE(aMap2.Contains(10));
EXPECT_TRUE(aMap2.Contains(20));
EXPECT_TRUE(aMap2.Contains(30));
// Check indices
EXPECT_EQ(aMap2.FindIndex(10), 1);
EXPECT_EQ(aMap2.FindIndex(20), 2);
EXPECT_EQ(aMap2.FindIndex(30), 3);
// Modify original to ensure deep copy
aMap1.Add(40);
EXPECT_EQ(aMap1.Extent(), 4);
EXPECT_EQ(aMap2.Extent(), 3);
EXPECT_FALSE(aMap2.Contains(40));
}
TEST(NCollection_IndexedMapTest, AssignmentOperator)
{
NCollection_IndexedMap<KeyType> aMap1;
NCollection_IndexedMap<KeyType> aMap2;
// Add elements to first map
aMap1.Add(10);
aMap1.Add(20);
// Add different elements to second map
aMap2.Add(30);
aMap2.Add(40);
aMap2.Add(50);
// Assign first to second
aMap2 = aMap1;
// Check that second map now matches first
EXPECT_EQ(aMap2.Extent(), 2);
EXPECT_TRUE(aMap2.Contains(10));
EXPECT_TRUE(aMap2.Contains(20));
EXPECT_FALSE(aMap2.Contains(30));
EXPECT_FALSE(aMap2.Contains(40));
EXPECT_FALSE(aMap2.Contains(50));
}
TEST(NCollection_IndexedMapTest, Iterator)
{
NCollection_IndexedMap<KeyType> aMap;
// Add elements
aMap.Add(10);
aMap.Add(20);
aMap.Add(30);
// Use iterator to check all elements
Standard_Boolean found10 = Standard_False;
Standard_Boolean found20 = Standard_False;
Standard_Boolean found30 = Standard_False;
Standard_Size count = 0;
for (NCollection_IndexedMap<KeyType>::Iterator it(aMap); it.More(); it.Next(), ++count)
{
const KeyType& key = it.Value();
if (key == 10)
found10 = Standard_True;
else if (key == 20)
found20 = Standard_True;
else if (key == 30)
found30 = Standard_True;
}
EXPECT_EQ(count, 3);
EXPECT_TRUE(found10);
EXPECT_TRUE(found20);
EXPECT_TRUE(found30);
}
TEST(NCollection_IndexedMapTest, StlIterator)
{
NCollection_IndexedMap<KeyType> aMap;
// Add elements
aMap.Add(10);
aMap.Add(20);
aMap.Add(30);
// Use STL-style iterator
Standard_Boolean found10 = Standard_False;
Standard_Boolean found20 = Standard_False;
Standard_Boolean found30 = Standard_False;
Standard_Size count = 0;
for (auto it = aMap.cbegin(); it != aMap.cend(); ++it, ++count)
{
if (*it == 10)
found10 = Standard_True;
else if (*it == 20)
found20 = Standard_True;
else if (*it == 30)
found30 = Standard_True;
}
EXPECT_EQ(count, 3);
EXPECT_TRUE(found10);
EXPECT_TRUE(found20);
EXPECT_TRUE(found30);
}
TEST(NCollection_IndexedMapTest, StringKeys)
{
// Test with string keys
NCollection_IndexedMap<TCollection_AsciiString> aStringMap;
// Add string keys
Standard_Integer index1 = aStringMap.Add(TCollection_AsciiString("First"));
Standard_Integer index2 = aStringMap.Add(TCollection_AsciiString("Second"));
Standard_Integer index3 = aStringMap.Add(TCollection_AsciiString("Third"));
EXPECT_EQ(index1, 1);
EXPECT_EQ(index2, 2);
EXPECT_EQ(index3, 3);
// Find by key
EXPECT_EQ(aStringMap.FindIndex(TCollection_AsciiString("First")), 1);
EXPECT_EQ(aStringMap.FindIndex(TCollection_AsciiString("Second")), 2);
EXPECT_EQ(aStringMap.FindIndex(TCollection_AsciiString("Third")), 3);
// Find by index
EXPECT_TRUE(aStringMap.FindKey(1).IsEqual("First"));
EXPECT_TRUE(aStringMap.FindKey(2).IsEqual("Second"));
EXPECT_TRUE(aStringMap.FindKey(3).IsEqual("Third"));
}
TEST(NCollection_IndexedMapTest, ComplexKeys)
{
// Create map with custom key and hasher
NCollection_IndexedMap<TestKey, TestKeyHasher> aComplexMap;
// Add complex keys
TestKey key1(1, "One");
TestKey key2(2, "Two");
TestKey key3(3, "Three");
Standard_Integer index1 = aComplexMap.Add(key1);
Standard_Integer index2 = aComplexMap.Add(key2);
Standard_Integer index3 = aComplexMap.Add(key3);
EXPECT_EQ(index1, 1);
EXPECT_EQ(index2, 2);
EXPECT_EQ(index3, 3);
// Find by key
EXPECT_EQ(aComplexMap.FindIndex(key1), 1);
EXPECT_EQ(aComplexMap.FindIndex(key2), 2);
EXPECT_EQ(aComplexMap.FindIndex(key3), 3);
// Find by index
EXPECT_EQ(aComplexMap.FindKey(1).GetId(), 1);
EXPECT_EQ(aComplexMap.FindKey(2).GetId(), 2);
EXPECT_EQ(aComplexMap.FindKey(3).GetId(), 3);
// Test contains
EXPECT_TRUE(aComplexMap.Contains(TestKey(1, "One")));
EXPECT_FALSE(aComplexMap.Contains(TestKey(4, "Four")));
}
TEST(NCollection_IndexedMapTest, Exchange)
{
NCollection_IndexedMap<KeyType> aMap1;
NCollection_IndexedMap<KeyType> aMap2;
// Add elements to first map
aMap1.Add(10);
aMap1.Add(20);
// Add different elements to second map
aMap2.Add(30);
aMap2.Add(40);
aMap2.Add(50);
// Exchange maps
aMap1.Exchange(aMap2);
// Check that maps are exchanged
EXPECT_EQ(aMap1.Extent(), 3);
EXPECT_TRUE(aMap1.Contains(30));
EXPECT_TRUE(aMap1.Contains(40));
EXPECT_TRUE(aMap1.Contains(50));
EXPECT_EQ(aMap2.Extent(), 2);
EXPECT_TRUE(aMap2.Contains(10));
EXPECT_TRUE(aMap2.Contains(20));
}
TEST(NCollection_IndexedMapTest, ReSize)
{
NCollection_IndexedMap<KeyType> aMap(3); // Start with small bucket count
// Add many elements to trigger resize
for (Standard_Integer i = 1; i <= 100; ++i)
{
aMap.Add(i);
}
// Verify all elements are present
EXPECT_EQ(aMap.Extent(), 100);
for (Standard_Integer i = 1; i <= 100; ++i)
{
EXPECT_TRUE(aMap.Contains(i));
EXPECT_EQ(aMap.FindIndex(i), i);
EXPECT_EQ(aMap.FindKey(i), i);
}
// Explicitly resize
aMap.ReSize(200);
// Check that elements are still accessible
EXPECT_EQ(aMap.Extent(), 100);
for (Standard_Integer i = 1; i <= 100; ++i)
{
EXPECT_TRUE(aMap.Contains(i));
EXPECT_EQ(aMap.FindIndex(i), i);
EXPECT_EQ(aMap.FindKey(i), i);
}
}

View File

@@ -0,0 +1,402 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <NCollection_List.hxx>
#include <Standard_Integer.hxx>
#include <gtest/gtest.h>
// Test fixture for NCollection_List tests
class NCollection_ListTest : public testing::Test
{
protected:
void SetUp() override {}
void TearDown() override {}
};
TEST_F(NCollection_ListTest, DefaultConstructor)
{
// Default constructor should create an empty list
NCollection_List<Standard_Integer> aList;
EXPECT_TRUE(aList.IsEmpty());
EXPECT_EQ(0, aList.Size());
EXPECT_EQ(0, aList.Extent());
}
TEST_F(NCollection_ListTest, Append)
{
NCollection_List<Standard_Integer> aList;
// Test Append method
EXPECT_EQ(10, aList.Append(10));
EXPECT_EQ(20, aList.Append(20));
EXPECT_EQ(30, aList.Append(30));
EXPECT_FALSE(aList.IsEmpty());
EXPECT_EQ(3, aList.Size());
// Test First and Last access
EXPECT_EQ(10, aList.First());
EXPECT_EQ(30, aList.Last());
}
TEST_F(NCollection_ListTest, Prepend)
{
NCollection_List<Standard_Integer> aList;
// Test Prepend method
EXPECT_EQ(30, aList.Prepend(30));
EXPECT_EQ(20, aList.Prepend(20));
EXPECT_EQ(10, aList.Prepend(10));
EXPECT_FALSE(aList.IsEmpty());
EXPECT_EQ(3, aList.Size());
// Test First and Last access
EXPECT_EQ(10, aList.First());
EXPECT_EQ(30, aList.Last());
}
TEST_F(NCollection_ListTest, IteratorAccess)
{
NCollection_List<Standard_Integer> aList;
aList.Append(10);
aList.Append(20);
aList.Append(30);
// Test iteration using OCCT iterator
NCollection_List<Standard_Integer>::Iterator it(aList);
Standard_Integer expectedValues[] = {10, 20, 30};
Standard_Integer index = 0;
for (; it.More(); it.Next(), index++)
{
EXPECT_EQ(expectedValues[index], it.Value());
}
EXPECT_EQ(3, index); // Ensure we iterated through all elements
}
TEST_F(NCollection_ListTest, STLIterators)
{
NCollection_List<Standard_Integer> aList;
aList.Append(10);
aList.Append(20);
aList.Append(30);
// Test STL-compatible iterators
Standard_Integer expectedValues[] = {10, 20, 30};
Standard_Integer index = 0;
for (auto it = aList.begin(); it != aList.end(); ++it, ++index)
{
EXPECT_EQ(expectedValues[index], *it);
}
EXPECT_EQ(3, index);
// Test range-based for loop
index = 0;
for (const auto& value : aList)
{
EXPECT_EQ(expectedValues[index++], value);
}
EXPECT_EQ(3, index);
}
TEST_F(NCollection_ListTest, RemoveFirst)
{
NCollection_List<Standard_Integer> aList;
aList.Append(10);
aList.Append(20);
aList.Append(30);
// Test RemoveFirst
aList.RemoveFirst();
EXPECT_EQ(2, aList.Size());
EXPECT_EQ(20, aList.First());
aList.RemoveFirst();
EXPECT_EQ(1, aList.Size());
EXPECT_EQ(30, aList.First());
aList.RemoveFirst();
EXPECT_TRUE(aList.IsEmpty());
}
TEST_F(NCollection_ListTest, Remove)
{
NCollection_List<Standard_Integer> aList;
aList.Append(10);
aList.Append(20);
aList.Append(30);
// Test Remove with iterator
NCollection_List<Standard_Integer>::Iterator it(aList);
it.Next(); // Point to second element (20)
aList.Remove(it); // Remove 20, iterator now points to 30
// Check the list after removal
EXPECT_EQ(2, aList.Size());
EXPECT_EQ(10, aList.First());
EXPECT_EQ(30, aList.Last());
EXPECT_EQ(30, it.Value()); // Iterator should now point to 30
}
TEST_F(NCollection_ListTest, RemoveByValue)
{
NCollection_List<Standard_Integer> aList;
aList.Append(10);
aList.Append(20);
aList.Append(10); // Add duplicate
aList.Append(30);
// Test removing by value - should remove the first occurrence only
bool removed = aList.Remove(10);
EXPECT_TRUE(removed);
EXPECT_EQ(3, aList.Size());
EXPECT_EQ(20, aList.First());
// Try to remove a non-existent value
removed = aList.Remove(50);
EXPECT_FALSE(removed);
EXPECT_EQ(3, aList.Size());
// Remove the second occurrence of 10
removed = aList.Remove(10);
EXPECT_TRUE(removed);
EXPECT_EQ(2, aList.Size());
// Check final list state
NCollection_List<Standard_Integer>::Iterator it(aList);
EXPECT_EQ(20, it.Value());
it.Next();
EXPECT_EQ(30, it.Value());
}
TEST_F(NCollection_ListTest, Clear)
{
NCollection_List<Standard_Integer> aList;
aList.Append(10);
aList.Append(20);
aList.Append(30);
// Test Clear
aList.Clear();
EXPECT_TRUE(aList.IsEmpty());
EXPECT_EQ(0, aList.Size());
}
TEST_F(NCollection_ListTest, Assignment)
{
NCollection_List<Standard_Integer> aList1;
aList1.Append(10);
aList1.Append(20);
aList1.Append(30);
// Test assignment operator
NCollection_List<Standard_Integer> aList2;
aList2 = aList1;
// Check both lists have the same content
EXPECT_EQ(aList1.Size(), aList2.Size());
NCollection_List<Standard_Integer>::Iterator it1(aList1);
NCollection_List<Standard_Integer>::Iterator it2(aList2);
for (; it1.More() && it2.More(); it1.Next(), it2.Next())
{
EXPECT_EQ(it1.Value(), it2.Value());
}
// Modify original to ensure deep copy
aList1.First() = 100;
EXPECT_EQ(100, aList1.First());
EXPECT_EQ(10, aList2.First());
}
TEST_F(NCollection_ListTest, AssignMethod)
{
NCollection_List<Standard_Integer> aList1;
aList1.Append(10);
aList1.Append(20);
aList1.Append(30);
// Test Assign method
NCollection_List<Standard_Integer> aList2;
aList2.Append(40); // Add some initial content
aList2.Assign(aList1); // This should replace aList2's content
EXPECT_EQ(aList1.Size(), aList2.Size());
// Check values
NCollection_List<Standard_Integer>::Iterator it2(aList2);
EXPECT_EQ(10, it2.Value());
it2.Next();
EXPECT_EQ(20, it2.Value());
it2.Next();
EXPECT_EQ(30, it2.Value());
}
TEST_F(NCollection_ListTest, AppendList)
{
NCollection_List<Standard_Integer> aList1;
aList1.Append(10);
aList1.Append(20);
NCollection_List<Standard_Integer> aList2;
aList2.Append(30);
aList2.Append(40);
// Test Append(List)
aList1.Append(aList2);
EXPECT_EQ(4, aList1.Size());
EXPECT_TRUE(aList2.IsEmpty()); // aList2 should be cleared
// Check values in aList1
NCollection_List<Standard_Integer>::Iterator it(aList1);
EXPECT_EQ(10, it.Value());
it.Next();
EXPECT_EQ(20, it.Value());
it.Next();
EXPECT_EQ(30, it.Value());
it.Next();
EXPECT_EQ(40, it.Value());
}
TEST_F(NCollection_ListTest, PrependList)
{
NCollection_List<Standard_Integer> aList1;
aList1.Append(30);
aList1.Append(40);
NCollection_List<Standard_Integer> aList2;
aList2.Append(10);
aList2.Append(20);
// Test Prepend(List)
aList1.Prepend(aList2);
EXPECT_EQ(4, aList1.Size());
EXPECT_TRUE(aList2.IsEmpty()); // aList2 should be cleared
// Check values in aList1
NCollection_List<Standard_Integer>::Iterator it(aList1);
EXPECT_EQ(10, it.Value());
it.Next();
EXPECT_EQ(20, it.Value());
it.Next();
EXPECT_EQ(30, it.Value());
it.Next();
EXPECT_EQ(40, it.Value());
}
TEST_F(NCollection_ListTest, InsertBefore)
{
NCollection_List<Standard_Integer> aList;
aList.Append(10);
aList.Append(30);
// Get iterator to second element
NCollection_List<Standard_Integer>::Iterator it(aList);
it.Next();
// Insert before the second element
EXPECT_EQ(20, aList.InsertBefore(20, it));
// Check the list
EXPECT_EQ(3, aList.Size());
NCollection_List<Standard_Integer>::Iterator checkIt(aList);
EXPECT_EQ(10, checkIt.Value());
checkIt.Next();
EXPECT_EQ(20, checkIt.Value());
checkIt.Next();
EXPECT_EQ(30, checkIt.Value());
}
TEST_F(NCollection_ListTest, InsertAfter)
{
NCollection_List<Standard_Integer> aList;
aList.Append(10);
aList.Append(30);
// Get iterator to first element
NCollection_List<Standard_Integer>::Iterator it(aList);
// Insert after the first element
EXPECT_EQ(20, aList.InsertAfter(20, it));
// Check the list
EXPECT_EQ(3, aList.Size());
NCollection_List<Standard_Integer>::Iterator checkIt(aList);
EXPECT_EQ(10, checkIt.Value());
checkIt.Next();
EXPECT_EQ(20, checkIt.Value());
checkIt.Next();
EXPECT_EQ(30, checkIt.Value());
}
TEST_F(NCollection_ListTest, InsertList)
{
NCollection_List<Standard_Integer> aList1;
aList1.Append(10);
aList1.Append(40);
NCollection_List<Standard_Integer> aList2;
aList2.Append(20);
aList2.Append(30);
// Get iterator to the second element in aList1
NCollection_List<Standard_Integer>::Iterator it(aList1);
it.Next();
// Insert aList2 before the second element in aList1
aList1.InsertBefore(aList2, it);
EXPECT_EQ(4, aList1.Size());
EXPECT_TRUE(aList2.IsEmpty());
// Check the resulting list
NCollection_List<Standard_Integer>::Iterator checkIt(aList1);
EXPECT_EQ(10, checkIt.Value());
checkIt.Next();
EXPECT_EQ(20, checkIt.Value());
checkIt.Next();
EXPECT_EQ(30, checkIt.Value());
checkIt.Next();
EXPECT_EQ(40, checkIt.Value());
}
TEST_F(NCollection_ListTest, Reverse)
{
NCollection_List<Standard_Integer> aList;
aList.Append(10);
aList.Append(20);
aList.Append(30);
// Test Reverse
aList.Reverse();
// Check the reversed list
EXPECT_EQ(30, aList.First());
EXPECT_EQ(10, aList.Last());
NCollection_List<Standard_Integer>::Iterator it(aList);
EXPECT_EQ(30, it.Value());
it.Next();
EXPECT_EQ(20, it.Value());
it.Next();
EXPECT_EQ(10, it.Value());
}

View File

@@ -0,0 +1,191 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <NCollection_LocalArray.hxx>
#include <gtest/gtest.h>
// Test default constructor and initial state
TEST(NCollection_LocalArrayTest, DefaultConstructor)
{
NCollection_LocalArray<int> array;
EXPECT_EQ(0, array.Size());
}
// Test constructor with size
TEST(NCollection_LocalArrayTest, ConstructorWithSize)
{
const size_t size = 100;
NCollection_LocalArray<int> array(size);
EXPECT_EQ(size, array.Size());
}
// Test allocation with small size (using buffer)
TEST(NCollection_LocalArrayTest, SmallSizeAllocation)
{
const size_t size = 10; // Less than MAX_ARRAY_SIZE
NCollection_LocalArray<int, 1024> array(size);
EXPECT_EQ(size, array.Size());
// Populate array
for (size_t i = 0; i < size; ++i)
{
array[i] = static_cast<int>(i * 10);
}
// Verify array contents
for (size_t i = 0; i < size; ++i)
{
EXPECT_EQ(static_cast<int>(i * 10), array[i]);
}
}
// Test allocation with large size (heap allocation)
TEST(NCollection_LocalArrayTest, LargeSizeAllocation)
{
const size_t size = 2000; // Greater than default MAX_ARRAY_SIZE of 1024
NCollection_LocalArray<int> array(size);
EXPECT_EQ(size, array.Size());
// Populate array
for (size_t i = 0; i < size; ++i)
{
array[i] = static_cast<int>(i * 10);
}
// Verify array contents
for (size_t i = 0; i < size; ++i)
{
EXPECT_EQ(static_cast<int>(i * 10), array[i]);
}
}
// Test reallocation
TEST(NCollection_LocalArrayTest, Reallocation)
{
NCollection_LocalArray<int> array(10);
EXPECT_EQ(10, array.Size());
// Populate array
for (size_t i = 0; i < 10; ++i)
{
array[i] = static_cast<int>(i);
}
// Reallocate to larger size
array.Allocate(50);
EXPECT_EQ(50, array.Size());
// Populate new elements
for (size_t i = 0; i < 50; ++i)
{
array[i] = static_cast<int>(i * 2);
}
// Verify array contents
for (size_t i = 0; i < 50; ++i)
{
EXPECT_EQ(static_cast<int>(i * 2), array[i]);
}
// Reallocate to smaller size
array.Allocate(5);
EXPECT_EQ(5, array.Size());
// Verify array contents
for (size_t i = 0; i < 5; ++i)
{
EXPECT_EQ(static_cast<int>(i * 2), array[i]);
}
}
// Test with custom MAX_ARRAY_SIZE
TEST(NCollection_LocalArrayTest, CustomMaxArraySize)
{
const size_t customMaxSize = 50;
// Test with size less than custom max
NCollection_LocalArray<int, customMaxSize> smallArray(20);
EXPECT_EQ(20, smallArray.Size());
// Test with size greater than custom max
NCollection_LocalArray<int, customMaxSize> largeArray(100);
EXPECT_EQ(100, largeArray.Size());
}
// Test with custom type
struct TestStruct
{
int a;
double b;
bool operator==(const TestStruct& other) const { return a == other.a && b == other.b; }
};
TEST(NCollection_LocalArrayTest, CustomType)
{
NCollection_LocalArray<TestStruct> array(5);
EXPECT_EQ(5, array.Size());
TestStruct ts{10, 3.14};
// Set and retrieve values
array[0] = ts;
EXPECT_TRUE(ts == array[0]);
}
// Test transition from stack to heap allocation and back
TEST(NCollection_LocalArrayTest, TransitionStackToHeap)
{
const int maxSize = 10;
NCollection_LocalArray<int, maxSize> array;
// Initially allocate in stack buffer
array.Allocate(5);
for (size_t i = 0; i < 5; ++i)
{
array[i] = static_cast<int>(i);
}
// Verify array contents
for (size_t i = 0; i < 5; ++i)
{
EXPECT_EQ(static_cast<int>(i), array[i]);
}
// Now allocate larger size, forcing heap allocation
array.Allocate(maxSize + 10);
for (size_t i = 0; i < maxSize + 10; ++i)
{
array[i] = static_cast<int>(i * 3);
}
// Verify heap allocation
for (size_t i = 0; i < maxSize + 10; ++i)
{
EXPECT_EQ(static_cast<int>(i * 3), array[i]);
}
// Now go back to stack allocation
array.Allocate(maxSize - 5);
for (size_t i = 0; i < maxSize - 5; ++i)
{
array[i] = static_cast<int>(i * 5);
}
// Verify stack allocation again
for (size_t i = 0; i < maxSize - 5; ++i)
{
EXPECT_EQ(static_cast<int>(i * 5), array[i]);
}
}

View File

@@ -0,0 +1,218 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <NCollection_Map.hxx>
#include <Standard_Integer.hxx>
#include <TCollection_AsciiString.hxx>
#include <gtest/gtest.h>
TEST(NCollection_MapTest, DefaultConstructor)
{
// Default constructor should create an empty map
NCollection_Map<Standard_Integer> aMap(101);
EXPECT_TRUE(aMap.IsEmpty());
EXPECT_EQ(0, aMap.Size());
EXPECT_EQ(0, aMap.Extent());
EXPECT_EQ(101, aMap.NbBuckets());
}
TEST(NCollection_MapTest, ConstructorWithBuckets)
{
// Constructor with number of buckets
const Standard_Integer nbBuckets = 100;
NCollection_Map<Standard_Integer> aMap(nbBuckets);
EXPECT_TRUE(aMap.IsEmpty());
EXPECT_EQ(0, aMap.Size());
EXPECT_EQ(0, aMap.Extent());
EXPECT_EQ(nbBuckets, aMap.NbBuckets());
}
TEST(NCollection_MapTest, AddAndContains)
{
NCollection_Map<Standard_Integer> aMap;
// Test Add method
EXPECT_TRUE(aMap.Add(10));
EXPECT_TRUE(aMap.Add(20));
EXPECT_TRUE(aMap.Add(30));
// Adding duplicates should return false
EXPECT_FALSE(aMap.Add(10));
EXPECT_FALSE(aMap.Add(20));
// Map size should account for unique elements only
EXPECT_EQ(3, aMap.Size());
// Test Contains
EXPECT_TRUE(aMap.Contains(10));
EXPECT_TRUE(aMap.Contains(20));
EXPECT_TRUE(aMap.Contains(30));
EXPECT_FALSE(aMap.Contains(40));
}
TEST(NCollection_MapTest, Remove)
{
NCollection_Map<Standard_Integer> aMap;
aMap.Add(10);
aMap.Add(20);
aMap.Add(30);
// Test Remove
EXPECT_TRUE(aMap.Remove(20));
EXPECT_EQ(2, aMap.Size());
EXPECT_FALSE(aMap.Contains(20));
EXPECT_TRUE(aMap.Contains(10));
EXPECT_TRUE(aMap.Contains(30));
// Try to remove non-existent element
EXPECT_FALSE(aMap.Remove(40));
EXPECT_EQ(2, aMap.Size());
}
TEST(NCollection_MapTest, Clear)
{
NCollection_Map<Standard_Integer> aMap;
aMap.Add(10);
aMap.Add(20);
aMap.Add(30);
EXPECT_FALSE(aMap.IsEmpty());
// Test Clear
aMap.Clear();
EXPECT_TRUE(aMap.IsEmpty());
EXPECT_EQ(0, aMap.Size());
EXPECT_FALSE(aMap.Contains(10));
EXPECT_FALSE(aMap.Contains(20));
EXPECT_FALSE(aMap.Contains(30));
}
TEST(NCollection_MapTest, Assignment)
{
NCollection_Map<Standard_Integer> aMap1;
aMap1.Add(10);
aMap1.Add(20);
aMap1.Add(30);
// Test assignment operator
NCollection_Map<Standard_Integer> aMap2;
aMap2 = aMap1;
// Check both maps have the same content
EXPECT_EQ(aMap1.Size(), aMap2.Size());
EXPECT_TRUE(aMap2.Contains(10));
EXPECT_TRUE(aMap2.Contains(20));
EXPECT_TRUE(aMap2.Contains(30));
// Modify original map to ensure deep copy
aMap1.Add(40);
aMap1.Remove(10);
EXPECT_EQ(3, aMap1.Size());
EXPECT_EQ(3, aMap2.Size());
EXPECT_TRUE(aMap2.Contains(10));
EXPECT_FALSE(aMap1.Contains(10));
EXPECT_TRUE(aMap1.Contains(40));
EXPECT_FALSE(aMap2.Contains(40));
}
TEST(NCollection_MapTest, IteratorAccess)
{
NCollection_Map<Standard_Integer> aMap;
aMap.Add(10);
aMap.Add(20);
aMap.Add(30);
// Test iteration using OCCT iterator
NCollection_Map<Standard_Integer>::Iterator it(aMap);
// Create set to check all keys are visited
std::set<Standard_Integer> foundKeys;
for (; it.More(); it.Next())
{
foundKeys.insert(it.Value());
}
// Check all keys were visited
EXPECT_EQ(3, foundKeys.size());
EXPECT_TRUE(foundKeys.find(10) != foundKeys.end());
EXPECT_TRUE(foundKeys.find(20) != foundKeys.end());
EXPECT_TRUE(foundKeys.find(30) != foundKeys.end());
}
TEST(NCollection_MapTest, Resize)
{
NCollection_Map<Standard_Integer> aMap(10);
// Add elements
for (Standard_Integer i = 0; i < 100; ++i)
{
aMap.Add(i);
}
// Check initial state
EXPECT_EQ(100, aMap.Size());
// Before resize, remember which elements are contained
std::vector<Standard_Integer> elements;
for (NCollection_Map<Standard_Integer>::Iterator it(aMap); it.More(); it.Next())
{
elements.push_back(it.Value());
}
// Test Resize
aMap.ReSize(200);
// Resize shouldn't change the map contents
EXPECT_EQ(100, aMap.Size());
for (const auto& element : elements)
{
EXPECT_TRUE(aMap.Contains(element));
}
}
TEST(NCollection_MapTest, ExhaustiveIterator)
{
const int NUM_ELEMENTS = 1000;
// Create a map with many elements to test iterator efficiency
NCollection_Map<Standard_Integer> aMap;
// Add many elements
for (int i = 0; i < NUM_ELEMENTS; ++i)
{
aMap.Add(i);
}
EXPECT_EQ(NUM_ELEMENTS, aMap.Size());
// Count elements using iterator
int count = 0;
int sum = 0;
NCollection_Map<Standard_Integer>::Iterator it(aMap);
for (; it.More(); it.Next())
{
sum += it.Value();
count++;
}
EXPECT_EQ(NUM_ELEMENTS, count);
// Calculate expected sum: 0 + 1 + 2 + ... + (NUM_ELEMENTS-1)
int expectedSum = (NUM_ELEMENTS * (NUM_ELEMENTS - 1)) / 2;
EXPECT_EQ(expectedSum, sum);
}

View File

@@ -0,0 +1,375 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <NCollection_Sequence.hxx>
#include <NCollection_IncAllocator.hxx>
#include <NCollection_BaseAllocator.hxx>
#include <gtest/gtest.h>
// Basic test type for the Sequence
typedef Standard_Integer ItemType;
// Custom class for testing complex types in the Sequence
class TestClass
{
public:
TestClass(int id = 0, const char* name = "")
: myId(id),
myName(name)
{
}
int GetId() const { return myId; }
const char* GetName() const { return myName.c_str(); }
bool operator==(const TestClass& other) const
{
return (myId == other.myId && myName == other.myName);
}
private:
int myId;
std::string myName;
};
TEST(NCollection_SequenceTest, BasicFunctions)
{
// Test default constructor and initial state
NCollection_Sequence<ItemType> aSeq;
EXPECT_TRUE(aSeq.IsEmpty());
EXPECT_EQ(aSeq.Size(), 0);
EXPECT_EQ(aSeq.Length(), 0);
// Test Append
aSeq.Append(10);
aSeq.Append(20);
aSeq.Append(30);
EXPECT_EQ(aSeq.Size(), 3);
EXPECT_FALSE(aSeq.IsEmpty());
// Test access operations
EXPECT_EQ(aSeq(1), 10);
EXPECT_EQ(aSeq(2), 20);
EXPECT_EQ(aSeq(3), 30);
EXPECT_EQ(aSeq.First(), 10);
EXPECT_EQ(aSeq.Last(), 30);
// Test bounds
EXPECT_EQ(aSeq.Lower(), 1);
EXPECT_EQ(aSeq.Upper(), 3);
}
TEST(NCollection_SequenceTest, ModifyingOperations)
{
NCollection_Sequence<ItemType> aSeq;
// Test Prepend
aSeq.Prepend(100);
aSeq.Prepend(200);
EXPECT_EQ(aSeq.Size(), 2);
EXPECT_EQ(aSeq.First(), 200);
EXPECT_EQ(aSeq.Last(), 100);
// Test SetValue
aSeq.SetValue(1, 210);
EXPECT_EQ(aSeq(1), 210);
// Test ChangeValue
aSeq.ChangeValue(2) = 110;
EXPECT_EQ(aSeq(2), 110);
// Test InsertBefore
aSeq.InsertBefore(1, 300);
EXPECT_EQ(aSeq.Size(), 3);
EXPECT_EQ(aSeq(1), 300);
EXPECT_EQ(aSeq(2), 210);
EXPECT_EQ(aSeq(3), 110);
// Test InsertAfter
aSeq.InsertAfter(2, 400);
EXPECT_EQ(aSeq.Size(), 4);
EXPECT_EQ(aSeq(1), 300);
EXPECT_EQ(aSeq(2), 210);
EXPECT_EQ(aSeq(3), 400);
EXPECT_EQ(aSeq(4), 110);
// Test Remove
aSeq.Remove(3);
EXPECT_EQ(aSeq.Size(), 3);
EXPECT_EQ(aSeq(1), 300);
EXPECT_EQ(aSeq(2), 210);
EXPECT_EQ(aSeq(3), 110);
// Test Remove with range
aSeq.Append(500);
aSeq.Append(600);
EXPECT_EQ(aSeq.Size(), 5);
aSeq.Remove(2, 4);
EXPECT_EQ(aSeq.Size(), 2);
EXPECT_EQ(aSeq(1), 300);
EXPECT_EQ(aSeq(2), 600);
}
TEST(NCollection_SequenceTest, IteratorFunctions)
{
NCollection_Sequence<ItemType> aSeq;
aSeq.Append(10);
aSeq.Append(20);
aSeq.Append(30);
// Test Iterator
NCollection_Sequence<ItemType>::Iterator anIt(aSeq);
EXPECT_TRUE(anIt.More());
EXPECT_EQ(anIt.Value(), 10);
anIt.Next();
EXPECT_TRUE(anIt.More());
EXPECT_EQ(anIt.Value(), 20);
anIt.Next();
EXPECT_TRUE(anIt.More());
EXPECT_EQ(anIt.Value(), 30);
anIt.Next();
EXPECT_FALSE(anIt.More());
// Test value modification through iterator
NCollection_Sequence<ItemType>::Iterator aModIt(aSeq);
aModIt.ChangeValue() = 15;
aModIt.Next();
aModIt.ChangeValue() = 25;
EXPECT_EQ(aSeq(1), 15);
EXPECT_EQ(aSeq(2), 25);
EXPECT_EQ(aSeq(3), 30);
// Test STL-style iteration
int index = 0;
int expectedValues[] = {15, 25, 30};
for (const auto& item : aSeq)
{
EXPECT_EQ(item, expectedValues[index++]);
}
EXPECT_EQ(index, 3);
}
TEST(NCollection_SequenceTest, CopyAndAssignment)
{
NCollection_Sequence<ItemType> aSeq1;
aSeq1.Append(10);
aSeq1.Append(20);
aSeq1.Append(30);
// Test copy constructor
NCollection_Sequence<ItemType> aSeq2(aSeq1);
EXPECT_EQ(aSeq2.Size(), 3);
EXPECT_EQ(aSeq2(1), 10);
EXPECT_EQ(aSeq2(2), 20);
EXPECT_EQ(aSeq2(3), 30);
// Test assignment operator
NCollection_Sequence<ItemType> aSeq3;
aSeq3 = aSeq1;
EXPECT_EQ(aSeq3.Size(), 3);
EXPECT_EQ(aSeq3(1), 10);
EXPECT_EQ(aSeq3(2), 20);
EXPECT_EQ(aSeq3(3), 30);
// Modify original and verify copies don't change
aSeq1.SetValue(2, 25);
EXPECT_EQ(aSeq1(2), 25);
EXPECT_EQ(aSeq2(2), 20);
EXPECT_EQ(aSeq3(2), 20);
}
TEST(NCollection_SequenceTest, CombiningSequences)
{
NCollection_Sequence<ItemType> aSeq1;
aSeq1.Append(10);
aSeq1.Append(20);
NCollection_Sequence<ItemType> aSeq2;
aSeq2.Append(30);
aSeq2.Append(40);
// Test Append(Sequence)
NCollection_Sequence<ItemType> aSeq3(aSeq1);
aSeq3.Append(aSeq2);
EXPECT_EQ(aSeq3.Size(), 4);
EXPECT_EQ(aSeq3(1), 10);
EXPECT_EQ(aSeq3(2), 20);
EXPECT_EQ(aSeq3(3), 30);
EXPECT_EQ(aSeq3(4), 40);
EXPECT_TRUE(aSeq2.IsEmpty()); // Original sequence should be emptied
// Test Prepend(Sequence)
aSeq2.Append(50);
aSeq2.Append(60);
NCollection_Sequence<ItemType> aSeq4;
aSeq4.Append(70);
aSeq4.Prepend(aSeq2);
EXPECT_EQ(aSeq4.Size(), 3);
EXPECT_EQ(aSeq4(1), 50);
EXPECT_EQ(aSeq4(2), 60);
EXPECT_EQ(aSeq4(3), 70);
EXPECT_TRUE(aSeq2.IsEmpty()); // Original sequence should be emptied
// Test InsertAfter(Sequence)
aSeq2.Append(80);
aSeq2.Append(90);
NCollection_Sequence<ItemType> aSeq5;
aSeq5.Append(100);
aSeq5.Append(110);
aSeq5.InsertAfter(1, aSeq2);
EXPECT_EQ(aSeq5.Size(), 4);
EXPECT_EQ(aSeq5(1), 100);
EXPECT_EQ(aSeq5(2), 80);
EXPECT_EQ(aSeq5(3), 90);
EXPECT_EQ(aSeq5(4), 110);
EXPECT_TRUE(aSeq2.IsEmpty()); // Original sequence should be emptied
}
TEST(NCollection_SequenceTest, AdvancedOperations)
{
NCollection_Sequence<ItemType> aSeq;
aSeq.Append(10);
aSeq.Append(20);
aSeq.Append(30);
aSeq.Append(40);
aSeq.Append(50);
// Test Exchange
aSeq.Exchange(2, 4);
EXPECT_EQ(aSeq(1), 10);
EXPECT_EQ(aSeq(2), 40);
EXPECT_EQ(aSeq(3), 30);
EXPECT_EQ(aSeq(4), 20);
EXPECT_EQ(aSeq(5), 50);
// Test Reverse
aSeq.Reverse();
EXPECT_EQ(aSeq(1), 50);
EXPECT_EQ(aSeq(2), 20);
EXPECT_EQ(aSeq(3), 30);
EXPECT_EQ(aSeq(4), 40);
EXPECT_EQ(aSeq(5), 10);
// Test Split
NCollection_Sequence<ItemType> aSeq2;
aSeq.Split(2, aSeq2);
EXPECT_EQ(aSeq.Size(), 1);
EXPECT_EQ(aSeq(1), 50);
EXPECT_EQ(aSeq2.Size(), 4);
EXPECT_EQ(aSeq2(1), 20);
EXPECT_EQ(aSeq2(2), 30);
EXPECT_EQ(aSeq2(3), 40);
EXPECT_EQ(aSeq2(4), 10);
// Test Clear
aSeq.Clear();
EXPECT_TRUE(aSeq.IsEmpty());
EXPECT_EQ(aSeq.Size(), 0);
}
TEST(NCollection_SequenceTest, ComplexTypeSequence)
{
NCollection_Sequence<TestClass> aSeq;
TestClass a(1, "First");
TestClass b(2, "Second");
TestClass c(3, "Third");
// Test appending complex types
aSeq.Append(a);
aSeq.Append(b);
aSeq.Append(c);
EXPECT_EQ(aSeq.Size(), 3);
EXPECT_EQ(aSeq(1).GetId(), 1);
EXPECT_STREQ(aSeq(1).GetName(), "First");
EXPECT_EQ(aSeq(2).GetId(), 2);
EXPECT_STREQ(aSeq(2).GetName(), "Second");
EXPECT_EQ(aSeq(3).GetId(), 3);
EXPECT_STREQ(aSeq(3).GetName(), "Third");
// Test modifying complex types
aSeq.ChangeValue(2) = TestClass(22, "Modified");
EXPECT_EQ(aSeq(2).GetId(), 22);
EXPECT_STREQ(aSeq(2).GetName(), "Modified");
// Test erasing with complex type
aSeq.Remove(1);
EXPECT_EQ(aSeq.Size(), 2);
EXPECT_EQ(aSeq.First().GetId(), 22);
}
TEST(NCollection_SequenceTest, AllocatorTest)
{
// Test with custom allocator
Handle(NCollection_BaseAllocator) aAlloc = new NCollection_IncAllocator();
NCollection_Sequence<ItemType> aSeq(aAlloc);
aSeq.Append(10);
aSeq.Append(20);
aSeq.Append(30);
EXPECT_EQ(aSeq.Size(), 3);
EXPECT_EQ(aSeq(1), 10);
EXPECT_EQ(aSeq(2), 20);
EXPECT_EQ(aSeq(3), 30);
// Test Clear with new allocator
Handle(NCollection_BaseAllocator) aAlloc2 = new NCollection_IncAllocator();
aSeq.Clear(aAlloc2);
EXPECT_TRUE(aSeq.IsEmpty());
// Add new items to verify the new allocator is working
aSeq.Append(40);
EXPECT_EQ(aSeq(1), 40);
}
TEST(NCollection_SequenceTest, MoveOperations)
{
// Test move constructor
NCollection_Sequence<ItemType> aSeq1;
aSeq1.Append(10);
aSeq1.Append(20);
aSeq1.Append(30);
NCollection_Sequence<ItemType> aSeq2(std::move(aSeq1));
EXPECT_TRUE(aSeq1.IsEmpty()); // Original sequence should be empty after move
EXPECT_EQ(aSeq2.Size(), 3);
EXPECT_EQ(aSeq2(1), 10);
EXPECT_EQ(aSeq2(2), 20);
EXPECT_EQ(aSeq2(3), 30);
// Test move assignment
NCollection_Sequence<ItemType> aSeq3;
aSeq3.Append(40);
NCollection_Sequence<ItemType> aSeq4;
aSeq4 = std::move(aSeq3);
EXPECT_TRUE(aSeq3.IsEmpty()); // Original sequence should be empty after move
EXPECT_EQ(aSeq4.Size(), 1);
EXPECT_EQ(aSeq4(1), 40);
}

View File

@@ -0,0 +1,301 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <NCollection_SparseArray.hxx>
#include <gtest/gtest.h>
// Basic test type for the SparseArray
typedef Standard_Integer ItemType;
// Custom class for testing complex types in the SparseArray
class TestClass
{
public:
TestClass(int id = 0, double value = 0.0)
: myId(id),
myValue(value)
{
}
bool operator==(const TestClass& other) const
{
return myId == other.myId && fabs(myValue - other.myValue) < 1e-10;
}
bool operator!=(const TestClass& other) const { return !(*this == other); }
int GetId() const { return myId; }
double GetValue() const { return myValue; }
void SetValue(double value) { myValue = value; }
private:
int myId;
double myValue;
};
TEST(NCollection_SparseArrayTest, BasicFunctions)
{
// Test constructor with increment
NCollection_SparseArray<ItemType> anArray(10);
// Test initial state
EXPECT_TRUE(anArray.IsEmpty());
EXPECT_EQ(anArray.Size(), 0);
EXPECT_EQ(anArray.Extent(), 0);
// Test setting values
anArray.SetValue(5, 55);
anArray.SetValue(15, 155);
EXPECT_FALSE(anArray.IsEmpty());
EXPECT_EQ(anArray.Size(), 2);
// Test value access
EXPECT_EQ(anArray.Value(5), 55);
EXPECT_EQ(anArray(15), 155);
// Test HasValue (IsBound)
EXPECT_TRUE(anArray.HasValue(5));
EXPECT_TRUE(anArray.IsBound(15));
EXPECT_FALSE(anArray.HasValue(10));
EXPECT_FALSE(anArray.IsBound(20));
// Test UnsetValue (UnBind)
EXPECT_TRUE(anArray.UnsetValue(5));
EXPECT_FALSE(anArray.HasValue(5));
EXPECT_EQ(anArray.Size(), 1);
// Test modifying a value
anArray.ChangeValue(15) = 255;
EXPECT_EQ(anArray.Value(15), 255);
}
TEST(NCollection_SparseArrayTest, LargeIndices)
{
NCollection_SparseArray<ItemType> anArray(10);
// Test with large indices
const Standard_Size largeIndex1 = 1000;
const Standard_Size largeIndex2 = 10000;
anArray.SetValue(largeIndex1, 1000);
anArray.SetValue(largeIndex2, 10000);
EXPECT_EQ(anArray.Size(), 2);
EXPECT_TRUE(anArray.HasValue(largeIndex1));
EXPECT_TRUE(anArray.HasValue(largeIndex2));
EXPECT_EQ(anArray.Value(largeIndex1), 1000);
EXPECT_EQ(anArray.Value(largeIndex2), 10000);
}
TEST(NCollection_SparseArrayTest, SparseDistribution)
{
NCollection_SparseArray<ItemType> anArray(8);
// Set values with sparse distribution
anArray.SetValue(3, 3);
anArray.SetValue(10, 10);
anArray.SetValue(17, 17);
anArray.SetValue(100, 100);
anArray.SetValue(1000, 1000);
EXPECT_EQ(anArray.Size(), 5);
EXPECT_TRUE(anArray.HasValue(3));
EXPECT_TRUE(anArray.HasValue(10));
EXPECT_TRUE(anArray.HasValue(17));
EXPECT_TRUE(anArray.HasValue(100));
EXPECT_TRUE(anArray.HasValue(1000));
// Test gaps have no value
EXPECT_FALSE(anArray.HasValue(4));
EXPECT_FALSE(anArray.HasValue(11));
EXPECT_FALSE(anArray.HasValue(101));
}
TEST(NCollection_SparseArrayTest, IteratorFunctions)
{
NCollection_SparseArray<ItemType> anArray(8);
// Set some values
anArray.SetValue(5, 50);
anArray.SetValue(10, 100);
anArray.SetValue(20, 200);
anArray.SetValue(30, 300);
// Test const iterator
NCollection_SparseArray<ItemType>::ConstIterator anIt(anArray);
// Check that iterator finds all values in some order
Standard_Boolean found5 = Standard_False;
Standard_Boolean found10 = Standard_False;
Standard_Boolean found20 = Standard_False;
Standard_Boolean found30 = Standard_False;
Standard_Size count = 0;
for (; anIt.More(); anIt.Next(), ++count)
{
Standard_Size index = anIt.Index();
ItemType value = anIt.Value();
if (index == 5 && value == 50)
found5 = Standard_True;
else if (index == 10 && value == 100)
found10 = Standard_True;
else if (index == 20 && value == 200)
found20 = Standard_True;
else if (index == 30 && value == 300)
found30 = Standard_True;
}
EXPECT_EQ(count, 4);
EXPECT_TRUE(found5);
EXPECT_TRUE(found10);
EXPECT_TRUE(found20);
EXPECT_TRUE(found30);
// Test non-const iterator
NCollection_SparseArray<ItemType>::Iterator aModIt(anArray);
// Modify values through iterator
for (; aModIt.More(); aModIt.Next())
{
aModIt.ChangeValue() *= 2;
}
// Check modified values
EXPECT_EQ(anArray.Value(5), 100);
EXPECT_EQ(anArray.Value(10), 200);
EXPECT_EQ(anArray.Value(20), 400);
EXPECT_EQ(anArray.Value(30), 600);
}
TEST(NCollection_SparseArrayTest, ComplexType)
{
NCollection_SparseArray<TestClass> anArray(10);
// Set values with complex type
anArray.SetValue(5, TestClass(5, 3.14));
anArray.SetValue(10, TestClass(10, 2.718));
EXPECT_EQ(anArray.Size(), 2);
// Check values
EXPECT_EQ(anArray.Value(5).GetId(), 5);
EXPECT_DOUBLE_EQ(anArray.Value(5).GetValue(), 3.14);
EXPECT_EQ(anArray.Value(10).GetId(), 10);
EXPECT_DOUBLE_EQ(anArray.Value(10).GetValue(), 2.718);
// Modify through ChangeValue
anArray.ChangeValue(5).SetValue(6.28);
EXPECT_DOUBLE_EQ(anArray.Value(5).GetValue(), 6.28);
// Test unset with complex type
EXPECT_TRUE(anArray.UnsetValue(5));
EXPECT_FALSE(anArray.HasValue(5));
}
TEST(NCollection_SparseArrayTest, Clear)
{
NCollection_SparseArray<ItemType> anArray(8);
// Set some values
anArray.SetValue(5, 5);
anArray.SetValue(10, 10);
anArray.SetValue(15, 15);
EXPECT_EQ(anArray.Size(), 3);
// Clear the array
anArray.Clear();
EXPECT_TRUE(anArray.IsEmpty());
EXPECT_EQ(anArray.Size(), 0);
EXPECT_FALSE(anArray.HasValue(5));
EXPECT_FALSE(anArray.HasValue(10));
EXPECT_FALSE(anArray.HasValue(15));
}
TEST(NCollection_SparseArrayTest, DataMapInterface)
{
NCollection_SparseArray<ItemType> anArray(10);
// Test Bind method
anArray.Bind(5, 50);
anArray.Bind(15, 150);
EXPECT_TRUE(anArray.IsBound(5));
EXPECT_TRUE(anArray.IsBound(15));
// Test Find method
EXPECT_EQ(anArray.Find(5), 50);
EXPECT_EQ(anArray.Find(15), 150);
// Test ChangeFind method
anArray.ChangeFind(5) = 55;
EXPECT_EQ(anArray.Find(5), 55);
// Test UnBind method
EXPECT_TRUE(anArray.UnBind(5));
EXPECT_FALSE(anArray.IsBound(5));
EXPECT_EQ(anArray.Size(), 1);
}
TEST(NCollection_SparseArrayTest, AssignAndExchange)
{
// Create and populate first array
NCollection_SparseArray<ItemType> anArray1(10);
anArray1.SetValue(5, 50);
anArray1.SetValue(15, 150);
// Test Assign method
NCollection_SparseArray<ItemType> anArray2(20);
anArray2.SetValue(7, 70);
anArray2.Assign(anArray1);
EXPECT_EQ(anArray2.Size(), 2);
EXPECT_TRUE(anArray2.HasValue(5));
EXPECT_TRUE(anArray2.HasValue(15));
EXPECT_EQ(anArray2.Value(5), 50);
EXPECT_EQ(anArray2.Value(15), 150);
EXPECT_FALSE(anArray2.HasValue(7)); // Should be removed after Assign
// Test Exchange method
NCollection_SparseArray<ItemType> anArray3(30);
anArray3.SetValue(10, 100);
anArray3.SetValue(20, 200);
anArray2.Exchange(anArray3);
// Check anArray2 after exchange (should have anArray3's values)
EXPECT_EQ(anArray2.Size(), 2);
EXPECT_TRUE(anArray2.HasValue(10));
EXPECT_TRUE(anArray2.HasValue(20));
EXPECT_EQ(anArray2.Value(10), 100);
EXPECT_EQ(anArray2.Value(20), 200);
EXPECT_FALSE(anArray2.HasValue(5));
EXPECT_FALSE(anArray2.HasValue(15));
// Check anArray3 after exchange (should have anArray2's values)
EXPECT_EQ(anArray3.Size(), 2);
EXPECT_TRUE(anArray3.HasValue(5));
EXPECT_TRUE(anArray3.HasValue(15));
EXPECT_EQ(anArray3.Value(5), 50);
EXPECT_EQ(anArray3.Value(15), 150);
EXPECT_FALSE(anArray3.HasValue(10));
EXPECT_FALSE(anArray3.HasValue(20));
}

View File

@@ -0,0 +1,382 @@
// Copyright (c) 2025 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <NCollection_BaseAllocator.hxx>
#include <NCollection_Vector.hxx>
#include <Standard_Integer.hxx>
#include <gtest/gtest.h>
TEST(NCollection_VectorTest, DefaultConstructor)
{
// Default constructor should create an empty vector
NCollection_Vector<Standard_Integer> aVector;
EXPECT_EQ(0, aVector.Length());
EXPECT_TRUE(aVector.IsEmpty());
}
TEST(NCollection_VectorTest, ResizeConstructor)
{
// Test constructor with initial size
const Standard_Integer initialSize = 10;
const Standard_Integer initialValue = 42;
NCollection_Vector<Standard_Integer> aVector(initialSize);
// Initialize all elements to the same value
for (Standard_Integer i = 0; i < initialSize; i++)
{
aVector.SetValue(i, initialValue);
}
EXPECT_EQ(initialSize, aVector.Length());
EXPECT_FALSE(aVector.IsEmpty());
// Check all values are initialized
for (Standard_Integer i = 0; i < initialSize; i++)
{
EXPECT_EQ(initialValue, aVector(i));
}
}
TEST(NCollection_VectorTest, Append)
{
NCollection_Vector<Standard_Integer> aVector;
// Test Append method
aVector.Append(10);
aVector.Append(20);
aVector.Append(30);
EXPECT_EQ(3, aVector.Length());
EXPECT_EQ(10, aVector(0));
EXPECT_EQ(20, aVector(1));
EXPECT_EQ(30, aVector(2));
}
TEST(NCollection_VectorTest, SetValue)
{
NCollection_Vector<Standard_Integer> aVector(5, 0);
// Test SetValue method
aVector.SetValue(2, 42);
EXPECT_EQ(42, aVector(2));
EXPECT_EQ(0, aVector(0));
EXPECT_EQ(0, aVector(1));
// Test operator()
aVector(3) = 99;
EXPECT_EQ(99, aVector(3));
}
TEST(NCollection_VectorTest, Value)
{
NCollection_Vector<Standard_Integer> aVector;
aVector.Append(10);
aVector.Append(20);
// Test Value and operator()
EXPECT_EQ(10, aVector.Value(0));
EXPECT_EQ(20, aVector.Value(1));
EXPECT_EQ(aVector.Value(0), aVector(0));
EXPECT_EQ(aVector.Value(1), aVector(1));
}
TEST(NCollection_VectorTest, ChangeValue)
{
NCollection_Vector<Standard_Integer> aVector;
aVector.Append(10);
aVector.Append(20);
// Test ChangeValue
aVector.ChangeValue(1) = 25;
EXPECT_EQ(25, aVector(1));
// Equivalent using operator()
aVector(0) = 15;
EXPECT_EQ(15, aVector(0));
}
TEST(NCollection_VectorTest, FirstLast)
{
NCollection_Vector<Standard_Integer> aVector;
aVector.Append(10);
aVector.Append(20);
aVector.Append(30);
// Test First and Last
EXPECT_EQ(10, aVector.First());
EXPECT_EQ(30, aVector.Last());
// Test ChangeFirst and ChangeLast
aVector.ChangeFirst() = 15;
aVector.ChangeLast() = 35;
EXPECT_EQ(15, aVector.First());
EXPECT_EQ(35, aVector.Last());
}
TEST(NCollection_VectorTest, CopyConstructor)
{
NCollection_Vector<Standard_Integer> aVector1;
aVector1.Append(10);
aVector1.Append(20);
aVector1.Append(30);
// Test copy constructor
NCollection_Vector<Standard_Integer> aVector2(aVector1);
EXPECT_EQ(aVector1.Length(), aVector2.Length());
for (Standard_Integer i = 0; i < aVector1.Length(); i++)
{
EXPECT_EQ(aVector1(i), aVector2(i));
}
// Modify original to ensure deep copy
aVector1(1) = 25;
EXPECT_EQ(20, aVector2(1));
}
TEST(NCollection_VectorTest, AssignmentOperator)
{
NCollection_Vector<Standard_Integer> aVector1;
aVector1.Append(10);
aVector1.Append(20);
aVector1.Append(30);
// Test assignment operator
NCollection_Vector<Standard_Integer> aVector2;
aVector2 = aVector1;
EXPECT_EQ(aVector1.Length(), aVector2.Length());
for (Standard_Integer i = 0; i < aVector1.Length(); i++)
{
EXPECT_EQ(aVector1(i), aVector2(i));
}
// Modify original to ensure deep copy
aVector1(1) = 25;
EXPECT_EQ(20, aVector2(1));
}
TEST(NCollection_VectorTest, Clear)
{
NCollection_Vector<Standard_Integer> aVector;
aVector.Append(10);
aVector.Append(20);
// Test Clear
aVector.Clear();
EXPECT_EQ(0, aVector.Length());
EXPECT_TRUE(aVector.IsEmpty());
}
TEST(NCollection_VectorTest, Iterator)
{
NCollection_Vector<Standard_Integer> aVector;
aVector.Append(10);
aVector.Append(20);
aVector.Append(30);
// Test iterator
Standard_Integer sum = 0;
for (NCollection_Vector<Standard_Integer>::Iterator it(aVector); it.More(); it.Next())
{
sum += it.Value();
}
EXPECT_EQ(60, sum);
// Test modifying values through iterator
for (NCollection_Vector<Standard_Integer>::Iterator it(aVector); it.More(); it.Next())
{
it.ChangeValue() *= 2;
}
EXPECT_EQ(20, aVector(0));
EXPECT_EQ(40, aVector(1));
EXPECT_EQ(60, aVector(2));
}
TEST(NCollection_VectorTest, STLIterators)
{
NCollection_Vector<Standard_Integer> aVector;
aVector.Append(10);
aVector.Append(20);
aVector.Append(30);
// Test C++11 range-based for loop with STL-style iterators
Standard_Integer sum = 0;
for (const auto& val : aVector)
{
sum += val;
}
EXPECT_EQ(60, sum);
// Test modification through iterator
sum = 0;
for (auto& val : aVector)
{
val *= 2; // Double each value
sum += val;
}
EXPECT_EQ(120, sum);
// Verify the modifications
EXPECT_EQ(20, aVector(0));
EXPECT_EQ(40, aVector(1));
EXPECT_EQ(60, aVector(2));
}
TEST(NCollection_VectorTest, Grow)
{
NCollection_Vector<Standard_Integer> aVector;
// Test automatic resize through many appends
for (Standard_Integer i = 0; i < 1000; i++)
{
aVector.Append(i);
}
EXPECT_EQ(1000, aVector.Length());
for (Standard_Integer i = 0; i < 1000; i++)
{
EXPECT_EQ(i, aVector(i));
}
}
TEST(NCollection_VectorTest, Move)
{
NCollection_Vector<Standard_Integer> aVector1;
aVector1.Append(10);
aVector1.Append(20);
// Test Move constructor
NCollection_Vector<Standard_Integer> aVector2 = std::move(aVector1);
EXPECT_EQ(0, aVector1.Length()); // aVector1 should be empty after move
EXPECT_EQ(2, aVector2.Length());
EXPECT_EQ(10, aVector2(0));
EXPECT_EQ(20, aVector2(1));
// Test Move assignment
NCollection_Vector<Standard_Integer> aVector3;
aVector3.Append(30);
aVector3 = std::move(aVector2);
EXPECT_EQ(0, aVector2.Length()); // aVector2 should be empty after move
EXPECT_EQ(2, aVector3.Length());
EXPECT_EQ(10, aVector3(0));
EXPECT_EQ(20, aVector3(1));
}
TEST(NCollection_VectorTest, EraseLast)
{
NCollection_Vector<Standard_Integer> aVector;
aVector.Append(10);
aVector.Append(20);
aVector.Append(30);
EXPECT_EQ(3, aVector.Length());
// Test EraseLast method
aVector.EraseLast();
EXPECT_EQ(2, aVector.Length());
EXPECT_EQ(10, aVector(0));
EXPECT_EQ(20, aVector(1));
// Remove another element
aVector.EraseLast();
EXPECT_EQ(1, aVector.Length());
EXPECT_EQ(10, aVector(0));
// Remove the last element
aVector.EraseLast();
EXPECT_EQ(0, aVector.Length());
EXPECT_TRUE(aVector.IsEmpty());
// Calling EraseLast on an empty vector should not cause errors
aVector.EraseLast();
EXPECT_EQ(0, aVector.Length());
}
TEST(NCollection_VectorTest, Appended)
{
NCollection_Vector<Standard_Integer> aVector;
// Test Appended method - returns reference to the appended element
Standard_Integer& ref1 = aVector.Appended();
ref1 = 10;
Standard_Integer& ref2 = aVector.Appended();
ref2 = 20;
EXPECT_EQ(2, aVector.Length());
EXPECT_EQ(10, aVector(0));
EXPECT_EQ(20, aVector(1));
// Modify through the reference
ref1 = 15;
EXPECT_EQ(15, aVector(0));
}
TEST(NCollection_VectorTest, CustomAllocator)
{
// Test with custom allocator
Handle(NCollection_BaseAllocator) anAlloc = NCollection_BaseAllocator::CommonBaseAllocator();
NCollection_Vector<Standard_Integer> aVector(256, anAlloc);
// Verify vector works with custom allocator
aVector.Append(10);
aVector.Append(20);
aVector.Append(30);
EXPECT_EQ(3, aVector.Length());
EXPECT_EQ(10, aVector(0));
EXPECT_EQ(20, aVector(1));
EXPECT_EQ(30, aVector(2));
// Test clear with custom allocator
aVector.Clear();
EXPECT_EQ(0, aVector.Length());
}
TEST(NCollection_VectorTest, SetIncrement)
{
NCollection_Vector<Standard_Integer> aVector;
// SetIncrement only works on empty vectors
aVector.SetIncrement(512);
// Fill the vector to test the custom increment size
for (Standard_Integer i = 0; i < 1000; i++)
{
aVector.Append(i);
}
EXPECT_EQ(1000, aVector.Length());
// Verify data integrity with the custom increment
for (Standard_Integer i = 0; i < 1000; i++)
{
EXPECT_EQ(i, aVector(i));
}
}

View File

@@ -28,28 +28,29 @@ namespace opencascade
//! The default value for the seed is optimal for general cases at a certain hash size.
namespace MurmurHash
{
uint32_t MurmurHash2A(const void* theKey, int theLen, uint32_t theSeed);
uint64_t MurmurHash64A(const void* theKey, int theLen, uint64_t theSeed);
uint32_t MurmurHash2A(const void* theKey, int theLen, uint32_t theSeed) noexcept;
uint64_t MurmurHash64A(const void* theKey, int theLen, uint64_t theSeed) noexcept;
template <typename T1, typename T = size_t>
typename std::enable_if<sizeof(T) == 8, uint64_t>::type hash_combine(
const T1& theValue,
const int theLen = sizeof(T1),
const T theSeed = 0xA329F1D3A586ULL)
const T theSeed = 0xA329F1D3A586ULL) noexcept
{
return MurmurHash::MurmurHash64A(&theValue, theLen, theSeed);
}
template <typename T1, typename T = size_t>
typename std::enable_if<sizeof(T) != 8, T>::type hash_combine(const T1& theValue,
const int theLen = sizeof(T1),
const T theSeed = 0xc70f6907U)
typename std::enable_if<sizeof(T) != 8, T>::type hash_combine(
const T1& theValue,
const int theLen = sizeof(T1),
const T theSeed = 0xc70f6907U) noexcept
{
return static_cast<T>(MurmurHash::MurmurHash2A(&theValue, theLen, theSeed));
}
template <typename T = size_t>
constexpr T optimalSeed()
constexpr T optimalSeed() noexcept
{
return sizeof(T) == 8 ? static_cast<T>(0xA329F1D3A586ULL) : static_cast<T>(0xc70f6907U);
}
@@ -63,47 +64,48 @@ constexpr T optimalSeed()
//! The default value for the seed is optimal for general cases at a certain hash size.
namespace FNVHash
{
uint32_t FNVHash1A(const void* theKey, int theLen, uint32_t theSeed);
uint64_t FNVHash64A(const void* theKey, int theLen, uint64_t theSeed);
uint32_t FNVHash1A(const void* theKey, int theLen, uint32_t theSeed) noexcept;
uint64_t FNVHash64A(const void* theKey, int theLen, uint64_t theSeed) noexcept;
template <typename T1, typename T = size_t>
static typename std::enable_if<sizeof(T) == 8, uint64_t>::type hash_combine(
const T1& theValue,
const int theLen = sizeof(T1),
const T theSeed = 14695981039346656037ULL)
const T theSeed = 14695981039346656037ULL) noexcept
{
return FNVHash::FNVHash64A(&theValue, theLen, theSeed);
}
template <typename T1, typename T = size_t>
static typename std::enable_if<sizeof(T) != 8, T>::type hash_combine(const T1& theValue,
const int theLen = sizeof(T1),
const T theSeed = 2166136261U)
static typename std::enable_if<sizeof(T) != 8, T>::type hash_combine(
const T1& theValue,
const int theLen = sizeof(T1),
const T theSeed = 2166136261U) noexcept
{
return static_cast<T>(FNVHash::FNVHash1A(&theValue, theLen, theSeed));
}
template <typename T = size_t>
constexpr T optimalSeed()
constexpr T optimalSeed() noexcept
{
return sizeof(T) == 8 ? static_cast<T>(14695981039346656037ULL) : static_cast<T>(2166136261U);
}
}; // namespace FNVHash
template <typename T1, typename T = size_t>
T hash(const T1 theValue) noexcept
T hash(const T1& theValue) noexcept
{
return opencascade::MurmurHash::hash_combine<T1, T>(theValue);
}
template <typename T1, typename T = size_t>
T hashBytes(const T1* theKey, int theLen)
T hashBytes(const T1* theKey, int theLen) noexcept
{
return opencascade::MurmurHash::hash_combine<T1, T>(*theKey, theLen);
}
template <typename T1, typename T = size_t>
T hash_combine(const T1 theValue, const int theLen, const T theSeed)
T hash_combine(const T1& theValue, const int theLen, const T theSeed) noexcept
{
return opencascade::MurmurHash::hash_combine<T1, T>(theValue, theLen, theSeed);
}

View File

@@ -19,24 +19,50 @@ namespace MurmurHash
{
namespace MurmurHashUtils
{
inline uint64_t shift_mix(uint64_t theV)
inline uint64_t shift_mix(uint64_t theV) noexcept
{
return theV ^ (theV >> 47);
}
// Loads n bytes, where 1 <= n < 8.
inline uint64_t load_bytes(const char* thePnt, int theNb)
// Loads n bytes, where 1 <= n < 8
inline uint64_t load_bytes(const char* thePnt, int theNb) noexcept
{
uint64_t aRes = 0;
--theNb;
do
aRes = (aRes << 8) + static_cast<unsigned char>(thePnt[theNb]);
while (--theNb >= 0);
return aRes;
// Initialize result value
uint64_t aResult = 0;
// Use switch with fall-through for better performance and branch prediction
switch (theNb)
{
case 7:
aResult = (static_cast<uint64_t>(static_cast<unsigned char>(thePnt[6])) << 48) | aResult;
Standard_FALLTHROUGH
case 6:
aResult = (static_cast<uint64_t>(static_cast<unsigned char>(thePnt[5])) << 40) | aResult;
Standard_FALLTHROUGH
case 5:
aResult = (static_cast<uint64_t>(static_cast<unsigned char>(thePnt[4])) << 32) | aResult;
Standard_FALLTHROUGH
case 4:
aResult = (static_cast<uint64_t>(static_cast<unsigned char>(thePnt[3])) << 24) | aResult;
Standard_FALLTHROUGH
case 3:
aResult = (static_cast<uint64_t>(static_cast<unsigned char>(thePnt[2])) << 16) | aResult;
Standard_FALLTHROUGH
case 2:
aResult = (static_cast<uint64_t>(static_cast<unsigned char>(thePnt[1])) << 8) | aResult;
Standard_FALLTHROUGH
case 1:
aResult = static_cast<uint64_t>(static_cast<unsigned char>(thePnt[0])) | aResult;
Standard_FALLTHROUGH
default:
break;
}
return aResult;
}
template <typename T>
inline T unaligned_load(const char* thePnt)
inline T unaligned_load(const char* thePnt) noexcept
{
T aRes;
memcpy(&aRes, thePnt, sizeof(aRes));
@@ -48,7 +74,7 @@ inline T unaligned_load(const char* thePnt)
// function : MurmurHash64A
// purpose :
//=======================================================================
inline uint64_t MurmurHash64A(const void* theKey, int theLen, uint64_t theSeed)
inline uint64_t MurmurHash64A(const void* theKey, int theLen, uint64_t theSeed) noexcept
{
static constexpr uint64_t aMul = (((uint64_t)0xc6a4a793UL) << 32UL) + (uint64_t)0x5bd1e995UL;
const char* const aBuf = static_cast<const char*>(theKey);
@@ -80,11 +106,11 @@ inline uint64_t MurmurHash64A(const void* theKey, int theLen, uint64_t theSeed)
// function : MurmurHash2A
// purpose :
//=======================================================================
inline uint32_t MurmurHash2A(const void* theKey, int theLen, uint32_t theSeed)
inline uint32_t MurmurHash2A(const void* theKey, int theLen, uint32_t theSeed) noexcept
{
const uint32_t aMul = 0x5bd1e995;
uint32_t aHash = theSeed ^ theLen;
const char* aBuf = static_cast<const char*>(theKey);
constexpr uint32_t aMul = 0x5bd1e995;
uint32_t aHash = theSeed ^ theLen;
const char* aBuf = static_cast<const char*>(theKey);
// Mix 4 bytes at a time into the hash.
while (theLen >= 4)
@@ -131,7 +157,7 @@ namespace FNVHash
// function : FNVHash1A
// purpose :
//=======================================================================
inline uint32_t FNVHash1A(const void* theKey, int theLen, uint32_t theSeed)
inline uint32_t FNVHash1A(const void* theKey, int theLen, uint32_t theSeed) noexcept
{
const char* cptr = static_cast<const char*>(theKey);
for (; theLen; --theLen)
@@ -146,7 +172,7 @@ inline uint32_t FNVHash1A(const void* theKey, int theLen, uint32_t theSeed)
// function : FNVHash64A
// purpose :
//=======================================================================
inline uint64_t FNVHash64A(const void* theKey, int theLen, uint64_t theSeed)
inline uint64_t FNVHash64A(const void* theKey, int theLen, uint64_t theSeed) noexcept
{
const char* cptr = static_cast<const char*>(theKey);
for (; theLen; --theLen)

View File

@@ -193,8 +193,11 @@ provider.STEP.OCC.write.color : 1
provider.STEP.OCC.write.nonmanifold : 0
provider.STEP.OCC.write.name : 1
provider.STEP.OCC.write.layer : 1
provider.STEP.OCC.write.material : 1
provider.STEP.OCC.write.vismaterial : 0
provider.STEP.OCC.write.props : 1
provider.STEP.OCC.write.model.type : 0
provider.STEP.OCC.write.cleanduplicates : 0
provider.STEP.OCC.healing.tolerance3d : 1e-06
provider.STEP.OCC.healing.max.tolerance3d : 1
provider.STEP.OCC.healing.min.tolerance3d : 1e-07

View File

@@ -139,7 +139,10 @@ provider.STEP.OCC.write.nonmanifold : 0
provider.STEP.OCC.write.name : 1
provider.STEP.OCC.write.layer : 1
provider.STEP.OCC.write.props : 1
provider.STEP.OCC.write.material : 1
provider.STEP.OCC.write.vismaterial : 0
provider.STEP.OCC.write.model.type : 0
provider.STEP.OCC.write.cleanduplicates : 0
provider.STEP.OCC.healing.tolerance3d : 1e-06
provider.STEP.OCC.healing.max.tolerance3d : 1
provider.STEP.OCC.healing.min.tolerance3d : 1e-07