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
|
# VRML import prototype
#
# strubi@blender.nl
#
"""VRML import module
This is a prototype for VRML97 file import
Supported:
- Object hierarchies, transform collapsing (optional)
- Meshes (IndexedFaceSet, no Basic primitives yet)
- Materials
- Textures (jpg, tga), conversion option from alien formats
"""
import Blender.sys as os # Blender os emulation
from beta import Scenegraph
Transform = Scenegraph.Transform
import beta.Objects
_b = beta.Objects
#from Blender import Mesh
Color = _b.Color
DEFAULTFLAGS = _b.DEFAULTFLAGS
FACEFLAGS = _b.FACEFLAGS
shadowNMesh = _b.shadowNMesh
quat = Scenegraph.quat # quaternion math
vect = quat.vect # vector math module
from vrml import loader
#### GLOBALS
OB = Scenegraph.Object.Types # CONST values
LA = Scenegraph.Lamp.Types
g_level = 1
g_supported_fileformats = ["jpg", "jpeg", "tga"]
#### OPTIONS
OPTIONS = {'cylres' : 16, # resolution of cylinder
'flipnormals' : 0, # flip normals (force)
'mat_as_vcol' : 0, # material as vertex color - warning, this increases mem usage drastically on big files
'notextures' : 0, # no textures - saves some memory
'collapseDEFs' : 0, # collapse DEF nodes
'collapseTF' : 0, # collapse Transforms (as far as possible,
# i.e. currently to Object transform level)
}
#### CONSTANTS
LAYER_EMPTY = (1 << 2)
LAYER_LAMP = (1 << 4)
LAYER_CAMERA = 1 + (1 << 4)
CREASE_ANGLE_THRESHOLD = 0.45 # radians
PARSE_TIME = (loader.parser.IMPORT_PARSE_TIME )
PROCESS_TIME = (1.0 - PARSE_TIME )
PROGRESS_DEPTH = loader.parser.PROGRESS_DEPTH
VERBOSE_DEPTH = PROGRESS_DEPTH
#### DEBUG
def warn(text):
print "###", text
def debug2(text):
print (g_level - 1) * 4 * " " + text
def verbose(text):
print text
def quiet(text):
pass
debug = quiet
#### ERROR message filtering:
g_error = {} # dictionary for non-fatal errors to mark whether an error
# was already reported
def clrError():
global g_error
g_error['toomanyfaces'] = 0
def isError(name):
return g_error[name]
def setError(name):
global g_error
g_error[name] = 1
#### ERROR handling
class baseError:
def __init__(self, value):
self.value = value
def __str__(self):
return `self.value`
class MeshError(baseError):
pass
UnfinishedError = loader.parser.UnfinishedError
##########################################################
# HELPER ROUTINES
def assignImage(f, img):
f.image = img
def assignUV(f, uv):
if len(uv) != len(f.v):
uv = uv[:len(f.v)]
#raise MeshError, "Number of UV coordinates does not match number of vertices in face"
f.uv = []
for u in uv:
f.uv.append((u[0], u[1])) # make sure it's a tuple
#### VRML STUFF
# this is used for transform collapsing
class TransformStack:
def __init__(self):
self.stack = [Transform()]
def push(self, t):
self.stack.append(t)
def pop(self):
return self.stack.pop()
def last(self):
return self.stack[-1]
def fromVRMLTransform(tfnode):
t = Transform()
s = tfnode.scale
t.scale = (s[0], s[1], s[2])
r = tfnode.rotation
if r[0] == 0.0 and r[1] == 0.0 and r[2] == 0.0:
rotaxis = (0.0, 0.0, 1.0)
ang = 0.0
else:
rotaxis = vect.norm3(r[:3])
ang = r[3]
#t.rotation = (rotaxis, ang)
t.calcRotfromAxis((rotaxis, ang))
tr = tfnode.translation
t.translation = (tr[0], tr[1], tr[2])
# XXX more to come..
return t
### TODO: enable material later on
#class dummyMaterial:
#def setMode(self, *args):
#pass
def fromVRMLMaterial(mat):
name = mat.DEF
from Blender import Material
m = Material.New(name)
m.rgbCol = mat.diffuseColor
m.alpha = 1.0 - mat.transparency
m.emit = vect.len3(mat.emissiveColor)
if m.Emit > 0.01:
if vect.cross(mat.diffuseColor, mat.emissiveColor) > 0.01 * m.Emit:
m.rgbCol = mat.emissiveColor
m.ref = 1.0
m.spec = mat.shininess
m.specCol = mat.specularColor
m.amb = mat.ambientIntensity
return m
# override:
#def fromVRMLMaterial(mat):
# return dummyMaterial()
def buildVRMLTextureMatrix(tr):
from math import sin, cos
newMat = vect.Matrix
newVec = vect.Vector
# rotmatrix
s = tr.scale
t = tr.translation
c = tr.center
phi = tr.rotation
SR = newMat()
C = newMat()
C[2] = newVec(c[0], c[1], 1.0)
if abs(phi) > 0.00001:
SR[0] = newVec(s[0] * cos(phi), s[1] * sin(phi), 0.0)
SR[1] = newVec(-s[0] * sin(phi), s[1] * cos(phi), 0.0)
else:
SR[0] = newVec(s[0], 0.0, 0.0)
SR[1] = newVec(0.0, s[1], 0.0)
SR = C * SR * C.inverse() # rotate & scale about rotation center
T = newMat()
T[2] = newVec(t[0], t[1], 1.0)
return SR * T # texture transform matrix
def imageConvert(fromfile, tofile):
"""This should convert from a image file to another file, type is determined
automatically (on extension). It's currently just a stub - users can override
this function to implement their own converters"""
return 0 # we just fail in general
def addImage(path, filename):
"returns a possibly existing image which is imported by Blender"
from Blender import Image
img = None
try:
r = filename.rindex('.')
except:
return None
naked = filename[:r]
ext = filename[r+1:].lower()
if path:
name = os.sep.join([path, filename])
file = os.sep.join([path, naked])
else:
name = filename
file = naked
if not ext in g_supported_fileformats:
tgafile = file + '.tga'
jpgfile = file + '.jpg'
for f in tgafile, jpgfile: # look for jpg, tga
try:
img = Image.Load(f)
if img:
verbose("couldn't load %s (unsupported).\nFound %s instead" % (name, f))
return img
except IOError, msg:
pass
try:
imgfile = open(name, "rb")
imgfile.close()
except IOError, msg:
warn("Image %s not found" % name)
return None
verbose("Format unsupported, trying to convert to %s" % tgafile)
if not imageConvert(name, tgafile):
warn("image conversion failed")
return None
else:
return Image.Load(tgafile)
return None # failed
try:
img = Image.Load(name)
except IOError, msg:
warn("Image %s not found" % name)
return img
# ok, is supported
def callMethod(_class, method, vnode, newnode, warn = 1):
meth = None
try:
meth = getattr(_class, method)
except AttributeError:
if warn:
unknownType(method)
return None, None
if meth:
return meth(vnode, parent = newnode)
def unknownType(type):
warn("unsupported:" + repr(type))
def getChildren(vnode):
try:
children = vnode.children
except:
children = None
return children
def getNodeType(vnode):
return vnode.__gi__
GroupingNodeTypes = ["Group", "Collision", "Anchor", "Billboard", "Inline",
"LOD", "Switch", "Transform"]
################################################################################
#
#### PROCESSING CLASSES
class NullProcessor:
def __init__(self, tstack = TransformStack()):
self.stack = tstack
self.walker = None
self.mesh = None
self.ObjectNode = Scenegraph.NodefromData # may be altered...
self.MaterialCache = {}
self.ImageCache = {}
# This is currently not used XXX
class DEFcollapser(NullProcessor):
"""This is for collapsing DEF Transform nodes into a single object"""
def __init__(self):
self.collapsedNodes = []
def Transform(self, curnode, parent, **kw):
name = curnode.DEF
if not name: # node is a DEF node
return None, None
return children, None
class Processor(NullProcessor):
"""The processor class defines the handler for a VRML Scenegraph node.
Definition of a handler method simply happens by use of the VRML Scenegraph
entity name.
A handler usually creates a new Scenegraph node in the target scenegraph,
converting the data from the given VRML node.
A handler takes the arguments:
curnode: the currently visited VRML node
parent: the previously generated target scenegraph parent node
**kw: additional keywords
It MUST return: (children, newBnode) where:
children: the children of the current VRML node. These will be further
processed by the processor. If this is not wanted (because they
might have been processed by the handler), None must be returned.
newBnode: the newly created target node or None.
"""
def _handleProto(self, curnode, parent, **kw):
p = curnode.PROTO
if not p.sceneGraph:
print curnode.__gi__, "unsupported"
return None, None
def _dummy(self, curnode, parent, **kw):
print curnode.sceneGraph
return None, None
#def __getattr__(self, name):
#"""If method is not statically defined, look up prototypes"""
#return self._handleProto
def _currentTransform(self):
return self.stack.last()
def _parent(self, curnode, parent, trans):
name = curnode.DEF
children = getChildren(curnode)
debug("children: %s" % children)
objects = []
transforms = []
groups = []
isempty = 0
for c in children:
type = getNodeType(c)
if type == 'Transform':
transforms.append(c)
elif type in GroupingNodeTypes:
groups.append(c)
#else:
elif hasattr(self, type):
objects.append(c)
if transforms or groups or len(objects) != 1:
# it's an empty
if not name:
name = 'EMPTY'
Bnode = self.ObjectNode(None, OB.EMPTY, name) # empty Blender Object node
if options['layers']:
Bnode.object.Layer = LAYER_EMPTY
Bnode.transform = trans
Bnode.update()
isempty = 1
parent.insert(Bnode)
else: # don't insert extra empty if only one object has children
Bnode = parent
for node in objects:
c, new = self.walker.walk(node, Bnode)
if not isempty: # only apply transform if no extra transform empty in hierarchy
new.transform = trans
Bnode.insert(new)
for node in transforms:
self.walker.walk(node, Bnode)
for node in groups:
self.walker.walk(node, Bnode)
return None, None
def sceneGraph(self, curnode, parent, **kw):
parent.type = 'ROOT'
return curnode.children, None
def Transform(self, curnode, parent, **kw):
# we support 'center' and 'scaleOrientation' by inserting
# another Empty in between the Transforms
t = fromVRMLTransform(curnode)
cur = self._currentTransform()
chainable = 0
if OPTIONS['collapseTF']:
try:
cur = cur * t # chain transforms
except:
cur = self._currentTransform()
chainable = 1
self.stack.push(cur)
# here comes the tricky hacky transformation conversion
# TODO: SR not supported yet
if chainable == 1: # collapse, but not chainable
# insert extra transform:
Bnode = self.ObjectNode(None, OB.EMPTY, 'Transform') # Empty
Bnode.transform = cur
parent.insert(Bnode)
parent = Bnode
c = curnode.center
if c != [0.0, 0.0, 0.0]:
chainable = 1
trans = Transform()
trans.translation = (-c[0], -c[1], -c[2])
tr = t.translation
t.translation = (tr[0] + c[0], tr[1] + c[1], tr[2] + c[2])
Bnode = self.ObjectNode(None, OB.EMPTY, 'C') # Empty
Bnode.transform = t
parent.insert(Bnode)
parent = Bnode
else:
trans = t
if chainable == 2: # collapse and is chainable
# don't parent, insert into root node:
for c in getChildren(curnode):
dummy, node = self.walker.walk(c, parent) # skip transform node, insert into parent
if node: # a valid Blender node
node.transform = cur
else:
self._parent(curnode, parent, trans)
self.stack.pop()
return None, None
def Switch(self, curnode, parent, **kw):
return None, None
def Group(self, curnode, parent, **kw):
if OPTIONS['collapseTF']:
cur = self._currentTransform()
# don't parent, insert into root node:
children = getChildren(curnode)
for c in children:
dummy, node = self.walker.walk(c, parent) # skip transform node, insert into parent
if node: # a valid Blender node
node.transform = cur
else:
t = Transform()
self._parent(curnode, parent, t)
return None, None
def Collision(self, curnode, parent, **kw):
return self.Group(curnode, parent)
# def LOD(self, curnode, parent, **kw):
# c, node = self.walker.walk(curnode.level[0], parent)
# parent.insert(node)
# return None, None
def Appearance(self, curnode, parent, **kw):
# material colors:
mat = curnode.material
self.curColor = mat.diffuseColor
name = mat.DEF
if name:
if self.MaterialCache.has_key(name):
self.curmaterial = self.MaterialCache[name]
else:
m = fromVRMLMaterial(mat)
self.MaterialCache[name] = m
self.curmaterial = m
else:
if curnode.DEF:
name = curnode.DEF
if self.MaterialCache.has_key(name):
self.curmaterial = self.MaterialCache[name]
else:
m = fromVRMLMaterial(mat)
self.MaterialCache[name] = m
self.curmaterial = m
else:
self.curmaterial = fromVRMLMaterial(mat)
try:
name = curnode.texture.url[0]
except:
name = None
if name:
if self.ImageCache.has_key(name):
self.curImage = self.ImageCache[name]
else:
self.ImageCache[name] = self.curImage = addImage(self.curpath, name)
else:
self.curImage = None
tr = curnode.textureTransform
if tr:
self.curtexmatrix = buildVRMLTextureMatrix(tr)
else:
self.curtexmatrix = None
return None, None
def Shape(self, curnode, parent, **kw):
name = curnode.DEF
debug(name)
#self.mesh = Mesh.rawMesh()
self.mesh = shadowNMesh()
self.mesh.name = name
# don't mess with the order of these..
if curnode.appearance:
self.walker.preprocess(curnode.appearance, self.walker.preprocessor)
else:
# no appearance, get colors from shape (vertex colors)
self.curColor = None
self.curImage = None
self.walker.preprocess(curnode.geometry, self.walker.preprocessor)
if hasattr(self, 'curmaterial'):
self.mesh.assignMaterial(self.curmaterial)
meshobj = self.mesh.write() # write mesh
del self.mesh
bnode = Scenegraph.ObjectNode(meshobj, OB.MESH, name)
if name:
curnode.setTargetnode(bnode) # mark as already processed
return None, bnode
def Box(self, curnode, parent, **kw):
col = apply(Color, self.curColor)
faces = []
x, y, z = curnode.size
x *= 0.5; y *= 0.5; z *= 0.5
name = curnode.DEF
m = self.mesh
v0 = m.addVert((-x, -y, -z))
v1 = m.addVert(( x, -y, -z))
v2 = m.addVert(( x, y, -z))
v3 = m.addVert((-x, y, -z))
v4 = m.addVert((-x, -y, z))
v5 = m.addVert(( x, -y, z))
v6 = m.addVert(( x, y, z))
v7 = m.addVert((-x, y, z))
flags = DEFAULTFLAGS
if not self.curImage:
uvflag = 1
else:
uvflag = 0
m.addFace([v3, v2, v1, v0], flags, uvflag)
m.addFace([v0, v1, v5, v4], flags, uvflag)
m.addFace([v1, v2, v6, v5], flags, uvflag)
m.addFace([v2, v3, v7, v6], flags, uvflag)
m.addFace([v3, v0, v4, v7], flags, uvflag)
m.addFace([v4, v5, v6, v7], flags, uvflag)
for f in m.faces:
f.col = [col, col, col, col]
return None, None
def Viewpoint(self, curnode, parent, **kw):
t = Transform()
r = curnode.orientation
name = 'View_' + curnode.description
t.calcRotfromAxis((r[:3], r[3]))
t.translation = curnode.position
Bnode = self.ObjectNode(None, OB.CAMERA, name) # Empty
Bnode.object.Layer = LAYER_CAMERA
Bnode.transform = t
return None, Bnode
def DirectionalLight(self, curnode, parent, **kw):
loc = (0.0, 10.0, 0.0)
l = self._lamp(curnode, loc)
l.object.data.type = LA.SUN
return None, l
def PointLight(self, curnode, parent, **kw):
l = self._lamp(curnode, curnode.location)
l.object.data.type = LA.LOCAL
return None, l
def _lamp(self, curnode, location):
t = Transform()
name = curnode.DEF
energy = curnode.intensity
t.translation = location
Bnode = self.ObjectNode(None, OB.LAMP, "Lamp")
Bnode.object.data.energy = energy * 5.0
if options['layers']:
Bnode.object.Layer = LAYER_LAMP
Bnode.transform = t
return Bnode
def IndexedFaceSet(self, curnode, **kw):
matxvec = vect.matxvec
mesh = self.mesh
debug("IFS, read mesh")
texcoo = curnode.texCoord
uvflag = 0
if curnode.color:
colors = curnode.color.color
if curnode.colorIndex: # we have color indices
colindex = curnode.colorIndex
else:
colindex = curnode.coordIndex
if not texcoo:
uvflag = 1
else:
colors = None
faceflags = DEFAULTFLAGS
if not texcoo and OPTIONS['mat_as_vcol'] and self.curColor:
uvflag = 1
col = apply(Color, self.curColor)
elif self.curImage:
faceflags += FACEFLAGS.TEX
# MAKE VERTICES
coo = curnode.coord
ncoo = len(coo.point)
if curnode.normal: # normals defined
normals = curnode.normal.vector
if curnode.normalPerVertex and len(coo.point) == len(normals):
self.mesh.recalc_normals = 0
normindex = curnode.normalIndex
i = 0
for v in coo.point:
newv = mesh.addVert(v)
n = newv.no
n[0], n[1], n[2] = normals[normindex[i]]
i += 1
else:
for v in coo.point:
mesh.addVert(v)
else:
for v in coo.point:
mesh.addVert(v)
if curnode.creaseAngle < CREASE_ANGLE_THRESHOLD:
self.mesh.smooth = 1
nvertices = len(mesh.vertices)
if nvertices != ncoo:
print "todo: %d, done: %d" % (ncoo, nvertices)
raise RuntimeError, "FATAL: could not create all vertices"
# MAKE FACES
index = curnode.coordIndex
vlist = []
flip = OPTIONS['flipnormals']
facecount = 0
vertcount = 0
cols = []
if curnode.colorPerVertex: # per vertex colors
for i in index:
if i == -1:
if flip or (curnode.ccw == 0 and not flip): # counterclockwise face def
vlist.reverse()
f = mesh.addFace(vlist, faceflags, uvflag)
if uvflag or colors:
f.col = cols
cols = []
vlist = []
else:
if colors:
col = apply(Color, colors[colindex[vertcount]])
cols.append(col)
vertcount += 1
v = mesh.vertices[i]
vlist.append(v)
else: # per face colors
for i in index:
if i == -1:
if flip or (curnode.ccw == 0 and not flip): # counterclockwise face def
vlist.reverse()
f = mesh.addFace(vlist, faceflags, uvflag)
facecount += 1
if colors:
col = apply(Color, colors[colindex[facecount]])
cols = len(f.v) * [col]
if uvflag or colors:
f.col = cols
vlist = []
else:
v = mesh.vertices[i]
vlist.append(v)
# TEXTURE COORDINATES
if not texcoo:
return None, None
self.curmaterial.setMode("traceable", "shadow", "texFace")
m = self.curtexmatrix
if m: # texture transform exists:
for uv in texcoo.point:
v = (uv[0], uv[1], 1.0)
v1 = matxvec(m, v)
uv[0], uv[1] = v1[0], v1[1]
UVindex = curnode.texCoordIndex
if not UVindex:
UVindex = curnode.coordIndex
# go assign UVs
self.mesh.hasFaceUV(1)
j = 0
uv = []
for i in UVindex:
if i == -1: # flush
if not curnode.ccw:
uv.reverse()
assignUV(f, uv)
assignImage(f, self.curImage)
uv = []
j +=1
else:
f = mesh.faces[j]
uv.append(texcoo.point[i])
return None, None
class PostProcessor(NullProcessor):
def Shape(self, curnode, **kw):
pass
return None, None
def Transform(self, curnode, **kw):
return None, None
class Walker:
"""The node visitor (walker) class for VRML nodes"""
def __init__(self, pre, post = NullProcessor(), progress = None):
self.scene = Scenegraph.BScene()
self.preprocessor = pre
self.postprocessor = post
pre.walker = self # processor knows about walker
post.walker = self
self.nodes = 1
self.depth = 0
self.progress = progress
self.processednodes = 0
def walk(self, vnode, parent):
"""Essential walker routine. It walks along the scenegraph nodes and
processes them according to its pre/post processor methods.
The preprocessor methods return the children of the node remaining
to be processed or None. Also, a new created target node is returned.
If the target node is == None, the current node will be skipped in the
target scenegraph generation. If it is a valid node, the walker routine
inserts it into the 'parent' node of the target scenegraph, which
must be a valid root node on first call, leading us to the example usage:
p = Processor()
w = Walker(p, PostProcessor())
root = Scenegraph.RootNode()
w.walk(SG, root) # SG is a VRML scenegraph
"""
global g_level #XXX
self.depth += 1
g_level = self.depth
if self.depth < PROGRESS_DEPTH:
self.processednodes += 1
if self.progress:
ret = self.progress(PARSE_TIME + PROCESS_TIME * float(self.processednodes) / self.nodes)
if not ret:
progress(1.0)
raise UnfinishedError, "User cancelled conversion"
# if vnode has already been processed, call Linker method, Processor method otherwise
id = vnode.DEF # get name
if not id:
id = 'Object'
processed = vnode.getTargetnode()
if processed: # has been processed ?
debug("linked obj: %s" % id)
children, bnode = self.link(processed, parent)
else:
children, bnode = self.preprocess(vnode, parent)
if not bnode:
bnode = parent # pass on
else:
parent.insert(bnode) # insert into SG
if children:
for c in children:
self.walk(c, bnode)
if not processed:
self.postprocess(vnode, bnode)
self.depth -= 1
return children, bnode
def link(self, bnode, parent):
"""Link already processed data"""
# link data:
new = bnode.clone()
if not new:
raise RuntimeError, "couldn't clone object"
return None, new
def preprocess(self, vnode, newnode = None):
"""Processes a VRML node 'vnode' and returns a custom node. The processor must
be specified in 'p'.
Optionally, a custom parent node (previously created) is passed as 'newnode'."""
pre = "pre"
nodetype = vnode.__gi__
debug(pre + "process:" + repr(nodetype) + " " + vnode.DEF)
return callMethod(self.preprocessor, nodetype, vnode, newnode)
def postprocess(self, vnode, newnode = None):
"""Postprocessing of a VRML node, see Walker.preprocess()"""
nodetype = vnode.__gi__
pre = "post"
debug(pre + "process:" + repr(nodetype) + " " + vnode.DEF)
return callMethod(self.postprocessor, nodetype, vnode, newnode, 0)
testfile2 = '/home/strubi/exotic/wrl/BrownTrout1.wrl'
testfile = '/home/strubi/exotic/wrl/examples/VRML_Model_HSL.wrl'
def fix_VRMLaxes(root, scale):
from Blender import Object, Scene
q = quat.fromRotAxis((1.0, 0.0, 0.0), 1.57079)
empty = Object.New(OB.EMPTY)
empty.layer = LAYER_EMPTY
Scene.getCurrent().link(empty)
node = Scenegraph.ObjectNode(empty, None, "VRMLscene")
node.transform.rotation = q
if scale:
node.transform.scale = (0.01, 0.01, 0.01)
for c in root.children:
node.insert(c)
node.update()
root.children = [node]
#################################################################
# these are the routines that must be provided for the importer
# interface in blender
def checkmagic(name):
"check for file magic"
f = open(name, "r")
magic = loader.getFileType(f)
f.close()
if magic == 'vrml':
return 1
elif magic == 'gzip':
verbose("gzipped file detected")
try:
import gzip
except ImportError, value:
warn("Importing gzip module: %s" % value)
return 0
f = gzip.open(name, 'rb')
header = f.readline()
f.close()
if header[:10] == "#VRML V2.0":
return 1
else:
return 0
print "unknown file"
return 0
g_infotxt = ""
def progress(done):
from Blender import Window
ret = Window.draw_progressbar(done, g_infotxt)
return ret
class Counter:
def __init__(self):
self._count = 0
self.depth = 0
def count(self, node):
if self.depth >= PROGRESS_DEPTH:
return 0
self.depth += 1
self._count += 1
if not getChildren(node):
self.depth -= 1
return 0
else:
for c in node.children:
self.count(c)
self.depth -= 1
return self._count
################################################################################
# MAIN ROUTINE
def importfile(name):
global g_infotxt
global options
global DEFAULTFLAGS
from Blender import Get # XXX
options = Get('vrmloptions')
DEFAULTFLAGS = FACEFLAGS.LIGHT + FACEFLAGS.DYNAMIC
if options['twoside']:
print "TWOSIDE"
DEFAULTFLAGS |= FACEFLAGS.TWOSIDE
clrError()
g_infotxt = "load & parse file..."
progress(0.0)
root = Scenegraph.RootNode()
try:
l = loader.Loader(name, progress)
SG = l.load()
p = Processor()
w = Walker(p, PostProcessor(), progress)
g_infotxt = "convert data..."
p.curpath = os.path.dirname(name)
print "counting nodes...",
c = Counter()
nodes = c.count(SG)
print "done."
w.nodes = nodes # let walker know about number of nodes parsed # XXX
w.walk(SG, root)
except UnfinishedError, msg:
print msg
progress(1.0)
fix_VRMLaxes(root, options['autoscale']) # rotate coordinate system: in VRML, y is up!
root.update() # update baselist for proper display
return root
|