[Bf-extensions-cvs] SVN commit: /data/svn/bf-extensions [1999] trunk/py/scripts/addons/ io_scene_x3d/export_x3d.py: - ensure unique names ( before it was possible 2+ cleaned names would collide)

Campbell Barton ideasman42 at gmail.com
Fri Jun 3 03:43:05 CEST 2011


Revision: 1999
          http://projects.blender.org/scm/viewvc.php?view=rev&root=bf-extensions&revision=1999
Author:   campbellbarton
Date:     2011-06-03 01:43:04 +0000 (Fri, 03 Jun 2011)
Log Message:
-----------
- ensure unique names (before it was possible 2+ cleaned names would collide)
- use XML escaping rather then cleaning to for strings

Modified Paths:
--------------
    trunk/py/scripts/addons/io_scene_x3d/export_x3d.py

Modified: trunk/py/scripts/addons/io_scene_x3d/export_x3d.py
===================================================================
--- trunk/py/scripts/addons/io_scene_x3d/export_x3d.py	2011-06-02 23:30:51 UTC (rev 1998)
+++ trunk/py/scripts/addons/io_scene_x3d/export_x3d.py	2011-06-03 01:43:04 UTC (rev 1999)
@@ -73,26 +73,13 @@
     return tuple([max(min(c, 1.0), 0.0) for c in col])
 
 
-def matrix_direction_neg_z(mtx):
-    return (mathutils.Vector((0.0, 0.0, -1.0)) * mtx.to_3x3()).normalized()[:]
+def matrix_direction_neg_z(matrix):
+    return (mathutils.Vector((0.0, 0.0, -1.0)) * matrix.to_3x3()).normalized()[:]
 
 
-def clean_str(name, prefix='rsvd_'):
-    """cleanStr(name,prefix) - try to create a valid VRML DEF name from object name"""
+def prefix_quoted_str(value, prefix):
+    return value[0] + prefix + value[1:]
 
-    newName = name
-
-    if newName in x3d_names_reserved:
-        newName = '%s%s' % (prefix, newName)
-
-    if newName[0].isdigit():
-        newName = '%s%s' % ('_', newName)
-
-    for bad in [' ', '"', '#', "'", ', ', '.', '[', '\\', ']', '{', '}']:
-        newName = newName.replace(bad, '_')
-    return newName
-
-
 ##########################################################
 # Functions for writing output file
 ##########################################################
@@ -109,8 +96,18 @@
            ):
 
     # -------------------------------------------------------------------------
-    # global setup
+    # Global Setup
     # -------------------------------------------------------------------------
+    from bpy_extras.io_utils import unique_name
+    from xml.sax.saxutils import quoteattr
+
+    uuid_cache_object = {}    # object
+    uuid_cache_view = {}      # object, different namespace
+    uuid_cache_mesh = {}      # mesh
+    uuid_cache_material = {}  # material
+    uuid_cache_image = {}     # image
+    uuid_cache_world = {}     # world
+
     fw = file.write
     dirname = os.path.dirname(file.name)
     gpu_shader_cache = {}
@@ -120,13 +117,14 @@
         gpu_shader_dummy_mat = bpy.data.materials.new('X3D_DYMMY_MAT')
         gpu_shader_cache[None] = gpu.export_shader(scene, gpu_shader_dummy_mat)
 
-##########################################################
-# Writing nodes routines
-##########################################################
+    # -------------------------------------------------------------------------
+    # File Writing Functions
+    # -------------------------------------------------------------------------
 
     def writeHeader(ident):
-        filepath = fw.__self__.name
-        bfile = repr(os.path.basename(filepath).replace('<', '&lt').replace('>', '&gt'))[1:-1]  # use outfile name
+        filepath_quoted = quoteattr(os.path.basename(file.name))
+        blender_ver_quoted = quoteattr('Blender %s' % bpy.app.version_string)
+
         fw('%s<?xml version="1.0" encoding="UTF-8"?>\n' % ident)
         if use_h3d:
             fw('%s<X3D profile="H3DAPI" version="1.4">\n' % ident)
@@ -137,8 +135,8 @@
         ident += '\t'
         fw('%s<head>\n' % ident)
         ident += '\t'
