STEPFileReader.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /*
  2. Open Asset Import Library (ASSIMP)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2010, ASSIMP Development Team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the ASSIMP team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the ASSIMP Development Team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file STEPFileReader.cpp
  34. * @brief Implementation of the STEP file parser, which fills a
  35. * STEP::DB with data read from a file.
  36. */
  37. #include "AssimpPCH.h"
  38. #include "STEPFileReader.h"
  39. #include "TinyFormatter.h"
  40. #include "fast_atof.h"
  41. using namespace Assimp;
  42. namespace EXPRESS = STEP::EXPRESS;
  43. #include <functional>
  44. // ------------------------------------------------------------------------------------------------
  45. // From http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring
  46. // trim from start
  47. static inline std::string &ltrim(std::string &s) {
  48. s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1( std::ptr_fun(Assimp::IsSpace<char>))));
  49. return s;
  50. }
  51. // trim from end
  52. static inline std::string &rtrim(std::string &s) {
  53. s.erase(std::find_if(s.rbegin(), s.rend(), std::not1( std::ptr_fun(Assimp::IsSpace<char>))).base(),s.end());
  54. return s;
  55. }
  56. // trim from both ends
  57. static inline std::string &trim(std::string &s) {
  58. return ltrim(rtrim(s));
  59. }
  60. // ------------------------------------------------------------------------------------------------
  61. std::string AddLineNumber(const std::string& s,uint64_t line /*= LINE_NOT_SPECIFIED*/, const std::string& prefix = "")
  62. {
  63. return line == STEP::SyntaxError::LINE_NOT_SPECIFIED ? prefix+s : static_cast<std::string>( (Formatter::format(),prefix,"(line ",line,") ",s) );
  64. }
  65. // ------------------------------------------------------------------------------------------------
  66. std::string AddEntityID(const std::string& s,uint64_t entity /*= ENTITY_NOT_SPECIFIED*/, const std::string& prefix = "")
  67. {
  68. return entity == STEP::TypeError::ENTITY_NOT_SPECIFIED ? prefix+s : static_cast<std::string>( (Formatter::format(),prefix,"(entity #",entity,") ",s));
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. STEP::SyntaxError::SyntaxError (const std::string& s,uint64_t line /* = LINE_NOT_SPECIFIED */)
  72. : DeadlyImportError(AddLineNumber(s,line))
  73. {
  74. }
  75. // ------------------------------------------------------------------------------------------------
  76. STEP::TypeError::TypeError (const std::string& s,uint64_t entity /* = ENTITY_NOT_SPECIFIED */,uint64_t line /*= LINE_NOT_SPECIFIED*/)
  77. : DeadlyImportError(AddLineNumber(AddEntityID(s,entity),line))
  78. {
  79. }
  80. // ------------------------------------------------------------------------------------------------
  81. STEP::DB* STEP::ReadFileHeader(boost::shared_ptr<IOStream> stream)
  82. {
  83. boost::shared_ptr<StreamReaderLE> reader = boost::shared_ptr<StreamReaderLE>(new StreamReaderLE(stream));
  84. std::auto_ptr<STEP::DB> db = std::auto_ptr<STEP::DB>(new STEP::DB(reader));
  85. LineSplitter& splitter = db->GetSplitter();
  86. if (!splitter || *splitter != "ISO-10303-21;") {
  87. throw STEP::SyntaxError("expected magic token: ISO-10303-21",1);
  88. }
  89. HeaderInfo& head = db->GetHeader();
  90. for(++splitter; splitter; ++splitter) {
  91. const std::string& s = *splitter;
  92. if (s == "DATA;") {
  93. // here we go, header done, start of data section
  94. ++splitter;
  95. break;
  96. }
  97. // want one-based line numbers for human readers, so +1
  98. const uint64_t line = splitter.get_index()+1;
  99. if (s.substr(0,11) == "FILE_SCHEMA") {
  100. const char* sz = s.c_str()+11;
  101. SkipSpaces(sz,&sz);
  102. std::auto_ptr< const EXPRESS::DataType > schema = std::auto_ptr< const EXPRESS::DataType >( EXPRESS::DataType::Parse(sz) );
  103. // the file schema should be a regular list entity, although it usually contains exactly one entry
  104. // since the list itself is contained in a regular parameter list, we actually have
  105. // two nested lists.
  106. const EXPRESS::LIST* list = dynamic_cast<const EXPRESS::LIST*>(schema.get());
  107. if (list && list->GetSize()) {
  108. list = dynamic_cast<const EXPRESS::LIST*>( (*list)[0] );
  109. if (!list) {
  110. throw STEP::SyntaxError("expected FILE_SCHEMA to be a list",line);
  111. }
  112. // XXX need support for multiple schemas?
  113. if (list->GetSize() > 1) {
  114. DefaultLogger::get()->warn(AddLineNumber("multiple schemas currently not supported",line));
  115. }
  116. const EXPRESS::STRING* string;
  117. if (!list->GetSize() || !(string=dynamic_cast<const EXPRESS::STRING*>( (*list)[0] ))) {
  118. throw STEP::SyntaxError("expected FILE_SCHEMA to contain a single string literal",line);
  119. }
  120. head.fileSchema = *string;
  121. }
  122. }
  123. // XXX handle more header fields
  124. }
  125. return db.release();
  126. }
  127. // ------------------------------------------------------------------------------------------------
  128. void STEP::ReadFile(DB& db,const EXPRESS::ConversionSchema& scheme,const char* const* arr, size_t len)
  129. {
  130. db.SetSchema(scheme);
  131. db.SetTypesToTrack(arr,len);
  132. const DB::ObjectMap& map = db.GetObjects();
  133. LineSplitter& splitter = db.GetSplitter();
  134. for(; splitter; ++splitter) {
  135. const std::string& s = *splitter;
  136. if (s == "ENDSEC;") {
  137. break;
  138. }
  139. // want one-based line numbers for human readers, so +1
  140. const uint64_t line = splitter.get_index()+1;
  141. // LineSplitter already ignores empty lines
  142. ai_assert(s.length());
  143. if (s[0] != '#') {
  144. DefaultLogger::get()->warn(AddLineNumber("expected token \'#\'",line));
  145. continue;
  146. }
  147. // ---
  148. // extract id, entity class name and argument string,
  149. // but don't create the actual object yet.
  150. // ---
  151. const std::string::size_type n0 = s.find_first_of('=');
  152. if (n0 == std::string::npos) {
  153. DefaultLogger::get()->warn(AddLineNumber("expected token \'=\'",line));
  154. continue;
  155. }
  156. const uint64_t id = strtoul10_64(s.substr(1,n0-1).c_str());
  157. if (!id) {
  158. DefaultLogger::get()->warn(AddLineNumber("expected positive, numeric entity id",line));
  159. continue;
  160. }
  161. const std::string::size_type n1 = s.find_first_of('(',n0);
  162. if (n1 == std::string::npos) {
  163. DefaultLogger::get()->warn(AddLineNumber("expected token \'(\'",line));
  164. continue;
  165. }
  166. const std::string::size_type n2 = s.find_last_of(')');
  167. if (n2 == std::string::npos || n2 < n1) {
  168. DefaultLogger::get()->warn(AddLineNumber("expected token \')\'",line));
  169. continue;
  170. }
  171. if (map.find(id) != map.end()) {
  172. DefaultLogger::get()->warn(AddLineNumber((Formatter::format(),"an object with the id #",id," already exists"),line));
  173. }
  174. std::string type = s.substr(n0+1,n1-n0-1);
  175. trim(type);
  176. std::transform( type.begin(), type.end(), type.begin(), &Assimp::ToLower<char> );
  177. db.InternInsert(boost::shared_ptr<LazyObject>(new LazyObject(db,id,line,type,s.substr(n1,n2-n1+1))));
  178. }
  179. if (!splitter) {
  180. DefaultLogger::get()->warn("STEP: ignoring unexpected EOF");
  181. }
  182. if ( !DefaultLogger::isNullLogger() ){
  183. DefaultLogger::get()->debug((Formatter::format(),"STEP: got ",map.size()," object records"));
  184. }
  185. }
  186. // ------------------------------------------------------------------------------------------------
  187. const EXPRESS::DataType* EXPRESS::DataType::Parse(const char*& inout,uint64_t line, const EXPRESS::ConversionSchema* schema /*= NULL*/)
  188. {
  189. const char* cur = inout;
  190. SkipSpaces(&cur);
  191. if (*cur == ',' || IsSpaceOrNewLine(*cur)) {
  192. throw STEP::SyntaxError("unexpected token, expected parameter",line);
  193. }
  194. // just skip over constructions such as IFCPLANEANGLEMEASURE(0.01) and read only the value
  195. if (schema) {
  196. bool ok = false;
  197. for(const char* t = cur; *t && *t != ')' && *t != ','; ++t) {
  198. if (*t=='(') {
  199. if (!ok) {
  200. break;
  201. }
  202. for(--t;IsSpace(*t);--t);
  203. std::string s(cur,static_cast<size_t>(t-cur+1));
  204. std::transform(s.begin(),s.end(),s.begin(),&ToLower<char> );
  205. if (schema->IsKnownToken(s)) {
  206. for(cur = t+1;*cur++ != '(';);
  207. const EXPRESS::DataType* const dt = Parse(cur);
  208. inout = *cur ? cur+1 : cur;
  209. return dt;
  210. }
  211. break;
  212. }
  213. else if (!IsSpace(*t)) {
  214. ok = true;
  215. }
  216. }
  217. }
  218. if (*cur == '*' ) {
  219. inout = cur+1;
  220. return new EXPRESS::ISDERIVED();
  221. }
  222. else if (*cur == '$' ) {
  223. inout = cur+1;
  224. return new EXPRESS::UNSET();
  225. }
  226. else if (*cur == '(' ) {
  227. // start of an aggregate, further parsing is done by the LIST factory constructor
  228. inout = cur;
  229. return EXPRESS::LIST::Parse(inout,line,schema);
  230. }
  231. else if (*cur == '.' ) {
  232. // enum (includes boolean)
  233. const char* start = ++cur;
  234. for(;*cur != '.';++cur) {
  235. if (*cur == '\0') {
  236. throw STEP::SyntaxError("enum not closed",line);
  237. }
  238. }
  239. inout = cur+1;
  240. return new EXPRESS::ENUMERATION( std::string(start, static_cast<size_t>(cur-start) ));
  241. }
  242. else if (*cur == '#' ) {
  243. // object reference
  244. return new EXPRESS::ENTITY(strtoul10_64(++cur,&inout));
  245. }
  246. else if (*cur == '\'' ) {
  247. // string literal
  248. const char* start = ++cur;
  249. for(;*cur != '\'';++cur) {
  250. if (*cur == '\0') {
  251. throw STEP::SyntaxError("string literal not closed",line);
  252. }
  253. }
  254. if (cur[1]=='\'') {
  255. for(cur+=2;*cur != '\'';++cur) {
  256. if (*cur == '\0') {
  257. throw STEP::SyntaxError("string literal not closed",line);
  258. }
  259. }
  260. }
  261. inout = cur+1;
  262. return new EXPRESS::STRING( std::string(start, static_cast<size_t>(cur-start) ));
  263. }
  264. else if (*cur == '\"' ) {
  265. throw STEP::SyntaxError("binary data not supported yet",line);
  266. }
  267. // else -- must be a number. if there is a decimal dot in it,
  268. // parse it as real value, otherwise as integer.
  269. const char* start = cur;
  270. for(;*cur && *cur != ',' && *cur != ')' && !IsSpace(*cur);++cur) {
  271. if (*cur == '.') {
  272. // XXX many STEP files contain extremely accurate data, float's precision may not suffice in many cases
  273. float f;
  274. inout = fast_atof_move(start,f);
  275. return new EXPRESS::REAL(f);
  276. }
  277. }
  278. bool neg = false;
  279. if (*start == '-') {
  280. neg = true;
  281. ++start;
  282. }
  283. else if (*start == '+') {
  284. ++start;
  285. }
  286. int64_t num = static_cast<int64_t>( strtoul10_64(start,&inout) );
  287. return new EXPRESS::INTEGER(neg?-num:num);
  288. }
  289. // ------------------------------------------------------------------------------------------------
  290. const EXPRESS::LIST* EXPRESS::LIST::Parse(const char*& inout,uint64_t line, const EXPRESS::ConversionSchema* schema /*= NULL*/)
  291. {
  292. std::auto_ptr<EXPRESS::LIST> list(new EXPRESS::LIST());
  293. EXPRESS::LIST::MemberList& members = list->members;
  294. const char* cur = inout;
  295. if (*cur++ != '(') {
  296. throw STEP::SyntaxError("unexpected token, expected \'(\' token at beginning of list",line);
  297. }
  298. // estimate the number of items upfront - lists can grow large
  299. size_t count = 1;
  300. for(const char* c=cur; *c && *c != ')'; ++c) {
  301. count += (*c == ',' ? 1 : 0);
  302. }
  303. members.reserve(count);
  304. for(;;++cur) {
  305. if (!*cur) {
  306. throw STEP::SyntaxError("unexpected end of line while reading list");
  307. }
  308. SkipSpaces(cur,&cur);
  309. if (*cur == ')') {
  310. break;
  311. }
  312. members.push_back( boost::shared_ptr<const EXPRESS::DataType>(EXPRESS::DataType::Parse(cur,line,schema)));
  313. SkipSpaces(cur,&cur);
  314. if (*cur != ',') {
  315. if (*cur == ')') {
  316. break;
  317. }
  318. throw STEP::SyntaxError("unexpected token, expected \',\' or \')\' token after list element",line);
  319. }
  320. }
  321. inout = cur+1;
  322. return list.release();
  323. }
  324. // ------------------------------------------------------------------------------------------------
  325. STEP::LazyObject::LazyObject(DB& db, uint64_t id,uint64_t line,const std::string& type,const std::string& args)
  326. : db(db)
  327. , id(id)
  328. , line(line)
  329. , type(type)
  330. , obj()
  331. // need to initialize this upfront, otherwise the destructor
  332. // will crash if an exception is thrown in the c'tor
  333. , conv_args()
  334. {
  335. const char* arg = args.c_str();
  336. conv_args = EXPRESS::LIST::Parse(arg,line,&db.GetSchema());
  337. // find any external references and store them in the database.
  338. // this helps us emulate STEPs INVERSE fields.
  339. for (size_t i = 0; i < conv_args->GetSize(); ++i) {
  340. const EXPRESS::DataType* t = conv_args->operator [](i);
  341. if (const EXPRESS::ENTITY* e = t->ToPtr<EXPRESS::ENTITY>()) {
  342. db.MarkRef(*e,id);
  343. }
  344. }
  345. }
  346. // ------------------------------------------------------------------------------------------------
  347. STEP::LazyObject::~LazyObject()
  348. {
  349. // 'obj' always remains in our possession, so there is
  350. // no need for a smart pointer type.
  351. delete obj;
  352. delete conv_args;
  353. }
  354. // ------------------------------------------------------------------------------------------------
  355. void STEP::LazyObject::LazyInit() const
  356. {
  357. const EXPRESS::ConversionSchema& schema = db.GetSchema();
  358. STEP::ConvertObjectProc proc = schema.GetConverterProc(type);
  359. if (!proc) {
  360. throw STEP::TypeError("unknown object type: " + type,id,line);
  361. }
  362. // if the converter fails, it should throw an exception, but it should never return NULL
  363. try {
  364. obj = proc(db,*conv_args);
  365. }
  366. catch(const TypeError& t) {
  367. // augment line and entity information
  368. throw TypeError(t.what(),id,line);
  369. }
  370. ++db.evaluated_count;
  371. ai_assert(obj);
  372. // store the original id in the object instance
  373. obj->SetID(id);
  374. }