convert_obj_three.py 47 KB

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