-        fw('%s<meta name="filename" content="%s" />\n' % (ident, bfile))
-        fw('%s<meta name="generator" content="Blender %s" />\n' % (ident, bpy.app.version_string))
+        fw('%s<meta name="filename" content=%s />\n' % (ident, filepath_quoted))
+        fw('%s<meta name="generator" content=%s />\n' % (ident, blender_ver_quoted))
         # this info was never updated, so blender version should be enough
         # fw('%s<meta name="translator" content="X3D exporter v1.55 (2006/01/17)" />\n' % ident)
         ident = ident[:-1]
@@ -154,13 +152,14 @@
         fw('%s</X3D>' % ident)
         return ident
 
-    def writeViewpoint(ident, obj, mat, scene):
-        loc, quat, scale = mat.decompose()
+    def writeViewpoint(ident, obj, matrix, scene):
+        view_id = unique_name(obj, 'CA_' + obj.name, uuid_cache_view, clean_func=quoteattr)
 
+        loc, quat, scale = matrix.decompose()
+
         ident_step = ident + (' ' * (-len(ident) + \
         fw('%s<Viewpoint ' % ident)))
-        fw('DEF="%s"\n' % clean_str(obj.name))
-        fw(ident_step + 'description="%s"\n' % obj.name)
+        fw('DEF=%s\n' % view_id)
         fw(ident_step + 'centerOfRotation="0 0 0"\n')
         fw(ident_step + 'position="%3.2f %3.2f %3.2f"\n' % loc[:])
         fw(ident_step + 'orientation="%3.2f %3.2f %3.2f %3.2f"\n' % (quat.axis[:] + (quat.angle, )))
@@ -193,8 +192,10 @@
         fw(ident_step + 'avatarSize="0.25, 1.75, 0.75"\n')
         fw(ident_step + '/>\n')
 
-    def writeSpotLight(ident, obj, mtx, lamp, world):
-        safeName = clean_str(obj.name)
+    def writeSpotLight(ident, obj, matrix, lamp, world):
+        # note, lamp_id is not re-used
+        lamp_id = unique_name(obj, 'LA_' + obj.name, uuid_cache_object, clean_func=quoteattr)
+
         if world:
             ambi = world.ambient_color
             amb_intensity = ((ambi[0] + ambi[1] + ambi[2]) / 3.0) / 2.5
@@ -208,15 +209,15 @@
         # beamWidth=((lamp.spotSize*math.pi)/180.0)*.37
         cutOffAngle = beamWidth * 1.3
 
-        orientation = matrix_direction_neg_z(mtx)
+        orientation = matrix_direction_neg_z(matrix)
 
-        location = mtx.to_translation()[:]
+        location = matrix.to_translation()[:]
 
         radius = lamp.distance * math.cos(beamWidth)
         # radius = lamp.dist*math.cos(beamWidth)
         ident_step = ident + (' ' * (-len(ident) + \
         fw('%s<SpotLight ' % ident)))
-        fw('DEF="%s"\n' % safeName)
+        fw('DEF=%s\n' % lamp_id)
         fw(ident_step + 'radius="%.4g"\n' % radius)
         fw(ident_step + 'ambientIntensity="%.4g"\n' % amb_intensity)
         fw(ident_step + 'intensity="%.4g"\n' % intensity)
@@ -227,8 +228,10 @@
         fw(ident_step + 'location="%.4g %.4g %.4g"\n' % location)
         fw(ident_step + '/>\n')
 
-    def writeDirectionalLight(ident, obj, mtx, lamp, world):
-        safeName = clean_str(obj.name)
+    def writeDirectionalLight(ident, obj, matrix, lamp, world):
+        # note, lamp_id is not re-used
+        lamp_id = unique_name(obj, 'LA_' + obj.name, uuid_cache_object, clean_func=quoteattr)
+
         if world:
             ambi = world.ambient_color
             # ambi = world.amb
@@ -239,20 +242,21 @@
 
         intensity = min(lamp.energy / 1.75, 1.0)
 
-        orientation = matrix_direction_neg_z(mtx)
+        orientation = matrix_direction_neg_z(matrix)
 
         ident_step = ident + (' ' * (-len(ident) + \
         fw('%s<DirectionalLight ' % ident)))
-        fw('DEF="%s"\n' % safeName)
+        fw('DEF=%s\n' % lamp_id)
         fw(ident_step + 'ambientIntensity="%.4g"\n' % amb_intensity)
         fw(ident_step + 'color="%.4g %.4g %.4g"\n' % clamp_color(lamp.color))
         fw(ident_step + 'intensity="%.4g"\n' % intensity)
         fw(ident_step + 'direction="%.4g %.4g %.4g"\n' % orientation)
         fw(ident_step + '/>\n')
 
