Exemplo n.º 1
0
void VRMLFile::addRoute(const Char8  *szOutNodename,
                        const Char8  *szOutFieldname,
                        const Char8  *szInNodename,
                        const Char8  *szInFieldname )
{
    if(szOutNodename == NULL || szOutFieldname == NULL ||
       szInNodename  == NULL || szInFieldname  == NULL  )
    {
        FWARNING(("addRoute missing params\n"));
    }

    FieldContainer *pSrcNode = findReference(szOutNodename);
    FieldContainer *pDstNode = findReference(szInNodename);

    AttachmentContainer *pSrc = dynamic_cast<AttachmentContainer *>(pSrcNode);
    AttachmentContainer *pDst = dynamic_cast<AttachmentContainer *>(pDstNode);

    if(pSrc == NULL)
    {
        FWARNING(("Unknow src node %s\n", szOutNodename));
        return;
    }

    if(pDstNode == NULL)
    {
        FWARNING(("Unknow dst node %s\n", szInNodename));
        return;
    }

    VRMLGenericAtt *pSrcAtt = dynamic_cast<VRMLGenericAtt *>(
        pSrc->findAttachment(VRMLGenericAtt::getClassType()));

    VRMLGenericAtt *pDstAtt = NULL;

    if(pDst != NULL)
    {
        pDstAtt = dynamic_cast<VRMLGenericAtt *>(
            pDst->findAttachment(VRMLGenericAtt::getClassType()));
    }

    if(pSrcAtt == NULL)
    {
        Node *pNode = dynamic_cast<Node *>(pSrc);

        if(pNode != NULL && pNode->getCore() != NULL)
        {
            pSrcAtt = dynamic_cast<VRMLGenericAtt *>(
                pNode->getCore()->findAttachment(
                    VRMLGenericAtt::getClassType())); 
        }
    }

    if(pDstAtt == NULL)
    {
        Node *pNode = dynamic_cast<Node *>(pDst);

        if(pNode != NULL && pNode->getCore() != NULL)
        {
            pDstAtt = dynamic_cast<VRMLGenericAtt *>(
                pNode->getCore()->findAttachment(
                    VRMLGenericAtt::getClassType())); 
        }
    }

   
    std::string szOutFName = szOutFieldname;
    std::string szInFName  = szInFieldname;

    
    std::string::size_type uiPos = szOutFName.rfind(std::string("_changed"));


    if(uiPos != std::string::npos)
    {
        szOutFName.erase(uiPos, std::string::npos);
    }
    
    uiPos = szInFName.find(std::string("set_"));

    if(uiPos != std::string::npos)
    {
        szInFName.erase(uiPos, uiPos + 4);
    }


    if(pSrcAtt != NULL)
    {
        VRMLNodeHelper *pHelper = findNodeHelper(
            pSrcAtt->getVrmlNodeTypename().c_str());

        if(pHelper != NULL)
        {
            pHelper->mapFieldname(pSrcAtt->getVrmlNodeTypename(), szOutFName);
        }
    }

    if(pSrcAtt != NULL)
    {
        VRMLNodeHelper *pHelper = findNodeHelper(
            pDstAtt->getVrmlNodeTypename().c_str());

        if(pHelper != NULL)
        {
            pHelper->mapFieldname(pDstAtt->getVrmlNodeTypename(), szInFName);
        }
    }

    addConnection(pSrc,     szOutFName.c_str(),
                  pDstNode, szInFName .c_str());
}
Exemplo n.º 2
0
void RegisterCombinersChunk::activate( DrawActionBase *action, UInt32  )
{
    Window *win = action->getWindow();

    if(! win->hasExtension(_nvRegisterCombiners))
        return;

    // setup register combiners

    // functions

    void (OSG_APIENTRY*CombinerParameterfv)(GLenum pname, GLfloat *params) =
        reinterpret_cast<void (OSG_APIENTRY*)(GLenum pname, GLfloat *params)>(
            win->getFunction(_funcCombinerParameterfv));

    void (OSG_APIENTRY*CombinerStageParameterfv)(GLenum stage,
            GLenum pname,
            GLfloat *params) =
                reinterpret_cast<void (OSG_APIENTRY*)(GLenum stage,
                        GLenum pname,
                        GLfloat *params)>(
                    win->getFunction(_funcCombinerStageParameterfv));

    void (OSG_APIENTRY*CombinerInput)(GLenum stage,
                                      GLenum portion,
                                      GLenum variable,
                                      GLenum input,
                                      GLenum mapping,
                                      GLenum component) =
                                          reinterpret_cast<void (OSG_APIENTRY*)(GLenum stage,
                                                  GLenum portion,
                                                  GLenum variable,
                                                  GLenum input,
                                                  GLenum mapping,
                                                  GLenum component)>(
                                                          win->getFunction(_funcCombinerInput));

    void (OSG_APIENTRY*CombinerOutput)(GLenum stage,
                                       GLenum portion,
                                       GLenum abOut,
                                       GLenum cdOut,
                                       GLenum sumOut,
                                       GLenum scale,
                                       GLenum bias,
                                       GLboolean abdot,
                                       GLboolean cddot,
                                       GLboolean muxSum) =
                                           reinterpret_cast<void (OSG_APIENTRY*)(GLenum stage,
                                                   GLenum portion,
                                                   GLenum abOut,
                                                   GLenum cdOut,
                                                   GLenum sumOut,
                                                   GLenum scale,
                                                   GLenum bias,
                                                   GLboolean abdot,
                                                   GLboolean cddot,
                                                   GLboolean muxSum)>(
                                                           win->getFunction(_funcCombinerOutput));

    void (OSG_APIENTRY*FinalCombinerInput)(GLenum variable,
                                           GLenum input,
                                           GLenum mapping,
                                           GLenum component) =
                                                   reinterpret_cast<void (OSG_APIENTRY*)(GLenum variable,
                                                           GLenum input,
                                                           GLenum mapping,
                                                           GLenum component)>(
                                                                   win->getFunction(_funcFinalCombinerInput));

    // how many combiners do we need?

    Int32 ncomb;

    for(ncomb = OSG_NUM_COMBINERS - 1; ncomb >= 0; ncomb--)
    {
        if(getVariableArgb(ncomb * 3) != unused)
            break;
    }

    if(ncomb < 0)
    {
        // no combiner active, return

        glDisable(GL_REGISTER_COMBINERS_NV);
        return;
    }

    ncomb++;

    GLfloat dummy = GLfloat(ncomb);
    CombinerParameterfv(GL_NUM_GENERAL_COMBINERS_NV, &dummy);
    CombinerParameterfv(GL_CONSTANT_COLOR0_NV,
                        const_cast<GLfloat *>(getColor0().getValuesRGBA()));

    CombinerParameterfv(GL_CONSTANT_COLOR1_NV,
                        const_cast<GLfloat*>(getColor1().getValuesRGBA()));

    dummy = getColorSumClamp();
    CombinerParameterfv(GL_COLOR_SUM_CLAMP_NV, &dummy);

    // setup the general combiners

    bool hasRC2 = win->hasExtension(_nvRegisterCombiners2);

    for(UInt16 i = 0; i < ncomb; i++)
    {
        if(getVariableArgb(i * 3) != unused)
        {
            // RGB inputs
            CombinerInput(GL_COMBINER0_NV + i, GL_RGB, GL_VARIABLE_A_NV,
                          getVariableArgb(i * 3),
                          getVariableArgb(i * 3 + 1),
                          getVariableArgb(i * 3 + 2) );
            CombinerInput(GL_COMBINER0_NV + i, GL_RGB, GL_VARIABLE_B_NV,
                          getVariableBrgb(i * 3),
                          getVariableBrgb(i * 3 + 1),
                          getVariableBrgb(i * 3 + 2) );
            CombinerInput(GL_COMBINER0_NV + i, GL_RGB, GL_VARIABLE_C_NV,
                          getVariableCrgb(i * 3),
                          getVariableCrgb(i * 3 + 1),
                          getVariableCrgb(i * 3 + 2) );
            CombinerInput(GL_COMBINER0_NV + i, GL_RGB, GL_VARIABLE_D_NV,
                          getVariableDrgb(i * 3),
                          getVariableDrgb(i * 3 + 1),
                          getVariableDrgb(i * 3 + 2) );

            // RGB output
            CombinerOutput(GL_COMBINER0_NV + i, GL_RGB,
                           getOutputABrgb    (i),
                           getOutputCDrgb    (i),
                           getOutputSumrgb   (i),
                           getScalergb       (i),
                           getBiasrgb        (i),
                           getDotABrgb       (i),
                           getDotCDrgb       (i),
                           getMuxSumrgb      (i) );

        }
        else
        {
            CombinerInput(GL_COMBINER0_NV + i, GL_RGB, GL_VARIABLE_A_NV,
                          GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB);
            CombinerInput(GL_COMBINER0_NV + i, GL_RGB, GL_VARIABLE_B_NV,
                          GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB);
            CombinerInput(GL_COMBINER0_NV + i, GL_RGB, GL_VARIABLE_C_NV,
                          GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB);
            CombinerInput(GL_COMBINER0_NV + i, GL_RGB, GL_VARIABLE_D_NV,
                          GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB);

            CombinerOutput(GL_COMBINER0_NV + i, GL_RGB,
                           GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV,
                           GL_NONE, GL_NONE,
                           GL_FALSE, GL_FALSE, GL_FALSE );

        }

        if(getVariableAalpha(i * 3) != unused)
        {
            // Alpha inputs
            CombinerInput(GL_COMBINER0_NV + i, GL_ALPHA, GL_VARIABLE_A_NV,
                          getVariableAalpha(i * 3),
                          getVariableAalpha(i * 3 + 1),
                          getVariableAalpha(i * 3 + 2) );
            CombinerInput(GL_COMBINER0_NV + i, GL_ALPHA, GL_VARIABLE_B_NV,
                          getVariableBalpha(i * 3),
                          getVariableBalpha(i * 3 + 1),
                          getVariableBalpha(i * 3 + 2) );
            CombinerInput(GL_COMBINER0_NV + i, GL_ALPHA, GL_VARIABLE_C_NV,
                          getVariableCalpha(i * 3),
                          getVariableCalpha(i * 3 + 1),
                          getVariableCalpha(i * 3 + 2) );
            CombinerInput(GL_COMBINER0_NV + i, GL_ALPHA, GL_VARIABLE_D_NV,
                          getVariableDalpha(i * 3),
                          getVariableDalpha(i * 3 + 1),
                          getVariableDalpha(i * 3 + 2) );

            // ALPHA output
            CombinerOutput(GL_COMBINER0_NV + i, GL_ALPHA,
                           getOutputABalpha    (i),
                           getOutputCDalpha    (i),
                           getOutputSumalpha   (i),
                           getScalealpha       (i),
                           getBiasalpha        (i),
                           GL_FALSE,
                           GL_FALSE,
                           getMuxSumalpha      (i) );
        }
        else
        {
            CombinerInput(GL_COMBINER0_NV + i, GL_ALPHA, GL_VARIABLE_A_NV,
                          GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_ALPHA);
            CombinerInput(GL_COMBINER0_NV + i, GL_ALPHA, GL_VARIABLE_B_NV,
                          GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_ALPHA);
            CombinerInput(GL_COMBINER0_NV + i, GL_ALPHA, GL_VARIABLE_C_NV,
                          GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_ALPHA);
            CombinerInput(GL_COMBINER0_NV + i, GL_ALPHA, GL_VARIABLE_D_NV,
                          GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_ALPHA);

            CombinerOutput(GL_COMBINER0_NV + i, GL_ALPHA,
                           GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV,
                           GL_NONE, GL_NONE,
                           GL_FALSE, GL_FALSE, GL_FALSE );
        }

        if(getPerStageConstants())
        {
            if(hasRC2)
            {
                CombinerStageParameterfv(
                    GL_COMBINER0_NV + i,
                    GL_CONSTANT_COLOR0_NV,
                    const_cast<GLfloat*>(
                        getCombinerColor0(i).getValuesRGBA()));

                CombinerStageParameterfv(
                    GL_COMBINER0_NV + i,
                    GL_CONSTANT_COLOR1_NV,
                    const_cast<GLfloat*>(
                        getCombinerColor1(i).getValuesRGBA()));

            }
            else
            {
                FWARNING(("RegisterCombinersChunk::register_combiners2 not"
                          "supported, constant colors ignored!!\n"));
            }
        }
    }

    if(hasRC2)
    {
        if(getPerStageConstants())
        {
            glEnable(GL_PER_STAGE_CONSTANTS_NV);
        }
        else
        {
            glDisable(GL_PER_STAGE_CONSTANTS_NV);
        }
    }

    glErr("RegisterCombinersChunk::general combiners setup");

    // setup the final combiner

    FinalCombinerInput(GL_VARIABLE_A_NV,
                       getVariableArgb(OSG_NUM_COMBINERS * 3),
                       getVariableArgb(OSG_NUM_COMBINERS * 3 + 1),
                       getVariableArgb(OSG_NUM_COMBINERS * 3 + 2));

    glErr("RegisterCombinersChunk::final combiner var a setup");

    FinalCombinerInput(GL_VARIABLE_B_NV,
                       getVariableBrgb(OSG_NUM_COMBINERS * 3),
                       getVariableBrgb(OSG_NUM_COMBINERS * 3 + 1),
                       getVariableBrgb(OSG_NUM_COMBINERS * 3 + 2));

    glErr("RegisterCombinersChunk::final combiner var b setup");

    FinalCombinerInput(GL_VARIABLE_C_NV,
                       getVariableCrgb(OSG_NUM_COMBINERS * 3),
                       getVariableCrgb(OSG_NUM_COMBINERS * 3 + 1),
                       getVariableCrgb(OSG_NUM_COMBINERS * 3 + 2));

    glErr("RegisterCombinersChunk::final combiner var c setup");

    FinalCombinerInput(GL_VARIABLE_D_NV,
                       getVariableDrgb(OSG_NUM_COMBINERS * 3),
                       getVariableDrgb(OSG_NUM_COMBINERS * 3 + 1),
                       getVariableDrgb(OSG_NUM_COMBINERS * 3 + 2));

    glErr("RegisterCombinersChunk::final combiner var d setup");

    FinalCombinerInput(GL_VARIABLE_E_NV,
                       getVariableE(0),
                       getVariableE(1),
                       getVariableE(2));

    glErr("RegisterCombinersChunk::final combiner var e setup");

    FinalCombinerInput(GL_VARIABLE_F_NV,
                       getVariableF(0),
                       getVariableF(1),
                       getVariableF(2));

    glErr("RegisterCombinersChunk::final combiner var f setup");

    FinalCombinerInput(GL_VARIABLE_G_NV,
                       getVariableG(0),
                       getVariableG(1),
                       getVariableG(2));

    glErr("RegisterCombinersChunk::final combiner setup");
    // and activate everything

    glEnable(GL_REGISTER_COMBINERS_NV);

    glErr("RegisterCombinersChunk::activate");
}
/*! Fills the "pointer field" described by \a ptrField with the correct
    pointers.

    \param[in] ptrField Field to fill.
 */
