osg复制多个相同物体修改材质属性问题

转自http://www.cnblogs.com/ylwn817/articles/2153982.html

当通过osg复制多个相同物体时候,修改复制过来的某个物体材质属性时候,假设我们物体透明度,这个时候我们可能会发现修改某个物体,会导致其他复制过来的物体同样也被透明化。下面是解决方案:获得物体时候,只能获得自身材质,而不能去获得孩子材质,如果修改孩子材质,将会导致其他复制过来的也会被透明。

 如下是详细代码:

osg::StateSet *state = iter->second->getOrCreateStateSet();//获得物体名字
  //osg::StateSet *state1=iter->second->getChild(0);//获得孩子属性//不能通过孩子修改透明度,否则会影响其他物体也变透明化。


  osg::Material* mat = dynamic_cast<osg::Material*>(state->getAttribute(osg::StateAttribute::MATERIAL));
  
  if (!mat)//判断是否材质,没有的话将子材质给父节点。
  {
   mat = new osg::Material;
   osg::Geode* geode=dynamic_cast<osg::Geode*>(iter->second->getChild(0));
   osg::Material* mat1=dynamic_cast<osg::Material*>(geode->getDrawable(0)->getOrCreateStateSet()->getAttribute(osg::StateAttribute::MATERIAL));//获得孩子材质属性
   osg::Material* mat2=new osg::Material;
   *mat2=*mat1;//修改父材质属性//防止物体变黑,失去原来物体的材质


   //设置透明度
   mat2->setAlpha(osg::Material::Face::FRONT_AND_BACK,0.3);


   //融合
   state->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
   state->setMode(GL_BLEND,osg::StateAttribute::ON);
   //融合函数
   osg::ref_ptr<osg::BlendFunc> blendFunc = new osg::BlendFunc();
   blendFunc->setSource(osg::BlendFunc::SRC_ALPHA);
   blendFunc->setDestination(osg::BlendFunc::ONE_MINUS_SRC_ALPHA);
   state->setAttributeAndModes(blendFunc, osg::StateAttribute::ON|osg::StateAttribute::OVERRIDE);


   state->setAttributeAndModes(mat2,osg::StateAttribute::ON|osg::StateAttribute::OVERRIDE);
  }
  else
  {


  
   if (!flag)
   {
    mat->setAlpha(osg::Material::Face::FRONT_AND_BACK,1);
   }
   else
   {
    mat->setAlpha(osg::Material::Face::FRONT_AND_BACK,0.3);
    
   }    
  
   //设置混色
   state->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
   state->setMode(GL_BLEND,osg::StateAttribute::ON);


   osg::ref_ptr<osg::BlendFunc> blendFunc = new osg::BlendFunc();
   blendFunc->setSource(osg::BlendFunc::SRC_ALPHA);
   blendFunc->setDestination(osg::BlendFunc::ONE_MINUS_SRC_ALPHA);
   state->setAttributeAndModes(blendFunc, osg::StateAttribute::ON|osg::StateAttribute::OVERRIDE);
   state->setAttributeAndModes(mat,osg::StateAttribute::ON|osg::StateAttribute::OVERRIDE);
  }

原文地址:https://www.cnblogs.com/blogofwu/p/4871280.html