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