void
OSBRootElement::mapPtrField(const PtrFieldInfo &ptrField)
{
    OSG_OSB_LOG(("OSBRootElement::mapPtrField\n"));

    PtrFieldInfo::PtrIdStoreConstIt   idIt       = ptrField.beginIdStore();
    PtrFieldInfo::PtrIdStoreConstIt   idEnd      = ptrField.endIdStore  ();

    PtrFieldInfo::BindingStoreConstIt bindingIt  = ptrField.beginBindingStore();
    PtrFieldInfo::BindingStoreConstIt bindingEnd = ptrField.endBindingStore  ();

    const FieldContainerIdMap        &idMap      = getIdMap();
          FieldContainerIdMapConstIt  idMapIt;
          FieldContainerIdMapConstIt  idMapEnd   = idMap.end();
        
    if(bindingIt != bindingEnd)
    {
        if(ptrField.getHandledField() == true)
        {
            FieldContainer    *fieldCon = ptrField.getContainer();
            UInt32             fieldId  = ptrField.getFieldId();
        
            EditFieldHandlePtr fHandle  = fieldCon->editField(fieldId);

            EditMapFieldHandlePtr sfMapField =
                boost::dynamic_pointer_cast<EditMapFieldHandle>(fHandle);

            if(sfMapField == NULL || sfMapField->isValid() == false)
                return;

            sfMapField->fillFrom(ptrField.getBindingStore(),
                                 ptrField.getIdStore     (),
                                 idMap);
        }
        else
        {
            Attachment          *att    = NULL;
            AttachmentContainer *attCon =
                dynamic_cast<AttachmentContainer *>(ptrField.getContainer());
            
            for(; (idIt != idEnd) && (bindingIt != bindingEnd); ++idIt, 
                                                                ++bindingIt)
            {
                if(*idIt != 0)
                {
                    idMapIt = idMap.find(*idIt);
                    
                    if(idMapIt != idMapEnd)
                    {
                        att = dynamic_cast<Attachment *>(
                            FieldContainerFactory::the()->getContainer(
                                idMapIt->second));
                    }
                    else
                    {
                        FWARNING(("OSBRootElement::mapPtrField: could not find "
                                  "FieldContainer with id [%u]\n", *idIt));
                        att = NULL;
                    }
                }
                else
                {
                    att = NULL;
                }
                
                if(att != NULL)
                {
                    OSG_OSB_LOG(("OSBRootElement::mapPtrField: adding "
                            "attchment [%u] [%u]\n",
                            att->getType().getGroupId(), *bindingIt));
                }

                attCon->addAttachment(att, *bindingIt);
            }
        }
    }
    else
    {
        FieldContainer    *fc       = NULL;
        FieldContainer    *fieldCon = ptrField.getContainer();
        UInt32             fieldId  = ptrField.getFieldId();
        
        EditFieldHandlePtr fHandle  = fieldCon->editField(fieldId);
        
        FieldContainerPtrSFieldBase::EditHandlePtr pSFHandle = 
            boost::dynamic_pointer_cast<
                FieldContainerPtrSFieldBase::EditHandle>(fHandle);
            
        FieldContainerPtrMFieldBase::EditHandlePtr pMFHandle = 
            boost::dynamic_pointer_cast<
                FieldContainerPtrMFieldBase::EditHandle>(fHandle);
        
        for(; idIt != idEnd; ++idIt)
        {
            if(*idIt != 0)
            {
                idMapIt = idMap.find(*idIt);
                
                if(idMapIt != idMapEnd)
                {
                    fc = FieldContainerFactory::the()->getContainer(
                        idMapIt->second);
                }
                else
                {
                    FWARNING(("OSBRootElement::mapPtrField: could not find "
                              "FieldContainer with (file) id [%u]\n", *idIt));
                    fc = NULL;
                }
            }
            else
            {
                fc = NULL;
            }

            if(pSFHandle != NULL && pSFHandle->isValid())
            {
                pSFHandle->set(fc);
            }
            else if(pMFHandle != NULL && pMFHandle->isValid())
            {
                pMFHandle->add(fc);
            }
            else
            {
                FWARNING(("OSBRootElement::mapPtrField: FieldHandles invalid, "
                          "can not set pointer - target fc [%u][%s] "
                          "fieldId [%u][%s] file id [%u] system id [%u]\n",
                          (fc != NULL ? fc->getId() : 0),
                          (fc != NULL ? fc->getType().getCName() : ""),
                          fieldId,
                          (fc != NULL ?
                          fc->getType().getFieldDesc(fieldId)->getCName() : ""),
                          *idIt,
                          (idMapIt != idMapEnd ? idMapIt->second : 0) ));
            }
        }
    }
}
Exemplo n.º 4
0
bool CSMWindow::init(void)
{
    bool returnValue = true;

    MFUnrecCSMViewportPtr::const_iterator vIt  = getMFViewports()->begin();
    MFUnrecCSMViewportPtr::const_iterator vEnd = getMFViewports()->end  ();

    while(vIt != vEnd)
    {
        returnValue = (*vIt)->init();

        if(returnValue == false)
        {
            break;
        }

        ++vIt;
    }

    if(_pWindow != NULL && returnValue == true)
    {
        vIt  = getMFViewports()->begin();
        vEnd = getMFViewports()->end  ();

        for(; vIt != vEnd; ++vIt)
        {
            CSMViewport::ViewportStoreConstIt pIt  = (*vIt)->beginViewports();
            CSMViewport::ViewportStoreConstIt pEnd = (*vIt)->endViewports  ();

            for(; pIt != pEnd; ++pIt)
            {
                _pWindow->addPort((*pIt));
            }
        }

        fprintf(stderr, "foo %p %d\n",
                ComplexSceneManager::the()->getDrawManager(),
                UInt32(ComplexSceneManager::the()->
                           getDrawManager()->getParallel()));

#ifndef __APPLE__
        UInt32 uiDrawMode = this->getPartitionDrawMode();
#else
        UInt32 uiDrawMode = Window::SequentialPartitionDraw;

        FWARNING(("Detected apple, only sequential draw mode available\n"));
#endif

        if(ComplexSceneManager::the()->getDrawManager()->getParallel() == true)
        {
            uiDrawMode |= Window::ParallelDrawer;
        }
        else
        {
            uiDrawMode |= Window::StdDrawer;
        }

        _pWindow->setRenderOptions    (this->getRenderOptions());
        _pWindow->setPartitionDrawMode(uiDrawMode              );
        _pWindow->setDrawerType       (uiDrawMode              );

        _pWindow->setIgnoreAllExtensions(this->getIgnoreAllExtensions());

        MFString::const_iterator ieIt  = _mfIgnoreExtensions.begin();
        MFString::const_iterator ieEnd = _mfIgnoreExtensions.end  ();

        for(; ieIt != ieEnd; ++ieIt)
        {
            Window::ignoreExtensions(ieIt->c_str());
        }
    }
    
//    OSGSceneFileType::the().writeContainer(_pWindow, "/tmp/window.osg");

    if(this->getDumpContainer() == true)
    {
        FieldContainerFactory::the()->dump();
    }

    return returnValue;
}
Exemplo n.º 5
0
void MergeGraphOp::processGeometries(Node * const node)
{
    MFUnrecChildNodePtr::const_iterator mfit = node->getMFChildren()->begin();
    MFUnrecChildNodePtr::const_iterator mfen = node->getMFChildren()->end  ();

    std::vector<Node        *> toSub;
    std::vector<NodeUnrecPtr > toAdd;
    
    for ( ; mfit != mfen; ++mfit )
    {
        bool special=isInExcludeList(*mfit);
        
        if ((*mfit)->getCore()->getType().isDerivedFrom(
                Geometry::getClassType()))
        {
#ifndef OSG2_MERGE_MISSING
            Geometry *geo = dynamic_cast<Geometry *>((*mfit)->getCore());
#endif
            //if a geometry, try to merge it in another geometry
            //if successfull, delete it.
            //check also if it is added for exclusion

            bool inSubList=false;

            std::vector<Node *>::const_iterator it3=toSub.begin();
            std::vector<Node *>::const_iterator en3=toSub.end();

            for ( ; it3 != en3; ++it3 ) 
                if (*it3==*mfit) { inSubList=true; break; }

            if (!special && !inSubList)
            {
                //ok, try
                MFUnrecChildNodePtr::const_iterator it2=mfit+1;
                Geometry *new_geo=NULL;
                for ( ; it2!=mfen; ++it2)
                {
                    if (!isInExcludeList(*it2) && (*it2)->getCore()->getType().isDerivedFrom(Geometry::getClassType()))
                    {
#ifndef OSG2_MERGE_MISSING
                        Geometry *geo2 = dynamic_cast<Geometry *>((*it2)->getCore());
                        if (geo->isMergeable(geo2))
                        {
                            // HACK merge crashes when indices == NULL!
                            if(geo->getIndices() == NULL)
                                OSG::createSharedIndex(geo);
                            if(geo2->getIndices() == NULL)
                                OSG::createSharedIndex(geo2);
                            if (new_geo==NULL)
                            {
                                new_geo=Geometry::create();
                                if (new_geo->merge(geo))
                                    toSub.push_back(*it);
                                else FWARNING(("MergeGraphOp: processGeometries problem 1\n"));

                                if (new_geo->merge(geo2))
                                    toSub.push_back(*it2);
                                else FWARNING(("MergeGraphOp: processGeometries problem 2\n"));
                            }
                            else
                            {
                                if (new_geo->merge(geo2))
                                    toSub.push_back(*it2);
                            }
                        }
#endif
                    }
                }
                if (new_geo!=NULL)
                {
                    NodeUnrecPtr new_node=Node::create();
                    new_node->setCore(new_geo);

                    toAdd.push_back(new_node);
                }
            }
            else
            {
                //hmm...have to skip it
            }
        }
    }
    
    std::vector<NodeUnrecPtr>::const_iterator ait = toAdd.begin();
    std::vector<NodeUnrecPtr>::const_iterator aen = toAdd.end  ();
    
    for ( ; ait != aen; ++ait )
    {
        node->addChild(*ait);
    }

    std::vector<Node *>::const_iterator sit = toSub.begin();
    std::vector<Node *>::const_iterator sen = toSub.end  ();
    
    for ( ; sit != sen; ++sit )
    {
        node->subChild(*sit);
    }
}
void
OSBTextureChunkElement::read(const std::string &typeName)
{
    OSG_OSB_LOG(("OSBTextureChunkElement::read: [%s]\n", typeName.c_str()));

    BinaryReadHandler *rh = editRoot()->getReadHandler();
    
    UInt8  ptrTypeId;
    UInt16 version;

    rh->getValue(ptrTypeId);
    rh->getValue(version  );

    OSG_OSB_LOG(("OSBTextureChunkElement::read: version: [%u]\n", version));
    
    // create the two replacement chunks
    _pTexObj = TextureObjChunk::create();
    _pTexEnv = TextureEnvChunk::create();
        
    std::string    fieldName;
    std::string    fieldTypeName;
    UInt32         fieldSize;
    PtrFieldListIt ptrFieldIt;
    
    while(readFieldHeader("", fieldName, fieldTypeName, fieldSize))
    {
        // some fields need to be duplicated for the two replacement chunks
        if(fieldName == "parents")
        {
            // parent fields are ignored
            rh->skip(fieldSize);
        }    
        else if(fieldName == "internal")
        {
            bool fieldValue;
            rh->getValue(fieldValue);
            
            _pTexObj->setInternal(fieldValue);
            _pTexEnv->setInternal(fieldValue);
        }
        else if(fieldName == "ignore")
        {
            bool fieldValue;
            rh->getValue(fieldValue);
            
            _pTexObj->setIgnore(fieldValue);
            _pTexEnv->setIgnore(fieldValue);
        }        
        else if(isTexObjField(fieldName))
        {
            // set TexObj as container for reading the field
            setContainer(_pTexObj);
            readFieldContent(fieldName, fieldTypeName, fieldSize, "", ptrFieldIt);
        }
        else if(isTexEnvField(fieldName))
        {
            // set TexEnv as container for reading the field
            setContainer(_pTexEnv);
            readFieldContent(fieldName, fieldTypeName, fieldSize, "", ptrFieldIt);
        }
        else
        {
            FWARNING(("OSBTextureChunkElement::read: Skipping unrecognized "
                      "field [%s].\n", fieldName.c_str()));
                      
            rh->skip(fieldSize);
        }
    }
    
    // set TexObj as "the" container
    setContainer(_pTexObj);
}
Exemplo n.º 7
0
bool FrustumVolume::isOnSurface(const Pnt3f &OSG_CHECK_ARG(point)) const
{
    FWARNING(("FrustumVolume::isOnSurface: NYI!\n"));
    return false;
}
Exemplo n.º 8
0
void
OSBGeometryElement::postReadV100(void)
{
    OSG_OSB_LOG(("OSBGeometryElement::postReadV100\n"));

    OSBRootElement  *root             = editRoot();
    Geometry        *geo              =
        dynamic_cast<Geometry*>(getContainer());
    UInt32           indexMappingSize = UInt32(_indexMapping.size());

    if(indexMappingSize <= 1)
    {
        OSG_OSB_LOG(("OSBGeometryElement::postReadV100: "
                "Converting single index.\n"          ));

        if(_indicesPacked)
        {
            OSG_OSB_LOG(("OSBGeometryElement::postReadV100: "
                    "Converting packed indices.\n"        ));
            geo->setIndices(_indices);
        }
        else
        {
            OSG_OSB_LOG(("OSBGeometryElement::postReadV100: "
                    "Converting non-packed indices.\n"    ));

            // indices stored in container with id _indicesId
            // create PtrFieldInfo structure to set all entries of field
            // "propIndices" to the container with id _indicesId

            FieldDescriptionBase *indFieldDesc =
                geo->getFieldDescription("propIndices");
            UInt32                indFieldId   = indFieldDesc->getFieldId();

            root->editPtrFieldList().push_back(PtrFieldInfo(geo, indFieldId));
            PtrFieldInfo &indFieldPFI = root->editPtrFieldList().back();

            for(UInt32 i = 0; i < Geometry::MaxAttribs; ++i)
            {
                indFieldPFI.editIdStore().push_back(_indicesId);
            }
        }
    }
    else
    {
        OSG_OSB_LOG(("OSBGeometryElement::postReadV100: "
                "Converting multi index.\n"          ));

        OSBGeometryHelper gh;

        if(_indicesPacked)
        {
            OSG_OSB_LOG(("OSBGeometryElement::postReadV100: "
                    "Converting packed indices.\n"        ));

            // create 16 bit or 32 bit indices
            if(_indices16Bit)
            {
                GeoUInt16Property *ui16Indices =
                    dynamic_pointer_cast<GeoUInt16Property>(_indices);

                gh.splitMultiIndex<GeoUInt16Property *>(
                    _indexMapping, ui16Indices, geo);
            }
            else
            {
                GeoUInt32Property *ui32Indices =
                    dynamic_pointer_cast<GeoUInt32Property>(_indices);

                gh.splitMultiIndex<GeoUInt32Property *>(
                    _indexMapping, ui32Indices, geo);
            }
        }
        else
        {
            OSG_OSB_LOG(("OSBGeometryElement::postReadV100: "
                         "Converting non-packed indices.\n"    ));

            FieldContainerIdMapConstIt mapIt =
                root->getIdMap().find(_indicesId);

            if(mapIt != root->getIdMap().end())
            {
                _indices = dynamic_cast<GeoIntegralProperty *>(
                    FieldContainerFactory::the()->getContainer(mapIt->second));
            }
            else
            {
                FWARNING(("OSBGeometryElement::postReadV100: "
                          "Could not find indices property.\n"));
                return;
            }

            if(_indices->getFormatSize() == sizeof(UInt16))
            {
                GeoUInt16Property *ui16Indices =
                    dynamic_pointer_cast<GeoUInt16Property>(_indices);

                gh.splitMultiIndex<GeoUInt16Property *>(
                    _indexMapping, ui16Indices, geo);
            }
            else if(_indices->getFormatSize() == sizeof(UInt32))
            {
                GeoUInt32Property *ui32Indices =
                    dynamic_pointer_cast<GeoUInt32Property>(_indices);

                gh.splitMultiIndex<GeoUInt32Property *>(
                    _indexMapping, ui32Indices, geo);
            }
        }
    }
}
	virtual void  initialize(void)
	{
		// Check necessary stuff
		if(_win == NullFC)
		{
			FWARNING(("SceneManager::initialize: window not set, "
					  "ignoring!\n"));
			return;
		}
	    
		// the rendering action
		_ownAction = RenderAction::create();
		_action = _ownAction;

		// the camera and light beacon
		NodePtr cartN = Node::create();
		_cart = Transform::create();

		beginEditCP(cartN);
			cartN->setCore(_cart);
		endEditCP(cartN);

		// the headlight
		_internalRoot = Node::create();
		_headlight    = DirectionalLight::create();

		addRefCP(_internalRoot);
		beginEditCP(_internalRoot);
			_internalRoot->setCore(_headlight);
			_internalRoot->addChild(cartN);
		endEditCP(_internalRoot);

		beginEditCP(_headlight);
			_headlight->setAmbient  (.3, .3, .3, 1);
			_headlight->setDiffuse  ( 1,  1,  1, 1);
			_headlight->setSpecular ( 1,  1,  1, 1);
			_headlight->setDirection( 0,  0,  1);
			_headlight->setBeacon   (cartN);
		endEditCP(_headlight);

		// the camera
		_camera = PerspectiveCamera::create();
		addRefCP(_camera);
		beginEditCP(PerspectiveCameraPtr::dcast(_camera));
			PerspectiveCameraPtr::dcast(_camera)->setBeacon(cartN);
			PerspectiveCameraPtr::dcast(_camera)->setFov   (deg2rad(60.f));
			PerspectiveCameraPtr::dcast(_camera)->setNear  (0.1f);
			PerspectiveCameraPtr::dcast(_camera)->setFar   (10000.f);
		endEditCP(PerspectiveCameraPtr::dcast(_camera));

		// need a viewport?
		if(_win->getPort().size() == 0)
		{
			SolidBackgroundPtr bg = SolidBackground::create();
			beginEditCP(bg);
				bg->setColor(Color3f(0, 0, 0));
			endEditCP(bg);

			ViewportPtr vp = Viewport::create();
			beginEditCP(vp);
				vp->setCamera                  (_camera);
				vp->setRoot                    (_internalRoot);
				vp->setSize                    (0,0, 1,1);
				vp->setBackground              (bg);
			endEditCP(vp);

			beginEditCP(_win);
				_win->addPort(vp);
			endEditCP(_win);
		}

	}
