Index: Contrib/BackgroundLoader/OSGBackgroundLoader.cpp =================================================================== --- Contrib/BackgroundLoader/OSGBackgroundLoader.cpp (revision 0) +++ Contrib/BackgroundLoader/OSGBackgroundLoader.cpp (revision 0) @@ -0,0 +1,235 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +OSG_USING_NAMESPACE +OSG_BEGIN_NAMESPACE +OSG_SINGLETON_INST(BackgroundLoaderBase) + +BackgroundLoaderBase::BackgroundLoaderBase(void) + : mLoadThreads() + , mFinishedLock(NULL) + , mLoadCondVar(NULL) + , mStopRunning(false) +{ + mStopRunning = false; + mFinishedLock = Lock::get("BackgroundLoader-FinishedLock"); + mLoadCondVar = CondVar::get("BackgroundLoader-CondVar"); +} + +BackgroundLoaderBase::~BackgroundLoaderBase(void) +{ + stop(); +} + +void BackgroundLoaderBase::stop(void) +{ + if (mLoadThreads.size() > 0) + { + OSG_ASSERT(!mStopRunning && "BackgroundLoaderBase::stop() Already stopped, but thread is not NULL"); + mStopRunning = true; + mLoadCondVar->broadcast(); + + for (std::vector::iterator itr = mLoadThreads.begin(); + itr != mLoadThreads.end(); itr++) + { + OSG::Thread::join(*itr); + (*itr) = NULL; + } + mLoadThreads.clear(); + } +} + +void BackgroundLoaderBase::addRequest(RequestPtr req) +{ + mLoadCondVar->acquire(); + mPendingRequests.push_back(req); + mLoadCondVar->release(); + mLoadCondVar->signal(); +} + +void BackgroundLoaderBase::removeRequest(RequestPtr req) +{ + mLoadCondVar->acquire(); + request_queue_t::iterator found = std::find(mPendingRequests.begin(), mPendingRequests.end(), req); + if (found != mPendingRequests.end()) + { + mPendingRequests.erase(found); + } + mLoadCondVar->release(); + // XXX: We should not need this. + mLoadCondVar->signal(); +} + +void BackgroundLoaderBase::start(const OSG::UInt16 numThreads) +{ + OSG_ASSERT(0 == mLoadThreads.size() && "Can't have threads before starting."); + for (OSG::UInt16 i = 0; i < numThreads; i++) + { + OSG::Thread* new_thread = dynamic_cast(ThreadManager::the()->getThread(NULL)); + new_thread->runFunction((Thread::ThreadFuncF)loadProc, Thread::getCurrentAspect(), this); + mLoadThreads.push_back(new_thread); + } +} + +void BackgroundLoaderBase::processOne() +{ + OSG_ASSERT(0 == mLoadThreads.size() && "processOne can not be called with background thread active."); + + mLoadCondVar->acquire(); + if (!mPendingRequests.empty()) + { + OSG_ASSERT(!mPendingRequests.empty()); + + // Get the pending request with the highest priority. + RequestPtr req = RequestPtr(); + request_queue_t::iterator next_i = + std::min_element(mPendingRequests.begin(), mPendingRequests.end(), Request::comparePriority); + req = *next_i; + + // Erase our request from the pending list. + mPendingRequests.erase(next_i); + + if (NULL != req.get()) + { + req->execute(); + OSG::commitChanges(); + + mFinishedLock->acquire(); + mFinishedRequests.push_back(req); + mFinishedLock->release(); + } + } + mLoadCondVar->release(); +} + +unsigned BackgroundLoaderBase::getNumPendingRequests() +{ + unsigned ret_val(0); + mLoadCondVar->acquire(); + ret_val = mPendingRequests.size(); + mLoadCondVar->release(); + + return ret_val; +} + +BackgroundLoaderBase::desc_list_t BackgroundLoaderBase::getPendingDescriptionList() +{ + BackgroundLoaderBase::desc_list_t ret_list; + + mLoadCondVar->acquire(); + for(request_queue_t::iterator i = mPendingRequests.begin(); i!=mPendingRequests.end(); i++) + { + std::string desc = boost::str(boost::format("[%4.2f]: %s") % (*i)->getPriority() % (*i)->getDescription()); + ret_list.push_back(desc); + } + mLoadCondVar->release(); + + return ret_list; +} + +void BackgroundLoaderBase::loadProc(void* arg) +{ + // Get a pointer to the singleton object. + BackgroundLoaderBase* the = reinterpret_cast(arg); + OSG_ASSERT(NULL != the && "Should have a pointer to BackgroundLoader."); + + while(false == the->mStopRunning) + { + // Wait on a new request. + the->mLoadCondVar->acquire(); + while(false == the->mStopRunning && + the->mPendingRequests.empty()) + { + the->mLoadCondVar->wait(); + } + + // Early out if we are exiting the loop. + if (the->mStopRunning) + { continue; } + + OSG_ASSERT(!the->mPendingRequests.empty() && "Can't have empty pending list."); + + // Get the pending request with the highest priority. + RequestPtr req = RequestPtr(); + request_queue_t::iterator next_i = + std::min_element(the->mPendingRequests.begin(), the->mPendingRequests.end(), Request::comparePriority); + req = *next_i; + + // Erase our request from the pending list. + the->mPendingRequests.erase(next_i); + + // Now that we have a request to process, release condition variable. + the->mLoadCondVar->release(); + + // If we have a valid request, execute it and commit changes. + if (NULL != req.get()) + { + try + { + req->execute(); + OSG::commitChanges(); + } + catch (std::exception& ex) + { + std::cout << "ERROR: Exception thrown in execute: " << ex.what() << std::endl; + } + catch(...) + { + std::cout << "ERROR: Unknown exception thrown in execute." << std::endl; + } + + // Commit our changes to our aspect (shared) and clear out change list + // since we don't need it around any more. + // OSG::commitChanges(); + //OSG::Thread::getCurrentChangeList()->commitChangesAndClear(); + + the->mFinishedLock->acquire(); + the->mFinishedRequests.push_back(req); + the->mFinishedLock->release(); + } + } +} + +void BackgroundLoaderBase::sync(unsigned reqLimit) +{ + mFinishedLock->acquire(); + + if (0 == reqLimit) + { reqLimit = mFinishedRequests.size(); } + + while((!mFinishedRequests.empty()) && (reqLimit-- >= 0)) + { + RequestPtr req = mFinishedRequests.front(); + mFinishedRequests.pop_front(); + + try + { + req->sync(); + } + catch (std::exception& ex) + { + std::cout << "ERROR: Exception thrown in sync: " << ex.what() << std::endl; + } + catch(...) + { + std::cout << "ERROR: Unknown exception thrown in sync." << std::endl; + } + + req->mCompleted = true; + } + + // XXX: Don't know if this is needed to keep the change list from growing out of control. + //OSG::Thread::getCurrentChangeList()->commitChangesAndClear(); + mFinishedLock->release(); +} + +OSG_END_NAMESPACE Property changes on: Contrib/BackgroundLoader/OSGBackgroundLoader.cpp ___________________________________________________________________ Name: svn:eol-style + native Index: Contrib/BackgroundLoader/OSGRequest.cpp =================================================================== --- Contrib/BackgroundLoader/OSGRequest.cpp (revision 0) +++ Contrib/BackgroundLoader/OSGRequest.cpp (revision 0) @@ -0,0 +1,29 @@ +#include +#include + +OSG_USING_NAMESPACE +OSG_BEGIN_NAMESPACE + +Request::Request() + : mCompleted(false) + , mPriority(100.0) +{;} + +Request::~Request() +{;} + +bool Request::isCompleted() +{ return mCompleted; } + +float Request::getPriority() +{ return mPriority; } + +void Request::setPriority(float val) +{ mPriority = val; } + +bool Request::comparePriority(RequestPtr lhs, RequestPtr rhs) +{ + return (lhs->getPriority() < rhs->getPriority()); +} + +OSG_END_NAMESPACE Property changes on: Contrib/BackgroundLoader/OSGRequest.cpp ___________________________________________________________________ Name: svn:eol-style + native Index: Contrib/BackgroundLoader/OSGModelRequest.cpp =================================================================== --- Contrib/BackgroundLoader/OSGModelRequest.cpp (revision 0) +++ Contrib/BackgroundLoader/OSGModelRequest.cpp (revision 0) @@ -0,0 +1,49 @@ +// the general scene file loading handler +#include +#include + +#include +#include + +OSG_USING_NAMESPACE +OSG_BEGIN_NAMESPACE + +ModelRequest::ModelRequest() + : mParent(OSG::NullFC) + , mModel(OSG::NullFC) +{;} + +ModelRequest::~ModelRequest() +{;} + +std::string ModelRequest::getDescription() +{ + return std::string("ModelRequest: ") + mFilename; +} + +void ModelRequest::execute() +{ + std::cout << "ModelRequest: loading model: " << mFilename << std::endl; + mModel = OSG::NodeRefPtr(OSG::SceneFileHandler::the()->read(mFilename.c_str())); + +#if 1 + VerifyGraphOp* vop = new VerifyGraphOp; + vop->setRepair(true); + vop->setVerbose(true); + NodePtr node(mModel); + vop->traverse(node); + delete vop; +#endif +} + +void ModelRequest::sync() +{ + if (mParent != OSG::NullFC && mModel != OSG::NullFC) + { + std::cout << "ModelRequest: adding model to scene: " << mFilename << std::endl; + mParent->addChild(mModel); + } + mCompleted = true; +} + +OSG_END_NAMESPACE Property changes on: Contrib/BackgroundLoader/OSGModelRequest.cpp ___________________________________________________________________ Name: svn:eol-style + native Index: Contrib/BackgroundLoader/OSGBackgroundLoader.h =================================================================== --- Contrib/BackgroundLoader/OSGBackgroundLoader.h (revision 0) +++ Contrib/BackgroundLoader/OSGBackgroundLoader.h (revision 0) @@ -0,0 +1,91 @@ +#ifndef _OSG_BACKGROUND_LOADER_H_ +#define _OSG_BACKGROUND_LOADER_H_ + +#include + +#include +#include +#include + +#include + +OSG_BEGIN_NAMESPACE + +class CondVar; +class Lock; +class Thread; + +/** Helper class that supports processing requests + * such as loading files in a background thread. + */ +class OSG_UTIL_DLLMAPPING BackgroundLoaderBase +{ +public: + typedef std::vector desc_list_t; + +public: + /** + * Start load thread and start handling background requests. + */ + void start(const OSG::UInt16 numThreads = 1); + + /** + * Stop load thread and handling background requests. + */ + void stop(void); + + /** Add a new request to the queue to be processed. */ + void addRequest(RequestPtr req); + + /** Request removal of an existing request. + * If request is found, it is removed. + */ + void removeRequest(RequestPtr req); + + /** Sync up with the background loader and it's pending changes. + * @args reqLimit The max number of requests to process. 0-All + */ + void sync(unsigned reqLimit=0); + + /** Process a single request. + * This method can only be called if we are not running + * in a background thread but instead want to run synchronously. + */ + void processOne(); + + /** Return the number of pending requests. */ + unsigned getNumPendingRequests(); + + /** Return a list of the descriptions of all pending requests. */ + desc_list_t getPendingDescriptionList(); + +protected: + //void workerThread(void *); + //void renderThread(void *); + BackgroundLoaderBase(void); + virtual ~BackgroundLoaderBase(void); + + static void loadProc(void* arg); + +private: + template + friend class SingletonHolder; + /** default function (move to 'public' if needed). */ + BackgroundLoaderBase(const BackgroundLoaderBase &source); + /** \brief prohibit default function (move to 'public' if needed) */ + void operator =(const BackgroundLoaderBase &source); + + typedef std::list request_queue_t; + request_queue_t mPendingRequests; + request_queue_t mFinishedRequests; + std::vector mLoadThreads; + Lock* mFinishedLock; + CondVar* mLoadCondVar; // Cond var to protect the request queue + bool mStopRunning; +}; + +typedef SingletonHolder BackgroundLoader; + +OSG_END_NAMESPACE + +#endif /*_OSG_BACKGROUND_LOADER_H_*/ Property changes on: Contrib/BackgroundLoader/OSGBackgroundLoader.h ___________________________________________________________________ Name: svn:eol-style + native Index: Contrib/BackgroundLoader/OSGRequest.h =================================================================== --- Contrib/BackgroundLoader/OSGRequest.h (revision 0) +++ Contrib/BackgroundLoader/OSGRequest.h (revision 0) @@ -0,0 +1,64 @@ +#ifndef _OSG_REQUEST_H_ +#define _OSG_REQUEST_H_ + +#include +#include + +#include +#include +#include +#include +#include + + +OSG_BEGIN_NAMESPACE + +class Request; +typedef boost::shared_ptr RequestPtr; +typedef boost::weak_ptr RequestWeakPtr; + +/** A request to be processed by the background loader. + */ +class OSG_UTIL_DLLMAPPING Request +{ +protected: + Request(); + +public: + virtual ~Request(); + + /** Return a text description of the request. + * This could be used in a user interface or debug output to provide + * a user understandable description. + */ + virtual std::string getDescription() + { return std::string("Base Request"); } + + /** Called when it is time to execute the request and "do" something. + * Ex: load a file. + */ + virtual void execute() = 0; + + /** Called in the main thread when it is time to sync up + * and finish the processing. ex: add child node. + */ + virtual void sync() = 0; + + /** Return true if the request has been completed. */ + bool isCompleted(); + + float getPriority(); + + void setPriority(float val); + + static bool comparePriority(RequestPtr lhs, RequestPtr rhs); + + friend class BackgroundLoaderBase; +protected: + bool mCompleted; /**< True once the request has been completed and synced. */ + float mPriority; /**< Priority for this request. lower numbers are higher priority. */ +}; + +OSG_END_NAMESPACE + +#endif /*_REQUEST_H_*/ Property changes on: Contrib/BackgroundLoader/OSGRequest.h ___________________________________________________________________ Name: svn:eol-style + native Index: Contrib/BackgroundLoader/testBackgroundLoader.cpp =================================================================== --- Contrib/BackgroundLoader/testBackgroundLoader.cpp (revision 0) +++ Contrib/BackgroundLoader/testBackgroundLoader.cpp (revision 0) @@ -0,0 +1,228 @@ +// Headers +#include +#include +#include +#include +#include +#include +#include + +// New Headers + +// the general scene file loading handler +#include +#include +#include +#include +#include +#include +namespace fs = boost::filesystem; + +#include +#include + +// Activate the OpenSG namespace +OSG_USING_NAMESPACE + +// The SimpleSceneManager to manage simple applications +SimpleSceneManager *mgr; +GroupNodePtr gScene; + +unsigned gNextModelIdx = 0; + +// forward declaration so we can have the interesting stuff upfront +int setupGLUT( int *argc, char *argv[] ); + + +OSG::UInt64 getNumAllocatedFieldContainers() +{ + OSG::UInt64 num_allocated_fcs(0); + + OSG::FieldContainerFactoryBase* fcf = OSG::FieldContainerFactory::the(); + const OSG::FieldContainerFactoryBase::ContainerStore& fcs(fcf->getContainerStore()); + for(OSG::UInt64 i=0; iinit(OSG::NodeRefPtr(gScene.node()), filename); + OSG::BackgroundLoader::the()->addRequest(req); + } + } + } + +} + +// Initialize GLUT & OpenSG and set up the scene +int main(int argc, char **argv) +{ + // OSG init + osgInit(argc,argv); + + gScene = GroupNodePtr::create(); + + if (argc < 2) + { + std::cout << "Specify a directory to load models from." << std::endl; + exit(-1); + } + + findModels(std::string(argv[1])); + + // Start the background loader. + OSG::BackgroundLoader::the()->start(); + + // GLUT init + int winid = setupGLUT(&argc, argv); + + // the connection between GLUT and OpenSG + GLUTWindowPtr gwin= GLUTWindow::create(); + gwin->setId(winid); + gwin->init(); + + // create the SimpleSceneManager helper + mgr = new SimpleSceneManager; + + // tell the manager what to manage + mgr->setWindow(gwin ); + mgr->setRoot (gScene.node()); + + // show the whole scene + mgr->showAll(); + + // GLUT main loop + glutMainLoop(); + + OSG::BackgroundLoader::the()->stop(); + + return 0; +} + +// +// GLUT callback functions +// + +// redraw the window +void display(void) +{ + OSG::Thread::getCurrentChangeList()->commitChangesAndClear(); + + //OSG::BackgroundLoader::the()->processOne(); + // Sync changes from BackgroundLoader. + OSG::BackgroundLoader::the()->sync(); + + mgr->idle(); + mgr->redraw(); +} + +// react to size changes +void reshape(int w, int h) +{ + mgr->resize(w, h); + glutPostRedisplay(); +} + +// react to mouse button presses +void mouse(int button, int state, int x, int y) +{ + + if (state) + mgr->mouseButtonRelease(button, x, y); + else + mgr->mouseButtonPress(button, x, y); + + glutPostRedisplay(); +} + +// react to mouse motions with pressed buttons +void motion(int x, int y) +{ + + mgr->mouseMove(x, y); + glutPostRedisplay(); +} + +// react to keys +void keyboard(unsigned char k, int , int ) +{ + switch(k) + { + case 27: + { + OSG::osgExit(); + exit(0); + } + break; + + case 'f': + { + mgr->setNavigationMode(Navigator::FLY); + } + break; + + case 't': + { + mgr->setNavigationMode(Navigator::TRACKBALL); + } + break; + + case 'a': + { + mgr->showAll(); + } + break; + + case 's': + { + mgr->setStatistics(!mgr->getStatistics()); + } + break; + } +} + +// setup the GLUT library which handles the windows for us +int setupGLUT(int *argc, char *argv[]) +{ + glutInit(argc, argv); + glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); + + int winid = glutCreateWindow("OpenSG"); + + glutReshapeFunc(reshape); + glutDisplayFunc(display); + glutIdleFunc(display); + glutMouseFunc(mouse); + glutMotionFunc(motion); + glutKeyboardFunc(keyboard); + + return winid; +} Property changes on: Contrib/BackgroundLoader/testBackgroundLoader.cpp ___________________________________________________________________ Name: svn:eol-style + native Index: Contrib/BackgroundLoader/OSGModelRequest.h =================================================================== --- Contrib/BackgroundLoader/OSGModelRequest.h (revision 0) +++ Contrib/BackgroundLoader/OSGModelRequest.h (revision 0) @@ -0,0 +1,60 @@ +#ifndef _OSG_MODEL_REQUEST_H_ +#define _OSG_MODEL_REQUEST_H_ + +#include + +#include +#include +#include + +#include + +#include + +OSG_BEGIN_NAMESPACE + +class ModelRequest; +typedef boost::shared_ptr ModelRequestPtr; +typedef boost::weak_ptr ModelRequestWeakPtr; + +/** A request for loading a model. + * + * note: We hold on using refptrs, so all objects passed to us must have a positive ref count. + */ +class OSG_UTIL_DLLMAPPING ModelRequest : public boost::enable_shared_from_this, public Request +{ +protected: + ModelRequest(); + +public: + static ModelRequestPtr create() + { + return ModelRequestPtr(new ModelRequest); + } + + virtual ~ModelRequest(); + + ModelRequestPtr init(OSG::NodeRefPtr parent, const std::string& filename) + { + mParent = parent; + mFilename = filename; + + return shared_from_this(); + } + + virtual std::string getDescription(); + virtual void execute(); + virtual void sync(); + +protected: + // Note: We use RefPtrs so the code can still work + // even if the original nodes have been left to cleanup in the main program. (ie. removed) + // + OSG::NodeRefPtr mParent; /**< The node that we are supposed to load the model under. */ + OSG::NodeRefPtr mModel; /**< The model that we loaded. */ + std::string mFilename; +}; + +OSG_END_NAMESPACE + +#endif /*_OSG_MODEL_REQUEST_H_*/ Property changes on: Contrib/BackgroundLoader/OSGModelRequest.h ___________________________________________________________________ Name: svn:eol-style + native Index: Contrib/BackgroundLoader/build.info =================================================================== --- Contrib/BackgroundLoader/build.info (revision 0) +++ Contrib/BackgroundLoader/build.info (revision 0) @@ -0,0 +1,15 @@ +#!python +# +if option_pass: + print "Processing option pass" +else: + library = "OSGBackgroundLoader" + osg_dep_libs = ['OSGBase', 'OSGSystem'] + + # Tests' dependencies + osg_test_libs = [ 'OSGGroup','OSGDrawable', 'OSGState', + 'OSGFileIO', 'OSGText', 'OSGRenderTraversal', + 'OSGUtil', 'OSGWindowGLUT' ] + test_cpppath = [] + test_libpath = [] +