Coverage Report

Created: 2026-04-01 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/assimp/code/PostProcessing/RemoveRedundantMaterials.cpp
Line
Count
Source
1
/*
2
---------------------------------------------------------------------------
3
Open Asset Import Library (assimp)
4
---------------------------------------------------------------------------
5
6
Copyright (c) 2006-2026, assimp team
7
8
All rights reserved.
9
10
Redistribution and use of this software in source and binary forms,
11
with or without modification, are permitted provided that the following
12
conditions are met:
13
14
* Redistributions of source code must retain the above
15
  copyright notice, this list of conditions and the
16
  following disclaimer.
17
18
* Redistributions in binary form must reproduce the above
19
  copyright notice, this list of conditions and the
20
  following disclaimer in the documentation and/or other
21
  materials provided with the distribution.
22
23
* Neither the name of the assimp team, nor the names of its
24
  contributors may be used to endorse or promote products
25
  derived from this software without specific prior
26
  written permission of the assimp team.
27
28
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39
---------------------------------------------------------------------------
40
*/
41
/** @file RemoveRedundantMaterials.cpp
42
 *  @brief Implementation of the "RemoveRedundantMaterials" post processing step
43
*/
44
45
// internal headers
46
#include "RemoveRedundantMaterials.h"
47
#include <assimp/ParsingUtils.h>
48
#include "ProcessHelper.h"
49
#include "Material/MaterialSystem.h"
50
#include <assimp/Exceptional.h>
51
#include <stdio.h>
52
53
using namespace Assimp;
54
55
// ------------------------------------------------------------------------------------------------
56
// Constructor to be privately used by Importer
57
5.13k
RemoveRedundantMatsProcess::RemoveRedundantMatsProcess() : mConfigFixedMaterials() {}
58
59
// ------------------------------------------------------------------------------------------------
60
// Returns whether the processing step is present in the given flag field.
61
1.54k
bool RemoveRedundantMatsProcess::IsActive( unsigned int pFlags) const {
62
1.54k
    return (pFlags & aiProcess_RemoveRedundantMaterials) != 0;
63
1.54k
}
64
65
// ------------------------------------------------------------------------------------------------
66
// Setup import properties
67
1.54k
void RemoveRedundantMatsProcess::SetupProperties(const Importer* pImp) {
68
    // Get value of AI_CONFIG_PP_RRM_EXCLUDE_LIST
69
1.54k
    mConfigFixedMaterials = pImp->GetPropertyString(AI_CONFIG_PP_RRM_EXCLUDE_LIST,"");
70
1.54k
}
71
72
// ------------------------------------------------------------------------------------------------
73
// Executes the post processing step on the given imported data.
74
1.54k
void RemoveRedundantMatsProcess::Execute( aiScene* pScene) {
75
1.54k
    ASSIMP_LOG_DEBUG("RemoveRedundantMatsProcess begin");
76
77
1.54k
    unsigned int redundantRemoved = 0, unreferencedRemoved = 0;
78
1.54k
    if (pScene->mNumMaterials == 0) {
79
0
        return;
80
0
    }
81
82
    // Find out which materials are referenced by meshes
83
1.54k
    std::vector<bool> abReferenced(pScene->mNumMaterials,false);
84
2.98k
    for (unsigned int i = 0;i < pScene->mNumMeshes;++i) {
85
1.43k
        abReferenced[pScene->mMeshes[i]->mMaterialIndex] = true;
86
1.43k
    }
87
88
    // If a list of materials to be excluded was given, match the list with
89
    // our imported materials and 'salt' all positive matches to ensure that
90
    // we get unique hashes later.
91
1.54k
    if (mConfigFixedMaterials.length()) {
92
0
        std::list<std::string> strings;
93
0
        ConvertListToStrings(mConfigFixedMaterials,strings);
94
95
0
        for (unsigned int i = 0; i < pScene->mNumMaterials;++i) {
96
0
            aiMaterial* mat = pScene->mMaterials[i];
97
0
            ai_assert(mat != nullptr);
98
0
            aiString name;
99
0
            mat->Get(AI_MATKEY_NAME,name);
100
101
0
            if (name.length != 0) {
102
0
                std::list<std::string>::const_iterator it = std::find(strings.begin(), strings.end(), name.data);
103
0
                if (it != strings.end()) {
104
                    // Our brilliant 'salt': A single material property with ~ as first
105
                    // character to mark it as internal and temporary.
106
0
                    const int dummy = 1;
107
0
                    ((aiMaterial*)mat)->AddProperty(&dummy,1,"~RRM.UniqueMaterial",0,0);
108
109
                    // Keep this material even if no mesh references it
110
0
                    abReferenced[i] = true;
111
0
                    ASSIMP_LOG_VERBOSE_DEBUG( "Found positive match in exclusion list: \'", name.data, "\'");
112
0
                }
113
0
            }
114
0
        }
115
0
    }
116
117
    // TODO: re-implement this algorithm to work in-place
118
1.54k
    unsigned int *aiMappingTable = new unsigned int[pScene->mNumMaterials];
119
4.16k
    for ( unsigned int i=0; i<pScene->mNumMaterials; i++ ) {
120
2.62k
        aiMappingTable[ i ] = 0;
121
2.62k
    }
122
1.54k
    unsigned int iNewNum = 0;
123
124
    // Iterate through all materials and calculate a hash for them
125
    // store all hashes in a list and so a quick search whether
126
    // we do already have a specific hash. This allows us to
127
    // determine which materials are identical.
128
1.54k
    uint32_t *aiHashes = new uint32_t[ pScene->mNumMaterials ];
129
4.16k
    for (unsigned int i = 0; i < pScene->mNumMaterials;++i) {
130
        // No mesh is referencing this material, remove it.
131
2.62k
        if (!abReferenced[i]) {
132
1.22k
            ++unreferencedRemoved;
133
1.22k
            delete pScene->mMaterials[i];
134
1.22k
            pScene->mMaterials[i] = nullptr;
135
1.22k
            continue;
136
1.22k
        }
137
138
        // Check all previously mapped materials for a matching hash.
139
        // On a match we can delete this material and just make it ref to the same index.
140
1.40k
        uint32_t me = aiHashes[i] = ComputeMaterialHash(pScene->mMaterials[i]);
141
1.73k
        for (unsigned int a = 0; a < i;++a) {
142
357
            if (abReferenced[a] && me == aiHashes[a]) {
143
20
                ++redundantRemoved;
144
20
                me = 0;
145
20
                aiMappingTable[i] = aiMappingTable[a];
146
20
                delete pScene->mMaterials[i];
147
20
                pScene->mMaterials[i] = nullptr;
148
20
                break;
149
20
            }
150
357
        }
151
        // This is a new material that is referenced, add to the map.
152
1.40k
        if (me) {
153
1.38k
            aiMappingTable[i] = iNewNum++;
154
1.38k
        }
155
1.40k
    }
156
    // If the new material count differs from the original,
157
    // we need to rebuild the material list and remap mesh material indexes.
158
1.54k
    if (iNewNum < 1) {
159
326
        delete [] aiMappingTable;
160
326
        delete [] aiHashes;
161
326
        pScene->mNumMaterials = 0;
162
326
        return;
163
326
    }
164
1.22k
    if (iNewNum != pScene->mNumMaterials) {
165
905
        ai_assert(iNewNum > 0);
166
905
        aiMaterial** ppcMaterials = new aiMaterial*[iNewNum];
167
905
        ::memset(ppcMaterials,0,sizeof(void*)*iNewNum);
168
2.81k
        for (unsigned int p = 0; p < pScene->mNumMaterials;++p) {
169
            // if the material is not referenced ... remove it
170
1.91k
            if (!abReferenced[p]) {
171
894
                continue;
172
894
            }
173
174
            // generate new names for modified materials that had no names
175
1.02k
            const unsigned int idx = aiMappingTable[p];
176
1.02k
            if (ppcMaterials[idx]) {
177
20
                aiString sz;
178
20
                if( ppcMaterials[idx]->Get(AI_MATKEY_NAME, sz) != AI_SUCCESS ) {
179
8
                    sz.length = ::ai_snprintf(sz.data, AI_MAXLEN,"JoinedMaterial_#%u",p);
180
8
                    ((aiMaterial*)ppcMaterials[idx])->AddProperty(&sz,AI_MATKEY_NAME);
181
8
                }
182
1.00k
            } else {
183
1.00k
                ppcMaterials[idx] = pScene->mMaterials[p];
184
1.00k
            }
185
1.02k
        }
186
        // update all material indices
187
1.94k
        for (unsigned int p = 0; p < pScene->mNumMeshes;++p) {
188
1.04k
            aiMesh* mesh = pScene->mMeshes[p];
189
1.04k
            ai_assert(nullptr != mesh);
190
1.04k
            mesh->mMaterialIndex = aiMappingTable[mesh->mMaterialIndex];
191
1.04k
        }
192
        // delete the old material list
193
905
        delete[] pScene->mMaterials;
194
905
        pScene->mMaterials = ppcMaterials;
195
905
        pScene->mNumMaterials = iNewNum;
196
905
    }
197
    // delete temporary storage
198
1.22k
    delete[] aiHashes;
199
1.22k
    delete[] aiMappingTable;
200
201
1.22k
    if (redundantRemoved == 0 && unreferencedRemoved == 0) {
202
317
        ASSIMP_LOG_DEBUG("RemoveRedundantMatsProcess finished ");
203
905
    } else {
204
        ASSIMP_LOG_INFO("RemoveRedundantMatsProcess finished. Removed ", redundantRemoved, " redundant and ",
205
905
            unreferencedRemoved, " unused materials.");
206
905
    }
207
1.22k
}