Exemplo n.º 10
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // Set up Window
    TutorialWindowEventProducer = createDefaultWindowEventProducer();
    WindowPtr MainWindow = TutorialWindowEventProducer->initWindow();

    TutorialWindowEventProducer->setDisplayCallback(display);
    TutorialWindowEventProducer->setReshapeCallback(reshape);

    //Add Window Listener
    TutorialKeyListener TheKeyListener;
    TutorialWindowEventProducer->addKeyListener(&TheKeyListener);
    TutorialMouseListener TheTutorialMouseListener;
    TutorialMouseMotionListener TheTutorialMouseMotionListener;
    TutorialWindowEventProducer->addMouseListener(&TheTutorialMouseListener);
    TutorialWindowEventProducer->addMouseMotionListener(&TheTutorialMouseMotionListener);

    // Create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

	
    // Tell the Manager what to manage
    mgr->setWindow(TutorialWindowEventProducer->getWindow());

    Path FBOFilePath;
    if(argc < 2)
    {
        FWARNING(("No FBO file given!\n"));
        FBOFilePath = Path("./Data/01LoadFBO.xml");
    }
    else
    {
        FBOFilePath = Path(std::string(argv[1]));
    }
    std::cout << "Loading xml File: " << FBOFilePath << std::endl;

    FCFileType::FCPtrStore NewContainers;
    NewContainers = FCFileHandler::the()->read(FBOFilePath);

    FCFileType::FCPtrStore::iterator Itor;
    for(Itor = NewContainers.begin() ; Itor != NewContainers.end() ; ++Itor)
    {
        if( (*Itor)->getType() == FBOViewport::getClassType())
        {
            TheFBOViewport = FBOViewport::Ptr::dcast(*Itor);
        }
    }

    ChunkMaterialPtr BoxMaterial = ChunkMaterial::create();

    GeometryPtr BoxGeoCore = makeBoxGeo(1.0,1.0,1.0,2,2,2);
    beginEditCP(BoxGeoCore, Geometry::MaterialFieldMask);
        BoxGeoCore->setMaterial(BoxMaterial);
    endEditCP(BoxGeoCore, Geometry::MaterialFieldMask);

    NodePtr BoxGeoNode = Node::create();
    beginEditCP(BoxGeoNode, Node::CoreFieldMask);
        BoxGeoNode->setCore(BoxGeoCore);
    endEditCP(BoxGeoNode, Node::CoreFieldMask);

    NodePtr SceneNode = Node::create();
    beginEditCP(SceneNode, Node::CoreFieldMask | Node::ChildrenFieldMask);
        SceneNode->setCore(Group::create());
        SceneNode->addChild(BoxGeoNode);
    endEditCP(SceneNode, Node::CoreFieldMask | Node::ChildrenFieldMask);

    // tell the manager what to manage
    mgr->setRoot  (SceneNode);

    // show the whole scene
    mgr->showAll();
    
    if(TheFBOViewport != NullFC)
    {
        //Add the texture chunk of the FBO to the Material for the box
        beginEditCP(BoxMaterial, ChunkMaterial::ChunksFieldMask);
            BoxMaterial->addChunk(TheFBOViewport->editTextures(0));
        endEditCP(BoxMaterial, ChunkMaterial::ChunksFieldMask);

        //Add The FBO Viewport the the Window
        beginEditCP(TheFBOViewport, FBOViewport::ParentFieldMask);
            TheFBOViewport->setParent(TutorialWindowEventProducer->getWindow());
        endEditCP(TheFBOViewport, FBOViewport::ParentFieldMask);

        beginEditCP(TutorialWindowEventProducer->getWindow());
            ViewportPtr vp = TutorialWindowEventProducer->getWindow()->getPort(0);
            addRefCP(vp);
            
            TutorialWindowEventProducer->getWindow()->subPort(0);

            //Put the FBO Vieport in front, so it is rendered first
            TutorialWindowEventProducer->getWindow()->addPort(TheFBOViewport);
            TutorialWindowEventProducer->getWindow()->addPort(vp   );
        endEditCP  (TutorialWindowEventProducer->getWindow());
    }

    Vec2f WinSize(TutorialWindowEventProducer->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindowEventProducer->getDesktopSize() - WinSize) *0.5);
    TutorialWindowEventProducer->openWindow(WinPos,
                        WinSize,
                                        "07LoadFBO");

    //Main Loop
    TutorialWindowEventProducer->mainLoop();

    osgExit();

    return 0;
}
bool CSMClusterWindow::init(void)
{
    MultiDisplayWindowUnrecPtr  pCMDWindow = NULL;
    BalancedMultiWindowUnrecPtr pCBMWindow = NULL;
    SortFirstWindowUnrecPtr     pCSFWindow = NULL;
    SortLastWindowUnrecPtr      pCSLWindow = NULL;
  
    if(_sfClusterMode.getValue() == "Multi")
    {
        pCMDWindow = MultiDisplayWindow::create();

        _pWindow        = pCMDWindow;
        _pClusterWindow = pCMDWindow;
    }
    else if(_sfClusterMode.getValue() == "Balanced")
    {
        pCBMWindow = BalancedMultiWindow::create();

        pCMDWindow = pCBMWindow;

        _pWindow        = pCBMWindow;
        _pClusterWindow = pCBMWindow;
    }
    else if(_sfClusterMode.getValue() == "SortFirst")
    {
        pCSFWindow = SortFirstWindow::create();

        _pWindow        = pCSFWindow;
        _pClusterWindow = pCSFWindow;
    }
    else if(_sfClusterMode.getValue() == "SortLast")
    {
        pCSLWindow = SortLastWindow::create();

        _pWindow        = pCSLWindow;
        _pClusterWindow = pCSLWindow;
    }
    else
    {
        fprintf(stderr, "Unknown cluster mode %s\n",
                _sfClusterMode.getValue().c_str());
    }

    MFString::const_iterator serverIt  = this->getMFServers()->begin();
    MFString::const_iterator serverEnd = this->getMFServers()->end  ();

    UInt32 uiNumServer = 0;

    while(serverIt != serverEnd)
    {
        fprintf(stderr, "Connecting to %s\n", serverIt->c_str());
        
        _pClusterWindow->editMFServers()->push_back(serverIt->c_str());
        
        ++uiNumServer;
        ++serverIt;
    }

    bool bServerIdsValid = false;

    if(this->getMFServers()->size() <= this->getMFServerIds()->size())
    {
        _pClusterWindow->editMFServerIds()->setValues(
            *(this->getMFServerIds()));

        bServerIdsValid = true;
    }
    else
    {
        if(this->getMFServerIds()->size() != 0)
        {
            FWARNING(("Not enough server ids (%d/%d), field ignored\n",
                      this->getMFServerIds()->size(),
                      this->getMFServers  ()->size()                  ));
        }
    }

    _pClusterWindow->setSize(UInt16(this->getXSize()), 
                             UInt16(this->getYSize()));

    _pClusterWindow->setConnectionType(this->getConnectionType());

    if(this->getSFComposer()->getValue() != NULL)
    {
        _pClusterWindow->setComposer(this->getSFComposer()->getValue());
    }

    if(pCMDWindow != NULL)
    {
        if(uiNumServer != 0)
        {
            pCMDWindow->setHServers(uiNumServer / this->getServerRows());
            
            pCMDWindow->setVServers(this->getServerRows());
        }
        else
        {
            pCMDWindow->setHServers(1);
            pCMDWindow->setVServers(1);
        }
        
        CSMMultiWinOptions *pOpts = 
            dynamic_cast<CSMMultiWinOptions *>(this->getOptions());

        if(pOpts != NULL)
        {
            pCMDWindow->setXOverlap(pOpts->getXOverlap());
            pCMDWindow->setYOverlap(pOpts->getYOverlap());

            pCMDWindow->setManageClientViewports(
                pOpts->getManageClientViewports());
        }
    }


    if(pCBMWindow != NULL)
    {
        CSMMultiWinOptions *pOpts = 
            dynamic_cast<CSMMultiWinOptions *>(this->getOptions());

        if(pOpts != NULL)
        {
            pCBMWindow->setBalance      (pOpts->getBalance      ());
            pCBMWindow->setBestCut      (pOpts->getBestCut      ());
            pCBMWindow->setShowBalancing(pOpts->getShowBalancing());
        }
    }

    if(pCSFWindow != NULL)
    {
        CSMSortFirstWinOptions *pOpts = 
            dynamic_cast<CSMSortFirstWinOptions *>(this->getOptions());

        if(pOpts != NULL)
        {
            pCSFWindow->setCompression        (pOpts->getCompression        ());
            pCSFWindow->setCompose            (pOpts->getCompose            ());
            pCSFWindow->setSubtileSize        (pOpts->getSubtileSize        ());
            pCSFWindow->setUseFaceDistribution(pOpts->getUseFaceDistribution());
        }
    }

    if(pCMDWindow != NULL)
    {
        MFUnrecCSMViewportPtr::const_iterator vIt  = getMFViewports()->begin();
        MFUnrecCSMViewportPtr::const_iterator vEnd = getMFViewports()->end  ();

        while(vIt != vEnd)
        {
            if((*vIt)->getServerId() != -1)
            {
                UInt32 uiRealServerId = (*vIt)->getServerId();

                if(bServerIdsValid == true)
                {
                    Int32 iIdx = 
                        this->getMFServerIds()->findIndex(uiRealServerId);

                    if(iIdx != -1)
                        uiRealServerId = iIdx;
                }

                UInt32 uiHor  = uiRealServerId % pCMDWindow->getHServers();
                UInt32 uiVert = uiRealServerId / pCMDWindow->getHServers();
                
                Real32 rHFact = 1.f / Real32(pCMDWindow->getHServers());
                Real32 rVFact = 1.f / Real32(pCMDWindow->getVServers());

                Vec2f leftBottom(Real32(uiHor ) * rHFact,
                                 Real32(uiVert) * rVFact);

                Vec2f rightTop  (Real32(uiHor  + 1) * rHFact,
                                 Real32(uiVert + 1) * rVFact);

                (*vIt)->setLeftBottom(leftBottom);
                (*vIt)->setRightTop  (rightTop  );
            }            
            ++vIt;
        }
    }

    if(_sfClientWindow.getValue() != NULL)
    {
        _sfClientWindow.getValue()->init();

        if(this->getRenderClient() == true)
        {
            _pClusterWindow->setClientWindow(
                _sfClientWindow.getValue()->getWindow());
        }
    }

    _pClusterWindow->init();

    Inherited::init();

    return true;
}
Exemplo n.º 12
0
void HDRStage::resizeStageData(HDRStageData *pData,
                               Int32         iPixelWidth,
                               Int32         iPixelHeight)
{
    FWARNING(("HDRStage resize not implemented ==> wrong results\n"));
}
UInt32 ShaderExecutableChunk::handleGL(DrawEnv                 *pEnv, 
                                       UInt32                   id, 
                                       Window::GLObjectStatusE  mode,
                                       UInt32                   uiOptions)
{
    UInt32  returnValue = 0;
    Window *pWin        = pEnv->getWindow();

    if(!pWin->hasExtension(_extSHL))
    {
        FWARNING(("OpenGL Shading Language is not supported, couldn't find "
                  "extension 'GL_ARB_shading_language_100'!\n"));

        pWin->setGLObjectId(getGLId(), 0);

        return returnValue;
    }

    if(mode == Window::initialize   || 
       mode == Window::reinitialize ||
       mode == Window::needrefresh   )
    {
        GLuint uiProgram = GLuint(pWin->getGLObjectId(getGLId()));;

        if(mode != Window::needrefresh)
        {
            if(uiProgram != 0)
            {
                OSGGETGLFUNC(OSGglDeleteProgramProc,
                             osgGlDeleteProgram,
                             ShaderProgram::getFuncIdDeleteProgram());

                osgGlDeleteProgram(uiProgram);
            }

            OSGGETGLFUNC(OSGglCreateProgramProc,
                         osgGlCreateProgram,
                         ShaderProgram::getFuncIdCreateProgram());

            OSGGETGLFUNC(OSGglAttachShaderProc,
                         osgGlAttachShader,
                         ShaderProgram::getFuncIdAttachShader());

            OSGGETGLFUNC(OSGglLinkProgramProc,
                         osgGlLinkProgram,
                         ShaderProgram::getFuncIdLinkProgram());

            uiProgram = osgGlCreateProgram();

            FragmentShaderIt fIt  = _mfFragmentShader.begin();
            FragmentShaderIt fEnd = _mfFragmentShader.end  ();
            
            for(; fIt != fEnd; ++fIt)
            {
                (*fIt)->validate(pEnv);

                GLuint uiShader = 
                    GLuint(pWin->getGLObjectId((*fIt)->getGLId()));

                if(uiShader != 0)
                    osgGlAttachShader(uiProgram, uiShader);
            }
    
            GeometryShaderIt gIt  = _mfGeometryShader.begin();
            GeometryShaderIt gEnd = _mfGeometryShader.end  ();
            
            for(; gIt != gEnd; ++gIt)
            {
                (*gIt)->validate(pEnv);

                GLuint uiShader = 
                    GLuint(pWin->getGLObjectId((*gIt)->getGLId()));

                if(uiShader != 0)
                    osgGlAttachShader(uiProgram, uiShader);
            }
        
            VertexShaderIt vIt  = _mfVertexShader.begin();
            VertexShaderIt vEnd = _mfVertexShader.end  ();
            
            for(; vIt != vEnd; ++vIt)
            {
                (*vIt)->validate(pEnv);

                GLuint uiShader = 
                    GLuint(pWin->getGLObjectId((*vIt)->getGLId()));

                if(uiShader != 0)
                    osgGlAttachShader(uiProgram, uiShader);
            }

            // attribute binding must be done before linking
            updateAttribBindings(pEnv, uiProgram);

            // parameters must be set before linking
            updateParameters(pEnv, uiProgram);
            
            osgGlLinkProgram(uiProgram);

            GLint  iInfoLength;
            Char8 *szInfoBuffer = NULL;

            OSGGETGLFUNC(OSGglGetProgramivProc,
                         osgGlGetProgramiv,
                         ShaderProgram::getFuncIdGetProgramiv());

            osgGlGetProgramiv(uiProgram, 
                              GL_OBJECT_INFO_LOG_LENGTH_ARB, 
                              &iInfoLength);

            if(iInfoLength > 0)
            {
                szInfoBuffer = new Char8[iInfoLength];
                szInfoBuffer[0] = '\0';

                OSGGETGLFUNC(OSGglGetProgramInfoLogProc,
                             osgGlGetProgramInfoLog,
                             ShaderProgram::getFuncIdGetProgramInfoLog());

                osgGlGetProgramInfoLog( uiProgram, 
                                        iInfoLength, 
                                       &iInfoLength, 
                                        szInfoBuffer);
            }

            GLint iStatus = 0;

            osgGlGetProgramiv(uiProgram, GL_LINK_STATUS, &iStatus);

            if(iStatus == 0)
            {
                if(szInfoBuffer != NULL && szInfoBuffer[0] != '\0')
                {
                    FFATAL(("Couldn't link vertex and fragment program!\n%s\n",
                            szInfoBuffer));
                }
                else
                {
                    FFATAL(("Couldn't link vertex and fragment program!\n"
                            "No further info available\n"));
                }

                OSGGETGLFUNC(OSGglDeleteProgramProc,
                             osgGlDeleteProgram,
                             ShaderProgram::getFuncIdDeleteProgram());

                osgGlDeleteProgram(uiProgram);

                uiProgram = 0;
            }
            else
            {
                if(szInfoBuffer != NULL && szInfoBuffer[0] != '\0')
                {
                    FWARNING(("SHLChunk: link status: %s\n", szInfoBuffer));
                }
            }

            pWin->setGLObjectId(getGLId(), uiProgram);

            updateVariableLocations(pEnv, uiProgram);
            
            delete [] szInfoBuffer;
        }

        if(uiProgram != 0)
        {
            OSGGETGLFUNC(OSGglUseProgramProc,
                         osgGlUseProgram,
                         ShaderProgram::getFuncIdUseProgram());

            pEnv->setActiveShader(uiProgram);
            osgGlUseProgram      (uiProgram);
        
            updateVariables(pEnv, uiProgram);
        
            if(0x0000 == (uiOptions & KeepProgActive))
            {
                pEnv->setActiveShader(0);
                osgGlUseProgram      (0);
            }
            else
            {
                returnValue |= ProgActive;
            }
        }
    }

    return returnValue;
}
Exemplo n.º 14
0
UInt32 ComputeShaderChunk::handleGL(DrawEnv                 *pEnv, 
                                    UInt32                   id, 
                                    Window::GLObjectStatusE  mode,
                                    UInt64                   uiOptions)
{
    UInt32  returnValue = 0;
    Window *pWin        = pEnv->getWindow();

    if(!pWin->hasExtOrVersion(_arbComputeShader, 0x0403, 0xFFFF))
    {
        FWARNING(("OpenGL compute shader is not supported, couldn't find "
                  "extension 'GL_ARB_compute_shader'!\n"));

        pWin->setGLObjectId(getGLId(), 0);

        return returnValue;
    }

    if(mode == Window::initialize   || 
       mode == Window::reinitialize ||
       mode == Window::needrefresh   )
    {
        GLuint uiProgram = GLuint(pWin->getGLObjectId(getGLId()));;

        if(mode != Window::needrefresh)
        {
            if(uiProgram != 0)
            {
                OSGGETGLFUNCBYID_GL3_ES(glDeleteProgram,
                                        osgGlDeleteProgram,
                                        ShaderProgram::getFuncIdDeleteProgram(),
                                        pWin);

                osgGlDeleteProgram(uiProgram);
            }

            OSGGETGLFUNCBYID_GL3_ES(glCreateProgram,
                                    osgGlCreateProgram,
                                    ShaderProgram::getFuncIdCreateProgram(),
                                    pWin);

            OSGGETGLFUNCBYID_GL3_ES(glAttachShader,
                                    osgGlAttachShader,
                                    ShaderProgram::getFuncIdAttachShader(),
                                    pWin);

            OSGGETGLFUNCBYID_GL3_ES(glLinkProgram,
                                    osgGlLinkProgram,
                                    ShaderProgram::getFuncIdLinkProgram(),
                                    pWin);

            uiProgram = osgGlCreateProgram();
        
            ComputeShaderIt vIt  = _mfComputeShader.begin();
            ComputeShaderIt vEnd = _mfComputeShader.end  ();
            
            for(; vIt != vEnd; ++vIt)
            {
                (*vIt)->validate(pEnv);

                GLuint uiShader = 
                    GLuint(pWin->getGLObjectId((*vIt)->getGLId()));

                if(uiShader != 0)
                    osgGlAttachShader(uiProgram, uiShader);
            }

            osgGlLinkProgram(uiProgram);

            GLint  iInfoLength;
            Char8 *szInfoBuffer = NULL;

            OSGGETGLFUNCBYID_GL3_ES(glGetProgramiv,
                                    osgGlGetProgramiv,
                                    ShaderProgram::getFuncIdGetProgramiv(),
                                    pWin);

            osgGlGetProgramiv(uiProgram, 
                              GL_OBJECT_INFO_LOG_LENGTH_ARB, 
                              &iInfoLength);

            if(iInfoLength > 0)
            {
                szInfoBuffer = new Char8[iInfoLength];
                szInfoBuffer[0] = '\0';

                OSGGETGLFUNCBYID_GL3_ES(
                    glGetProgramInfoLog,
                    osgGlGetProgramInfoLog,
                    ShaderProgram::getFuncIdGetProgramInfoLog(),
                    pWin);

                osgGlGetProgramInfoLog( uiProgram, 
                                        iInfoLength, 
                                       &iInfoLength, 
                                        szInfoBuffer);
            }

            GLint iStatus = 0;

            osgGlGetProgramiv(uiProgram, GL_LINK_STATUS, &iStatus);

            if(iStatus == 0)
            {
                if(szInfoBuffer != NULL && szInfoBuffer[0] != '\0')
                {
                    FFATAL(("Couldn't link compute program!\n%s\n",
                            szInfoBuffer));
                }
                else
                {
                    FFATAL(("Couldn't link compute program!\n"
                            "No further info available\n"));
                }

                OSGGETGLFUNCBYID_GL3_ES(glDeleteProgram,
                                        osgGlDeleteProgram,
                                        ShaderProgram::getFuncIdDeleteProgram(),
                                        pWin);

                osgGlDeleteProgram(uiProgram);

                uiProgram = 0;
            }
            else
            {
                if(szInfoBuffer != NULL && szInfoBuffer[0] != '\0')
                {
                    FWARNING(("ComputeShaderChunk: link status: %s\n", 
                              szInfoBuffer));
                }
            }

            pWin->setGLObjectId(getGLId(), uiProgram);

            updateVariableLocations(pEnv, uiProgram);
        }

        if(uiProgram != 0)
        {
            OSGGETGLFUNCBYID_GL3_ES(glUseProgram,
                                    osgGlUseProgram,
                                    ShaderProgram::getFuncIdUseProgram(),
                                    pWin);
        
            osgGlUseProgram(uiProgram);
        
            updateVariables(pEnv, uiProgram);
        
            if(0x0000 == (uiOptions & KeepProgActive))
            {
                osgGlUseProgram(0);
            }
            else
            {
                returnValue |= ProgActive;
            }
        }
    }

    return returnValue;
}
UInt64 PNGImageFileType::storeData(const Image  *OSG_PNG_ARG  (pImage  ), 
                                         UChar8 *OSG_PNG_ARG  (buffer ),
                                         Int32   OSG_CHECK_ARG(memSize))
{
#ifdef OSG_WITH_PNG

    png_structp png_ptr;
    png_infop info_ptr;

    if(pImage->getDimension() < 1 || pImage->getDimension() > 2)
    {
        FWARNING(("PNGImageFileType::write: invalid dimension %d!\n",
                  pImage->getDimension()));
        return 0;
    }

    /* Create and initialize the png_struct with the desired error handler
    * functions.  If you want to use the default stderr and longjump method,
    * you can supply NULL for the last three parameters.  We also check that
    * the library version is compatible with the one used at compile time,
    * in case we are using dynamically linked libraries.  REQUIRED.
    */

    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
                                      0, &errorOutput, &warningOutput);
    
    if (png_ptr == NULL)
    {
        return 0;
    }

    /* Allocate/initialize the image information data.  REQUIRED */
    info_ptr = png_create_info_struct(png_ptr);

    if(info_ptr == NULL)
    {
        png_destroy_write_struct(&png_ptr,  NULL);
        return 0;
    }
    
    BufferInfo bufferInfo;
    bufferInfo.buffer = buffer;
    bufferInfo.length = 0;

    png_set_write_fn(png_ptr, 
                     static_cast<void *>(&bufferInfo), 
                     user_write_data, 
                     user_flush_data);

    /* This is the hard way */

    /* Set the image information here.  Width and height are up to 2^31,
    * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
    * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
    * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
    * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
    * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
    * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
    */

    Int32 ctype;
    switch(pImage->getPixelFormat())
    {
        case Image::OSG_L_PF:
            ctype = PNG_COLOR_TYPE_GRAY;        
            break;
            
        case Image::OSG_LA_PF:
            ctype = PNG_COLOR_TYPE_GRAY_ALPHA;          
            break;
            
#if defined(GL_BGR) || defined(GL_BGR_EXT)
        case Image::OSG_BGR_PF:
#endif
        case Image::OSG_RGB_PF: 
            ctype = PNG_COLOR_TYPE_RGB;                 
            break;
            
#if defined(GL_BGRA) || defined(GL_BGRA_EXT)
        case Image::OSG_BGRA_PF:
#endif
        case Image::OSG_RGBA_PF:
            ctype = PNG_COLOR_TYPE_RGB_ALPHA;           
            break;
            
        default:
            FWARNING(("PNGImageFileType::write: unknown pixel format %d!\n",
                      pImage->getPixelFormat()));
            png_destroy_write_struct(&png_ptr,  NULL);

            return 0;
    }
    
    Int32 bit_depth;

    switch (pImage->getDataType()) 
    {
        case Image::OSG_UINT8_IMAGEDATA:
            bit_depth = 8;
            break;
        case Image::OSG_UINT16_IMAGEDATA:
            bit_depth = 16;
            break;
        default:
            FWARNING (("Invalid pixeldepth, cannot store data\n"));
            return 0;
    };

    png_set_IHDR(png_ptr, 
                 info_ptr, 
                 pImage->getWidth(), 
                 pImage->getHeight(),
                 bit_depth,
                 ctype,      
                 PNG_INTERLACE_NONE, 
                 PNG_COMPRESSION_TYPE_BASE, 
                 PNG_FILTER_TYPE_BASE);
    
    /* other optional chunks like cHRM, bKGD, tRNS, tIME, oFFs, pHYs, */
    /* note that if sRGB is present the gAMA and cHRM chunks must be ignored
    * on read and must be written in accordance with the sRGB profile */

    /* Write the file header information.  REQUIRED */

    png_write_info(png_ptr, info_ptr);

