convert_obj_threejs_slim.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  1. """Convert Wavefront OBJ / MTL files into Three.js (slim models version, to be used with web worker based ascii / binary loader)
  2. -------------------------
  3. How to use this converter
  4. -------------------------
  5. python convert_obj_threejs_slim.py -i infile.obj -o outfile.js [-a center|top|bottom] [-s smooth|flat] [-t ascii|binary] [-d invert|normal]
  6. Notes:
  7. - by default:
  8. converted model will be centered (middle of bounding box goes to 0,0,0)
  9. use smooth shading (if there were vertex normals in the original model)
  10. will be in ASCII format
  11. original model is assumed to use non-inverted transparency / dissolve (0.0 fully transparent, 1.0 fully opaque)
  12. - binary conversion will create two files:
  13. outfile.js (materials)
  14. outfile.bin (binary buffers)
  15. --------------------------------------------------
  16. How to use generated JS file in your HTML document
  17. --------------------------------------------------
  18. <script type="text/javascript" src="Three.js"></script>
  19. ...
  20. <script type="text/javascript">
  21. ...
  22. var loader = new THREE.Loader();
  23. // load ascii model
  24. loader.loadAscii( "Model_slim.js", function( geometry ) { createScene( geometry) }, path_to_textures );
  25. // load binary model
  26. loader.loadBinary( "Model_bin.js", function( geometry ) { createScene( geometry) }, path_to_textures );
  27. function createScene( geometry ) {
  28. var normalizeUVsFlag = 1; // set to 1 if canvas render has missing materials
  29. var mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial(), normalizeUVsFlag );
  30. }
  31. ...
  32. </script>
  33. -------------------------------------
  34. Parsers based on formats descriptions
  35. -------------------------------------
  36. http://en.wikipedia.org/wiki/Obj
  37. http://en.wikipedia.org/wiki/Material_Template_Library
  38. -------------------
  39. Current limitations
  40. -------------------
  41. - for the moment, only diffuse color and texture are used
  42. (will need to extend shaders / renderers / materials in Three)
  43. - models can have more than 65,536 vertices,
  44. but in most cases it will not work well with browsers,
  45. which currently seem to have troubles with handling
  46. large JS files
  47. - texture coordinates can be wrong in canvas renderer
  48. (there is crude normalization, but it doesn't
  49. work for all cases)
  50. - smoothing can be turned on/off only for the whole mesh
  51. ----------------------------------------------
  52. How to get proper OBJ + MTL files with Blender
  53. ----------------------------------------------
  54. 0. Remove default cube (press DEL and ENTER)
  55. 1. Import / create model
  56. 2. Select all meshes (Select -> Select All by Type -> Mesh)
  57. 3. Export to OBJ (File -> Export -> Wavefront .obj) [*]
  58. - enable following options in exporter
  59. Material Groups
  60. Rotate X90
  61. Apply Modifiers
  62. High Quality Normals
  63. Copy Images
  64. Selection Only
  65. Objects as OBJ Objects
  66. UVs
  67. Normals
  68. Materials
  69. Edges
  70. - select empty folder
  71. - give your exported file name with "obj" extension
  72. - click on "Export OBJ" button
  73. 4. Your model is now all files in this folder (OBJ, MTL, number of images)
  74. - this converter assumes all files staying in the same folder,
  75. (OBJ / MTL files use relative paths)
  76. - for WebGL, textures must be power of 2 sized
  77. [*] If OBJ export fails (Blender 2.54 beta), patch your Blender installation
  78. following instructions here:
  79. http://www.blendernation.com/2010/09/12/blender-2-54-beta-released/
  80. ------
  81. Author
  82. ------
  83. AlteredQualia http://alteredqualia.com
  84. """
  85. import fileinput
  86. import operator
  87. import random
  88. import os.path
  89. import getopt
  90. import sys
  91. import struct
  92. import math
  93. # #####################################################
  94. # Configuration
  95. # #####################################################
  96. ALIGN = "center" # center bottom top none
  97. SHADING = "smooth" # smooth flat
  98. TYPE = "ascii" # ascii binary
  99. TRANSPARENCY = "normal" # normal invert
  100. # default colors for debugging (each material gets one distinct color):
  101. # white, red, green, blue, yellow, cyan, magenta
  102. COLORS = [0xeeeeee, 0xee0000, 0x00ee00, 0x0000ee, 0xeeee00, 0x00eeee, 0xee00ee]
  103. # #####################################################
  104. # Templates
  105. # #####################################################
  106. TEMPLATE_FILE_ASCII = u"""\
  107. // Converted from: %(fname)s
  108. // vertices: %(nvertex)d
  109. // faces: %(nface)d
  110. // materials: %(nmaterial)d
  111. //
  112. // Generated with OBJ -> Three.js converter
  113. // http://github.com/alteredq/three.js/blob/master/utils/exporters/convert_obj_threejs_slim.py
  114. var model = {
  115. 'materials': [%(materials)s],
  116. 'normals': [%(normals)s],
  117. 'vertices': [%(vertices)s],
  118. 'uvs': [%(uvs)s],
  119. 'triangles': [%(triangles)s],
  120. 'triangles_n': [%(triangles_n)s],
  121. 'triangles_uv': [%(triangles_uv)s],
  122. 'triangles_n_uv': [%(triangles_n_uv)s],
  123. 'quads': [%(quads)s],
  124. 'quads_n': [%(quads_n)s],
  125. 'quads_uv': [%(quads_uv)s],
  126. 'quads_n_uv': [%(quads_n_uv)s],
  127. 'end': (new Date).getTime()
  128. }
  129. postMessage( model );
  130. """
  131. TEMPLATE_FILE_BIN = u"""\
  132. // Converted from: %(fname)s
  133. // vertices: %(nvertex)d
  134. // faces: %(nface)d
  135. // materials: %(nmaterial)d
  136. //
  137. // Generated with OBJ -> Three.js converter
  138. // http://github.com/alteredq/three.js/blob/master/utils/exporters/convert_obj_threejs_slim.py
  139. var model = {
  140. 'materials': [%(materials)s],
  141. 'buffers': '%(buffers)s',
  142. 'end': (new Date).getTime()
  143. }
  144. postMessage( model );
  145. """
  146. TEMPLATE_VERTEX = "%f,%f,%f"
  147. TEMPLATE_UV_TRI = "%f,%f,%f,%f,%f,%f"
  148. TEMPLATE_UV_QUAD = "%f,%f,%f,%f,%f,%f,%f,%f"
  149. TEMPLATE_TRI = "%d,%d,%d,%d"
  150. TEMPLATE_QUAD = "%d,%d,%d,%d,%d"
  151. TEMPLATE_TRI_UV = "%d,%d,%d,%d,%d,%d,%d"
  152. TEMPLATE_QUAD_UV = "%d,%d,%d,%d,%d,%d,%d,%d,%d"
  153. TEMPLATE_TRI_N = "%d,%d,%d,%d,%d,%d,%d"
  154. TEMPLATE_QUAD_N = "%d,%d,%d,%d,%d,%d,%d,%d,%d"
  155. TEMPLATE_TRI_N_UV = "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d"
  156. TEMPLATE_QUAD_N_UV = "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d"
  157. TEMPLATE_N = "%f,%f,%f"
  158. TEMPLATE_UV = "%f,%f"
  159. # #####################################################
  160. # Utils
  161. # #####################################################
  162. def file_exists(filename):
  163. """Return true if file exists and is accessible for reading.
  164. Should be safer than just testing for existence due to links and
  165. permissions magic on Unix filesystems.
  166. @rtype: boolean
  167. """
  168. try:
  169. f = open(filename, 'r')
  170. f.close()
  171. return True
  172. except IOError:
  173. return False
  174. def get_name(fname):
  175. """Create model name based of filename ("path/fname.js" -> "fname").
  176. """
  177. return os.path.basename(fname).split(".")[0]
  178. def bbox(vertices):
  179. """Compute bounding box of vertex array.
  180. """
  181. if len(vertices)>0:
  182. minx = maxx = vertices[0][0]
  183. miny = maxy = vertices[0][1]
  184. minz = maxz = vertices[0][2]
  185. for v in vertices[1:]:
  186. if v[0]<minx:
  187. minx = v[0]
  188. elif v[0]>maxx:
  189. maxx = v[0]
  190. if v[1]<miny:
  191. miny = v[1]
  192. elif v[1]>maxy:
  193. maxy = v[1]
  194. if v[2]<minz:
  195. minz = v[2]
  196. elif v[2]>maxz:
  197. maxz = v[2]
  198. return { 'x':[minx,maxx], 'y':[miny,maxy], 'z':[minz,maxz] }
  199. else:
  200. return { 'x':[0,0], 'y':[0,0], 'z':[0,0] }
  201. def translate(vertices, t):
  202. """Translate array of vertices by vector t.
  203. """
  204. for i in xrange(len(vertices)):
  205. vertices[i][0] += t[0]
  206. vertices[i][1] += t[1]
  207. vertices[i][2] += t[2]
  208. def center(vertices):
  209. """Center model (middle of bounding box).
  210. """
  211. bb = bbox(vertices)
  212. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  213. cy = bb['y'][0] + (bb['y'][1] - bb['y'][0])/2.0
  214. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  215. translate(vertices, [-cx,-cy,-cz])
  216. def top(vertices):
  217. """Align top of the model with the floor (Y-axis) and center it around X and Z.
  218. """
  219. bb = bbox(vertices)
  220. cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0
  221. cy = bb['y'][1]
  222. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  223. translate(vertices, [-cx,-cy,-cz])
  224. def bottom(vertices):
  225. """Align bottom 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'][0]
  230. cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0
  231. translate(vertices, [-cx,-cy,-cz])
  232. def normalize(v):
  233. """Normalize 3d vector"""
  234. l = math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
  235. v[0] /= l
  236. v[1] /= l
  237. v[2] /= l
  238. # #####################################################
  239. # MTL parser
  240. # #####################################################
  241. def parse_mtl(fname):
  242. """Parse MTL file.
  243. """
  244. materials = {}
  245. for line in fileinput.input(fname):
  246. chunks = line.split()
  247. if len(chunks) > 0:
  248. # Material start
  249. # newmtl identifier
  250. if chunks[0] == "newmtl" and len(chunks) == 2:
  251. identifier = chunks[1]
  252. if not identifier in materials:
  253. materials[identifier] = {}
  254. # Diffuse color
  255. # Kd 1.000 1.000 1.000
  256. if chunks[0] == "Kd" and len(chunks) == 4:
  257. materials[identifier]["col_diffuse"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  258. # Ambient color
  259. # Ka 1.000 1.000 1.000
  260. if chunks[0] == "Ka" and len(chunks) == 4:
  261. materials[identifier]["col_ambient"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  262. # Specular color
  263. # Ks 1.000 1.000 1.000
  264. if chunks[0] == "Ks" and len(chunks) == 4:
  265. materials[identifier]["col_specular"] = [float(chunks[1]), float(chunks[2]), float(chunks[3])]
  266. # Specular coefficient
  267. # Ns 154.000
  268. if chunks[0] == "Ns" and len(chunks) == 2:
  269. materials[identifier]["specular_coef"] = float(chunks[1])
  270. # Transparency
  271. # Tr 0.9 or d 0.9
  272. if (chunks[0] == "Tr" or chunks[0] == "d") and len(chunks) == 2:
  273. if TRANSPARENCY == "invert":
  274. materials[identifier]["transparency"] = 1.0 - float(chunks[1])
  275. else:
  276. materials[identifier]["transparency"] = float(chunks[1])
  277. # Optical density
  278. # Ni 1.0
  279. if chunks[0] == "Ni" and len(chunks) == 2:
  280. materials[identifier]["optical_density"] = float(chunks[1])
  281. # Diffuse texture
  282. # map_Kd texture_diffuse.jpg
  283. if chunks[0] == "map_Kd" and len(chunks) == 2:
  284. materials[identifier]["map_diffuse"] = chunks[1]
  285. # Ambient texture
  286. # map_Ka texture_ambient.jpg
  287. if chunks[0] == "map_Ka" and len(chunks) == 2:
  288. materials[identifier]["map_ambient"] = chunks[1]
  289. # Specular texture
  290. # map_Ks texture_specular.jpg
  291. if chunks[0] == "map_Ks" and len(chunks) == 2:
  292. materials[identifier]["map_specular"] = chunks[1]
  293. # Alpha texture
  294. # map_d texture_alpha.png
  295. if chunks[0] == "map_d" and len(chunks) == 2:
  296. materials[identifier]["map_alpha"] = chunks[1]
  297. # Bump texture
  298. # map_bump texture_bump.jpg or bump texture_bump.jpg
  299. if (chunks[0] == "map_bump" or chunks[0] == "bump") and len(chunks) == 2:
  300. materials[identifier]["map_bump"] = chunks[1]
  301. # Illumination
  302. # illum 2
  303. #
  304. # 0. Color on and Ambient off
  305. # 1. Color on and Ambient on
  306. # 2. Highlight on
  307. # 3. Reflection on and Ray trace on
  308. # 4. Transparency: Glass on, Reflection: Ray trace on
  309. # 5. Reflection: Fresnel on and Ray trace on
  310. # 6. Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  311. # 7. Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  312. # 8. Reflection on and Ray trace off
  313. # 9. Transparency: Glass on, Reflection: Ray trace off
  314. # 10. Casts shadows onto invisible surfaces
  315. if chunks[0] == "illum" and len(chunks) == 2:
  316. materials[identifier]["illumination"] = int(chunks[1])
  317. return materials
  318. # #####################################################
  319. # OBJ parser
  320. # #####################################################
  321. def parse_vertex(text):
  322. """Parse text chunk specifying single vertex.
  323. Possible formats:
  324. vertex index
  325. vertex index / texture index
  326. vertex index / texture index / normal index
  327. vertex index / / normal index
  328. """
  329. v = 0
  330. t = 0
  331. n = 0
  332. chunks = text.split("/")
  333. v = int(chunks[0])
  334. if len(chunks) > 1:
  335. if chunks[1]:
  336. t = int(chunks[1])
  337. if len(chunks) > 2:
  338. if chunks[2]:
  339. n = int(chunks[2])
  340. return { 'v':v, 't':t, 'n':n }
  341. def parse_obj(fname):
  342. """Parse OBJ file.
  343. """
  344. vertices = []
  345. normals = []
  346. uvs = []
  347. faces = []
  348. materials = {}
  349. mcounter = 0
  350. mcurrent = 0
  351. mtllib = ""
  352. # current face state
  353. group = 0
  354. object = 0
  355. smooth = 0
  356. for line in fileinput.input(fname):
  357. chunks = line.split()
  358. if len(chunks) > 0:
  359. # Vertices as (x,y,z) coordinates
  360. # v 0.123 0.234 0.345
  361. if chunks[0] == "v" and len(chunks) == 4:
  362. x = float(chunks[1])
  363. y = float(chunks[2])
  364. z = float(chunks[3])
  365. vertices.append([x,y,z])
  366. # Normals in (x,y,z) form; normals might not be unit
  367. # vn 0.707 0.000 0.707
  368. if chunks[0] == "vn" and len(chunks) == 4:
  369. x = float(chunks[1])
  370. y = float(chunks[2])
  371. z = float(chunks[3])
  372. normals.append([x,y,z])
  373. # Texture coordinates in (u,v[,w]) coordinates, w is optional
  374. # vt 0.500 -1.352 [0.234]
  375. if chunks[0] == "vt" and len(chunks) >= 3:
  376. u = float(chunks[1])
  377. v = float(chunks[2])
  378. w = 0
  379. if len(chunks)>3:
  380. w = float(chunks[3])
  381. uvs.append([u,v,w])
  382. # Face
  383. if chunks[0] == "f" and len(chunks) >= 4:
  384. vertex_index = []
  385. uv_index = []
  386. normal_index = []
  387. for v in chunks[1:]:
  388. vertex = parse_vertex(v)
  389. if vertex['v']:
  390. vertex_index.append(vertex['v'])
  391. if vertex['t']:
  392. uv_index.append(vertex['t'])
  393. if vertex['n']:
  394. normal_index.append(vertex['n'])
  395. faces.append({
  396. 'vertex':vertex_index,
  397. 'uv':uv_index,
  398. 'normal':normal_index,
  399. 'material':mcurrent,
  400. 'group':group,
  401. 'object':object,
  402. 'smooth':smooth,
  403. })
  404. # Group
  405. if chunks[0] == "g" and len(chunks) == 2:
  406. group = chunks[1]
  407. # Object
  408. if chunks[0] == "o" and len(chunks) == 2:
  409. object = chunks[1]
  410. # Materials definition
  411. if chunks[0] == "mtllib" and len(chunks) == 2:
  412. mtllib = chunks[1]
  413. # Material
  414. if chunks[0] == "usemtl" and len(chunks) == 2:
  415. material = chunks[1]
  416. if not material in materials:
  417. mcurrent = mcounter
  418. materials[material] = mcounter
  419. mcounter += 1
  420. else:
  421. mcurrent = materials[material]
  422. # Smooth shading
  423. if chunks[0] == "s" and len(chunks) == 2:
  424. smooth = chunks[1]
  425. return faces, vertices, uvs, normals, materials, mtllib
  426. # #####################################################
  427. # Generator
  428. # #####################################################
  429. def generate_vertex(v):
  430. return TEMPLATE_VERTEX % (v[0], v[1], v[2])
  431. def generate_triangle(f):
  432. v = f['vertex']
  433. return TEMPLATE_TRI % (v[0]-1, v[1]-1, v[2]-1,
  434. f['material'])
  435. def generate_triangle_uv(f):
  436. v = f['vertex']
  437. uv = f['uv']
  438. return TEMPLATE_TRI_UV % (v[0]-1, v[1]-1, v[2]-1,
  439. f['material'],
  440. uv[0]-1, uv[1]-1, uv[2]-1)
  441. def generate_triangle_n(f):
  442. v = f['vertex']
  443. n = f['normal']
  444. return TEMPLATE_TRI_N % (v[0]-1, v[1]-1, v[2]-1,
  445. f['material'],
  446. n[0]-1, n[1]-1, n[2]-1)
  447. def generate_triangle_n_uv(f):
  448. v = f['vertex']
  449. n = f['normal']
  450. uv = f['uv']
  451. return TEMPLATE_TRI_N_UV % (v[0]-1, v[1]-1, v[2]-1,
  452. f['material'],
  453. n[0]-1, n[1]-1, n[2]-1,
  454. uv[0]-1, uv[1]-1, uv[2]-1)
  455. def generate_quad(f):
  456. vi = f['vertex']
  457. return TEMPLATE_QUAD % (vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  458. f['material'])
  459. def generate_quad_uv(f):
  460. v = f['vertex']
  461. uv = f['uv']
  462. return TEMPLATE_QUAD_UV % (v[0]-1, v[1]-1, v[2]-1, v[3]-1,
  463. f['material'],
  464. uv[0]-1, uv[1]-1, uv[2]-1, uv[3]-1)
  465. def generate_quad_n(f):
  466. v = f['vertex']
  467. n = f['normal']
  468. return TEMPLATE_QUAD_N % (v[0]-1, v[1]-1, v[2]-1, v[3]-1,
  469. f['material'],
  470. n[0]-1, n[1]-1, n[2]-1, n[3]-1)
  471. def generate_quad_n_uv(f):
  472. v = f['vertex']
  473. n = f['normal']
  474. uv = f['uv']
  475. return TEMPLATE_QUAD_N_UV % (v[0]-1, v[1]-1, v[2]-1, v[3]-1,
  476. f['material'],
  477. n[0]-1, n[1]-1, n[2]-1, n[3]-1,
  478. uv[0]-1, uv[1]-1, uv[2]-1, uv[3]-1)
  479. def generate_normal(n):
  480. return TEMPLATE_N % (n[0], n[1], n[2])
  481. def generate_uv(uv):
  482. return TEMPLATE_UV % (uv[0], 1.0 - uv[1])
  483. # #####################################################
  484. # Materials
  485. # #####################################################
  486. def generate_color(i):
  487. """Generate hex color corresponding to integer.
  488. Colors should have well defined ordering.
  489. First N colors are hardcoded, then colors are random
  490. (must seed random number generator with deterministic value
  491. before getting colors).
  492. """
  493. if i < len(COLORS):
  494. return "0x%06x" % COLORS[i]
  495. else:
  496. return "0x%06x" % int(0xffffff * random.random())
  497. def value2string(v):
  498. if type(v)==str and v[0:2] != "0x":
  499. return '"%s"' % v
  500. return str(v)
  501. def generate_materials(mtl, materials):
  502. """Generate JS array of materials objects
  503. JS material objects are basically prettified one-to-one
  504. mappings of MTL properties in JSON format.
  505. """
  506. mtl_array = []
  507. for m in mtl:
  508. index = materials[m]
  509. # add debug information
  510. # materials should be sorted according to how
  511. # they appeared in OBJ file (for the first time)
  512. # this index is identifier used in face definitions
  513. mtl[m]['a_dbg_name'] = m
  514. mtl[m]['a_dbg_index'] = index
  515. mtl[m]['a_dbg_color'] = generate_color(index)
  516. mtl_raw = ",\n".join(['\t"%s" : %s' % (n, value2string(v)) for n,v in sorted(mtl[m].items())])
  517. mtl_string = "\t{\n%s\n\t}" % mtl_raw
  518. mtl_array.append([index, mtl_string])
  519. return ",\n\n".join([m for i,m in sorted(mtl_array)])
  520. def generate_mtl(materials):
  521. """Generate dummy materials (if there is no MTL file).
  522. """
  523. mtl = {}
  524. for m in materials:
  525. index = materials[m]
  526. mtl[m] = {
  527. 'a_dbg_name': m,
  528. 'a_dbg_index': index,
  529. 'a_dbg_color': generate_color(index)
  530. }
  531. return mtl
  532. def generate_materials_string(materials, mtllib):
  533. """Generate final materials string.
  534. """
  535. random.seed(42) # to get well defined color order for materials
  536. # default materials with debug colors for when
  537. # there is no specified MTL / MTL loading failed,
  538. # or if there were no materials / null materials
  539. if not materials:
  540. materials = { 'default':0 }
  541. mtl = generate_mtl(materials)
  542. if mtllib:
  543. # create full pathname for MTL (included from OBJ)
  544. path = os.path.dirname(infile)
  545. fname = os.path.join(path, mtllib)
  546. if file_exists(fname):
  547. # override default materials with real ones from MTL
  548. # (where they exist, otherwise keep defaults)
  549. mtl.update(parse_mtl(fname))
  550. else:
  551. print "Couldn't find [%s]" % fname
  552. return generate_materials(mtl, materials)
  553. # #####################################################
  554. # Faces
  555. # #####################################################
  556. def is_triangle_flat(f):
  557. return len(f['vertex'])==3 and not (f["normal"] and SHADING == "smooth") and not f['uv']
  558. def is_triangle_flat_uv(f):
  559. return len(f['vertex'])==3 and not (f["normal"] and SHADING == "smooth") and len(f['uv'])==3
  560. def is_triangle_smooth(f):
  561. return len(f['vertex'])==3 and f["normal"] and SHADING == "smooth" and not f['uv']
  562. def is_triangle_smooth_uv(f):
  563. return len(f['vertex'])==3 and f["normal"] and SHADING == "smooth" and len(f['uv'])==3
  564. def is_quad_flat(f):
  565. return len(f['vertex'])==4 and not (f["normal"] and SHADING == "smooth") and not f['uv']
  566. def is_quad_flat_uv(f):
  567. return len(f['vertex'])==4 and not (f["normal"] and SHADING == "smooth") and len(f['uv'])==4
  568. def is_quad_smooth(f):
  569. return len(f['vertex'])==4 and f["normal"] and SHADING == "smooth" and not f['uv']
  570. def is_quad_smooth_uv(f):
  571. return len(f['vertex'])==4 and f["normal"] and SHADING == "smooth" and len(f['uv'])==4
  572. def sort_faces(faces):
  573. data = {
  574. 'triangles_flat': [],
  575. 'triangles_flat_uv': [],
  576. 'triangles_smooth': [],
  577. 'triangles_smooth_uv': [],
  578. 'quads_flat': [],
  579. 'quads_flat_uv': [],
  580. 'quads_smooth': [],
  581. 'quads_smooth_uv': []
  582. }
  583. for f in faces:
  584. if is_triangle_flat(f):
  585. data['triangles_flat'].append(f)
  586. elif is_triangle_flat_uv(f):
  587. data['triangles_flat_uv'].append(f)
  588. elif is_triangle_smooth(f):
  589. data['triangles_smooth'].append(f)
  590. elif is_triangle_smooth_uv(f):
  591. data['triangles_smooth_uv'].append(f)
  592. elif is_quad_flat(f):
  593. data['quads_flat'].append(f)
  594. elif is_quad_flat_uv(f):
  595. data['quads_flat_uv'].append(f)
  596. elif is_quad_smooth(f):
  597. data['quads_smooth'].append(f)
  598. elif is_quad_smooth_uv(f):
  599. data['quads_smooth_uv'].append(f)
  600. return data
  601. # #####################################################
  602. # API - ASCII converter
  603. # #####################################################
  604. def convert_ascii(infile, outfile):
  605. """Convert infile.obj to outfile.js
  606. Here is where everything happens. If you need to automate conversions,
  607. just import this file as Python module and call this method.
  608. """
  609. if not file_exists(infile):
  610. print "Couldn't find [%s]" % infile
  611. return
  612. faces, vertices, uvs, normals, materials, mtllib = parse_obj(infile)
  613. if ALIGN == "center":
  614. center(vertices)
  615. elif ALIGN == "bottom":
  616. bottom(vertices)
  617. elif ALIGN == "top":
  618. top(vertices)
  619. normals_string = ""
  620. if SHADING == "smooth":
  621. normals_string = ",".join(generate_normal(n) for n in normals)
  622. sfaces = sort_faces(faces)
  623. text = TEMPLATE_FILE_ASCII % {
  624. "name" : get_name(outfile),
  625. "vertices" : ",".join(generate_vertex(v) for v in vertices),
  626. "triangles" : ",".join(generate_triangle(f) for f in sfaces['triangles_flat']),
  627. "triangles_n" : ",".join(generate_triangle_n(f) for f in sfaces['triangles_smooth']),
  628. "triangles_uv" : ",".join(generate_triangle_uv(f) for f in sfaces['triangles_flat_uv']),
  629. "triangles_n_uv": ",".join(generate_triangle_n_uv(f) for f in sfaces['triangles_smooth_uv']),
  630. "quads" : ",".join(generate_quad(f) for f in sfaces['quads_flat']),
  631. "quads_n" : ",".join(generate_quad_n(f) for f in sfaces['quads_smooth']),
  632. "quads_uv" : ",".join(generate_quad_uv(f) for f in sfaces['quads_flat_uv']),
  633. "quads_n_uv" : ",".join(generate_quad_n_uv(f) for f in sfaces['quads_smooth_uv']),
  634. "uvs" : ",".join(generate_uv(uv) for uv in uvs),
  635. "normals" : normals_string,
  636. "materials" : generate_materials_string(materials, mtllib),
  637. "fname" : infile,
  638. "nvertex" : len(vertices),
  639. "nface" : len(faces),
  640. "nmaterial" : len(materials)
  641. }
  642. out = open(outfile, "w")
  643. out.write(text)
  644. out.close()
  645. print "%d vertices, %d faces, %d materials" % (len(vertices), len(faces), len(materials))
  646. # #############################################################################
  647. # API - Binary converter
  648. # #############################################################################
  649. def convert_binary(infile, outfile):
  650. """Convert infile.obj to outfile.js + outfile.bin
  651. """
  652. if not file_exists(infile):
  653. print "Couldn't find [%s]" % infile
  654. return
  655. binfile = get_name(outfile) + ".bin"
  656. faces, vertices, uvs, normals, materials, mtllib = parse_obj(infile)
  657. if ALIGN == "center":
  658. center(vertices)
  659. elif ALIGN == "bottom":
  660. bottom(vertices)
  661. elif ALIGN == "top":
  662. top(vertices)
  663. sfaces = sort_faces(faces)
  664. # ###################
  665. # generate JS file
  666. # ###################
  667. text = TEMPLATE_FILE_BIN % {
  668. "name" : get_name(outfile),
  669. "materials" : generate_materials_string(materials, mtllib),
  670. "buffers" : binfile,
  671. "fname" : infile,
  672. "nvertex" : len(vertices),
  673. "nface" : len(faces),
  674. "nmaterial" : len(materials)
  675. }
  676. out = open(outfile, "w")
  677. out.write(text)
  678. out.close()
  679. # ###################
  680. # generate BIN file
  681. # ###################
  682. if SHADING == "smooth":
  683. nnormals = len(normals)
  684. else:
  685. nnormals = 0
  686. buffer = []
  687. # header
  688. # ------
  689. header_bytes = struct.calcsize('<8s')
  690. header_bytes += struct.calcsize('<BBBBBBBB')
  691. header_bytes += struct.calcsize('<IIIIIIIIIII')
  692. # signature
  693. signature = struct.pack('<8s', 'Three.js')
  694. # metadata (all data is little-endian)
  695. vertex_coordinate_bytes = 4
  696. normal_coordinate_bytes = 1
  697. uv_coordinate_bytes = 4
  698. vertex_index_bytes = 4
  699. normal_index_bytes = 4
  700. uv_index_bytes = 4
  701. material_index_bytes = 2
  702. # header_bytes unsigned char 1
  703. # vertex_coordinate_bytes unsigned char 1
  704. # normal_coordinate_bytes unsigned char 1
  705. # uv_coordinate_bytes unsigned char 1
  706. # vertex_index_bytes unsigned char 1
  707. # normal_index_bytes unsigned char 1
  708. # uv_index_bytes unsigned char 1
  709. # material_index_bytes unsigned char 1
  710. bdata = struct.pack('<BBBBBBBB', header_bytes,
  711. vertex_coordinate_bytes,
  712. normal_coordinate_bytes,
  713. uv_coordinate_bytes,
  714. vertex_index_bytes,
  715. normal_index_bytes,
  716. uv_index_bytes,
  717. material_index_bytes)
  718. # nvertices unsigned int 4
  719. # nnormals unsigned int 4
  720. # nuvs unsigned int 4
  721. # ntri_flat unsigned int 4
  722. # ntri_smooth unsigned int 4
  723. # ntri_flat_uv unsigned int 4
  724. # ntri_smooth_uv unsigned int 4
  725. # nquad_flat unsigned int 4
  726. # nquad_smooth unsigned int 4
  727. # nquad_flat_uv unsigned int 4
  728. # nquad_smooth_uv unsigned int 4
  729. ndata = struct.pack('<IIIIIIIIIII', len(vertices),
  730. nnormals,
  731. len(uvs),
  732. len(sfaces['triangles_flat']),
  733. len(sfaces['triangles_smooth']),
  734. len(sfaces['triangles_flat_uv']),
  735. len(sfaces['triangles_smooth_uv']),
  736. len(sfaces['quads_flat']),
  737. len(sfaces['quads_smooth']),
  738. len(sfaces['quads_flat_uv']),
  739. len(sfaces['quads_smooth_uv']))
  740. buffer.append(signature)
  741. buffer.append(bdata)
  742. buffer.append(ndata)
  743. # 1. vertices
  744. # ------------
  745. # x float 4
  746. # y float 4
  747. # z float 4
  748. for v in vertices:
  749. data = struct.pack('<fff', v[0], v[1], v[2])
  750. buffer.append(data)
  751. # 2. normals
  752. # ---------------
  753. # x signed char 1
  754. # y signed char 1
  755. # z signed char 1
  756. if SHADING == "smooth":
  757. for n in normals:
  758. normalize(n)
  759. data = struct.pack('<bbb', math.floor(n[0]*127+0.5),
  760. math.floor(n[1]*127+0.5),
  761. math.floor(n[2]*127+0.5))
  762. buffer.append(data)
  763. # 3. uvs
  764. # -----------
  765. # u float 4
  766. # v float 4
  767. for uv in uvs:
  768. data = struct.pack('<ff', uv[0], 1.0-uv[1])
  769. buffer.append(data)
  770. # 4. flat triangles
  771. # ------------------
  772. # a unsigned int 4
  773. # b unsigned int 4
  774. # c unsigned int 4
  775. # m unsigned short 2
  776. for f in sfaces['triangles_flat']:
  777. vi = f['vertex']
  778. data = struct.pack('<IIIH',
  779. vi[0]-1, vi[1]-1, vi[2]-1,
  780. f['material'])
  781. buffer.append(data)
  782. # 5. smooth triangles
  783. # -------------------
  784. # a unsigned int 4
  785. # b unsigned int 4
  786. # c unsigned int 4
  787. # m unsigned short 2
  788. # na unsigned int 4
  789. # nb unsigned int 4
  790. # nc unsigned int 4
  791. for f in sfaces['triangles_smooth']:
  792. vi = f['vertex']
  793. ni = f['normal']
  794. data = struct.pack('<IIIHIII',
  795. vi[0]-1, vi[1]-1, vi[2]-1,
  796. f['material'],
  797. ni[0]-1, ni[1]-1, ni[2]-1)
  798. buffer.append(data)
  799. # 6. flat triangles uv
  800. # --------------------
  801. # a unsigned int 4
  802. # b unsigned int 4
  803. # c unsigned int 4
  804. # m unsigned short 2
  805. # ua unsigned int 4
  806. # ub unsigned int 4
  807. # uc unsigned int 4
  808. for f in sfaces['triangles_flat_uv']:
  809. vi = f['vertex']
  810. ui = f['uv']
  811. data = struct.pack('<IIIHIII',
  812. vi[0]-1, vi[1]-1, vi[2]-1,
  813. f['material'],
  814. ui[0]-1, ui[1]-1, ui[2]-1)
  815. buffer.append(data)
  816. # 7. smooth triangles uv
  817. # ----------------------
  818. # a unsigned int 4
  819. # b unsigned int 4
  820. # c unsigned int 4
  821. # m unsigned short 2
  822. # na unsigned int 4
  823. # nb unsigned int 4
  824. # nc unsigned int 4
  825. # ua unsigned int 4
  826. # ub unsigned int 4
  827. # uc unsigned int 4
  828. for f in sfaces['triangles_smooth_uv']:
  829. vi = f['vertex']
  830. ni = f['normal']
  831. ui = f['uv']
  832. data = struct.pack('<IIIHIIIIII',
  833. vi[0]-1, vi[1]-1, vi[2]-1,
  834. f['material'],
  835. ni[0]-1, ni[1]-1, ni[2]-1,
  836. ui[0]-1, ui[1]-1, ui[2]-1)
  837. buffer.append(data)
  838. # 8. flat quads
  839. # ------------------
  840. # a unsigned int 4
  841. # b unsigned int 4
  842. # c unsigned int 4
  843. # d unsigned int 4
  844. # m unsigned short 2
  845. for f in sfaces['quads_flat']:
  846. vi = f['vertex']
  847. data = struct.pack('<IIIIH',
  848. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  849. f['material'])
  850. buffer.append(data)
  851. # 9. smooth quads
  852. # -------------------
  853. # a unsigned int 4
  854. # b unsigned int 4
  855. # c unsigned int 4
  856. # d unsigned int 4
  857. # m unsigned short 2
  858. # na unsigned int 4
  859. # nb unsigned int 4
  860. # nc unsigned int 4
  861. # nd unsigned int 4
  862. for f in sfaces['quads_smooth']:
  863. vi = f['vertex']
  864. ni = f['normal']
  865. data = struct.pack('<IIIIHIIII',
  866. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  867. f['material'],
  868. ni[0]-1, ni[1]-1, ni[2]-1, ni[3]-1)
  869. buffer.append(data)
  870. # 10. flat quads uv
  871. # ------------------
  872. # a unsigned int 4
  873. # b unsigned int 4
  874. # c unsigned int 4
  875. # d unsigned int 4
  876. # m unsigned short 2
  877. # ua unsigned int 4
  878. # ub unsigned int 4
  879. # uc unsigned int 4
  880. # ud unsigned int 4
  881. for f in sfaces['quads_flat_uv']:
  882. vi = f['vertex']
  883. ui = f['uv']
  884. data = struct.pack('<IIIIHIIII',
  885. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  886. f['material'],
  887. ui[0]-1, ui[1]-1, ui[2]-1, ui[3]-1)
  888. buffer.append(data)
  889. # 11. smooth quads uv
  890. # -------------------
  891. # a unsigned int 4
  892. # b unsigned int 4
  893. # c unsigned int 4
  894. # d unsigned int 4
  895. # m unsigned short 2
  896. # na unsigned int 4
  897. # nb unsigned int 4
  898. # nc unsigned int 4
  899. # nd unsigned int 4
  900. # ua unsigned int 4
  901. # ub unsigned int 4
  902. # uc unsigned int 4
  903. # ud unsigned int 4
  904. for f in sfaces['quads_smooth_uv']:
  905. vi = f['vertex']
  906. ni = f['normal']
  907. ui = f['uv']
  908. data = struct.pack('<IIIIHIIIIIIII',
  909. vi[0]-1, vi[1]-1, vi[2]-1, vi[3]-1,
  910. f['material'],
  911. ni[0]-1, ni[1]-1, ni[2]-1, ni[3]-1,
  912. ui[0]-1, ui[1]-1, ui[2]-1, ui[3]-1)
  913. buffer.append(data)
  914. path = os.path.dirname(outfile)
  915. fname = os.path.join(path, binfile)
  916. out = open(fname, "wb")
  917. out.write("".join(buffer))
  918. out.close()
  919. # #############################################################################
  920. # Helpers
  921. # #############################################################################
  922. def usage():
  923. print "Usage: %s -i filename.obj -o filename.js [-a center|top|bottom] [-s flat|smooth] [-t binary|ascii] [-d invert|normal]" % os.path.basename(sys.argv[0])
  924. # #####################################################
  925. # Main
  926. # #####################################################
  927. if __name__ == "__main__":
  928. # get parameters from the command line
  929. try:
  930. opts, args = getopt.getopt(sys.argv[1:], "hi:o:a:s:t:d:", ["help", "input=", "output=", "align=", "shading=", "type=", "dissolve="])
  931. except getopt.GetoptError:
  932. usage()
  933. sys.exit(2)
  934. infile = outfile = ""
  935. for o, a in opts:
  936. if o in ("-h", "--help"):
  937. usage()
  938. sys.exit()
  939. elif o in ("-i", "--input"):
  940. infile = a
  941. elif o in ("-o", "--output"):
  942. outfile = a
  943. elif o in ("-a", "--align"):
  944. if a in ("top", "bottom", "center"):
  945. ALIGN = a
  946. elif o in ("-s", "--shading"):
  947. if a in ("flat", "smooth"):
  948. SHADING = a
  949. elif o in ("-t", "--type"):
  950. if a in ("binary", "ascii"):
  951. TYPE = a
  952. elif o in ("-d", "--dissolve"):
  953. if a in ("normal", "invert"):
  954. TRANSPARENCY = a
  955. if infile == "" or outfile == "":
  956. usage()
  957. sys.exit(2)
  958. print "Converting [%s] into [%s] ..." % (infile, outfile)
  959. if TYPE == "ascii":
  960. convert_ascii(infile, outfile)
  961. elif TYPE == "binary":
  962. convert_binary(infile, outfile)