forked from Unreality3D/Unreality3D
-
Notifications
You must be signed in to change notification settings - Fork 0
/
io_export_ogreDotScene.py
7478 lines (6535 loc) · 299 KB
/
io_export_ogreDotScene.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2010 Brett Hartshorn
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
VERSION = '0.5.9'
'''
CHANGELOG
0.5.9
* apply patch from Thomas for Blender 2.6x support
0.5.8
* Clean all names that will be used as filenames on disk. Adjust all places
that use these names for refs instead of ob.name/ob.data.name. Replaced chars
are \, /, :, *, ?, ", <, >, | and spaces. Tested on work with ogre
material, mesh and skeleton writing/refs inside the files and txml refs.
Shows warning at final report if we had to resort to the renaming so user
can possibly rename the object.
* Added silent auto update checks if blender2ogre was installed using
the .exe installer. This will keep people up to date when new versions are out.
* Fix tracker issue 48: Needs to check if outputting to /tmp or
~/.wine/drive_c/tmp on Linux. Thanks to vax456 for providing the patch,
added him to contributors. Preview mesh's are now placed under /tmp
on Linux systems if the OgreMeshy executable ends with .exe
* Fix tracker issue 46: add operationtype to <submesh>
* Implement a modal dialog that reports if material names have invalid
characters and cant be saved on disk. This small popup will show until
user presses left or right mouse (anywhere).
* Fix tracker issue 44: XML Attributes not properly escaped in .scene file
* Implemented reading OgreXmlConverter path from windows registry.
The .exe installer will ship with certain tools so we can stop guessing
and making the user install tools separately and setting up paths.
* Fix bug that .mesh files were not generated while doing a .txml export.
This was result of the late 2.63 mods that forgot to update object
facecount before determining if mesh should be exported.
* Fix bug that changed settings in the export dialog were forgotten when you
re-exported without closing blender. Now settings should persist always
from the last export. They are also stored to disk so the same settings
are in use when if you restart Blender.
* Fix bug that once you did a export, the next time the export location was
forgotten. Now on sequential exports, the last export path is remembered in
the export dialog.
* Remove all local:// from asset refs and make them relative in .txml export.
Having relative refs is the best for local preview and importing the txml
to existing scenes.
* Make .material generate what version of this plugins was used to generate
the material file. Will be helpful in production to catch things.
Added pretty printing line endings so the raw .material data is easier to read.
* Improve console logging for the export stages. Run Blender from
cmd prompt to see this information.
* Clean/fix documentation in code for future development
* Add todo to code for future development
* Restructure/move code for easier readability
* Remove extra white spaces and convert tabs to space
0.5.7
* Update to Blender 2.6.3.
* Fixed xz-y Skeleton rotation (again)
* Added additional Keyframe at the end of each animation to prevent
ogre from interpolating back to the start
* Added option to ignore non-deformable bones
* Added option to export nla-strips independently from each other
TODO
* Remove this section and integrate below with code :)
* Fix terrain collision offset bug
* Add realtime transform (rotation is missing)
* Fix camera rotated -90 ogre-dot-scene
* Set description field for all pyRNA
'''
bl_info = {
"name": "OGRE Exporter (.scene, .mesh, .skeleton) and RealXtend (.txml)",
"author": "Brett, S.Rombauts, F00bar, Waruck, Mind Calamity, Mr.Magne, Jonne Nauha, vax456",
"version": (0, 5, 8),
"blender": (2, 6, 3),
"location": "File > Export...",
"description": "Export to Ogre xml and binary formats",
"wiki_url": "http://code.google.com/p/blender2ogre/w/list",
"tracker_url": "http://code.google.com/p/blender2ogre/issues/list",
"category": "Import-Export"
}
## Public API
## Search for "Public API" to find more
UI_CLASSES = []
def UI(cls):
''' Toggles the Ogre interface panels '''
if cls not in UI_CLASSES:
UI_CLASSES.append(cls)
return cls
def hide_user_interface():
for cls in UI_CLASSES:
bpy.utils.unregister_class( cls )
def uid(ob):
if ob.uid == 0:
high = 0
multires = 0
for o in bpy.data.objects:
if o.uid > high: high = o.uid
if o.use_multires_lod: multires += 1
high += 1 + (multires*10)
if high < 100: high = 100 # start at 100
ob.uid = high
return ob.uid
## Imports
import os, sys, time, array, ctypes, math
try:
# Inside blender
import bpy, mathutils
from bpy.props import *
except ImportError:
# If we end up here we are outside blender (compile optional C module)
assert __name__ == '__main__'
print('Trying to compile Rpython C-library')
assert sys.version_info.major == 2 # rpython only works from Python2
print('...searching for rpythonic...')
sys.path.append('../rpythonic')
import rpythonic
rpythonic.set_pypy_root( '../pypy' )
import pypy.rpython.lltypesystem.rffi as rffi
from pypy.rlib import streamio
rpy = rpythonic.RPython( 'blender2ogre' )
@rpy.bind(
path=str,
facesAddr=int,
facesSmoothAddr=int,
facesMatAddr=int,
vertsPosAddr=int,
vertsNorAddr=int,
numFaces=int,
numVerts=int,
materialNames=str, # [str] is too tricky to convert py-list to rpy-list
)
def dotmesh( path, facesAddr, facesSmoothAddr, facesMatAddr, vertsPosAddr, vertsNorAddr, numFaces, numVerts, materialNames ):
print('PATH----------------', path)
materials = []
for matname in materialNames.split(';'):
print( 'Material Name: %s' %matname )
materials.append( matname )
file = streamio.open_file_as_stream( path, 'w')
faces = rffi.cast( rffi.UINTP, facesAddr ) # face vertex indices
facesSmooth = rffi.cast( rffi.CCHARP, facesSmoothAddr )
facesMat = rffi.cast( rffi.USHORTP, facesMatAddr )
vertsPos = rffi.cast( rffi.FLOATP, vertsPosAddr )
vertsNor = rffi.cast( rffi.FLOATP, vertsNorAddr )
VB = [
'<sharedgeometry>',
'<vertexbuffer positions="true" normals="true">'
]
fastlookup = {}
ogre_vert_index = 0
triangles = []
for fidx in range( numFaces ):
smooth = ord( facesSmooth[ fidx ] ) # ctypes.c_bool > char > int
matidx = facesMat[ fidx ]
i = fidx*4
ai = faces[ i ]; bi = faces[ i+1 ]
ci = faces[ i+2 ]; di = faces[ i+3 ]
triangle = []
for J in [ai, bi, ci]:
i = J*3
x = rffi.cast( rffi.DOUBLE, vertsPos[ i ] )
y = rffi.cast( rffi.DOUBLE, vertsPos[ i+1 ] )
z = rffi.cast( rffi.DOUBLE, vertsPos[ i+2 ] )
pos = (x,y,z)
#if smooth:
x = rffi.cast( rffi.DOUBLE, vertsNor[ i ] )
y = rffi.cast( rffi.DOUBLE, vertsNor[ i+1 ] )
z = rffi.cast( rffi.DOUBLE, vertsNor[ i+2 ] )
nor = (x,y,z)
SIG = (pos,nor)#, matidx)
skip = False
if J in fastlookup:
for otherSIG in fastlookup[ J ]:
if SIG == otherSIG:
triangle.append( fastlookup[J][otherSIG] )
skip = True
break
if not skip:
triangle.append( ogre_vert_index )
print("%4i -> ogre %4i" % (J,ogre_vert_index))
fastlookup[ J ][ SIG ] = ogre_vert_index
else:
triangle.append( ogre_vert_index )
print("%4i -> ogre %4i" % (J,ogre_vert_index))
fastlookup[ J ] = { SIG : ogre_vert_index }
if skip: continue
xml = [
'<vertex>',
'<position x="%s" y="%s" z="%s" />' %pos, # funny that tuple is valid here
'<normal x="%s" y="%s" z="%s" />' %nor,
'</vertex>'
]
VB.append( '\n'.join(xml) )
ogre_vert_index += 1
triangles.append( triangle )
VB.append( '</vertexbuffer>' )
VB.append( '</sharedgeometry>' )
file.write( '\n'.join(VB) )
del VB # free memory
SMS = ['<submeshes>']
#for matidx, matname in ...:
SM = [
'<submesh usesharedvertices="true" use32bitindexes="true" material="%s" operationtype="triangle_list">' % 'somemat',
'<faces count="%s">' %'100',
]
for tri in triangles:
#x,y,z = tri # rpython bug, when in a new 'block' need to unpack/repack tuple
#s = '<face v1="%s" v2="%s" v3="%s" />' %(x,y,z)
assert isinstance(tri,tuple) #and len(tri)==3 # this also works
s = '<face v1="%s" v2="%s" v3="%s" />' %tri # but tuple is not valid here
SM.append( s )
SM.append( '</faces>' )
SM.append( '</submesh>' )
file.write( '\n'.join(SM) )
file.close()
rpy.cache(refresh=1)
sys.exit('OK: module compiled and cached')
## More imports now that Blender is imported
import hashlib, getpass, tempfile, configparser, subprocess, pickle
from xml.sax.saxutils import XMLGenerator, quoteattr
class CMesh(object):
def __init__(self, data):
self.numVerts = N = len( data.vertices )
self.numFaces = Nfaces = len(data.tessfaces)
self.vertex_positions = (ctypes.c_float * (N * 3))()
data.vertices.foreach_get( 'co', self.vertex_positions )
v = self.vertex_positions
self.vertex_normals = (ctypes.c_float * (N * 3))()
data.vertices.foreach_get( 'normal', self.vertex_normals )
self.faces = (ctypes.c_uint * (Nfaces * 4))()
data.tessfaces.foreach_get( 'vertices_raw', self.faces )
self.faces_normals = (ctypes.c_float * (Nfaces * 3))()
data.tessfaces.foreach_get( 'normal', self.faces_normals )
self.faces_smooth = (ctypes.c_bool * Nfaces)()
data.tessfaces.foreach_get( 'use_smooth', self.faces_smooth )
self.faces_material_index = (ctypes.c_ushort * Nfaces)()
data.tessfaces.foreach_get( 'material_index', self.faces_material_index )
self.vertex_colors = []
if len( data.vertex_colors ):
vc = data.vertex_colors[0]
n = len(vc.data)
# no colors_raw !!?
self.vcolors1 = (ctypes.c_float * (n * 3))() # face1
vc.data.foreach_get( 'color1', self.vcolors1 )
self.vertex_colors.append( self.vcolors1 )
self.vcolors2 = (ctypes.c_float * (n * 3))() # face2
vc.data.foreach_get( 'color2', self.vcolors2 )
self.vertex_colors.append( self.vcolors2 )
self.vcolors3 = (ctypes.c_float * (n * 3))() # face3
vc.data.foreach_get( 'color3', self.vcolors3 )
self.vertex_colors.append( self.vcolors3 )
self.vcolors4 = (ctypes.c_float * (n * 3))() # face4
vc.data.foreach_get( 'color4', self.vcolors4 )
self.vertex_colors.append( self.vcolors4 )
self.uv_textures = []
if data.uv_textures.active:
for layer in data.uv_textures:
n = len(layer.data) * 8
a = (ctypes.c_float * n)()
layer.data.foreach_get( 'uv_raw', a ) # 4 faces
self.uv_textures.append( a )
def save( blenderobject, path ):
cmesh = Mesh( blenderobject.data )
start = time.time()
dotmesh(
path,
ctypes.addressof( cmesh.faces ),
ctypes.addressof( cmesh.faces_smooth ),
ctypes.addressof( cmesh.faces_material_index ),
ctypes.addressof( cmesh.vertex_positions ),
ctypes.addressof( cmesh.vertex_normals ),
cmesh.numFaces,
cmesh.numVerts,
)
print('Mesh dumped in %s seconds' % (time.time()-start))
## Make sure we can import from same directory
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
if SCRIPT_DIR not in sys.path:
sys.path.append( SCRIPT_DIR )
## Avatar
bpy.types.Object.use_avatar = BoolProperty(
name='enable avatar',
description='enables EC_Avatar',
default=False)
bpy.types.Object.avatar_reference = StringProperty(
name='avatar reference',
description='sets avatar reference URL',
maxlen=128,
default='')
BoolProperty( name='enable avatar', description='enables EC_Avatar', default=False) # todo: is this used?
# Tundra IDs
bpy.types.Object.uid = IntProperty(
name="unique ID",
description="unique ID for Tundra",
default=0, min=0, max=2**14)
# Rendering
bpy.types.Object.use_draw_distance = BoolProperty(
name='enable draw distance',
description='use LOD draw distance',
default=False)
bpy.types.Object.draw_distance = FloatProperty(
name='draw distance',
description='distance at which to begin drawing object',
default=0.0, min=0.0, max=10000.0)
bpy.types.Object.cast_shadows = BoolProperty(
name='cast shadows',
description='cast shadows',
default=False)
bpy.types.Object.use_multires_lod = BoolProperty(
name='Enable Multires LOD',
description='enables multires LOD',
default=False)
bpy.types.Object.multires_lod_range = FloatProperty(
name='multires LOD range',
description='far distance at which multires is set to base level',
default=30.0, min=0.0, max=10000.0)
## Physics
_physics_modes = [
('NONE', 'NONE', 'no physics'),
('RIGID_BODY', 'RIGID_BODY', 'rigid body'),
('SOFT_BODY', 'SOFT_BODY', 'soft body'),
]
_collision_modes = [
('NONE', 'NONE', 'no collision'),
('PRIMITIVE', 'PRIMITIVE', 'primitive collision type'),
('MESH', 'MESH', 'triangle-mesh or convex-hull collision type'),
('DECIMATED', 'DECIMATED', 'auto-decimated collision type'),
('COMPOUND', 'COMPOUND', 'children primitive compound collision type'),
('TERRAIN', 'TERRAIN', 'terrain (height map) collision type'),
]
bpy.types.Object.physics_mode = EnumProperty(
items = _physics_modes,
name = 'physics mode',
description='physics mode',
default='NONE')
bpy.types.Object.physics_friction = FloatProperty(
name='Simple Friction',
description='physics friction',
default=0.1, min=0.0, max=1.0)
bpy.types.Object.physics_bounce = FloatProperty(
name='Simple Bounce',
description='physics bounce',
default=0.01, min=0.0, max=1.0)
bpy.types.Object.collision_terrain_x_steps = IntProperty(
name="Ogre Terrain: x samples",
description="resolution in X of height map",
default=64, min=4, max=8192)
bpy.types.Object.collision_terrain_y_steps = IntProperty(
name="Ogre Terrain: y samples",
description="resolution in Y of height map",
default=64, min=4, max=8192)
bpy.types.Object.collision_mode = EnumProperty(
items = _collision_modes,
name = 'primary collision mode',
description='collision mode',
default='NONE')
bpy.types.Object.subcollision = BoolProperty(
name="collision compound",
description="member of a collision compound",
default=False)
## Sound
bpy.types.Speaker.play_on_load = BoolProperty(
name='play on load',
default=False)
bpy.types.Speaker.loop = BoolProperty(
name='loop sound',
default=False)
bpy.types.Speaker.use_spatial = BoolProperty(
name='3D spatial sound',
default=True)
## ImageMagick
_IMAGE_FORMATS = [
('NONE','NONE', 'do not convert image'),
('bmp', 'bmp', 'bitmap format'),
('jpg', 'jpg', 'jpeg format'),
('gif', 'gif', 'gif format'),
('png', 'png', 'png format'),
('tga', 'tga', 'targa format'),
('dds', 'dds', 'nvidia dds format'),
]
bpy.types.Image.use_convert_format = BoolProperty(
name='use convert format',
default=False
)
bpy.types.Image.convert_format = EnumProperty(
name='convert to format',
description='converts to image format using imagemagick',
items=_IMAGE_FORMATS,
default='NONE')
bpy.types.Image.jpeg_quality = IntProperty(
name="jpeg quality",
description="quality of jpeg",
default=80, min=0, max=100)
bpy.types.Image.use_color_quantize = BoolProperty(
name='use color quantize',
default=False)
bpy.types.Image.use_color_quantize_dither = BoolProperty(
name='use color quantize dither',
default=True)
bpy.types.Image.color_quantize = IntProperty(
name="color quantize",
description="reduce to N colors (requires ImageMagick)",
default=32, min=2, max=256)
bpy.types.Image.use_resize_half = BoolProperty(
name='resize by 1/2',
default=False)
bpy.types.Image.use_resize_absolute = BoolProperty(
name='force image resize',
default=False)
bpy.types.Image.resize_x = IntProperty(
name='resize X',
description='only if image is larger than defined, use ImageMagick to resize it down',
default=256, min=2, max=4096)
bpy.types.Image.resize_y = IntProperty(
name='resize Y',
description='only if image is larger than defined, use ImageMagick to resize it down',
default=256, min=2, max=4096)
# Materials
bpy.types.Material.ogre_depth_write = BoolProperty(
# Material.ogre_depth_write = AUTO|ON|OFF
name='depth write',
default=True)
bpy.types.Material.ogre_depth_check = BoolProperty(
# If depth-buffer checking is on, whenever a pixel is about to be written to
# the frame buffer the depth buffer is checked to see if the pixel is in front
# of all other pixels written at that point. If not, the pixel is not written.
# If depth checking is off, pixels are written no matter what has been rendered before.
name='depth check',
default=True)
bpy.types.Material.ogre_alpha_to_coverage = BoolProperty(
# Sets whether this pass will use 'alpha to coverage', a way to multisample alpha
# texture edges so they blend more seamlessly with the background. This facility
# is typically only available on cards from around 2006 onwards, but it is safe to
# enable it anyway - Ogre will just ignore it if the hardware does not support it.
# The common use for alpha to coverage is foliage rendering and chain-link fence style textures.
name='multisample alpha edges',
default=False)
bpy.types.Material.ogre_light_scissor = BoolProperty(
# This option is usually only useful if this pass is an additive lighting pass, and is
# at least the second one in the technique. Ie areas which are not affected by the current
# light(s) will never need to be rendered. If there is more than one light being passed to
# the pass, then the scissor is defined to be the rectangle which covers all lights in screen-space.
# Directional lights are ignored since they are infinite. This option does not need to be specified
# if you are using a standard additive shadow mode, i.e. SHADOWTYPE_STENCIL_ADDITIVE or
# SHADOWTYPE_TEXTURE_ADDITIVE, since it is the default behaviour to use a scissor for each additive
# shadow pass. However, if you're not using shadows, or you're using Integrated Texture Shadows
# where passes are specified in a custom manner, then this could be of use to you.
name='light scissor',
default=False)
bpy.types.Material.ogre_light_clip_planes = BoolProperty(
name='light clip planes',
default=False)
bpy.types.Material.ogre_normalise_normals = BoolProperty(
name='normalise normals',
default=False,
description="Scaling objects causes normals to also change magnitude, which can throw off your lighting calculations. By default, the SceneManager detects this and will automatically re-normalise normals for any scaled object, but this has a cost. If you'd prefer to control this manually, call SceneManager::setNormaliseNormalsOnScale(false) and then use this option on materials which are sensitive to normals being resized.")
bpy.types.Material.ogre_lighting = BoolProperty(
# Sets whether or not dynamic lighting is turned on for this pass or not. If lighting is turned off,
# all objects rendered using the pass will be fully lit. This attribute has no effect if a vertex program is used.
name='dynamic lighting',
default=True)
bpy.types.Material.ogre_colour_write = BoolProperty(
# If colour writing is off no visible pixels are written to the screen during this pass. You might think
# this is useless, but if you render with colour writing off, and with very minimal other settings,
# you can use this pass to initialise the depth buffer before subsequently rendering other passes which
# fill in the colour data. This can give you significant performance boosts on some newer cards, especially
# when using complex fragment programs, because if the depth check fails then the fragment program is never run.
name='color-write',
default=True)
bpy.types.Material.use_fixed_pipeline = BoolProperty(
# Fixed pipeline is oldschool
# todo: whats the meaning of this?
name='fixed pipeline',
default=True)
bpy.types.Material.use_material_passes = BoolProperty(
# hidden option - gets turned on by operator
# todo: What is a hidden option, is this needed?
name='use ogre extra material passes (layers)',
default=False)
bpy.types.Material.use_in_ogre_material_pass = BoolProperty(
name='Layer Toggle',
default=True)
bpy.types.Material.use_ogre_advanced_options = BoolProperty(
name='Show Advanced Options',
default=False)
bpy.types.Material.use_ogre_parent_material = BoolProperty(
name='Use Script Inheritance',
default=False)
bpy.types.Material.ogre_parent_material = EnumProperty(
name="Script Inheritence",
description='ogre parent material class', #default='NONE',
items=[])
bpy.types.Material.ogre_polygon_mode = EnumProperty(
name='faces draw type',
description="ogre face draw mode",
items=[ ('solid', 'solid', 'SOLID'),
('wireframe', 'wireframe', 'WIREFRAME'),
('points', 'points', 'POINTS') ],
default='solid')
bpy.types.Material.ogre_shading = EnumProperty(
name='hardware shading',
description="Sets the kind of shading which should be used for representing dynamic lighting for this pass.",
items=[ ('flat', 'flat', 'FLAT'),
('gouraud', 'gouraud', 'GOURAUD'),
('phong', 'phong', 'PHONG') ],
default='gouraud')
bpy.types.Material.ogre_cull_hardware = EnumProperty(
name='hardware culling',
description="If the option 'cull_hardware clockwise' is set, all triangles whose vertices are viewed in clockwise order from the camera will be culled by the hardware.",
items=[ ('clockwise', 'clockwise', 'CLOCKWISE'),
('anticlockwise', 'anticlockwise', 'COUNTER CLOCKWISE'),
('none', 'none', 'NONE') ],
default='clockwise')
bpy.types.Material.ogre_transparent_sorting = EnumProperty(
name='transparent sorting',
description="By default all transparent materials are sorted such that renderables furthest away from the camera are rendered first. This is usually the desired behaviour but in certain cases this depth sorting may be unnecessary and undesirable. If for example it is necessary to ensure the rendering order does not change from one frame to the next. In this case you could set the value to 'off' to prevent sorting.",
items=[ ('on', 'on', 'ON'),
('off', 'off', 'OFF'),
('force', 'force', 'FORCE ON') ],
default='on')
bpy.types.Material.ogre_illumination_stage = EnumProperty(
name='illumination stage',
description='When using an additive lighting mode (SHADOWTYPE_STENCIL_ADDITIVE or SHADOWTYPE_TEXTURE_ADDITIVE), the scene is rendered in 3 discrete stages, ambient (or pre-lighting), per-light (once per light, with shadowing) and decal (or post-lighting). Usually OGRE figures out how to categorise your passes automatically, but there are some effects you cannot achieve without manually controlling the illumination.',
items=[ ('', '', 'autodetect'),
('ambient', 'ambient', 'ambient'),
('per_light', 'per_light', 'lights'),
('decal', 'decal', 'decal') ],
default=''
)
_ogre_depth_func = [
('less_equal', 'less_equal', '<='),
('less', 'less', '<'),
('equal', 'equal', '=='),
('not_equal', 'not_equal', '!='),
('greater_equal', 'greater_equal', '>='),
('greater', 'greater', '>'),
('always_fail', 'always_fail', 'false'),
('always_pass', 'always_pass', 'true'),
]
bpy.types.Material.ogre_depth_func = EnumProperty(
items=_ogre_depth_func,
name='depth buffer function',
description='If depth checking is enabled (see depth_check) a comparison occurs between the depth value of the pixel to be written and the current contents of the buffer. This comparison is normally less_equal, i.e. the pixel is written if it is closer (or at the same distance) than the current contents',
default='less_equal')
_ogre_scene_blend_ops = [
('add', 'add', 'DEFAULT'),
('subtract', 'subtract', 'SUBTRACT'),
('reverse_subtract', 'reverse_subtract', 'REVERSE SUBTRACT'),
('min', 'min', 'MIN'),
('max', 'max', 'MAX'),
]
bpy.types.Material.ogre_scene_blend_op = EnumProperty(
items=_ogre_scene_blend_ops,
name='scene blending operation',
description='This directive changes the operation which is applied between the two components of the scene blending equation',
default='add')
_ogre_scene_blend_types = [
('one zero', 'one zero', 'DEFAULT'),
('alpha_blend', 'alpha_blend', "The alpha value of the rendering output is used as a mask. Equivalent to 'scene_blend src_alpha one_minus_src_alpha'"),
('add', 'add', "The colour of the rendering output is added to the scene. Good for explosions, flares, lights, ghosts etc. Equivalent to 'scene_blend one one'."),
('modulate', 'modulate', "The colour of the rendering output is multiplied with the scene contents. Generally colours and darkens the scene, good for smoked glass, semi-transparent objects etc. Equivalent to 'scene_blend dest_colour zero'"),
('colour_blend', 'colour_blend', 'Colour the scene based on the brightness of the input colours, but dont darken. Equivalent to "scene_blend src_colour one_minus_src_colour"'),
]
for mode in 'dest_colour src_colour one_minus_dest_colour dest_alpha src_alpha one_minus_dest_alpha one_minus_src_alpha'.split():
_ogre_scene_blend_types.append( ('one %s'%mode, 'one %s'%mode, '') )
del mode
bpy.types.Material.ogre_scene_blend = EnumProperty(
items=_ogre_scene_blend_types,
name='scene blend',
description='blending operation of material to scene',
default='one zero')
## FAQ
_faq_ = '''
Q: I have hundres of objects, is there a way i can merge them on export only?
A: Yes, just add them to a group named starting with "merge", or link the group.
Q: Can i use subsurf or multi-res on a mesh with an armature?
A: Yes.
Q: Can i use subsurf or multi-res on a mesh with shape animation?
A: No.
Q: I don't see any objects when i export?
A: You must select the objects you wish to export.
Q: I don't see my animations when exported?
A: Make sure you created an NLA strip on the armature.
Q: Do i need to bake my IK and other constraints into FK on my armature before export?
A: No.
'''
## DOCUMENTATION
''' todo: Update the nonsense C:\Tundra2 paths from defaul config and fix this doc.
Additionally point to some doc how to build opengl only version on windows if that really is needed and
remove the old Tundra 7z link. '''
_doc_installing_ = '''
Installing:
Installing the Addon:
You can simply copy io_export_ogreDotScene.py to your blender installation under blender/2.6x/scripts/addons/
and enable it in the user-prefs interface (CTRL+ALT+U)
Or you can use blenders interface, under user-prefs, click addons, and click 'install-addon'
(its a good idea to delete the old version first)
Required:
1. Blender 2.63
2. Install Ogre Command Line tools to the default path: C:\\OgreCommandLineTools from http://www.ogre3d.org/download/tools
* These tools are used to create the binary Mesh from the .xml mesh generated by this plugin.
* Linux users may use above and Wine, or install from source, or install via apt-get install ogre-tools.
Optional:
3. Install NVIDIA DDS Legacy Utilities - Install them to default path.
* http://developer.nvidia.com/object/dds_utilities_legacy.html
* Linux users will need to use Wine.
4. Install Image Magick
* http://www.imagemagick.org
5. Copy OgreMeshy to C:\\OgreMeshy
* If your using 64bit Windows, you may need to download a 64bit OgreMeshy
* Linux copy to your home folder.
6. realXtend Tundra
* For latest Tundra releases see http://code.google.com/p/realxtend-naali/downloads/list
- You may need to tweak the config to tell your Tundra path or install to C:\Tundra2
* Old OpenGL only build can be found from http://blender2ogre.googlecode.com/files/realxtend-Tundra-2.1.2-OpenGL.7z
- Windows: extract to C:\Tundra2
- Linux: extract to ~/Tundra2
'''
## Options
AXIS_MODES = [
('xyz', 'xyz', 'no swapping'),
('xz-y', 'xz-y', 'ogre standard'),
('-xzy', '-xzy', 'non standard'),
]
def swap(vec):
if CONFIG['SWAP_AXIS'] == 'xyz': return vec
elif CONFIG['SWAP_AXIS'] == 'xzy':
if len(vec) == 3: return mathutils.Vector( [vec.x, vec.z, vec.y] )
elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, vec.x, vec.z, vec.y] )
elif CONFIG['SWAP_AXIS'] == '-xzy':
if len(vec) == 3: return mathutils.Vector( [-vec.x, vec.z, vec.y] )
elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, -vec.x, vec.z, vec.y] )
elif CONFIG['SWAP_AXIS'] == 'xz-y':
if len(vec) == 3: return mathutils.Vector( [vec.x, vec.z, -vec.y] )
elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, vec.x, vec.z, -vec.y] )
else:
print( 'unknown swap axis mode', CONFIG['SWAP_AXIS'] )
assert 0
## Config
CONFIG_PATH = bpy.utils.user_resource('CONFIG', path='scripts', create=True)
CONFIG_FILENAME = 'blender2ogre.pickle'
CONFIG_FILEPATH = os.path.join(CONFIG_PATH, CONFIG_FILENAME)
_CONFIG_DEFAULTS_ALL = {
'TUNDRA_STREAMING' : True,
'COPY_SHADER_PROGRAMS' : True,
'MAX_TEXTURE_SIZE' : 4096,
'SWAP_AXIS' : 'xz-y', # ogre standard
'ONLY_ANIMATED_BONES' : False,
'ONLY_DEFORMABLE_BONES' : False,
'INDEPENDENT_ANIM' : False,
'FORCE_IMAGE_FORMAT' : 'NONE',
'TOUCH_TEXTURES' : True,
'SEP_MATS' : True,
'SCENE' : True,
'SELONLY' : True,
'FORCE_CAMERA' : True,
'FORCE_LAMPS' : True,
'MESH' : True,
'MESH_OVERWRITE' : True,
'ARM_ANIM' : True,
'SHAPE_ANIM' : True,
'ARRAY' : True,
'MATERIALS' : True,
'DDS_MIPS' : True,
'TRIM_BONE_WEIGHTS' : 0.01,
'lodLevels' : 0,
'lodDistance' : 300,
'lodPercent' : 40,
'nuextremityPoints' : 0,
'generateEdgeLists' : False,
'generateTangents' : True, # this is now safe - ignored if mesh is missing UVs
'tangentSemantic' : 'uvw',
'tangentUseParity' : 4,
'tangentSplitMirrored' : False,
'tangentSplitRotated' : False,
'reorganiseBuffers' : True,
'optimiseAnimations' : True,
}
_CONFIG_TAGS_ = 'OGRETOOLS_XML_CONVERTER OGRETOOLS_MESH_MAGICK TUNDRA_ROOT OGRE_MESHY IMAGE_MAGICK_CONVERT NVCOMPRESS NVIDIATOOLS_EXE USER_MATERIALS SHADER_PROGRAMS TUNDRA_STREAMING'.split()
''' todo: Change pretty much all of these windows ones. Make a smarter way of detecting
Ogre tools and Tundra from various default folders. Also consider making a installer that
ships Ogre cmd line tools to ease the setup steps for end users. '''
_CONFIG_DEFAULTS_WINDOWS = {
'OGRETOOLS_XML_CONVERTER' : 'C:\\OgreCommandLineTools\\OgreXmlConverter.exe',
'OGRETOOLS_MESH_MAGICK' : 'C:\\OgreCommandLineTools\\MeshMagick.exe',
'TUNDRA_ROOT' : 'C:\\Tundra2',
'OGRE_MESHY' : 'C:\\OgreMeshy\\Ogre Meshy.exe',
'IMAGE_MAGICK_CONVERT' : 'C:\\Program Files\\ImageMagick\\convert.exe',
'NVIDIATOOLS_EXE' : 'C:\\Program Files\\NVIDIA Corporation\\DDS Utilities\\nvdxt.exe',
'USER_MATERIALS' : 'C:\\Tundra2\\media\\materials',
'SHADER_PROGRAMS' : 'C:\\Tundra2\\media\\materials\\programs',
'NVCOMPRESS' : 'C:\\nvcompress.exe'
}
_CONFIG_DEFAULTS_UNIX = {
'OGRETOOLS_XML_CONVERTER' : '/usr/local/bin/OgreXMLConverter', # source build is better
'OGRETOOLS_MESH_MAGICK' : '/usr/local/bin/MeshMagick',
'TUNDRA_ROOT' : '~/Tundra2',
'OGRE_MESHY' : '~/OgreMeshy/Ogre Meshy.exe',
'IMAGE_MAGICK_CONVERT' : '/usr/bin/convert',
'NVIDIATOOLS_EXE' : '~/.wine/drive_c/Program Files/NVIDIA Corporation/DDS Utilities',
'USER_MATERIALS' : '~/Tundra2/media/materials',
'SHADER_PROGRAMS' : '~/Tundra2/media/materials/programs',
#'USER_MATERIALS' : '~/ogre_src_v1-7-3/Samples/Media/materials',
#'SHADER_PROGRAMS' : '~/ogre_src_v1-7-3/Samples/Media/materials/programs',
'NVCOMPRESS' : '/usr/local/bin/nvcompress'
}
# Unix: Replace ~ with absolute home dir path
if sys.platform.startswith('linux') or sys.platform.startswith('darwin') or sys.platform.startswith('freebsd'):
for tag in _CONFIG_DEFAULTS_UNIX:
path = _CONFIG_DEFAULTS_UNIX[ tag ]
if path.startswith('~'):
_CONFIG_DEFAULTS_UNIX[ tag ] = os.path.expanduser( path )
elif tag.startswith('OGRETOOLS') and not os.path.isfile( path ):
_CONFIG_DEFAULTS_UNIX[ tag ] = os.path.join( '/usr/bin', os.path.split( path )[-1] )
del tag
del path
## PUBLIC API continues
CONFIG = {}
def load_config():
global CONFIG
if os.path.isfile( CONFIG_FILEPATH ):
try:
with open( CONFIG_FILEPATH, 'rb' ) as f:
CONFIG = pickle.load( f )
except:
print('[ERROR]: Can not read config from %s' %CONFIG_FILEPATH)
for tag in _CONFIG_DEFAULTS_ALL:
if tag not in CONFIG:
CONFIG[ tag ] = _CONFIG_DEFAULTS_ALL[ tag ]
for tag in _CONFIG_TAGS_:
if tag not in CONFIG:
if sys.platform.startswith('win'):
CONFIG[ tag ] = _CONFIG_DEFAULTS_WINDOWS[ tag ]
elif sys.platform.startswith('linux') or sys.platform.startswith('darwin') or sys.platform.startswith('freebsd'):
CONFIG[ tag ] = _CONFIG_DEFAULTS_UNIX[ tag ]
else:
print( 'ERROR: unknown platform' )
assert 0
try:
if sys.platform.startswith('win'):
import winreg
# Find the blender2ogre install path from windows registry
registry_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r'Software\blender2ogre', 0, winreg.KEY_READ)
exe_install_dir = winreg.QueryValueEx(registry_key, "Path")[0]
if exe_install_dir != "":
# OgreXmlConverter
if os.path.isfile(exe_install_dir + "OgreXmlConverter.exe"):
print ("Using OgreXmlConverter from install path:", exe_install_dir + "OgreXmlConverter.exe")
CONFIG['OGRETOOLS_XML_CONVERTER'] = exe_install_dir + "OgreXmlConverter.exe"
# Run auto updater as silent. Notifies user if there is a new version out.
# This will not show any UI if there are no update and will go to network
# only once per 2 days so it wont be spending much resources either.
# todo: Move this to a more appropriate place than load_config()
if os.path.isfile(exe_install_dir + "check-for-updates.exe"):
subprocess.Popen([exe_install_dir + "check-for-updates.exe", "/silent"])
except Exception as e:
print("Exception while reading windows registry:", e)
# Setup temp hidden RNA to expose the file paths
for tag in _CONFIG_TAGS_:
default = CONFIG[ tag ]
func = eval( 'lambda self,con: CONFIG.update( {"%s" : self.%s} )' %(tag,tag) )
if type(default) is bool:
prop = BoolProperty(
name=tag, description='updates bool setting', default=default,
options={'SKIP_SAVE'}, update=func
)
else:
prop = StringProperty(
name=tag, description='updates path setting', maxlen=128, default=default,
options={'SKIP_SAVE'}, update=func
)
setattr( bpy.types.WindowManager, tag, prop )
return CONFIG
CONFIG = load_config()
def save_config():
#for key in CONFIG: print( '%s = %s' %(key, CONFIG[key]) )
if os.path.isdir( CONFIG_PATH ):
try:
with open( CONFIG_FILEPATH, 'wb' ) as f:
pickle.dump( CONFIG, f, -1 )
except:
print('[ERROR]: Can not write to %s' %CONFIG_FILEPATH)
else:
print('[ERROR:] Config directory does not exist %s' %CONFIG_PATH)
class Blender2Ogre_ConfigOp(bpy.types.Operator):
'''operator: saves current b2ogre configuration'''
bl_idname = "ogre.save_config"
bl_label = "save config file"
bl_options = {'REGISTER'}
@classmethod
def poll(cls, context):
return True
def invoke(self, context, event):
save_config()
Report.reset()
Report.messages.append('SAVED %s' %CONFIG_FILEPATH)
Report.show()
return {'FINISHED'}
# Make default material for missing materials:
# * Red flags for users so they can quickly see what they forgot to assign a material to.
# * Do not crash if no material on object - thats annoying for the user.
MISSING_MATERIAL = '''
material _missing_material_
{
receive_shadows off
technique
{
pass
{
ambient 0.1 0.1 0.1 1.0
diffuse 0.8 0.0 0.0 1.0
specular 0.5 0.5 0.5 1.0 12.5
emissive 0.3 0.3 0.3 1.0
}
}
}
'''
## Helper functions
def timer_diff_str(start):
return "%0.2f" % (time.time()-start)
def find_bone_index( ob, arm, groupidx): # sometimes the groups are out of order, this finds the right index.
if groupidx < len(ob.vertex_groups): # reported by Slacker
vg = ob.vertex_groups[ groupidx ]
j = 0
for i,bone in enumerate(arm.pose.bones):
if not bone.bone.use_deform and CONFIG['ONLY_DEFORMABLE_BONES']:
j+=1 # if we skip bones we need to adjust the id
if bone.name == vg.name:
return i-j
else:
print('WARNING: object vertex groups not in sync with armature', ob, arm, groupidx)
def mesh_is_smooth( mesh ):
for face in mesh.tessfaces:
if face.use_smooth: return True
def find_uv_layer_index( uvname, material=None ):
# This breaks if users have uv layers with same name with different indices over different objects
idx = 0
for mesh in bpy.data.meshes:
if material is None or material.name in mesh.materials:
if mesh.uv_textures:
names = [ uv.name for uv in mesh.uv_textures ]
if uvname in names:
idx = names.index( uvname )
break # should we check all objects using material and enforce the same index?
return idx
def has_custom_property( a, name ):
for prop in a.items():
n,val = prop
if n == name:
return True
def is_strictly_simple_terrain( ob ):
# A default plane, with simple-subsurf and displace modifier on Z
if len(ob.data.vertices) != 4 and len(ob.data.tessfaces) != 1:
return False
elif len(ob.modifiers) < 2:
return False
elif ob.modifiers[0].type != 'SUBSURF' or ob.modifiers[1].type != 'DISPLACE':
return False
elif ob.modifiers[0].subdivision_type != 'SIMPLE':
return False
elif ob.modifiers[1].direction != 'Z':
return False # disallow NORMAL and other modes
else:
return True
def get_image_textures( mat ):
r = []
for s in mat.texture_slots:
if s and s.texture.type == 'IMAGE':
r.append( s )