#if BYTE_ORDER == LITTLE_ENDIAN
    if (bit_depth == 16)
        png_set_swap(png_ptr);
#endif
    
    if(pImage->getPixelFormat() == Image::OSG_BGR_PF ||
       pImage->getPixelFormat() == Image::OSG_BGRA_PF)
    {
        /* flip BGR pixels to RGB */
        png_set_bgr(png_ptr);
        
        /* swap location of alpha bytes from ARGB to RGBA */
        png_set_swap_alpha(png_ptr);
    }
    
    /* The easiest way to write the image (you may have a different memory
     * layout, however, so choose what fits your needs best).  You need to
     * use the first method if you aren't handling interlacing yourself.
     */

    png_bytep *row_pointers = new png_bytep [pImage->getHeight()];
    
    for(Int32 k = 0; k < pImage->getHeight(); k++)
    {
        row_pointers[k] = 
            (const_cast<UInt8 *>(pImage->getData())) + 
            (pImage->getHeight() - 1 - k) * 
            pImage->getWidth() * pImage->getBpp();
    }
    
    /* write out the entire image data in one call */
    png_write_image(png_ptr, row_pointers);

    /* It is REQUIRED to call this to finish writing the rest of the file */
    png_write_end(png_ptr, info_ptr);
    
    /* clean up after the write, and free any memory allocated */
    png_destroy_write_struct(&png_ptr, &info_ptr);

    delete [] row_pointers;

    /* that's it */
    return bufferInfo.length;
#else
    SWARNING << getMimeType() 
             << " storeData is not compiled into the current binary " 
             << std::endl;

    return 0;
