convert_obj_three.py 46 KB

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