Avoid a race in MatModels loading

Add a mutex to ensure an SGMatModels only loads its models once. Caught
be ASan, hurrah.
This commit is contained in:
James Turner 2020-08-14 16:48:51 +01:00
parent b874201806
commit 297e509576
2 changed files with 35 additions and 31 deletions

View File

@ -103,37 +103,39 @@ SGMatModel::get_model_count( SGPropertyNode *prop_root )
inline void inline void
SGMatModel::load_models( SGPropertyNode *prop_root ) SGMatModel::load_models( SGPropertyNode *prop_root )
{ {
// Load model only on demand std::lock_guard<std::mutex> g(_loadMutex);
if (!_models_loaded) {
for (unsigned int i = 0; i < _paths.size(); i++) {
osg::Node *entity = SGModelLib::loadModel(_paths[i], prop_root);
if (entity != 0) {
// FIXME: this stuff can be handled
// in the XML wrapper as well (at least,
// the billboarding should be handled
// there).
if (_heading_type == HEADING_BILLBOARD) { // Load model only on demand
// if the model is a billboard, it is likely : if (!_models_loaded) {
// 1. a branch with only leaves, for (unsigned int i = 0; i < _paths.size(); i++) {
// 2. a tree or a non rectangular shape faked by transparency osg::Node* entity = SGModelLib::loadModel(_paths[i], prop_root);
// We add alpha clamp then if (entity != 0) {
osg::StateSet* stateSet = entity->getOrCreateStateSet(); // FIXME: this stuff can be handled
osg::AlphaFunc* alphaFunc = // in the XML wrapper as well (at least,
new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01f); // the billboarding should be handled
stateSet->setAttributeAndModes(alphaFunc, // there).
osg::StateAttribute::OVERRIDE);
stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); if (_heading_type == HEADING_BILLBOARD) {
// if the model is a billboard, it is likely :
// 1. a branch with only leaves,
// 2. a tree or a non rectangular shape faked by transparency
// We add alpha clamp then
osg::StateSet* stateSet = entity->getOrCreateStateSet();
osg::AlphaFunc* alphaFunc =
new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01f);
stateSet->setAttributeAndModes(alphaFunc,
osg::StateAttribute::OVERRIDE);
stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
}
_models.push_back(entity);
} else {
SG_LOG(SG_INPUT, SG_ALERT, "Failed to load object " << _paths[i]);
// Ensure the vector contains something, otherwise get_random_model below fails
_models.push_back(new osg::Node());
}
} }
_models.push_back(entity);
} else {
SG_LOG(SG_INPUT, SG_ALERT, "Failed to load object " << _paths[i]);
// Ensure the vector contains something, otherwise get_random_model below fails
_models.push_back(new osg::Node());
}
}
} }
_models_loaded = true; _models_loaded = true;
} }

View File

@ -149,6 +149,8 @@ private:
double _spacing_m; double _spacing_m;
double _range_m; double _range_m;
HeadingType _heading_type; HeadingType _heading_type;
std::mutex _loadMutex;
}; };