-    def writePointLight(ident, obj, mtx, lamp, world):
+    def writePointLight(ident, obj, matrix, lamp, world):
+        # note, lamp_id is not re-used
+        lamp_id = unique_name(obj, 'LA_' + obj.name, uuid_cache_object, clean_func=quoteattr)
 
-        safeName = clean_str(obj.name)
         if world:
             ambi = world.ambient_color
             # ambi = world.amb
@@ -262,11 +266,11 @@
             amb_intensity = 0.0
 
         intensity = min(lamp.energy / 1.75, 1.0)
-        location = mtx.to_translation()[:]
+        location = matrix.to_translation()[:]
 
         ident_step = ident + (' ' * (-len(ident) + \
         fw('%s<PointLight ' % ident)))
-        fw('DEF="%s"\n' % safeName)
+        fw('DEF=%s\n' % lamp_id)
         fw(ident_step + 'ambientIntensity="%.4g"\n' % amb_intensity)
         fw(ident_step + 'color="%.4g %.4g %.4g"\n' % clamp_color(lamp.color))
 
@@ -275,31 +279,13 @@
         fw(ident_step + 'location="%.4g %.4g %.4g"\n' % location)
         fw(ident_step + '/>\n')
 
-    def secureName(name):
-        name = name + str(secureName.nodeID)
-        secureName.nodeID += 1
-        if len(name) <= 3:
-            newname = '_' + str(secureName.nodeID)
-            return "%s" % (newname)
-        else:
-            for bad in ('"', '#', "'", ', ', '.', '[', '\\', ']', '{', '}'):
-                name = name.replace(bad, '_')
-            if name in x3d_names_reserved:
-                newname = name[0:3] + '_' + str(secureName.nodeID)
-                return "%s" % (newname)
-            elif name[0].isdigit():
-                newname = '_' + name + str(secureName.nodeID)
-                return "%s" % (newname)
-            else:
-                newname = name
-                return "%s" % (newname)
-    secureName.nodeID = 0
+    def writeIndexedFaceSet(ident, obj, mesh, matrix, world):
+        obj_id = unique_name(obj, 'OB_' + obj.name, uuid_cache_object, clean_func=quoteattr)
+        mesh_id = unique_name(mesh, 'ME_' + mesh.name, uuid_cache_mesh, clean_func=quoteattr)
+        mesh_id_group = prefix_quoted_str(mesh_id, 'group_')
+        mesh_id_coords = prefix_quoted_str(mesh_id, 'coords_')
+        mesh_id_normals = prefix_quoted_str(mesh_id, 'normals_')
 
-    def writeIndexedFaceSet(ident, obj, mesh, mtx, world):
-
-        shape_name_x3d = clean_str(obj.name)
-        mesh_name_x3d = clean_str(mesh.name)
-
         if not mesh.faces:
             return
 
@@ -336,11 +322,11 @@
         del texface_use_collision
         # del texface_use_object_color
 
-        loc, quat, sca = mtx.decompose()
+        loc, quat, sca = matrix.decompose()
 
         ident_step = ident + (' ' * (-len(ident) + \
         fw('%s<Transform ' % ident)))
-        fw('DEF="%s"\n' % shape_name_x3d)
+        fw('DEF=%s\n' % obj_id)
         fw(ident_step + 'translation="%.6g %.6g %.6g"\n' % loc[:])
         fw(ident_step + 'scale="%.6g %.6g %.6g"\n' % sca[:])
         fw(ident_step + 'rotation="%.6g %.6g %.6g %.6g"\n' % (quat.axis[:] + (quat.angle, )))
@@ -348,11 +334,11 @@
         ident += '\t'
 
         if mesh.tag:
-            fw('%s<Group USE="G_%s" />\n' % (ident, mesh_name_x3d))
+            fw('%s<Group USE=%s />\n' % (ident, mesh_id_group))
         else:
             mesh.tag = True
 
-            fw('%s<Group DEF="G_%s">\n' % (ident, mesh_name_x3d))
+            fw('%s<Group DEF=%s>\n' % (ident, mesh_id_group))
             ident += '\t'
 
             is_uv = bool(mesh.uv_textures.active)
@@ -480,11 +466,11 @@
 

@@ Diff output truncated at 10240 characters. @@


More information about the Bf-extensions-cvs mailing list