#endif
}
Exemplo n.º 16
0
// Initialize GLUT & OpenSG and set up the scene
int main(int argc, char **argv)
{
    // OSG init
    osgInit(argc,argv);

    // GLUT init
    int winid = setupGLUT(&argc, argv);

    // the connection between GLUT and OpenSG
    GLUTWindowPtr gwin= GLUTWindow::create();
    gwin->setId(winid);
    gwin->init();

    // load the scene
    
    if(argc < 2)
    {
        FWARNING(("No file given!\n"));
        FWARNING(("Supported file formats:\n"));
        
        std::list<const char*> suffixes;
        SceneFileHandler::the().getSuffixList(suffixes);
        
        for(std::list<const char*>::iterator it  = suffixes.begin();
                                             it != suffixes.end();
                                           ++it)
        {
            FWARNING(("%s\n", *it));
        }

        std::vector<std::string> suffixesVec;
        suffixesVec = FCFileHandler::the()->getSuffixList();
        
        for(std::vector<std::string>::iterator it  = suffixesVec.begin();
                                             it != suffixesVec.end();
                                           ++it)
        {
            FWARNING(("%s\n", *it));
        }

        RootNodes.push_back( makeTorus(.5, 2, 16, 16) );
        glutSetWindowTitle("No file Loaded");
    }
    else
    {
        glutSetWindowTitle(argv[1]);
        Load(std::string(argv[1]), RootNodes, Cameras);

		if(RootNodes.size() < 1)
		{
			std::cout << "There are no root nodes defined." << std::endl;
			return 0;
		}
    }

    //Create Statistics Foreground
    SimpleStatisticsForegroundPtr TheStatForeground = SimpleStatisticsForeground::create();
    beginEditCP(TheStatForeground);
        TheStatForeground->setSize(25);
        TheStatForeground->setColor(Color4f(0,1,0,0.7));
        TheStatForeground->addElement(RenderAction::statDrawTime, "Draw FPS: %r.3f");
        TheStatForeground->addElement(DrawActionBase::statTravTime, "TravTime: %.3f s");
        TheStatForeground->addElement(RenderAction::statDrawTime, "DrawTime: %.3f s");
        TheStatForeground->addElement(DrawActionBase::statCullTestedNodes, 
                           "%d Nodes culltested");
        TheStatForeground->addElement(DrawActionBase::statCulledNodes, 
                           "%d Nodes culled");
        TheStatForeground->addElement(RenderAction::statNMaterials, 
                           "%d material changes");
        TheStatForeground->addElement(RenderAction::statNMatrices, 
                           "%d matrix changes");
        TheStatForeground->addElement(RenderAction::statNGeometries, 
                           "%d Nodes drawn");
        TheStatForeground->addElement(RenderAction::statNTransGeometries, 
                           "%d transparent Nodes drawn");
        TheStatForeground->addElement(Drawable::statNTriangles, 
                           "%d triangles drawn");
        TheStatForeground->addElement(Drawable::statNLines, 
                           "%d lines drawn");
        TheStatForeground->addElement(Drawable::statNPoints, 
                           "%d points drawn");
        TheStatForeground->addElement(Drawable::statNPrimitives,
                            "%d primitive groups drawn");
        TheStatForeground->addElement(Drawable::statNVertices, 
                           "%d vertices transformed");
        TheStatForeground->addElement(Drawable::statNGeoBytes, "%d bytes of geometry used");
        TheStatForeground->addElement(RenderAction::statNTextures, "%d textures used");
        TheStatForeground->addElement(RenderAction::statNTexBytes, "%d bytes of texture used");
    endEditCP(TheStatForeground);

	//Set up Selection
	SelectedRootNode = 0;
	SelectedCamera = -1;

    // create the SimpleSceneManager helper
    mgr = new SimpleSceneManager;

    // tell the manager what to manage
    mgr->setWindow(gwin );
    mgr->setRoot  (RootNodes[SelectedRootNode]);
    mgr->turnHeadlightOff();

    beginEditCP(mgr->getWindow()->getPort(0), Viewport::ForegroundsFieldMask);
        mgr->getWindow()->getPort(0)->getForegrounds().push_back(TheStatForeground);
    endEditCP(mgr->getWindow()->getPort(0), Viewport::ForegroundsFieldMask);
    StatCollector *collector = &TheStatForeground->getCollector();
    
    // add optional elements
    collector->getElem(Drawable::statNTriangles);
    
    mgr->getAction()->setStatistics(collector);

    // show the whole scene
    mgr->showAll();

    // GLUT main loop
    glutMainLoop();

    return 0;
}
void GeoMultiProperty::activate(DrawEnv *pEnv, 
                                UInt32   slot )
{
    Window *win = pEnv->getWindow();
    bool isGeneric = (slot >= 16);  // !!!HACK. needs to be replaced for 2.0
    slot &= 15;
    
    if(!win->hasExtOrVersion(_extVertexBufferObject, 0x0105, 0x0200))
    {
        FWARNING(("GeoMultiProperty::activate: Window %p doesn't "
                  "support VBOs!\n", win));
                  return;
    }
    
    win->validateGLObject(getContainer()->getGLId(), pEnv);

     // get "glBindBufferARB" function pointer

    OSGGETGLFUNCBYID_GL3_ES( glBindBuffer, 
                             osgGlBindBuffer,
                            _funcBindBuffer, 
                             win);
   
    osgGlBindBuffer(GL_ARRAY_BUFFER_ARB, 
                    win->getGLObjectId(getContainer()->getGLId()));

#define BUFFER_OFFSET(i)     (static_cast<char *>(NULL) + (i))

    if(isGeneric)
    {
        OSGGETGLFUNCBYID_GL3_ES( glVertexAttribPointer, 
                                 osgGlVertexAttribPointer,
                                _funcglVertexAttribPointerARB,
                                 win);

        osgGlVertexAttribPointer(slot, 
                                 getDimension(), 
                                 getFormat(), 
                                 getNormalize(),
                                 getStride(), 
                                 BUFFER_OFFSET(getOffset()));

        OSGGETGLFUNCBYID_GL3_ES( glEnableVertexAttribArray,
                                 osgGlEnableVertexAttribArray,
                                _funcglEnableVertexAttribArrayARB,
                                 win);
 
        osgGlEnableVertexAttribArray(slot);
    }
    else
    {
#if !defined(OSG_OGL_COREONLY) || defined(OSG_CHECK_COREONLY)
        switch(slot)
        {
            case 0:     
                glVertexPointer(getDimension(), getFormat(),
                                getStride(), BUFFER_OFFSET(getOffset()));
                glEnableClientState(GL_VERTEX_ARRAY);
                break;
            case 2:     
                glNormalPointer(getFormat(),
                                getStride(), BUFFER_OFFSET(getOffset()));
                glEnableClientState(GL_NORMAL_ARRAY);
                break;
            case 3:     
                glColorPointer(getDimension(), getFormat(),
                               getStride(), BUFFER_OFFSET(getOffset()));
                glEnableClientState(GL_COLOR_ARRAY);
                break;
            case 4:     
                if (win->hasExtOrVersion(_extSecondaryColor, 0x0104))
                {
                    OSGGETGLFUNCBYID_EXT( glSecondaryColorPointer,
                                          osgGlSecondaryColorPointer,
                                         _funcglSecondaryColorPointer,
                                          win);

                    osgGlSecondaryColorPointer(getDimension(),
                                               getFormat(),
                                               getStride(), 
                                               BUFFER_OFFSET(getOffset()));

                    glEnableClientState(GL_SECONDARY_COLOR_ARRAY_EXT);
                }
                else
                {
                    FWARNING(("GeoVectorProperty::activate: Window "
                              "has no Secondary Color extension\n"));
                }
                break;
            case 8:  case 9: 
            case 10: case 11: 
            case 12: case 13: 
            case 14: case 15: 
            {
                OSGGETGLFUNCBYID_GL3_ES( glClientActiveTexture,
                                         osgGlClientActiveTexture,
                                        _funcglClientActiveTextureARB,
                                         win);

                osgGlClientActiveTexture(GL_TEXTURE0_ARB + slot - 8);

                glTexCoordPointer(getDimension(), 
                                  getFormat(),
                                  getStride(), 
                                  BUFFER_OFFSET(getOffset()));

                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
            }
            break;
            default:    FWARNING(("GeoVectorProperty::activate: Non-Generic"
                                  " attribute nr. %d unknown!\n", slot));
                break;
        }     
#endif
    } // isGeneric

    osgGlBindBuffer(GL_ARRAY_BUFFER_ARB, 0);
}
Exemplo n.º 18
0
/*! Init the window: create the context and setup the OpenGL.
*/
void XWindow::init(GLInitFunctor oFunc)
{  
    if(_sfFbConfigId.getValue() == -1)
    {
        classicInit();
    }
    else
    {
        OSGGETGLFUNCBYNAME(OSGglxChooseFBConfigProc, 
                           osgGlxChooseFBConfig,
                           "glXChooseFBConfig",
                           this);

        OSG_ASSERT(osgGlxChooseFBConfig != NULL);

        int iMatching;

        int fbAttr[] =
        {
            GLX_FBCONFIG_ID, _sfFbConfigId.getValue(),
            None
        };

        GLXFBConfig *fbConfigs = 
            osgGlxChooseFBConfig( getDisplay(),
                                  DefaultScreen(getDisplay()),
                                  fbAttr,
                                 &iMatching);

        if(iMatching <= 0)
        {
            fprintf(stderr, "no valid fbconfig %d\n",
                    _sfFbConfigId.getValue());

            exit(0);
        }


        OSGGETGLFUNCBYNAME(OSGglxCreateContextAttribsARB, 
                           osgGlXCreateContextAttribsARB,
                           "glXCreateContextAttribsARB",
                           this);

        if(osgGlXCreateContextAttribsARB != NULL)
        {
            std::vector<int> ctxAttr;
        
            if(getRequestMajor() > 0)
            {
                ctxAttr.push_back(GLX_CONTEXT_MAJOR_VERSION_ARB);
                ctxAttr.push_back(getRequestMajor());
                ctxAttr.push_back(GLX_CONTEXT_MINOR_VERSION_ARB);
                ctxAttr.push_back(getRequestMinor());
            }
         
            if(getContextFlags() != 0)
            {
                ctxAttr.push_back(GLX_CONTEXT_FLAGS_ARB);
                ctxAttr.push_back(getContextFlags()    );
            }
            
            ctxAttr.push_back(None);
            
            this->setContext(osgGlXCreateContextAttribsARB( getDisplay(),
                                                            fbConfigs[0],
                                                            None,
                                                            GL_TRUE,
                                                           &(ctxAttr.front())));
            
            if(getContext() == NULL)
            {
                FWARNING(("Could not create context, requested version "
                          "%d.%d might not be supported (guessing)\n",
                          getRequestMajor(),
                          getRequestMinor()));
                
                exit(0);
            }

            XFree(fbConfigs);
        }
        else
        {
            classicInit();
        }
    }

    Inherited::init(oFunc);
}
Exemplo n.º 19
0
bool DATImageFileType::read(      Image *image,
                            const Char8 *fileName)
{
    bool retCode = false;

    std::ifstream inDat(fileName), inVolS;
    std::istream *inVol;
    std::string keyStr, objectFileName;
    const UInt32 lineBufferSize = 1024;
    Char8 *value, *keySepPos, lineBuffer[lineBufferSize];
    const Char8 keySep = ':';
    int fileOffset, keyL, valueL;
    std::map<std::string, KeyType>::iterator keyI;
    std::map<std::string, FormatDesc>::iterator formatI;
    KeyType key;
    Image::Type formatType;
    UInt32 channel = 1;
    UInt32 res[3];
    UInt32 dataSize = 0;
    Image::PixelFormat pixelFormat = Image::OSG_L_PF;
    char *dataBuffer = 0;
    bool needConversion = false;
    // default endian type is big endian
    bool big_endian = true;

    res[0] = res[1] = res[2] = 0;
    fileOffset = 0;
    formatType = Image::OSG_INVALID_IMAGEDATATYPE;
    dataSize = 0;
    dataBuffer = 0;

    initTypeMap();

    // read the data file
    for(lineBuffer[0] = 0;
        inDat.getline(lineBuffer, lineBufferSize);
        lineBuffer[0] = 0)
    {
        if((keySepPos = strchr(lineBuffer,keySep)))
        {
            keyL = keySepPos - lineBuffer;
            keyStr.assign( lineBuffer, keyL );
            keyI = _keyStrMap.find(keyStr);
            key = ((keyI == _keyStrMap.end()) ? UNKNOWN_KT : keyI->second);
            value = keySepPos + 1;

            while (value && isspace(*value))
                value++;

            valueL = int(strlen(value));

            while (isspace(value[valueL-1]))
                value[--valueL] = 0;

            switch (key)
            {
                case OBJECT_FILE_NAME_KT:
                    objectFileName = value;
                    image->setAttachmentField ( keyStr, value );
                    break;
                case CHANNEL_KT:
                    sscanf ( value, "%u", &(channel) );
                    image->setAttachmentField ( keyStr, value );
                    break;
                case RESOLUTION_KT:
                    sscanf ( value, "%u %u %u",
                             &(res[0]), &(res[1]), &(res[2]));
                    image->setAttachmentField ( keyStr, value );
                    break;
                case FORMAT_KT:
                    formatI = _formatStrMap.find(value);
                    if (formatI != _formatStrMap.end())
                    {
                        formatType = formatI->second.type;
                    }
                    else
                    {
                        formatType = Image::OSG_INVALID_IMAGEDATATYPE;
                    }
                    image->setAttachmentField ( keyStr, value );
                    break;
                case ENDIAN_KT:
                    if(!strcmp(value, "LITTLE"))
                        big_endian = false;
                    image->setAttachmentField ( keyStr, value );
                    break;
                case FILE_OFFSET_KT:
                    sscanf ( value, "%d", &fileOffset );
                    image->setAttachmentField ( keyStr, value );
                    break;
                case UNKNOWN_KT:
                    FNOTICE (( "Uknown DAT file key: >%s<\n",
                                 keyStr.c_str() ));
                    image->setAttachmentField ( keyStr, value );
                    break;
                case SLICE_THICKNESS_KT:
                default:
                    image->setAttachmentField ( keyStr, value );
                    break;
            }
        }
        else
        {
            FINFO (("Skip DAT line\n"));
        }
    }

    // set pixelformat
    switch (channel) 
    {
        case 4:
            pixelFormat = Image::OSG_RGBA_PF;
            break;
        case 3:
            pixelFormat = Image::OSG_RGB_PF;
            break;
        case 2:
            pixelFormat = Image::OSG_LA_PF;
            break;
        default:
            pixelFormat = Image::OSG_L_PF;
            break;
    }

    // check the setting and read the raw vol data
    if (objectFileName.empty() == false)
    {
        if((res[0] > 0) && (res[1] > 0) && (res[2] > 0))
        {
            if(formatType != Image::OSG_INVALID_IMAGEDATATYPE)
            {
                inVolS.open(objectFileName.c_str(),
                            std::ios::in | std::ios::binary);

                if (inVolS.fail() && ImageFileHandler::the()->getPathHandler())
                {
                    // Try to find the file in the search path
                    inVolS.clear(); // reset the error state

                    PathHandler *ph =
                        ImageFileHandler::the()->getPathHandler();

                    inVolS.open(ph->findFile(objectFileName.c_str()).c_str(),
                                std::ios::in | std::ios::binary );
                }

                if(inVolS.fail())
                {
                    // Maybe compressed and name not changed?
                    std::string gzname = objectFileName + ".gz";

                    inVolS.clear(); // reset the error state

                    inVolS.open(gzname.c_str(),
                                std::ios::in | std::ios::binary );

                    if(inVolS.fail() &&
                       ImageFileHandler::the()->getPathHandler())
                    {
                        // Try to find the file in the search path
                        inVolS.clear(); // reset the error state

                        PathHandler *ph =
                            ImageFileHandler::the()->getPathHandler();

                        inVolS.open(ph->findFile(gzname.c_str()).c_str(),
                                    std::ios::in | std::ios::binary );
                    }
                }

                if(inVolS.good())
                {
#ifdef OSG_WITH_ZLIB
                    zip_istream *unzipper = NULL;
#endif

                    image->set(pixelFormat,
                               res[0], res[1], res[2],
                               1, 1, 0.0, 0,
                               formatType);

                    image->clear();

                    dataSize = image->getSize();

                    UInt32 fileDataSize = dataSize;

                    if(isGZip(inVolS))
                    {
#ifdef OSG_WITH_ZLIB
                        unzipper = new zip_istream(inVolS);
                        inVol = unzipper;
#else
                        SFATAL << "Compressed streams are not supported! "
                               << "Configure with --enable-png "
                               << "--with-png=DIR options." << std::endl;
#endif
                    }
                    else
                    {
                        inVol = &inVolS;

                        // get length of the stream.
                        inVol->seekg(0, std::ios::end);
                        UInt64 length = inVol->tellg();
                        inVol->seekg(0, std::ios::beg);

                        if(length < dataSize - fileOffset)
                        {
                            // correct dataSize.
                            fileDataSize = length;
                            FWARNING (( "RAW file length to small!\n" ));
                        }
                        else if(length > dataSize - fileOffset)
                        {
                            FWARNING (( "RAW file length to big!\n" ));
                        }
                    }

                    if(needConversion)
                    {
                        dataBuffer = new char [ dataSize ];
                    }
                    else
                    {
                        dataBuffer = 
                            reinterpret_cast<char *>(image->editData());
                    }

                    if(fileOffset != 0)
                        inVol->ignore (fileOffset);

                    inVol->read ( dataBuffer, fileDataSize );

#ifdef OSG_WITH_ZLIB
                    if(unzipper != NULL)
                        delete unzipper;
#endif
                }
                else
                {
                    FWARNING (( "Can not open %s image data\n",
                                objectFileName.c_str() ));
                }
            }
            else
            {
                FWARNING (( "Invalid/Missing DAT Format\n" ));
            }
        }
        else
        {
            FWARNING (( "Invalid/Missing DAT Resolution\n" ));
        }
    }
    else
    {
        FWARNING (( "Invalid/Missing DAT ObjectFileName\n" ));
    }

    // check/reformat vol data
    if (dataSize && dataBuffer)
    {
        // check host endian type
        UInt16 word = 0x0001;
        UInt8 *byte = reinterpret_cast<UInt8 *>(&word);
        bool host_big_endian = byte[0] ? false : true;

        if(big_endian != host_big_endian)
            image->swapDataEndian();

        if (needConversion)
        {
            FLOG (("DAT-Data convert not impl. yet !\n"));
            {
                switch (formatType)
                {
                    case Image::OSG_UINT8_IMAGEDATA:
                        break;
                    case Image::OSG_UINT16_IMAGEDATA:
                        break;
                    case Image::OSG_UINT32_IMAGEDATA:
                        break;
                    case Image::OSG_FLOAT32_IMAGEDATA:
                        break;
                    default:
                        ;
                }
            }
        }
        else
        {
            retCode = true;
        }
    }


    /* TODO
       std::ifstream in(fileName);
       Head head;
       void *headData = (void*)(&head);
       unsigned dataSize, headSize = sizeof(Head);

       if ( in &&
       in.read(static_cast<char *>(headData),
       headSize) && head.netToHost() &&
       image.set ( Image::PixelFormat(head.pixelFormat),
       head.width, head.height, head.depth, head.mipmapCount,
       head.frameCount, float(head.frameDelay) / 1000.0) &&
       (dataSize = image.getSize()) &&
       in.read((char *)(image.getData()), dataSize ))
       retCode = true;
       else
       retCode = false;
    */

    return retCode;
}
void init(int argc, char *argv[])
{
    OSG::osgInit(argc, argv);

    int glutWinId = setupGLUT(&argc, argv);

    // the connection between GLUT and OpenSG
    OSG::GLUTWindowUnrecPtr gwin= OSG::GLUTWindow::create();
    gwin->setGlutId(glutWinId);
    gwin->init();
    
    // load the scene
    root  = OSG::ChunkOverrideGroup::create();
    rootN = OSG::makeNodeFor(root);
        
    if(argc < 2)
    {
        FWARNING(("No file given!\n"));
        FWARNING(("Supported file formats:\n"));
            
        OSG::SceneFileHandler::the()->print();
        sceneN = OSG::makeTorus(.5, 2, 16, 16);
    }
    else
    {
        /*
          All scene file loading is handled via the SceneFileHandler.
        */
        sceneN = OSG::SceneFileHandler::the()->read(argv[1]);
    }

    OSG::TransformUnrecPtr xform  = OSG::Transform::create();
    OSG::NodeUnrecPtr      xformN = OSG::makeNodeFor(xform);

    // xform->editMatrix().setTranslate(OSG::Vec3f(100.f, 0.f, 0.f));
    // xform->editMatrix().setRotate(OSG::Quaternion(OSG::Vec3f(0.f, 1.f, 0.f), 0.3f * OSG::Pi));

    OSG::NodeUnrecPtr     boxN    = OSG::makeBox(1.f, 1.f, 5.f, 1, 1, 1);

    xformN->addChild(sceneN);
    rootN ->addChild(xformN);
    rootN ->addChild(boxN  );

    OSG::commitChanges();
    
    // collect geometries in the scene
    collectGeometry(rootN);

    // construct skin shader
    vpSkin = OSG::ShaderProgram::createVertexShader  ();
    vpSkin->setProgram(vpCode);

    fpSkin = OSG::ShaderProgram::createFragmentShader();
    fpSkin->setProgram(fpCode);

    shSkin = OSG::ShaderProgramChunk::create();
    shSkin->addShader(vpSkin);
    shSkin->addShader(fpSkin);

    matSkin = OSG::ChunkMaterial::create();
    matSkin->addChunk(shSkin);

    // process animations
    processAnim(sceneN);

    // create the SimpleSceneManager helper
    mgr = OSG::SimpleSceneManager::create();
    
    // tell the manager what to manage
    mgr->setWindow(gwin );
    mgr->setRoot  (rootN);
    
    // show the whole scene
    mgr->showAll();
}
Exemplo n.º 21
0
void TreeRenderer::initialize(Window *win)
{
    if(!_initDone)
    {
        // without this the registered extensions are not valid yet!
        win->frameInit();

        //check support for ShadowExtension
        if(!win->hasExtension(_depth_texture_extension))
        {
            SWARNING <<
                "No ARB_depth_texture-Extension available! All shadow modes disabled." << endLog;
            _useShadowExt = false;
        }
        else if(!win->hasExtension(_shadow_extension))
        {
            SWARNING <<
                "No ARB_shadow-Extension available! All shadow modes disabled."
                << endLog;
            _useShadowExt = false;
        }

        //check support for framebuffer objects
        _useFBO = _shadowVP->getFboOn();

        if(!win->hasExtension("GL_EXT_framebuffer_object"))
            _useFBO = false;

        if(_useFBO)
        {
            FNOTICE(("framebuffer objects supported.\n"));
        }
        else
        {
            FNOTICE(
                (
                "framebuffer objects not supported, try new video drivers. Some shadow modes will be disabled.\n"));
        }

        //check support for non-power-of-two textures
        _useNPOTTextures = true;

        if(!win->hasExtension("GL_ARB_texture_non_power_of_two"))
            _useNPOTTextures = false;

        if(_useNPOTTextures)
        {
            FNOTICE(("texture_non_power_of_two supported.\n"));
        }
        else
        {
            FNOTICE(("texture_non_power_of_two not supported by hardware.\n"));
        }

        //check if GLSL is available
        _useGLSL = true;
        if(!win->hasExtension("GL_ARB_shading_language_100") ||
           !win->hasExtension("GL_ARB_fragment_shader") ||
           !win->hasExtension("GL_ARB_vertex_shader") ||
           !win->hasExtension("GL_ARB_shader_objects"))
        {
            _useGLSL = false;
        }

        if(!_useGLSL)
        {
            FNOTICE(
                (
                "GLSL not supported, some shadow modes and real point lights will be disabled.\n"));
        }
        else
        {
            FNOTICE(("GLSL supported.\n"));
        }

        //check for Shader Model 3.0
        _useShaderModel3 = false;

        if(win->hasExtension("GL_NV_vertex_program3") ||
           win->hasExtension("GL_ATI_shader_texture_lod"))
            _useShaderModel3 = true;

        if(!_useShaderModel3)
        {
            FNOTICE(("Shader Model 3.0 NOT supported.\n"));
        }
        else
        {
            FNOTICE(("Shader Model 3.0 supported.\n"));
        }

        //No NPOTTextures supportet if FBOs are disabled
        if(!_useFBO)
            _useNPOTTextures = false;

        if(_useFBO)
        {
            GLenum  errCode;
            bool    FBOerror = false;

            glBindFramebufferEXT =
                reinterpret_cast<OSGGLBINDFRAMEBUFFEREXTPROC>(
                    win->getFunction(_funcBindFramebuffer));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glBindRenderbufferEXT =
                reinterpret_cast<OSGGLBINDRENDERBUFFEREXTPROC>(
                    win->getFunction(_funcBindRenderbuffer));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glCheckFramebufferStatusEXT =
                reinterpret_cast<OSGGLCHECKFRAMEBUFFERSTATUSEXTPROC>(
                    win->getFunction(_funcCheckFramebufferStatus));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glDeleteFramebuffersEXT =
                reinterpret_cast<OSGGLDELETEFRAMEBUFFERSEXTPROC>(
                    win->getFunction(_funcDeleteFramebuffers));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glDeleteRenderbuffersEXT =
                reinterpret_cast<OSGGLDELETERENDERBUFFERSEXTPROC>(
                    win->getFunction(_funcDeleteRenderbuffers));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glFramebufferRenderbufferEXT =
                reinterpret_cast<OSGGLFRAMEBUFFERRENDERBUFFEREXTPROC>(
                    win->getFunction(_funcFramebufferRenderbuffer));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glFramebufferTexture1DEXT =
                reinterpret_cast<OSGGLFRAMEBUFFERTEXTURE1DEXTPROC>(
                    win->getFunction(_funcFramebufferTexture1D));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glFramebufferTexture2DEXT =
                reinterpret_cast<OSGGLFRAMEBUFFERTEXTURE2DEXTPROC>(
                    win->getFunction(_funcFramebufferTexture2D));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glFramebufferTexture3DEXT =
                reinterpret_cast<OSGGLFRAMEBUFFERTEXTURE3DEXTPROC>(
                    win->getFunction(_funcFramebufferTexture3D));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glGenFramebuffersEXT =
                reinterpret_cast<OSGGLGENFRAMEBUFFERSEXTPROC>(
                    win->getFunction(_funcGenFramebuffers));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glGenRenderbuffersEXT =
                reinterpret_cast<OSGGLGENRENDERBUFFERSEXTPROC>(
                    win->getFunction(_funcGenRenderbuffers));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glGenerateMipmapEXT =
                reinterpret_cast<OSGGLGENERATEMIPMAPEXTPROC>(
                    win->getFunction(_funcGenerateMipmap));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glGetFramebufferAttachmentParameterivEXT =
                reinterpret_cast<
                    OSGGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC>(
                        win->getFunction(
                            _funcGetFramebufferAttachmentParameteriv));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glGetRenderbufferParameterivEXT =
                reinterpret_cast<OSGGLGETRENDERBUFFERPARAMETERIVEXTPROC>(
                    win->getFunction(_funcGetRenderbufferParameteriv));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glIsFramebufferEXT =
                reinterpret_cast<OSGGLISFRAMEBUFFEREXTPROC>(
                    win->getFunction(_funcIsFramebuffer));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glIsRenderbufferEXT =
                reinterpret_cast<OSGGLISRENDERBUFFEREXTPROC>(
                    win->getFunction(_funcIsRenderbuffer));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glRenderbufferStorageEXT =
                reinterpret_cast<OSGGLRENDERBUFFERSTORAGEEXTPROC>(
                    win->getFunction(_funcRenderbufferStorage));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            glDrawBuffersARB =
                reinterpret_cast<OSGGLDRAWBUFFERSARBPROC>(
                    win->getFunction(_funcDrawBuffers));

            if((errCode = glGetError()) != GL_NO_ERROR)
                FBOerror = true;

            GLenum  status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);

            if(FBOerror)
            {
                FNOTICE(
                    (
                    "Needed FBO functions could not be initialized (error code %d), FBOs disabled. Try new video drivers!\n", errCode));
                _useFBO = false;
            }

            switch(status)
            {
                case GL_FRAMEBUFFER_COMPLETE_EXT:
                    FINFO(("%x: framebuffer complete!\n", status));
                    break;
                case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
                    FWARNING(
                        ("%x: framebuffer GL_FRAMEBUFFER_UNSUPPORTED_EXT\n",
                         status));
                    break;
                default:
                    break;
            }
        }
        _initDone = true;
    }
}
static void warningOutput (png_structp OSG_CHECK_ARG(png_ptr), 
                           const char *message)
{
    FWARNING (("PNG: %s\n", message )); 
}
Exemplo n.º 23
0
/*!
    Tries to write the image object to the given output stream.
    Returns true on success.
*/
bool EXRImageFileType::write(const Image        *image, 
                                   std::ostream &os, 
                             const std::string  &mimetype)
{
#ifdef OSG_WITH_IMF
    if (!os.good())
        return false;

    if(image->getDataType() != Image::OSG_FLOAT16_IMAGEDATA)
    {
        FWARNING(("EXRImageFileType::write: Image has non float data type!\n"));
        return false;
    }
    if(image->getComponents() != 4)
    {
        FWARNING(("EXRImageFileType::write: Image has != 4 components!\n"));
        return false;
    }
    if (image->getSideCount() == 6)
    {
        FWARNING(("EXRImageFileType::write: NYI for cubemaps\n"));  //TODO
        return false;
    }

    try
    {
        Int32 width  = image->getWidth();
        Int32 height = image->getHeight();

        const char *dummy = "";
        StdOStream file(os, dummy);
        Imf::Header header(width, height);

#if 0
        // now add custom attributes
        ImageGenericAtt *att = dynamic_cast<ImageGenericAtt *>(
            image->findAttachment(
                ImageGenericAtt::getClassType().getGroupId()));

        if(att != NULL)
        {
            FieldContainerType  &fcType = att->getType();
            Int32 count = att->getType().getNumFieldDescs();

            for(Int32 i = 1; i <= count; ++i)
            {
                FieldDescriptionBase *fDesc = fcType.getFieldDesc(i);
                Field                *field = att->getField(i);

                if(fDesc != NULL && field != NULL)
                {
                    SFString *strField = dynamic_cast<SFString*>(field);

                    if(strField != NULL)
                    {
                        Imf::StringAttribute imfAttr(
                            strField->getValue().c_str());

                        header.insert(fDesc->getCName(), imfAttr);
                    }
                }
            }
        }
#endif

        // we write each side as 4 channels out
        // side 0 RGBA
        // side 1 R1G1B1A1
        // ...
        for(Int32 side=0;side<image->getSideCount();++side)
        {
            char cn[20];
            sprintf(cn, "%d", side);

            char name[20];
            sprintf(name, "R%s", side == 0 ? "" : cn);
            header.channels().insert(name, Imf::Channel(Imf::HALF));
            sprintf(name, "G%s", side == 0 ? "" : cn);
            header.channels().insert(name, Imf::Channel(Imf::HALF));
            sprintf(name, "B%s", side == 0 ? "" : cn);
            header.channels().insert(name, Imf::Channel(Imf::HALF));
            sprintf(name, "A%s", side == 0 ? "" : cn);
            header.channels().insert(name, Imf::Channel(Imf::HALF));
        }

        Imf::OutputFile stream(file, header);
        Imf::FrameBuffer frame_buffer;

        // we need to do a vertical flip so we write single scan lines out.
        for(int i=height-1;i>=0;--i)
        {
            for(Int32 side=0;side<image->getSideCount();++side)
            {
                const char *data = (reinterpret_cast<const char *>(image->getData(0, 0, side))) + i * (sizeof(Real16) * 4 * width);

                // writePixels() adds the current scan line index as an offset to the
                // base address we need to eliminate this!
                data -= stream.currentScanLine() * (sizeof(Real16) * 4 * width);

                char cn[20];
                sprintf(cn, "%d", side);
                char name[20];
                sprintf(name, "R%s", side == 0 ? "" : cn);
                frame_buffer.insert(name, Imf::Slice(Imf::HALF, 
                                                     const_cast<char *>(data), sizeof(Real16) * 4, sizeof(Real16) * 4 * width));
                sprintf(name, "G%s", side == 0 ? "" : cn);
                frame_buffer.insert(name, Imf::Slice(Imf::HALF, 
                                                     const_cast<char *>(data) + 1 * sizeof(Real16), sizeof(Real16) * 4, sizeof(Real16) * 4 * width));
                sprintf(name, "B%s", side == 0 ? "" : cn);
                frame_buffer.insert(name, Imf::Slice(Imf::HALF, 
                                                     const_cast<char *>(data) + 2 * sizeof(Real16), sizeof(Real16) * 4, sizeof(Real16) * 4 * width));
                sprintf(name, "A%s", side == 0 ? "" : cn);
                frame_buffer.insert(name, Imf::Slice(Imf::HALF, 
                                                     const_cast<char *>(data) + 3 * sizeof(Real16), sizeof(Real16) * 4, sizeof(Real16) * 4 * width));
            }
            stream.setFrameBuffer(frame_buffer);
            stream.writePixels(1);
        }

        return true;
    }
    catch(std::exception &e)
    {
        FFATAL(( "Error while trying to write OpenEXR Image from stream: %s\n",
                  e.what() ));
        return false;
    }

#else
    SWARNING << getMimeType()
             << " write is not compiled into the current binary "
             << std::endl;
    return false;
#endif
}
bool PNGImageFileType::read(      Image        *OSG_PNG_ARG(pImage  ), 
                                  std::istream &OSG_PNG_ARG(is      ),
                            const std::string  &OSG_PNG_ARG(mimetype))
{
#ifdef OSG_WITH_PNG

    bool                retCode;
    Image::PixelFormat  pixelFormat = OSG::Image::OSG_INVALID_PF;
    png_structp         png_ptr;
    png_infop           info_ptr;
    png_uint_32         width, wc, height, h, i, res_x, res_y;
    png_byte            bit_depth, channels, color_type;
    png_bytep           *row_pointers, base;

    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);

    if(!png_ptr)
        return false;

    png_set_error_fn(png_ptr, 0, &errorOutput, &warningOutput);

    info_ptr = png_create_info_struct(png_ptr);

    if(!info_ptr)
    {
        png_destroy_read_struct(&png_ptr, 0, 0);
        return false;
    }

    if(setjmp(png_ptr->jmpbuf))
    {
        png_destroy_read_struct(&png_ptr, &info_ptr, 0);
        return false;
    }

    png_set_read_fn(png_ptr, &is, &isReadFunc);

    png_read_info(png_ptr, info_ptr);

    width = png_get_image_width(png_ptr, info_ptr);
    height = png_get_image_height(png_ptr, info_ptr);
    bit_depth = png_get_bit_depth(png_ptr, info_ptr);
    res_x = png_get_x_pixels_per_meter(png_ptr, info_ptr);
    res_y = png_get_y_pixels_per_meter(png_ptr, info_ptr);
    channels = png_get_channels(png_ptr, info_ptr);
    color_type = png_get_color_type(png_ptr, info_ptr);

    // Convert paletted images to RGB
    if (color_type == PNG_COLOR_TYPE_PALETTE)
    {
        png_set_palette_to_rgb(png_ptr);
        channels = 3;
        bit_depth = 8;
    }

    // Convert < 8 bit to 8 bit
    if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
    {
        png_set_gray_1_2_4_to_8(png_ptr);
        bit_depth = 8;
    }

