convert_obj_three.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  1. """Convert Wavefront OBJ / MTL files into Three.js (JSON model version, to be used with ascii / binary loader)
  2. -------------------------
  3. How to use this converter
  4. -------------------------
  5. python convert_obj_three.py -i infile.obj -o outfile.js [-m "morphfiles*.obj"] [-c "morphcolors*.obj"] [-a center|centerxz|top|bottom|none] [-s smooth|flat] [-t ascii|binary] [-d invert|normal] [-b] [-e]
  6. Notes:
  7. - flags
  8. -i infile.obj input OBJ file
  9. -o outfile.js output JS file
  10. -m "morphfiles*.obj" morph OBJ files (can use wildcards, enclosed in quotes multiple patterns separate by space)
  11. -c "morphcolors*.obj" morph colors OBJ files (can use wildcards, enclosed in quotes multiple patterns separate by space)
  12. -a center|centerxz|top|bottom|none model alignment
  13. -s smooth|flat smooth = export vertex normals, flat = no normals (face normals computed in loader)
  14. -t ascii|binary export ascii or binary format (ascii has more features, binary just supports vertices, faces, normals, uvs and materials)
  15. -d invert|normal invert transparency
  16. -b bake material colors into face colors
  17. -x 10.0 scale and truncate
  18. -f 2 morph frame sampling step
  19. - by default:
  20. use smooth shading (if there were vertex normals in the original model)
  21. will be in ASCII format
  22. original model is assumed to use non-inverted transparency / dissolve (0.0 fully transparent, 1.0 fully opaque)
  23. no face colors baking
  24. no scale and truncate
  25. morph frame step = 1 (all files will be processed)
  26. - binary conversion will create two files:
  27. outfile.js (materials)
  28. outfile.bin (binary buffers)
  29. --------------------------------------------------
  30. How to use generated JS file in your HTML document
  31. --------------------------------------------------
  32. <script type="text/javascript" src="Three.js"></script>
  33. ...
  34. <script type="text/javascript">
  35. ...
  36. // load ascii model
  37. var jsonLoader = new THREE.JSONLoader();
  38. jsonLoader.load( "Model_ascii.js", createScene );
  39. // load binary model
  40. var binLoader = new THREE.BinaryLoader();
  41. binLoader.load( "Model_bin.js", createScene );
  42. function createScene( geometry, materials ) {
  43. var mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) );
  44. }
  45. ...
  46. </script>
  47. -------------------------------------
  48. Parsers based on formats descriptions
  49. -------------------------------------
  50. http://en.wikipedia.org/wiki/Obj
  51. http://en.wikipedia.org/wiki/Material_Template_Library
  52. -------------------
  53. Current limitations
  54. -------------------
  55. - for the moment, only diffuse color and texture are used
  56. (will need to extend shaders / renderers / materials in Three)
  57. - texture coordinates can be wrong in canvas renderer
  58. (there is crude normalization, but it doesn't
  59. work for all cases)
  60. - smoothing can be turned on/off only for the whole mesh
  61. ----------------------------------------------
  62. How to get proper OBJ + MTL files with Blender
  63. ----------------------------------------------
  64. 0. Remove default cube (press DEL and ENTER)
  65. 1. Import / create model
  66. 2. Select all meshes (Select -> Select All by Type -> Mesh)
  67. 3. Export to OBJ (File -> Export -> Wavefront .obj)
  68. - enable following options in exporter
  69. Material Groups
  70. Rotate X90
  71. Apply Modifiers
  72. High Quality Normals
  73. Copy Images
  74. Selection Only
  75. Objects as OBJ Objects
  76. UVs
  77. Normals
  78. Materials
  79. - select empty folder
  80. - give your exported file name with "obj" extension
  81. - click on "Export OBJ" button
  82. 4. Your model is now all files in this folder (OBJ, MTL, number of images)
  83. - this converter assumes all files staying in the same folder,
  84. (OBJ / MTL files use relative paths)
  85. - for WebGL, textures must be power of 2 sized
  86. ------
  87. Author
  88. ------
  89. AlteredQualia http://alteredqualia.com
  90. """
  91. import fileinput
  92. import operator
  93. import random
  94. import os.path
  95. import getopt
  96. import sys
  97. import struct
  98. import math
  99. import glob
  100. # #####################################################
  101. # Configuration
  102. # #####################################################
  103. ALIGN = "none" # center centerxz bottom top none
  104. SHADING = "smooth" # smooth flat
  105. TYPE = "ascii" # ascii binary
  106. TRANSPARENCY = "normal" # normal invert
  107. TRUNCATE = False
  108. SCALE = 1.0
  109. FRAMESTEP = 1
  110. BAKE_COLORS = False
  111. # default colors for debugging (each material gets one distinct color):
  112. # white, red, green, blue, yellow, cyan, magenta
  113. COLORS = [0xeeeeee, 0xee0000, 0x00ee00, 0x0000ee, 0xeeee00, 0x00eeee, 0xee00ee]
  114. # #####################################################
  115. # Templates
  116. # #####################################################
  117. TEMPLATE_FILE_ASCII = u"""\
  118. {
  119. "metadata" :
  120. {
  121. "formatVersion" : 3.1,
  122. "sourceFile" : "%(fname)s",
  123. "generatedBy" : "OBJConverter",
  124. "vertices" : %(nvertex)d,
  125. "faces" : %(nface)d,
  126. "normals" : %(nnormal)d,
  127. "colors" : %(ncolor)d,
  128. "uvs" : %(nuv)d,
  129. "materials" : %(nmaterial)d
  130. },
  131. "scale" : %(scale)f,
  132. "materials": [%(materials)s],
  133. "vertices": [%(vertices)s],
  134. "morphTargets": [%(morphTargets)s],
  135. "morphColors": [%(morphColors)s],
  136. "normals": [%(normals)s],
  137. "colors": [%(colors)s],
  138. "uvs": [[%(uvs)s]],
  139. "faces": [%(faces)s]
  140. }
  141. """
  142. TEMPLATE_FILE_BIN = u"""\
  143. {
  144. "metadata" :
  145. {
  146. "formatVersion" : 3.1,
  147. "sourceFile" : "%(fname)s",
  148. "generatedBy" : "OBJConverter",
  149. "vertices" : %(nvertex)d,
  150. "faces" : %(nface)d,
  151. "normals" : %(nnormal)d,
  152. "uvs" : %(nuv)d,
  153. "materials" : %(nmaterial)d
  154. },
  155. "materials": [%(materials)s],
  156. "buffers": "%(buffers)s"
  157. }
  158. """
  159. TEMPLATE_VERTEX = "%f,%f,%f"
  160. TEMPLATE_VERTEX_TRUNCATE = "%d,%d,%d"
  161. TEMPLATE_N = "%.5g,%.5g,%.5g"
  162. TEMPLATE_UV = "%.5g,%.5g"
  163. TEMPLATE_COLOR = "%.3g,%.3g,%.3g"
  164. TEMPLATE_COLOR_DEC = "%d"
  165. TEMPLATE_MORPH_VERTICES = '\t{ "name": "%s", "vertices": [%s] }'
  166. TEMPLATE_MORPH_COLORS = '\t{ "name": "%s", "colors": [%s] }'
  167. # #####################################################
  168. # Utils
  169. # #####################################################
  170. def file_exists(filename):
  171. """Return true if file exists and is accessible for reading.
  172. Should be safer than just testing for existence due to links and
  173. permissions magic on Unix filesystems.
  174. @rtype: boolean
  175. """
  176. try:
  177. f = open(filename, 'r')
  178. f.close()
  179. return True
  180. except IOError:
  181. return False
  182. def get_name(fname):
  183. """Create model name based of filename ("path/fname.js" -> "fname").
  184. """
  185. return os.path.splitext(os.path.basename(fname))[0]
  186. def bbox(vertices):
  187. """Compute bounding box of vertex array.
  188. """
  189. if len(vertices)>0:
  190. minx = maxx = vertices[0][0]
  191. miny = maxy = vertices[0][1]
  192. minz = maxz = vertices[0][2]
  193. for v in vertices[1:]:
  194. if v[0]<minx:
  195. minx = v[0]
  196. elif v[0]>maxx:
  197. maxx = v[0]
  198. if v[1]<miny:
  199. miny = v[1]
  200. elif v[1]>maxy:
  201. maxy = v[1]
  202. if v[2]<minz:
  203. minz = v[2]
  204. elif v[2]>maxz:
  205. maxz = v[2]
  206. return { 'x':[minx,maxx], 'y':[miny,maxy], 'z':[minz,maxz] }
  207. else:
  208. return { 'x':[0,0], 'y':[0,0], 'z':[0,0] }
  209. def translate(vertices, t):
  210. """Translate array of vertices by vector t.
  211. """
  212. for i in xrange(len(vertices)):
  213. vertices[i][0] += t[0]
  214. vertices[i][1] += t[1]
  215. vertices[i][2] += t[2]
  216. def center(vertices):
  217. """Center model (middle of bounding box).
  218. """
  219. bb = bbox(vertices)
  220. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  221. cy = bb['y'][0] + (bb['y'][1] - bb['y'][0])/2.0
  222. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  223. translate(vertices, [-cx,-cy,-cz])
  224. def top(vertices):
  225. """Align top of the model with the floor (Y-axis) and center it around X and Z.
  226. """
  227. bb = bbox(vertices)
  228. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  229. cy = bb['y'][1]
  230. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  231. translate(vertices, [-cx,-cy,-cz])
  232. def bottom(vertices):
  233. """Align bottom of the model with the floor (Y-axis) and center it around X and Z.
  234. """
  235. bb = bbox(vertices)
  236. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  237. cy = bb['y'][0]
  238. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  239. translate(vertices, [-cx,-cy,-cz])
  240. def centerxz(vertices):
  241. """Center model around X and Z.
  242. """
  243. bb = bbox(vertices)
  244. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  245. cy = 0
  246. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  247. translate(vertices, [-cx,-cy,-cz])
  248. def normalize(v):
  249. """Normalize 3d vector"""
  250. l = math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
  251. if l:
  252. v[0] /= l
  253. v[1] /= l
  254. v[2] /= l
  255. def veckey3(v):
  256. return round(v[0], 6), round(v[1], 6), round(v[2], 6)
  257. # #####################################################
  258. # MTL parser
  259. # #####################################################
  260. def texture_relative_path(fullpath):
  261. texture_file = os.path.basename(fullpath.replace("\\", "/"))
  262. return texture_file
  263. def parse_mtl(fname):
  264. """Parse MTL file.
  265. """
  266. materials = {}
  267. previous_line = ""
  268. for line in fileinput.input(fname):
  269. line = previous_line + line
  270. if line[-2:-1] == '\\':
  271. previous_line = line[:-2]
  272. continue
  273. previous_line = ""
  274. # Only split once initially for single-parameter tags that might have additional spaces in
  275. # their values (i.e. "newmtl Material with spaces").
  276. chunks = line.split(None, 1)
  277. if len(chunks) > 0:
  278. if len(chunks) > 1:
  279. chunks[1] = chunks[1].strip()
  280. # Material start
  281. # newmtl identifier
  282. if chunks[0] == "newmtl":
  283. if len(chunks) > 1:
  284. identifier = chunks[1]
  285. else:
  286. identifier = ""
  287. if not identifier in materials:
  288. materials[identifier] = {}
  289. # Diffuse texture
  290. # map_Kd texture_diffuse.jpg
  291. if chunks[0] == "map_Kd" and len(chunks) == 2:
  292. materials[identifier]["mapDiffuse"] = texture_relative_path(chunks[1])
  293. # Ambient texture
  294. # map_Ka texture_ambient.jpg
  295. if chunks[0] == "map_Ka" and len(chunks) == 2:
  296. materials[identifier]["mapAmbient"] = texture_relative_path(chunks[1])
  297. # Specular texture
  298. # map_Ks texture_specular.jpg
  299. if chunks[0] == "map_Ks" and len(chunks) == 2:
  300. materials[identifier]["mapSpecular"] = texture_relative_path(chunks[1])
  301. # Alpha texture
  302. # map_d texture_alpha.png
  303. if chunks[0] == "map_d" and len(chunks) == 2:
  304. materials[identifier]["transparent"] = True
  305. materials[identifier]["mapAlpha"] = texture_relative_path(chunks[1])
  306. # Bump texture
  307. # map_bump texture_bump.jpg or bump texture_bump.jpg
  308. if (chunks[0] == "map_bump" or chunks[0] == "bump") and len(chunks) == 2:
  309. materials[identifier]["mapBump"] = texture_relative_path(chunks[1])
  310. # Split the remaining parameters.
  311. if len(chunks) > 1:
  312. chunks = [chunks[0]] + chunks[1].split()
  313. # Diffuse color
  314. # Kd 1.000 1.000 1.000
  315. if chunks[0] == "Kd" and len(chunks) == 4:
  316. materials[identifier]["colorDiffuse"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  317. # Ambient color
  318. # Ka 1.000 1.000 1.000
  319. if chunks[0] == "Ka" and len(chunks) == 4:
  320. materials[identifier]["colorAmbient"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  321. # Specular color
  322. # Ks 1.000 1.000 1.000
  323. if chunks[0] == "Ks" and len(chunks) == 4:
  324. materials[identifier]["colorSpecular"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  325. # Specular coefficient
  326. # Ns 154.000
  327. if chunks[0] == "Ns" and len(chunks) == 2:
  328. materials[identifier]["specularCoef"] = float(chunks[1])
  329. # Transparency
  330. # Tr 0.9 or d 0.9
  331. if (chunks[0] == "Tr" or chunks[0] == "d") and len(chunks) == 2:
  332. materials[identifier]["transparent"] = True
  333. if TRANSPARENCY == "invert":
  334. materials[identifier]["transparency"] = 1.0 - float(chunks[1])
  335. else:
  336. materials[identifier]["transparency"] = float(chunks[1])
  337. # Optical density
  338. # Ni 1.0
  339. if chunks[0] == "Ni" and len(chunks) == 2:
  340. materials[identifier]["opticalDensity"] = float(chunks[1])
  341. # Illumination
  342. # illum 2
  343. #
  344. # 0. Color on and Ambient off
  345. # 1. Color on and Ambient on
  346. # 2. Highlight on
  347. # 3. Reflection on and Ray trace on
  348. # 4. Transparency: Glass on, Reflection: Ray trace on
  349. # 5. Reflection: Fresnel on and Ray trace on
  350. # 6. Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  351. # 7. Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  352. # 8. Reflection on and Ray trace off
  353. # 9. Transparency: Glass on, Reflection: Ray trace off
  354. # 10. Casts shadows onto invisible surfaces
  355. if chunks[0] == "illum" and len(chunks) == 2:
  356. materials[identifier]["illumination"] = int(chunks[1])
  357. return materials
  358. # #####################################################
  359. # OBJ parser
  360. # #####################################################
  361. def parse_vertex(text):
  362. """Parse text chunk specifying single vertex.
  363. Possible formats:
  364. vertex index
  365. vertex index / texture index
  366. vertex index / texture index / normal index
  367. vertex index / / normal index
  368. """
  369. v = 0
  370. t = 0
  371. n = 0
  372. chunks = text.split("/")
  373. v = int(chunks[0])
  374. if len(chunks) > 1:
  375. if chunks[1]:
  376. t = int(chunks[1])
  377. if len(chunks) > 2:
  378. if chunks[2]:
  379. n = int(chunks[2])
  380. return { 'v':v, 't':t, 'n':n }
  381. def parse_obj(fname):
  382. """Parse OBJ file.
  383. """
  384. vertices = []
  385. normals = []
  386. uvs = []
  387. faces = []
  388. materials = {}
  389. material = ""
  390. mcounter = 0
  391. mcurrent = 0
  392. mtllib = ""
  393. # current face state
  394. group = 0
  395. object = 0
  396. smooth = 0
  397. previous_line = ""
  398. for line in fileinput.input(fname):
  399. line = previous_line + line
  400. if line[-2:-1] == '\\':
  401. previous_line = line[:-2]
  402. continue
  403. previous_line = ""
  404. # Only split once initially for single-parameter tags that might have additional spaces in
  405. # their values (i.e. "usemtl Material with spaces").
  406. chunks = line.split(None, 1)
  407. if len(chunks) > 0:
  408. if len(chunks) > 1:
  409. chunks[1] = chunks[1].strip()
  410. # Group
  411. if chunks[0] == "g" and len(chunks) == 2:
  412. group = chunks[1]
  413. # Object
  414. if chunks[0] == "o" and len(chunks) == 2:
  415. object = chunks[1]
  416. # Materials definition
  417. if chunks[0] == "mtllib" and len(chunks) == 2:
  418. mtllib = chunks[1]
  419. # Material
  420. if chunks[0] == "usemtl":
  421. if len(chunks) > 1:
  422. material = chunks[1]
  423. else:
  424. material = ""
  425. if not material in materials:
  426. mcurrent = mcounter
  427. materials[material] = mcounter
  428. mcounter += 1
  429. else:
  430. mcurrent = materials[material]
  431. # Split the remaining parameters.
  432. if len(chunks) > 1:
  433. chunks = [chunks[0]] + chunks[1].split()
  434. # Vertices as (x,y,z) coordinates
  435. # v 0.123 0.234 0.345
  436. if chunks[0] == "v" and len(chunks) == 4:
  437. x = float(chunks[1])
  438. y = float(chunks[2])
  439. z = float(chunks[3])
  440. vertices.append([x,y,z])
  441. # Normals in (x,y,z) form; normals might not be unit
  442. # vn 0.707 0.000 0.707
  443. if chunks[0] == "vn" and len(chunks) == 4:
  444. x = float(chunks[1])
  445. y = float(chunks[2])
  446. z = float(chunks[3])
  447. normals.append([x,y,z])
  448. # Texture coordinates in (u,v[,w]) coordinates, w is optional
  449. # vt 0.500 -1.352 [0.234]
  450. if chunks[0] == "vt" and len(chunks) >= 3:
  451. u = float(chunks[1])
  452. v = float(chunks[2])
  453. w = 0
  454. if len(chunks)>3:
  455. w = float(chunks[3])
  456. uvs.append([u,v,w])
  457. # Face
  458. if chunks[0] == "f" and len(chunks) >= 4:
  459. vertex_index = []
  460. uv_index = []
  461. normal_index = []
  462. # Precompute vert / normal / uv lists
  463. # for negative index lookup
  464. vertlen = len(vertices) + 1
  465. normlen = len(normals) + 1
  466. uvlen = len(uvs) + 1
  467. for v in chunks[1:]:
  468. vertex = parse_vertex(v)
  469. if vertex['v']:
  470. if vertex['v'] < 0:
  471. vertex['v'] += vertlen
  472. vertex_index.append(vertex['v'])
  473. if vertex['t']:
  474. if vertex['t'] < 0:
  475. vertex['t'] += uvlen
  476. uv_index.append(vertex['t'])
  477. if vertex['n']:
  478. if vertex['n'] < 0:
  479. vertex['n'] += normlen
  480. normal_index.append(vertex['n'])
  481. faces.append({
  482. 'vertex':vertex_index,
  483. 'uv':uv_index,
  484. 'normal':normal_index,
  485. 'material':mcurrent,
  486. 'group':group,
  487. 'object':object,
  488. 'smooth':smooth,
  489. })
  490. # Smooth shading
  491. if chunks[0] == "s" and len(chunks) == 2:
  492. smooth = chunks[1]
  493. return faces, vertices, uvs, normals, materials, mtllib
  494. # #####################################################
  495. # Generator - faces
  496. # #####################################################
  497. def setBit(value, position, on):
  498. if on:
  499. mask = 1 << position
  500. return (value | mask)
  501. else:
  502. mask = ~(1 << position)
  503. return (value & mask)
  504. def generate_face(f, fc):
  505. isTriangle = ( len(f['vertex']) == 3 )
  506. if isTriangle:
  507. nVertices = 3
  508. else:
  509. nVertices = 4
  510. hasMaterial = True # for the moment OBJs without materials get default material
  511. hasFaceUvs = False # not supported in OBJ
  512. hasFaceVertexUvs = ( len(f['uv']) >= nVertices )
  513. hasFaceNormals = False # don't export any face normals (as they are computed in engine)
  514. hasFaceVertexNormals = ( len(f["normal"]) >= nVertices and SHADING == "smooth" )
  515. hasFaceColors = BAKE_COLORS
  516. hasFaceVertexColors = False # not supported in OBJ
  517. faceType = 0
  518. faceType = setBit(faceType, 0, not isTriangle)
  519. faceType = setBit(faceType, 1, hasMaterial)
  520. faceType = setBit(faceType, 2, hasFaceUvs)
  521. faceType = setBit(faceType, 3, hasFaceVertexUvs)
  522. faceType = setBit(faceType, 4, hasFaceNormals)
  523. faceType = setBit(faceType, 5, hasFaceVertexNormals)
  524. faceType = setBit(faceType, 6, hasFaceColors)
  525. faceType = setBit(faceType, 7, hasFaceVertexColors)
  526. faceData = []
  527. # order is important, must match order in JSONLoader
  528. # face type
  529. # vertex indices
  530. # material index
  531. # face uvs index
  532. # face vertex uvs indices
  533. # face normal index
  534. # face vertex normals indices
  535. # face color index
  536. # face vertex colors indices
  537. faceData.append(faceType)
  538. # must clamp in case on polygons bigger than quads
  539. for i in xrange(nVertices):
  540. index = f['vertex'][i] - 1
  541. faceData.append(index)
  542. faceData.append( f['material'] )
  543. if hasFaceVertexUvs:
  544. for i in xrange(nVertices):
  545. index = f['uv'][i] - 1
  546. faceData.append(index)
  547. if hasFaceVertexNormals:
  548. for i in xrange(nVertices):
  549. index = f['normal'][i] - 1
  550. faceData.append(index)
  551. if hasFaceColors:
  552. index = fc['material']
  553. faceData.append(index)
  554. return ",".join( map(str, faceData) )
  555. # #####################################################
  556. # Generator - chunks
  557. # #####################################################
  558. def hexcolor(c):
  559. return ( int(c[0] * 255) << 16 ) + ( int(c[1] * 255) << 8 ) + int(c[2] * 255)
  560. def generate_vertex(v, option_vertices_truncate, scale):
  561. if not option_vertices_truncate:
  562. return TEMPLATE_VERTEX % (v[0], v[1], v[2])
  563. else:
  564. return TEMPLATE_VERTEX_TRUNCATE % (scale * v[0], scale * v[1], scale * v[2])
  565. def generate_normal(n):
  566. return TEMPLATE_N % (n[0], n[1], n[2])
  567. def generate_uv(uv):
  568. return TEMPLATE_UV % (uv[0], uv[1])
  569. def generate_color_rgb(c):
  570. return TEMPLATE_COLOR % (c[0], c[1], c[2])
  571. def generate_color_decimal(c):
  572. return TEMPLATE_COLOR_DEC % hexcolor(c)
  573. # #####################################################
  574. # Morphs
  575. # #####################################################
  576. def generate_morph_vertex(name, vertices):
  577. vertex_string = ",".join(generate_vertex(v, TRUNCATE, SCALE) for v in vertices)
  578. return TEMPLATE_MORPH_VERTICES % (name, vertex_string)
  579. def generate_morph_color(name, colors):
  580. color_string = ",".join(generate_color_rgb(c) for c in colors)
  581. return TEMPLATE_MORPH_COLORS % (name, color_string)
  582. def extract_material_colors(materials, mtlfilename, basename):
  583. """Extract diffuse colors from MTL materials
  584. """
  585. if not materials:
  586. materials = { 'default': 0 }
  587. mtl = create_materials(materials, mtlfilename, basename)
  588. mtlColorArraySrt = []
  589. for m in mtl:
  590. if m in materials:
  591. index = materials[m]
  592. color = mtl[m].get("colorDiffuse", [1,0,0])
  593. mtlColorArraySrt.append([index, color])
  594. mtlColorArraySrt.sort()
  595. mtlColorArray = [x[1] for x in mtlColorArraySrt]
  596. return mtlColorArray
  597. def extract_face_colors(faces, material_colors):
  598. """Extract colors from materials and assign them to faces
  599. """
  600. faceColors = []
  601. for face in faces:
  602. material_index = face['material']
  603. faceColors.append(material_colors[material_index])
  604. return faceColors
  605. def generate_morph_targets(morphfiles, n_vertices, infile):
  606. skipOriginalMorph = False
  607. norminfile = os.path.normpath(infile)
  608. morphVertexData = []
  609. for mfilepattern in morphfiles.split():
  610. matches = glob.glob(mfilepattern)
  611. matches.sort()
  612. indices = range(0, len(matches), FRAMESTEP)
  613. for i in indices:
  614. path = matches[i]
  615. normpath = os.path.normpath(path)
  616. if normpath != norminfile or not skipOriginalMorph:
  617. name = os.path.basename(normpath)
  618. morphFaces, morphVertices, morphUvs, morphNormals, morphMaterials, morphMtllib = parse_obj(normpath)
  619. n_morph_vertices = len(morphVertices)
  620. if n_vertices != n_morph_vertices:
  621. print "WARNING: skipping morph [%s] with different number of vertices [%d] than the original model [%d]" % (name, n_morph_vertices, n_vertices)
  622. else:
  623. if ALIGN == "center":
  624. center(morphVertices)
  625. elif ALIGN == "centerxz":
  626. centerxz(morphVertices)
  627. elif ALIGN == "bottom":
  628. bottom(morphVertices)
  629. elif ALIGN == "top":
  630. top(morphVertices)
  631. morphVertexData.append((get_name(name), morphVertices))
  632. print "adding [%s] with %d vertices" % (name, n_morph_vertices)
  633. morphTargets = ""
  634. if len(morphVertexData):
  635. morphTargets = "\n%s\n\t" % ",\n".join(generate_morph_vertex(name, vertices) for name, vertices in morphVertexData)
  636. return morphTargets
  637. def generate_morph_colors(colorfiles, n_vertices, n_faces):
  638. morphColorData = []
  639. colorFaces = []
  640. materialColors = []
  641. for mfilepattern in colorfiles.split():
  642. matches = glob.glob(mfilepattern)
  643. matches.sort()
  644. for path in matches:
  645. normpath = os.path.normpath(path)
  646. name = os.path.basename(normpath)
  647. morphFaces, morphVertices, morphUvs, morphNormals, morphMaterials, morphMtllib = parse_obj(normpath)
  648. n_morph_vertices = len(morphVertices)
  649. n_morph_faces = len(morphFaces)
  650. if n_vertices != n_morph_vertices:
  651. print "WARNING: skipping morph color map [%s] with different number of vertices [%d] than the original model [%d]" % (name, n_morph_vertices, n_vertices)
  652. elif n_faces != n_morph_faces:
  653. print "WARNING: skipping morph color map [%s] with different number of faces [%d] than the original model [%d]" % (name, n_morph_faces, n_faces)
  654. else:
  655. morphMaterialColors = extract_material_colors(morphMaterials, morphMtllib, normpath)
  656. morphFaceColors = extract_face_colors(morphFaces, morphMaterialColors)
  657. morphColorData.append((get_name(name), morphFaceColors))
  658. # take first color map for baking into face colors
  659. if len(colorFaces) == 0:
  660. colorFaces = morphFaces
  661. materialColors = morphMaterialColors
  662. print "adding [%s] with %d face colors" % (name, len(morphFaceColors))
  663. morphColors = ""
  664. if len(morphColorData):
  665. morphColors = "\n%s\n\t" % ",\n".join(generate_morph_color(name, colors) for name, colors in morphColorData)
  666. return morphColors, colorFaces, materialColors
  667. # #####################################################
  668. # Materials
  669. # #####################################################
  670. def generate_color(i):
  671. """Generate hex color corresponding to integer.
  672. Colors should have well defined ordering.
  673. First N colors are hardcoded, then colors are random
  674. (must seed random number generator with deterministic value
  675. before getting colors).
  676. """
  677. if i < len(COLORS):
  678. #return "0x%06x" % COLORS[i]
  679. return COLORS[i]
  680. else:
  681. #return "0x%06x" % int(0xffffff * random.random())
  682. return int(0xffffff * random.random())
  683. def value2string(v):
  684. if type(v)==str and v[0:2] != "0x":
  685. return '"%s"' % v
  686. elif type(v) == bool:
  687. return str(v).lower()
  688. return str(v)
  689. def generate_materials(mtl, materials):
  690. """Generate JS array of materials objects
  691. JS material objects are basically prettified one-to-one
  692. mappings of MTL properties in JSON format.
  693. """
  694. mtl_array = []
  695. for m in mtl:
  696. if m in materials:
  697. index = materials[m]
  698. # add debug information
  699. # materials should be sorted according to how
  700. # they appeared in OBJ file (for the first time)
  701. # this index is identifier used in face definitions
  702. mtl[m]['DbgName'] = m
  703. mtl[m]['DbgIndex'] = index
  704. mtl[m]['DbgColor'] = generate_color(index)
  705. if BAKE_COLORS:
  706. mtl[m]['vertexColors'] = "face"
  707. mtl_raw = ",\n".join(['\t"%s" : %s' % (n, value2string(v)) for n,v in sorted(mtl[m].items())])
  708. mtl_string = "\t{\n%s\n\t}" % mtl_raw
  709. mtl_array.append([index, mtl_string])
  710. return ",\n\n".join([m for i,m in sorted(mtl_array)])
  711. def generate_mtl(materials):
  712. """Generate dummy materials (if there is no MTL file).
  713. """
  714. mtl = {}
  715. for m in materials:
  716. index = materials[m]
  717. mtl[m] = {
  718. 'DbgName': m,
  719. 'DbgIndex': index,
  720. 'DbgColor': generate_color(index)
  721. }
  722. return mtl
  723. def generate_materials_string(materials, mtlfilename, basename):
  724. """Generate final materials string.
  725. """
  726. if not materials:
  727. materials = { 'default': 0 }
  728. mtl = create_materials(materials, mtlfilename, basename)
  729. return generate_materials(mtl, materials)
  730. def create_materials(materials, mtlfilename, basename):
  731. """Parse MTL file and create mapping between its materials and OBJ materials.
  732. Eventual edge cases are handled here (missing materials, missing MTL file).
  733. """
  734. random.seed(42) # to get well defined color order for debug colors
  735. # default materials with debug colors for when
  736. # there is no specified MTL / MTL loading failed,
  737. # or if there were no materials / null materials
  738. mtl = generate_mtl(materials)
  739. if mtlfilename:
  740. # create full pathname for MTL (included from OBJ)
  741. path = os.path.dirname(basename)
  742. fname = os.path.join(path, mtlfilename)
  743. if file_exists(fname):
  744. # override default materials with real ones from MTL
  745. # (where they exist, otherwise keep defaults)
  746. mtl.update(parse_mtl(fname))
  747. else:
  748. print "Couldn't find [%s]" % fname
  749. return mtl
  750. # #####################################################
  751. # Faces
  752. # #####################################################
  753. def is_triangle_flat(f):
  754. return len(f['vertex'])==3 and not (f["normal"] and SHADING == "smooth") and not f['uv']
  755. def is_triangle_flat_uv(f):
  756. return len(f['vertex'])==3 and not (f["normal"] and SHADING == "smooth") and len(f['uv'])==3
  757. def is_triangle_smooth(f):
  758. return len(f['vertex'])==3 and f["normal"] and SHADING == "smooth" and not f['uv']
  759. def is_triangle_smooth_uv(f):
  760. return len(f['vertex'])==3 and f["normal"] and SHADING == "smooth" and len(f['uv'])==3
  761. def is_quad_flat(f):
  762. return len(f['vertex'])==4 and not (f["normal"] and SHADING == "smooth") and not f['uv']
  763. def is_quad_flat_uv(f):
  764. return len(f['vertex'])==4 and not (f["normal"] and SHADING == "smooth") and len(f['uv'])==4
  765. def is_quad_smooth(f):
  766. return len(f['vertex'])==4 and f["normal"] and SHADING == "smooth" and not f['uv']
  767. def is_quad_smooth_uv(f):
  768. return len(f['vertex'])==4 and f["normal"] and SHADING == "smooth" and len(f['uv'])==4
  769. def sort_faces(faces):
  770. data = {
  771. 'triangles_flat': [],
  772. 'triangles_flat_uv': [],
  773. 'triangles_smooth': [],
  774. 'triangles_smooth_uv': [],
  775. 'quads_flat': [],
  776. 'quads_flat_uv': [],
  777. 'quads_smooth': [],
  778. 'quads_smooth_uv': []
  779. }
  780. for f in faces:
  781. if is_triangle_flat(f):
  782. data['triangles_flat'].append(f)
  783. elif is_triangle_flat_uv(f):
  784. data['triangles_flat_uv'].append(f)
  785. elif is_triangle_smooth(f):
  786. data['triangles_smooth'].append(f)
  787. elif is_triangle_smooth_uv(f):
  788. data['triangles_smooth_uv'].append(f)
  789. elif is_quad_flat(f):
  790. data['quads_flat'].append(f)
  791. elif is_quad_flat_uv(f):
  792. data['quads_flat_uv'].append(f)
  793. elif is_quad_smooth(f):
  794. data['quads_smooth'].append(f)
  795. elif is_quad_smooth_uv(f):
  796. data['quads_smooth_uv'].append(f)
  797. return data
  798. # #####################################################
  799. # API - ASCII converter
  800. # #####################################################
  801. def convert_ascii(infile, morphfiles, colorfiles, outfile):
  802. """Convert infile.obj to outfile.js
  803. Here is where everything happens. If you need to automate conversions,
  804. just import this file as Python module and call this method.
  805. """
  806. if not file_exists(infile):
  807. print "Couldn't find [%s]" % infile
  808. return
  809. # parse OBJ / MTL files
  810. faces, vertices, uvs, normals, materials, mtllib = parse_obj(infile)
  811. n_vertices = len(vertices)
  812. n_faces = len(faces)
  813. # align model
  814. if ALIGN == "center":
  815. center(vertices)
  816. elif ALIGN == "centerxz":
  817. centerxz(vertices)
  818. elif ALIGN == "bottom":
  819. bottom(vertices)
  820. elif ALIGN == "top":
  821. top(vertices)
  822. # generate normals string
  823. nnormal = 0
  824. normals_string = ""
  825. if SHADING == "smooth":
  826. normals_string = ",".join(generate_normal(n) for n in normals)
  827. nnormal = len(normals)
  828. # extract morph vertices
  829. morphTargets = generate_morph_targets(morphfiles, n_vertices, infile)
  830. # extract morph colors
  831. morphColors, colorFaces, materialColors = generate_morph_colors(colorfiles, n_vertices, n_faces)
  832. # generate colors string
  833. ncolor = 0
  834. colors_string = ""
  835. if len(colorFaces) < len(faces):
  836. colorFaces = faces
  837. materialColors = extract_material_colors(materials, mtllib, infile)
  838. if BAKE_COLORS:
  839. colors_string = ",".join(generate_color_decimal(c) for c in materialColors)
  840. ncolor = len(materialColors)
  841. # generate ascii model string
  842. text = TEMPLATE_FILE_ASCII % {
  843. "name" : get_name(outfile),
  844. "fname" : os.path.basename(infile),
  845. "nvertex" : len(vertices),
  846. "nface" : len(faces),
  847. "nuv" : len(uvs),
  848. "nnormal" : nnormal,
  849. "ncolor" : ncolor,
  850. "nmaterial" : len(materials),
  851. "materials" : generate_materials_string(materials, mtllib, infile),
  852. "normals" : normals_string,
  853. "colors" : colors_string,
  854. "uvs" : ",".join(generate_uv(uv) for uv in uvs),
  855. "vertices" : ",".join(generate_vertex(v, TRUNCATE, SCALE) for v in vertices),
  856. "morphTargets" : morphTargets,
  857. "morphColors" : morphColors,
  858. "faces" : ",".join(generate_face(f, fc) for f, fc in zip(faces, colorFaces)),
  859. "scale" : SCALE
  860. }
  861. out = open(outfile, "w")
  862. out.write(text)
  863. out.close()
  864. print "%d vertices, %d faces, %d materials" % (len(vertices), len(faces), len(materials))
  865. # #############################################################################
  866. # API - Binary converter
  867. # #############################################################################
  868. def dump_materials_to_buffer(faces, buffer):
  869. for f in faces:
  870. data = struct.pack('<H',
  871. f['material'])
  872. buffer.append(data)
  873. def dump_vertices3_to_buffer(faces, buffer):
  874. for f in faces:
  875. vi = f['vertex']
  876. data = struct.pack('<III',
  877. vi[0]-1, vi[1]-1, vi[2]-1)
  878. buffer.append(data)
  879. def dump_vertices4_to_buffer(faces, buffer):
  880. for f in faces:
  881. vi = f['vertex']
  882. data = struct.pack('<IIII',
  883. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1)
  884. buffer.append(data)
  885. def dump_normals3_to_buffer(faces, buffer):
  886. for f in faces:
  887. ni = f['normal']
  888. data = struct.pack('<III',
  889. ni[0]-1, ni[1]-1, ni[2]-1)
  890. buffer.append(data)
  891. def dump_normals4_to_buffer(faces, buffer):
  892. for f in faces:
  893. ni = f['normal']
  894. data = struct.pack('<IIII',
  895. ni[0]-1, ni[1]-1, ni[2]-1, ni[3]-1)
  896. buffer.append(data)
  897. def dump_uvs3_to_buffer(faces, buffer):
  898. for f in faces:
  899. ui = f['uv']
  900. data = struct.pack('<III',
  901. ui[0]-1, ui[1]-1, ui[2]-1)
  902. buffer.append(data)
  903. def dump_uvs4_to_buffer(faces, buffer):
  904. for f in faces:
  905. ui = f['uv']
  906. data = struct.pack('<IIII',
  907. ui[0]-1, ui[1]-1, ui[2]-1, ui[3]-1)
  908. buffer.append(data)
  909. def add_padding(buffer, n):
  910. if n % 4:
  911. for i in range(4 - n % 4):
  912. data = struct.pack('<B', 0)
  913. buffer.append(data)
  914. def convert_binary(infile, outfile):
  915. """Convert infile.obj to outfile.js + outfile.bin
  916. """
  917. if not file_exists(infile):
  918. print "Couldn't find [%s]" % infile
  919. return
  920. binfile = get_name(outfile) + ".bin"
  921. faces, vertices, uvs, normals, materials, mtllib = parse_obj(infile)
  922. if ALIGN == "center":
  923. center(vertices)
  924. elif ALIGN == "centerxz":
  925. centerxz(vertices)
  926. elif ALIGN == "bottom":
  927. bottom(vertices)
  928. elif ALIGN == "top":
  929. top(vertices)
  930. sfaces = sort_faces(faces)
  931. if SHADING == "smooth":
  932. nnormals = len(normals)
  933. else:
  934. nnormals = 0
  935. # ###################
  936. # generate JS file
  937. # ###################
  938. text = TEMPLATE_FILE_BIN % {
  939. "name" : get_name(outfile),
  940. "materials" : generate_materials_string(materials, mtllib, infile),
  941. "buffers" : binfile,
  942. "fname" : os.path.basename(infile),
  943. "nvertex" : len(vertices),
  944. "nface" : len(faces),
  945. "nmaterial" : len(materials),
  946. "nnormal" : nnormals,
  947. "nuv" : len(uvs)
  948. }
  949. out = open(outfile, "w")
  950. out.write(text)
  951. out.close()
  952. # ###################
  953. # generate BIN file
  954. # ###################
  955. buffer = []
  956. # header
  957. # ------
  958. header_bytes = struct.calcsize('<12s')
  959. header_bytes += struct.calcsize('<BBBBBBBB')
  960. header_bytes += struct.calcsize('<IIIIIIIIIII')
  961. # signature
  962. signature = struct.pack('<12s', 'Three.js 003')
  963. # metadata (all data is little-endian)
  964. vertex_coordinate_bytes = 4
  965. normal_coordinate_bytes = 1
  966. uv_coordinate_bytes = 4
  967. vertex_index_bytes = 4
  968. normal_index_bytes = 4
  969. uv_index_bytes = 4
  970. material_index_bytes = 2
  971. # header_bytes unsigned char 1
  972. # vertex_coordinate_bytes unsigned char 1
  973. # normal_coordinate_bytes unsigned char 1
  974. # uv_coordinate_bytes unsigned char 1
  975. # vertex_index_bytes unsigned char 1
  976. # normal_index_bytes unsigned char 1
  977. # uv_index_bytes unsigned char 1
  978. # material_index_bytes unsigned char 1
  979. bdata = struct.pack('<BBBBBBBB', header_bytes,
  980. vertex_coordinate_bytes,
  981. normal_coordinate_bytes,
  982. uv_coordinate_bytes,
  983. vertex_index_bytes,
  984. normal_index_bytes,
  985. uv_index_bytes,
  986. material_index_bytes)
  987. ntri_flat = len(sfaces['triangles_flat'])
  988. ntri_smooth = len(sfaces['triangles_smooth'])
  989. ntri_flat_uv = len(sfaces['triangles_flat_uv'])
  990. ntri_smooth_uv = len(sfaces['triangles_smooth_uv'])
  991. nquad_flat = len(sfaces['quads_flat'])
  992. nquad_smooth = len(sfaces['quads_smooth'])
  993. nquad_flat_uv = len(sfaces['quads_flat_uv'])
  994. nquad_smooth_uv = len(sfaces['quads_smooth_uv'])
  995. # nvertices unsigned int 4
  996. # nnormals unsigned int 4
  997. # nuvs unsigned int 4
  998. # ntri_flat unsigned int 4
  999. # ntri_smooth unsigned int 4
  1000. # ntri_flat_uv unsigned int 4
  1001. # ntri_smooth_uv unsigned int 4
  1002. # nquad_flat unsigned int 4
  1003. # nquad_smooth unsigned int 4
  1004. # nquad_flat_uv unsigned int 4
  1005. # nquad_smooth_uv unsigned int 4
  1006. ndata = struct.pack('<IIIIIIIIIII', len(vertices),
  1007. nnormals,
  1008. len(uvs),
  1009. ntri_flat,
  1010. ntri_smooth,
  1011. ntri_flat_uv,
  1012. ntri_smooth_uv,
  1013. nquad_flat,
  1014. nquad_smooth,
  1015. nquad_flat_uv,
  1016. nquad_smooth_uv)
  1017. buffer.append(signature)
  1018. buffer.append(bdata)
  1019. buffer.append(ndata)
  1020. # 1. vertices
  1021. # ------------
  1022. # x float 4
  1023. # y float 4
  1024. # z float 4
  1025. for v in vertices:
  1026. data = struct.pack('<fff', v[0], v[1], v[2])
  1027. buffer.append(data)
  1028. # 2. normals
  1029. # ---------------
  1030. # x signed char 1
  1031. # y signed char 1
  1032. # z signed char 1
  1033. if SHADING == "smooth":
  1034. for n in normals:
  1035. normalize(n)
  1036. data = struct.pack('<bbb', math.floor(n[0]*127+0.5),
  1037. math.floor(n[1]*127+0.5),
  1038. math.floor(n[2]*127+0.5))
  1039. buffer.append(data)
  1040. add_padding(buffer, nnormals * 3)
  1041. # 3. uvs
  1042. # -----------
  1043. # u float 4
  1044. # v float 4
  1045. for uv in uvs:
  1046. data = struct.pack('<ff', uv[0], uv[1])
  1047. buffer.append(data)
  1048. # padding
  1049. #data = struct.pack('<BB', 0, 0)
  1050. #buffer.append(data)
  1051. # 4. flat triangles (vertices + materials)
  1052. # ------------------
  1053. # a unsigned int 4
  1054. # b unsigned int 4
  1055. # c unsigned int 4
  1056. # ------------------
  1057. # m unsigned short 2
  1058. dump_vertices3_to_buffer(sfaces['triangles_flat'], buffer)
  1059. dump_materials_to_buffer(sfaces['triangles_flat'], buffer)
  1060. add_padding(buffer, ntri_flat * 2)
  1061. # 5. smooth triangles (vertices + materials + normals)
  1062. # -------------------
  1063. # a unsigned int 4
  1064. # b unsigned int 4
  1065. # c unsigned int 4
  1066. # -------------------
  1067. # na unsigned int 4
  1068. # nb unsigned int 4
  1069. # nc unsigned int 4
  1070. # -------------------
  1071. # m unsigned short 2
  1072. dump_vertices3_to_buffer(sfaces['triangles_smooth'], buffer)
  1073. dump_normals3_to_buffer(sfaces['triangles_smooth'], buffer)
  1074. dump_materials_to_buffer(sfaces['triangles_smooth'], buffer)
  1075. add_padding(buffer, ntri_smooth * 2)
  1076. # 6. flat triangles uv (vertices + materials + uvs)
  1077. # --------------------
  1078. # a unsigned int 4
  1079. # b unsigned int 4
  1080. # c unsigned int 4
  1081. # --------------------
  1082. # ua unsigned int 4
  1083. # ub unsigned int 4
  1084. # uc unsigned int 4
  1085. # --------------------
  1086. # m unsigned short 2
  1087. dump_vertices3_to_buffer(sfaces['triangles_flat_uv'], buffer)
  1088. dump_uvs3_to_buffer(sfaces['triangles_flat_uv'], buffer)
  1089. dump_materials_to_buffer(sfaces['triangles_flat_uv'], buffer)
  1090. add_padding(buffer, ntri_flat_uv * 2)
  1091. # 7. smooth triangles uv (vertices + materials + normals + uvs)
  1092. # ----------------------
  1093. # a unsigned int 4
  1094. # b unsigned int 4
  1095. # c unsigned int 4
  1096. # --------------------
  1097. # na unsigned int 4
  1098. # nb unsigned int 4
  1099. # nc unsigned int 4
  1100. # --------------------
  1101. # ua unsigned int 4
  1102. # ub unsigned int 4
  1103. # uc unsigned int 4
  1104. # --------------------
  1105. # m unsigned short 2
  1106. dump_vertices3_to_buffer(sfaces['triangles_smooth_uv'], buffer)
  1107. dump_normals3_to_buffer(sfaces['triangles_smooth_uv'], buffer)
  1108. dump_uvs3_to_buffer(sfaces['triangles_smooth_uv'], buffer)
  1109. dump_materials_to_buffer(sfaces['triangles_smooth_uv'], buffer)
  1110. add_padding(buffer, ntri_smooth_uv * 2)
  1111. # 8. flat quads (vertices + materials)
  1112. # ------------------
  1113. # a unsigned int 4
  1114. # b unsigned int 4
  1115. # c unsigned int 4
  1116. # d unsigned int 4
  1117. # --------------------
  1118. # m unsigned short 2
  1119. dump_vertices4_to_buffer(sfaces['quads_flat'], buffer)
  1120. dump_materials_to_buffer(sfaces['quads_flat'], buffer)
  1121. add_padding(buffer, nquad_flat * 2)
  1122. # 9. smooth quads (vertices + materials + normals)
  1123. # -------------------
  1124. # a unsigned int 4
  1125. # b unsigned int 4
  1126. # c unsigned int 4
  1127. # d unsigned int 4
  1128. # --------------------
  1129. # na unsigned int 4
  1130. # nb unsigned int 4
  1131. # nc unsigned int 4
  1132. # nd unsigned int 4
  1133. # --------------------
  1134. # m unsigned short 2
  1135. dump_vertices4_to_buffer(sfaces['quads_smooth'], buffer)
  1136. dump_normals4_to_buffer(sfaces['quads_smooth'], buffer)
  1137. dump_materials_to_buffer(sfaces['quads_smooth'], buffer)
  1138. add_padding(buffer, nquad_smooth * 2)
  1139. # 10. flat quads uv (vertices + materials + uvs)
  1140. # ------------------
  1141. # a unsigned int 4
  1142. # b unsigned int 4
  1143. # c unsigned int 4
  1144. # d unsigned int 4
  1145. # --------------------
  1146. # ua unsigned int 4
  1147. # ub unsigned int 4
  1148. # uc unsigned int 4
  1149. # ud unsigned int 4
  1150. # --------------------
  1151. # m unsigned short 2
  1152. dump_vertices4_to_buffer(sfaces['quads_flat_uv'], buffer)
  1153. dump_uvs4_to_buffer(sfaces['quads_flat_uv'], buffer)
  1154. dump_materials_to_buffer(sfaces['quads_flat_uv'], buffer)
  1155. add_padding(buffer, nquad_flat_uv * 2)
  1156. # 11. smooth quads uv
  1157. # -------------------
  1158. # a unsigned int 4
  1159. # b unsigned int 4
  1160. # c unsigned int 4
  1161. # d unsigned int 4
  1162. # --------------------
  1163. # na unsigned int 4
  1164. # nb unsigned int 4
  1165. # nc unsigned int 4
  1166. # nd unsigned int 4
  1167. # --------------------
  1168. # ua unsigned int 4
  1169. # ub unsigned int 4
  1170. # uc unsigned int 4
  1171. # ud unsigned int 4
  1172. # --------------------
  1173. # m unsigned short 2
  1174. dump_vertices4_to_buffer(sfaces['quads_smooth_uv'], buffer)
  1175. dump_normals4_to_buffer(sfaces['quads_smooth_uv'], buffer)
  1176. dump_uvs4_to_buffer(sfaces['quads_smooth_uv'], buffer)
  1177. dump_materials_to_buffer(sfaces['quads_smooth_uv'], buffer)
  1178. add_padding(buffer, nquad_smooth_uv * 2)
  1179. path = os.path.dirname(outfile)
  1180. fname = os.path.join(path, binfile)
  1181. out = open(fname, "wb")
  1182. out.write("".join(buffer))
  1183. out.close()
  1184. # #############################################################################
  1185. # Helpers
  1186. # #############################################################################
  1187. def usage():
  1188. print "Usage: %s -i filename.obj -o filename.js [-m morphfiles*.obj] [-c morphcolors*.obj] [-a center|top|bottom] [-s flat|smooth] [-t binary|ascii] [-d invert|normal]" % os.path.basename(sys.argv[0])
  1189. # #####################################################
  1190. # Main
  1191. # #####################################################
  1192. if __name__ == "__main__":
  1193. # get parameters from the command line
  1194. try:
  1195. opts, args = getopt.getopt(sys.argv[1:], "hbi:m:c:b:o:a:s:t:d:x:f:", ["help", "bakecolors", "input=", "morphs=", "colors=", "output=", "align=", "shading=", "type=", "dissolve=", "truncatescale=", "framestep="])
  1196. except getopt.GetoptError:
  1197. usage()
  1198. sys.exit(2)
  1199. infile = outfile = ""
  1200. morphfiles = ""
  1201. colorfiles = ""
  1202. for o, a in opts:
  1203. if o in ("-h", "--help"):
  1204. usage()
  1205. sys.exit()
  1206. elif o in ("-i", "--input"):
  1207. infile = a
  1208. elif o in ("-m", "--morphs"):
  1209. morphfiles = a
  1210. elif o in ("-c", "--colors"):
  1211. colorfiles = a
  1212. elif o in ("-o", "--output"):
  1213. outfile = a
  1214. elif o in ("-a", "--align"):
  1215. if a in ("top", "bottom", "center", "centerxz", "none"):
  1216. ALIGN = a
  1217. elif o in ("-s", "--shading"):
  1218. if a in ("flat", "smooth"):
  1219. SHADING = a
  1220. elif o in ("-t", "--type"):
  1221. if a in ("binary", "ascii"):
  1222. TYPE = a
  1223. elif o in ("-d", "--dissolve"):
  1224. if a in ("normal", "invert"):
  1225. TRANSPARENCY = a
  1226. elif o in ("-b", "--bakecolors"):
  1227. BAKE_COLORS = True
  1228. elif o in ("-x", "--truncatescale"):
  1229. TRUNCATE = True
  1230. SCALE = float(a)
  1231. elif o in ("-f", "--framestep"):
  1232. FRAMESTEP = int(a)
  1233. if infile == "" or outfile == "":
  1234. usage()
  1235. sys.exit(2)
  1236. print "Converting [%s] into [%s] ..." % (infile, outfile)
  1237. if morphfiles:
  1238. print "Morphs [%s]" % morphfiles
  1239. if colorfiles:
  1240. print "Colors [%s]" % colorfiles
  1241. if TYPE == "ascii":
  1242. convert_ascii(infile, morphfiles, colorfiles, outfile)
  1243. elif TYPE == "binary":
  1244. convert_binary(infile, outfile)