BonnMotionFileCache.cc

00001 //
00002 // Copyright (C) 2005 Andras Varga
00003 //
00004 // This program is free software; you can redistribute it and/or
00005 // modify it under the terms of the GNU General Public License
00006 // as published by the Free Software Foundation; either version 2
00007 // of the License, or (at your option) any later version.
00008 //
00009 // This program is distributed in the hope that it will be useful,
00010 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00011 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012 // GNU General Public License for more details.
00013 //
00014 // You should have received a copy of the GNU General Public License
00015 // along with this program; if not, write to the Free Software
00016 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
00017 //
00018 
00019 #include <fstream>
00020 #include <sstream>
00021 #include "BonnMotionFileCache.h"
00022 
00023 
00024 const BonnMotionFile::Line *BonnMotionFile::getLine(int nodeId) const
00025 {
00026     LineList::const_iterator it = lines.begin();
00027     for (int i=0; i<nodeId && it!=lines.end(); i++) it++;
00028     return (it==lines.end()) ? NULL : &(*it);
00029 }
00030 
00031 
00032 BonnMotionFileCache *BonnMotionFileCache::inst;
00033 
00034 BonnMotionFileCache *BonnMotionFileCache::getInstance()
00035 {
00036     if (!inst)
00037         inst = new BonnMotionFileCache;
00038     return inst;
00039 }
00040 
00041 void BonnMotionFileCache::deleteInstance()
00042 {
00043     if (inst) 
00044     {
00045         delete inst;
00046         inst = NULL;
00047     }
00048 }
00049 
00050 const BonnMotionFile *BonnMotionFileCache::getFile(const char *filename)
00051 {
00052     // if found, return it from cache
00053     BMFileMap::iterator it = cache.find(std::string(filename));
00054     if (it!=cache.end())
00055         return &(it->second);
00056 
00057     // load and store in cache
00058     BonnMotionFile& bmFile = cache[filename];
00059     parseFile(filename, bmFile);
00060     return &bmFile;
00061 }
00062 
00063 void BonnMotionFileCache::parseFile(const char *filename, BonnMotionFile& bmFile)
00064 {
00065     std::ifstream in(filename, std::ios::in);
00066     if (in.fail())
00067         opp_error("Cannot open file '%s'",filename);
00068 
00069     std::string line;
00070     while (std::getline(in, line))
00071     {
00072         bmFile.lines.push_back(BonnMotionFile::Line());
00073         BonnMotionFile::Line& vec = bmFile.lines.back();
00074 
00075         std::stringstream linestream(line);
00076         double d;
00077         while (linestream >> d)
00078             vec.push_back(d);
00079     }
00080     in.close();
00081 }
00082 
00083 
00084