#if BYTE_ORDER == LITTLE_ENDIAN
    if (bit_depth == 16)
        png_set_swap(png_ptr);
#endif

    // Add a full alpha channel if there is transparency
    // information in a tRNS chunk
    if(png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
    {
        png_set_tRNS_to_alpha(png_ptr);
        ++channels;
    } 

    Int32 dataType;

    switch (bit_depth) 
    {
        case 8:
            dataType = Image::OSG_UINT8_IMAGEDATA;
            break;
        case 16:
            dataType = Image::OSG_UINT16_IMAGEDATA;
            break;
        default:
            FWARNING (( "Invalid bit_depth: %d, can not read png-data\n",
                        bit_depth ));
            return false;
    }

    switch(channels)
    {
        case 1:
            pixelFormat = Image::OSG_L_PF;
            break;
        case 2:
            pixelFormat = Image::OSG_LA_PF;
            break;
        case 3:
            pixelFormat = Image::OSG_RGB_PF;
            break;
        case 4:
            pixelFormat = Image::OSG_RGBA_PF;
        break;
    };
    
    if(pImage->set(pixelFormat, width, height,
                   1, 1, 1, 0.0, 0,
                   dataType))
    {
        // set resolution png supports only pixel per meter,
        // so we do a conversion to dpi with some rounding.
        res_x = png_uint_32((Real32(res_x) / 39.37007874f) < 0.0f ?
                            (Real32(res_x) / 39.37007874f) - 0.5f :
                            (Real32(res_x) / 39.37007874f) + 0.5f);
        res_y = png_uint_32((Real32(res_y) / 39.37007874f) < 0.0f ?
                            (Real32(res_y) / 39.37007874f) - 0.5f :
                            (Real32(res_y) / 39.37007874f) + 0.5f);

        pImage->setResX(Real32(res_x));
        pImage->setResY(Real32(res_y));
        pImage->setResUnit(Image::OSG_RESUNIT_INCH);

        // Calculate the row pointers
        row_pointers = new png_bytep[height];
        wc = width * channels * (bit_depth / 8);
        h = height - 1;
        base = pImage->editData();

        for(i = 0; i < height; ++i)
            row_pointers[i] = base + (h - i) * wc;

        // Read the image data
        png_read_image(png_ptr, row_pointers);

        delete[] row_pointers;

        retCode = true;
    }
    else
    {
        retCode = false;
    }

    png_destroy_read_struct(&png_ptr, &info_ptr, 0);

    return retCode;

#else

    SWARNING << getMimeType() 
             << " read is not compiled into the current binary " 
             << std::endl;

    return false;

#endif

}
Exemplo n.º 25
0
bool Text::fillImage(ImagePtr & image, 
                     std::vector<std::string> &lineVec, 
                     Color4ub *fg,
                     Color4ub *bg, 
                     bool forcePower2, 
                     Real32 *maxX,
                     Real32 *maxY,
                     ImageCreationMode OSG_CHECK_ARG(creationMode),
                     MergeMode OSG_CHECK_ARG(mergeMode), 
                     Int32 pixelDepth,
					 bool bConvertToBitmap ) const
{
    ImageFontGlyph  ***g;
    UChar8          *img = 0;
    const Int32     *res;
    const Char8     *text = 0;
    Int32           pen_x, pen_y, line, xoff, yoff;
    Int32           width = 0, overallWidth = 0, height = 0, overallHeight = 0;
    Int32           i, j, k, l, tmpMinY, tmpMaxY, strStart, strEnd, strStep;
    Int32           p, tmpWidth;
    UChar8          *srcPixel, *imageBuffer = 0, *row = 0, *dstPixel;
    bool            retVal;

    if(forcePower2 && (!maxX || !maxY))
        return false;

    if(_fontInstance)
    {
        g = new ImageFontGlyph **[lineVec.size()];
        for(line = 0; line < Int32(lineVec.size()); line++)
        {
            text = lineVec[line].c_str();
            g[line] = new ImageFontGlyph *[strlen(text)];
            tmpMinY = INT_MAX;
            tmpMaxY = -INT_MAX;
            for(i = 0; i < Int32(strlen(text)); i++)
            {
                g[line][i] = _fontInstance->getImageGlyph(text[i]);
                if(g[line][i])
                {
                    retVal = g[line][i]->create();
                    if(!retVal)
                    {
                        FWARNING(("Glyph generation failed."));
                        for(line = 0; line < Int32(lineVec.size()); line++)
                            delete[] g[line];
                        delete[] g;
                    }

                    width += (i + 1 == Int32(strlen(text)) ? 
                                g[line][i]->getImageSize()[0] : 
                                g[line][i]->getAdvance());
                    tmpMinY = g[line][i]->getBoundingBox()[2] < tmpMinY ? 
                                g[line][i]->getBoundingBox()[2] : 
                                tmpMinY;
                    tmpMaxY = g[line][i]->getBoundingBox()[3] > tmpMaxY ? 
                                g[line][i]->getBoundingBox()[3] : 
                                tmpMaxY;
                }
            }

            if(width > overallWidth)
                overallWidth = width;

            if(!tmpMinY && !tmpMaxY)
            {   // TXF-character not present -> all blanks..
                tmpMaxY = 
                    Int32(osgfloor(Real32(_fontInstance->getBaselineSkip())));
            }

            overallHeight += ( line + 1 == lineVec.size() ? 
                               Int32(osgfloor((abs(tmpMaxY) + 
                                               abs(tmpMinY)) * _spacing)) :
                               
                               Int32(osgfloor(
                                         Real32(_fontInstance->getBaselineSkip()) *
                                         Real32(_fontInstance->getYRes()) * 
                                         _spacing)));
            width = 0;
        }

        if(forcePower2)
        {
            height = 1;
            while(height < overallHeight)
                height *= 2;
            *maxY = (Real32(height)) / (Real32(overallHeight));
            overallHeight = height;

            width = 1;
            while(width < overallWidth)
                width *= 2;
            *maxX = (Real32(width)) / (Real32(overallWidth));
            overallWidth = width;
        }

        imageBuffer = new UChar8[overallWidth * overallHeight * pixelDepth];
        row = new UChar8[overallWidth * pixelDepth];

        for(i = 0; i < overallWidth * pixelDepth;)
        {
            for(l = 0; l < pixelDepth; l++, i++)
                row[i] = (*bg)[l];
        }

        for(i = 0; i < overallHeight; i++)
        {
            memcpy(imageBuffer + i * overallWidth * pixelDepth, row,
                               overallWidth * pixelDepth);
        }

        delete[] row;

        tmpMinY = INT_MAX;
        tmpMaxY = -INT_MAX;

        tmpWidth = 0;
        line = 0;
        for(i = 0; i != Int32(strlen(lineVec[line].c_str())); i++)
        {
            tmpMinY = g[line][i]->getBoundingBox()[2] < tmpMinY ? 
                        g[line][i]->getBoundingBox()[2] : 
                        tmpMinY;
            tmpMaxY = g[line][i]->getBoundingBox()[3] > tmpMaxY ? 
                        g[line][i]->getBoundingBox()[3] : 
                        tmpMaxY;
            tmpWidth += (i + 1 == Int32(strlen(text)) ? 
                            g[line][i]->getImageSize()[0] : 
                            g[line][i]->getAdvance());
        }

        height = abs(tmpMaxY) + abs(tmpMinY);
        yoff = _topToBottom ? overallHeight - height : 0;

        switch(_justifyMajor)
        {
        case FIRST_JT:
        case BEGIN_JT:
            xoff = 0;
            break;
        case MIDDLE_JT:
            xoff = (overallWidth - tmpWidth) / 2 * pixelDepth;
            break;
        case END_JT:
            xoff = (overallWidth - tmpWidth) * pixelDepth;
            break;
        default:
            FFATAL(("Invalid _justifyMajor entry (%d)\n", _justifyMajor));
            xoff = 0;
        }

        xoff -= g[line][0]->getBoundingBox()[0] * pixelDepth;

        tmpWidth = 0;

        for(line = 0; line < Int32(lineVec.size()); line++)
        {
            text = lineVec[line].c_str();

            if(_leftToRight)
            {
                strStart = 0;
                strEnd = strlen(text);
                strStep = 1;
            }
            else
            {
                strStart = strlen(text) - 1;
                strEnd = -1;
                strStep = -1;
            }

            for(i = strStart; i != strEnd; i += strStep)
            {
                pen_y = yoff + abs(tmpMinY) + g[line][i]->getBoundingBox()[2];
                pen_x = xoff + (g[line][i]->getBoundingBox()[0] * pixelDepth);
                img = g[line][i]->getImage();
                res = g[line][i]->getImageSize();

                for(j = res[1] - 1; j >= 0; j--)
                {
                    srcPixel = img + ((res[1] - j - 1) * res[2]);

                    dstPixel = imageBuffer + ((pen_y + j) * overallWidth * 
                                    pixelDepth) + pen_x;

                    for(k = 0; k < res[0]; k++, srcPixel++)
                    {
                        if(!(p = *(srcPixel)))
                        {
                            dstPixel += pixelDepth;
                            continue;
                        }

                        for(l = 0; l < pixelDepth; l++, dstPixel++)
                        {
                            *(dstPixel) =
                                    (
                                        (*fg)[l] *
                                        p +
                                        (*bg)[l] *
                                        (4 - p)
                                    ) >>
                                    2;
                        }
                    }
                }

                xoff += (g[line][i]->getAdvance() * pixelDepth);
            }

            if(line + 1 < Int32(lineVec.size()))
            {
                tmpWidth = 0;
                if(_justifyMajor == MIDDLE_JT || _justifyMajor == END_JT)
                {
                    for(i = 0; i != Int32(strlen(lineVec[line + 1].c_str()));
                                            i++)
                    {
                        tmpWidth += 
                            Int32(osgfloor(g[line + 1][i]->getAdvance()));
                    }
                }

                switch(_justifyMajor)
                {
                case FIRST_JT:
                case BEGIN_JT:
                    xoff = 0;
                    break;
                case MIDDLE_JT:
                    xoff = (overallWidth - tmpWidth) / 2 * pixelDepth;
                    break;
                case END_JT:
                    xoff = (overallWidth - tmpWidth) * pixelDepth;
                    break;
                }

                if(line + 1 == Int32(lineVec.size()) - 1)
                {
                    yoff = _topToBottom ? 0 : overallHeight - height;
                }
                else
                {
                    yoff += (_topToBottom ? -1 : 1) * 
                        Int32(osgfloor(
                                  Real32(_fontInstance->getBaselineSkip())*
                                  _fontInstance->getYRes() * _spacing));
                }
            }
        }

        for(line = 0; line < Int32(lineVec.size()); line++)
            delete[] g[line];
        delete[] g;


		// AT: Convert Image Buffer for usage with glBitmap
		Image::PixelFormat pixelFormat;
		if( bConvertToBitmap )
		{		
			pixelFormat = Image::OSG_L_PF;
#if 1
			//Int32 newOverallWidth = ceil(((float)(overallWidth))/8.0);

			UChar8* bitmapBuffer = new UChar8[ overallWidth * overallHeight ];
			memset( bitmapBuffer, '\0', overallWidth * overallHeight );

			for( int nY=0; nY<overallHeight; nY++ )
			{
				for( int nX=0; nX<overallWidth; nX +=8 )
				{	
					for( int nXplus = 0; (nXplus < 8) && (nXplus+nX < overallWidth); nXplus++ )
					{
						if( (imageBuffer[ ( nY*overallWidth*pixelDepth ) + nX + nXplus ] > 0) )
							bitmapBuffer[ ( nY*overallWidth ) + nX/8 ] += (128 >> nXplus) ;
					}
				}
			}
			delete [] imageBuffer;
			imageBuffer = bitmapBuffer;
			//overallWidth = newOverallWidth;
#endif

			// AT's conversion ready
		}
		else
		{
			pixelFormat = Image::OSG_RGBA_PF;
		}
		
        bool retval = image->set(pixelFormat, // Image::OSG_RGB_PF, 
                                 overallWidth, overallHeight, 1, 
                                 1, 
                                 1, 0.0, imageBuffer);
        delete [] imageBuffer;
        return retval;
    }
bool PNGImageFileType::write(const Image        *OSG_PNG_ARG(pImage  ), 
                                   std::ostream &OSG_PNG_ARG(os      ),
                             const std::string  &OSG_PNG_ARG(mimetype))
{
#ifdef OSG_WITH_PNG

    png_structp png_ptr;
    png_infop info_ptr;

    if(pImage->getDimension() < 1 || pImage->getDimension() > 2)
    {
        FWARNING(("PNGImageFileType::write: invalid dimension %d!\n",
                  pImage->getDimension()));

        return false;
    }
    
    /* Create and initialize the png_struct with the desired error handler
    * functions.  If you want to use the default stderr and longjump method,
    * you can supply NULL for the last three parameters.  We also check that
    * the library version is compatible with the one used at compile time,
    * in case we are using dynamically linked libraries.  REQUIRED.
     */
    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
                                      0, &errorOutput, &warningOutput);

    if(png_ptr == NULL)
        return false;

    /* Allocate/initialize the image information data.  REQUIRED */
    info_ptr = png_create_info_struct(png_ptr);

    if(info_ptr == NULL)
    {
        png_destroy_write_struct(&png_ptr,  NULL);
        return false;
    }
    
    /* set up the output handlers */
    png_set_write_fn(png_ptr, &os, &osWriteFunc, &osFlushFunc);

    /* This is the hard way */

    /* Set the image information here.  Width and height are up to 2^31,
    * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
    * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
    * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
    * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
    * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
    * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE. REQUIRED
    */

    Int32 ctype;
    switch(pImage->getPixelFormat())
    {
        case Image::OSG_L_PF:       
            ctype = PNG_COLOR_TYPE_GRAY;        
            break;
            
        case Image::OSG_LA_PF:      
            ctype = PNG_COLOR_TYPE_GRAY_ALPHA;          
            break;
            
#if defined(GL_BGR) || defined(GL_BGR_EXT)
        case Image::OSG_BGR_PF:
#endif
        case Image::OSG_RGB_PF:     
            ctype = PNG_COLOR_TYPE_RGB;                 
            break;
            
#if defined(GL_BGRA) || defined(GL_BGRA_EXT)
        case Image::OSG_BGRA_PF:
#endif
        case Image::OSG_RGBA_PF:    
            ctype = PNG_COLOR_TYPE_RGB_ALPHA;           
            break;
            
        default:
            FWARNING(("PNGImageFileType::write: unknown pixel format %d!\n",
                      pImage->getPixelFormat()));
            png_destroy_write_struct(&png_ptr,  NULL);
            return false;
            
    }
    
    Int32 bit_depth;
    switch(pImage->getDataType()) 
    {
        case Image::OSG_UINT8_IMAGEDATA:
            bit_depth = 8;
            break;
        case Image::OSG_UINT16_IMAGEDATA:
            bit_depth = 16;
            break;
        default:
            FWARNING (("Invalid pixeldepth, cannot store data\n"));
            return false;
    };

    png_set_IHDR(png_ptr, info_ptr, pImage->getWidth(), pImage->getHeight(),
                 bit_depth,ctype,      
                 PNG_INTERLACE_NONE, 
                 PNG_COMPRESSION_TYPE_BASE, 
                 PNG_FILTER_TYPE_BASE);

    // set resolution png supports only meter per pixel,
    // so we do a conversion from dpi with some rounding.
    png_uint_32 res_x = png_uint_32(pImage->getResX());
    png_uint_32 res_y = png_uint_32(pImage->getResY());
    if(pImage->getResUnit() == Image::OSG_RESUNIT_INCH)
    {
        res_x = png_uint_32((pImage->getResX() * 39.37007874f) < 0.0f ?
                            (pImage->getResX() * 39.37007874f) - 0.5f :
                            (pImage->getResX() * 39.37007874f) + 0.5f);
        res_y = png_uint_32((pImage->getResY() * 39.37007874f) < 0.0f ?
                            (pImage->getResY() * 39.37007874f) - 0.5f :
                            (pImage->getResY() * 39.37007874f) + 0.5f);
    }

    png_set_pHYs(png_ptr, info_ptr, res_x, res_y,
                 PNG_RESOLUTION_METER);

#if 0
    /* optional significant bit chunk */
    /* if we are dealing with a grayscale image then */
    sig_bit.gray = true_bit_depth;
    /* otherwise, if we are dealing with a color image then */
    sig_bit.red = true_red_bit_depth;
    sig_bit.green = true_green_bit_depth;
    sig_bit.blue = true_blue_bit_depth;
    /* if the image has an alpha channel then */
    sig_bit.alpha = true_alpha_bit_depth;
    png_set_sBIT(png_ptr, info_ptr, sig_bit);


    /* Optional gamma chunk is strongly suggested if you have any guess
    * as to the correct gamma of the image.
    */
    png_set_gAMA(png_ptr, info_ptr, gamma);

    /* Optionally write comments into the image */
    text_ptr[0].key = "Title";
    text_ptr[0].text = "Mona Lisa";
    text_ptr[0].compression = PNG_TEXT_COMPRESSION_NONE;
    text_ptr[1].key = "Author";
    text_ptr[1].text = "Leonardo DaVinci";
    text_ptr[1].compression = PNG_TEXT_COMPRESSION_NONE;
    text_ptr[2].key = "Description";
    text_ptr[2].text = "<long text>";
    text_ptr[2].compression = PNG_TEXT_COMPRESSION_zTXt;
#ifdef PNG_iTXt_SUPPORTED
    text_ptr[0].lang = NULL;
    text_ptr[1].lang = NULL;
    text_ptr[2].lang = NULL;
#endif
    png_set_text(png_ptr, info_ptr, text_ptr, 3);
#endif
    /* other optional chunks like cHRM, bKGD, tRNS, tIME, oFFs, pHYs, */
    /* note that if sRGB is present the gAMA and cHRM chunks must be ignored
    * on read and must be written in accordance with the sRGB profile */

    /* Write the file header information.  REQUIRED */
    png_write_info(png_ptr, info_ptr);

#if BYTE_ORDER == LITTLE_ENDIAN
    if (bit_depth == 16) 
      png_set_swap(png_ptr);
#endif

#if 0
    /* invert monochrome pixels */
    png_set_invert_mono(png_ptr);

    /* Shift the pixels up to a legal bit depth and fill in
    * as appropriate to correctly scale the image.
    */
    png_set_shift(png_ptr, &sig_bit);

    /* pack pixels into bytes */
    png_set_packing(png_ptr);

    /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
    * RGB (4 channels -> 3 channels). The second parameter is not used.
    */
    png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);

    /* swap bytes of 16-bit files to most significant byte first */
    png_set_swap(png_ptr);

    /* swap bits of 1, 2, 4 bit packed pixel formats */
    png_set_packswap(png_ptr);
#endif

    if(pImage->getPixelFormat() == Image::OSG_BGR_PF ||
       pImage->getPixelFormat() == Image::OSG_BGRA_PF )
    {
        /* flip BGR pixels to RGB */
        png_set_bgr(png_ptr);
        
        /* swap location of alpha bytes from ARGB to RGBA */
        png_set_swap_alpha(png_ptr);
    }
    
    /* The easiest way to write the image (you may have a different memory
     * layout, however, so choose what fits your needs best).  You need to
     * use the first method if you aren't handling interlacing yourself.
     */
    png_bytep *row_pointers = new png_bytep [pImage->getHeight()];
    
    for(Int32 k = 0; k < pImage->getHeight(); k++)
    {
        row_pointers[k] = 
            (const_cast<UInt8 *>(pImage->getData())) + 
            (pImage->getHeight() - 1 - k) * 
            pImage->getWidth() * pImage->getBpp();
    }
    
    /* write out the entire image data in one call */
    png_write_image(png_ptr, row_pointers);

    /* It is REQUIRED to call this to finish writing the rest of the file */
    png_write_end(png_ptr, info_ptr);
    
    /* clean up after the write, and free any memory allocated */
    png_destroy_write_struct(&png_ptr, &info_ptr);

    delete [] row_pointers;

    /* that's it */
    return true;

#else
    SWARNING << getMimeType() 
             << " write is not compiled into the current binary " 
             << endLog;

    return false;
#endif
}
/*! Reads from the stream set by a preceding call to initialiseRead. Since the
    root element is the first one created it reads the file header and
    creates the elements to read the data following the header.

    \param[in] typeName The argument is ignored.
 */
void
OSBRootElement::read(const std::string &/*typeName*/)
{
    OSG_OSB_LOG(("OSBRootElement::read\n"));

    BinaryReadHandler *rh           = getReadHandler();
    std::string        headerMarker;

    rh->getValue(headerMarker);

    if(headerMarker == OSGOSB_HEADER_ID_1)
    {
        OSG_OSB_LOG(("OSBRootElement::read: Header version: [%u]\n",
                OSGOSBHeaderVersion100));
        setHeaderVersion(OSGOSBHeaderVersion100);
    }
    else if(headerMarker == OSGOSB_HEADER_ID_2)
    {
        OSG_OSB_LOG(("OSBRootElement::read: Header version: [%u]\n",
                OSGOSBHeaderVersion200));
        setHeaderVersion(OSGOSBHeaderVersion200);
    }
//     else if(headerMarker == OSGOSB_HEADER_ID_201)
//     {
//         OSG_OSB_LOG(("OSBRootElement::read: Header version: [%u]\n",
//                 OSGOSBHeaderVersion201));
//         setHeaderVersion(OSGOSBHeaderVersion201);
//     }
    else
    {
        FWARNING(("OSBRootElement::read: Unrecognized file header, could not "
                  "load file.\n"));
        return;
    }

    std::string headerName;
    rh->getValue(headerName);
    std::string headerOptions;
    rh->getValue(headerOptions);
    UInt64 fileSize;
    rh->getValue(fileSize);

    OSG_OSB_LOG(("OSBRootElement::read: headerName: [%s]\n",
            headerName.c_str()));
    OSG_OSB_LOG(("OSBRootElement::read: headerOptions: [%s]\n",
            headerOptions.c_str()));
    OSG_OSB_LOG(("OSBRootElement::read: fileSize: [%" PRISize "]\n",
            fileSize));

    std::string     fcTypeName;
    UInt32          fcIdFile;    // id used in the file
    UInt32          fcIdSystem;  // id used in the system
    OSBElementBase *elem;

    while(true)
    {
        if(!readFieldContainerHeader(fcTypeName, fcIdFile))
            break;

        OSG_OSB_LOG(("OSBRootElement::read: fcTypeName [%s] fcIdFile: [%u]\n",
                fcTypeName.c_str(), fcIdFile));

        elem = OSBElementFactory::the()->acquire(fcTypeName, this);
        elem->setFCIdFile(fcIdFile  );
        elem->read       (fcTypeName);

        if(elem->getContainer() != NULL)
        {
            fcIdSystem = elem->getContainer()->getId();

            OSG_OSB_LOG(("OSBRootElement::read: fcIdFile: [%u] fcIdSystem: [%u]\n",
                    fcIdFile, fcIdSystem));

            editIdMap().insert(
                FieldContainerIdMap::value_type(fcIdFile, fcIdSystem));

            if(getContainer() == NULL)
            {
                setContainer(elem->getContainer());
            }

            editElementList().push_back(elem                          );
            editIdElemMap  ().insert   (std::make_pair(fcIdFile, elem));
        }
    }
}
UInt64 PNGImageFileType::restoreData(      Image  *OSG_PNG_ARG  (pImage ),
                                     const UChar8 *OSG_PNG_ARG  (buffer ),
                                           Int32   OSG_CHECK_ARG(memSize))
{
#ifdef OSG_WITH_PNG

    UInt64              retCode;
    Image::PixelFormat  pixelFormat = Image::OSG_INVALID_PF;
    png_structp         png_ptr;
    png_infop           info_ptr;
    png_uint_32         width, wc, height, h, i;
    png_byte            bit_depth, channels, color_type;
    png_bytep           *row_pointers, base;

    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);

    if(!png_ptr)
    {
        return 0;
    }

    png_set_error_fn(png_ptr, 0, &errorOutput, &warningOutput);

    info_ptr = png_create_info_struct(png_ptr);

    if(!info_ptr)
    {
        png_destroy_read_struct(&png_ptr, 0, 0);
        return 0;
    }

    if(setjmp(png_ptr->jmpbuf))
    {
        png_destroy_read_struct(&png_ptr, &info_ptr, 0);
        return 0;
    }

    BufferInfo bufferInfo;
    bufferInfo.buffer = const_cast<UChar8 *>(buffer);
    bufferInfo.length = 0;
    png_set_read_fn(png_ptr, static_cast<void *>(&bufferInfo), user_read_data);

    png_read_info(png_ptr, info_ptr);

    width = png_get_image_width(png_ptr, info_ptr);
    height = png_get_image_height(png_ptr, info_ptr);
    bit_depth = png_get_bit_depth(png_ptr, info_ptr);
    channels = png_get_channels(png_ptr, info_ptr);
    color_type = png_get_color_type(png_ptr, info_ptr);

    // Convert paletted images to RGB
    if(color_type == PNG_COLOR_TYPE_PALETTE)
    {
        png_set_palette_to_rgb(png_ptr);
        channels = 3;
        bit_depth = 8;
    }

    // Convert < 8 bit to 8 bit
    if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
    {
        png_set_gray_1_2_4_to_8(png_ptr);
        bit_depth = 8;
    }

#if BYTE_ORDER == LITTLE_ENDIAN
    if (bit_depth == 16)
        png_set_swap(png_ptr);
#endif
   
    // Add a full alpha channel if there is transparency
    // information in a tRNS chunk
    if(png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
    {
        png_set_tRNS_to_alpha(png_ptr);
        ++channels;
    }   
                                                                 
    Int32 dataType;

    switch (bit_depth) 
    {
        case 8:
            dataType = Image::OSG_UINT8_IMAGEDATA;
            break;
        case 16:
            dataType = Image::OSG_UINT16_IMAGEDATA;
            break;
        default:
            FWARNING (( "Invalid bit_depth: %d, can not read png-data\n",
                        bit_depth ));
            return false;
    }
    
    switch(channels)
    {
        case 1:
            pixelFormat = Image::OSG_L_PF;
            break;
        case 2:
            pixelFormat = Image::OSG_LA_PF;
            break;
        case 3:
            pixelFormat = Image::OSG_RGB_PF;
            break;
        case 4:
            pixelFormat = Image::OSG_RGBA_PF;
            break;
    };
    
    if(pImage->set(pixelFormat, width, height,
                   1, 1, 1, 0.0, 0,
                   dataType))
    {
        // Calculate the row pointers
        row_pointers = new png_bytep[height];
        wc = width * channels * (bit_depth / 8);
        h = height - 1;
        base = pImage->editData();

        for(i = 0; i < height; ++i)
            row_pointers[i] = base + (h - i) * wc;

        // Read the image data
        png_read_image(png_ptr, row_pointers);
        
        delete[] row_pointers;
        
        retCode = bufferInfo.length;
    }
    else
    {
        retCode = 0;
    }

    png_destroy_read_struct(&png_ptr, &info_ptr, 0);
    
    return retCode;

#else
    SWARNING << getMimeType() 
             << " restoreData is not compiled into the current binary " 
             << std::endl;

    return 0;
#endif
}
Exemplo n.º 29
0
bool subConnection(      OSG::AttachmentContainer *pSrcContainer,
                         const OSG::Char8               *szSrcName,
                         OSG::FieldContainer      *pDstContainer,
                         const OSG::Char8               *szDstName    )
{
    if(pSrcContainer == NULL)
    {
        return false;
    }


    const FieldDescriptionBase *pSrcDesc = NULL;

    GetFieldHandlePtr pSrcHnd;

    if(szSrcName != NULL)
    {
        pSrcHnd = pSrcContainer->getField(szSrcName);

        if(pSrcHnd != NULL && pSrcHnd->isValid() == true)
        {
            pSrcDesc = pSrcHnd->getDescription();
        }

        // check core for node
        if(pSrcDesc == NULL)
        {
            Node *pNode = dynamic_cast<Node *>(pSrcContainer);

            if(pNode != NULL && pNode->getCore() != NULL)
            {
                pSrcHnd = pNode->getCore()->getField(szSrcName);

                if(pSrcHnd != NULL && pSrcHnd->isValid() == true)
                {
                    pSrcDesc = pSrcHnd->getDescription();
                }
            }
        }
    }


    const FieldDescriptionBase *pDstDesc = NULL;

    GetFieldHandlePtr pDstHnd;

    if(pDstContainer != NULL && szDstName != NULL)
    {
        pDstHnd = pDstContainer->getField(szDstName);

        if(pDstHnd != NULL && pDstHnd->isValid() == true)
        {
            pDstDesc = pDstHnd->getDescription();
        }

        // same here
        if(pDstDesc == NULL)
        {
            Node *pNode = dynamic_cast<Node *>(pDstContainer);

            if(pNode != NULL && pNode->getCore() != NULL)
            {
                pDstHnd = pNode->getCore()->getField(szDstName);

                if(pDstHnd != NULL && pDstHnd->isValid() == true)
                {
                    pDstDesc = pDstHnd->getDescription();
                }
            }
        }
    }


#if 0
    if(pSrcDesc == NULL)
    {
        FWARNING(("subConnection: Failed to obtain field description for: "
                  "source container [%p] field [%s]\n",
                  pSrcContainer, szSrcName));

        return false;
    }
#endif

    BitVector bSrcMask = TypeTraits<BitVector>::BitsClear;
    BitVector bDstMask = TypeTraits<BitVector>::BitsClear;

    if(pSrcDesc != NULL)
    {
        bSrcMask = pSrcDesc->getFieldMask();

        pSrcContainer =
            dynamic_cast<AttachmentContainer *>(pSrcHnd->getContainer());
    }
    else if(szSrcName == NULL)
    {
        bSrcMask = TypeTraits<BitVector>::BitsSet;
    }

    if(pDstDesc != NULL)
    {
        bDstMask = pDstDesc->getFieldMask();

        pDstContainer =
            dynamic_cast<AttachmentContainer *>(pDstHnd->getContainer());
    }
    else if(szDstName == NULL)
    {
        bDstMask = TypeTraits<BitVector>::BitsSet;
    }

    subConnector(pSrcContainer, bSrcMask,
                 pDstContainer, bDstMask);

    return false;
}
//! initialize the static features of the class, e.g. action callbacks
void MaterialDrawable::drawPrimitives(DrawEnv *)
{
    FWARNING (("You should overload drawPrimitives in your code\n"));

    return;
}