From db873182d963fe81996103f69e8e9a4750ce519a Mon Sep 17 00:00:00 2001 From: Campbell Barton Date: Thu, 2 Jun 2011 01:59:46 +0000 Subject: switch quoting not to do \" all over. --- io_scene_x3d/export_x3d.py | 483 ++++++++++++++++++++++----------------------- 1 file changed, 241 insertions(+), 242 deletions(-) (limited to 'io_scene_x3d') diff --git a/io_scene_x3d/export_x3d.py b/io_scene_x3d/export_x3d.py index 1d4f4367..26fb5923 100644 --- a/io_scene_x3d/export_x3d.py +++ b/io_scene_x3d/export_x3d.py @@ -41,32 +41,32 @@ import mathutils from bpy_extras.io_utils import create_derived_objects, free_derived_objects -x3d_names_reserved = {"Anchor", "Appearance", "Arc2D", "ArcClose2D", "AudioClip", "Background", "Billboard", - "BooleanFilter", "BooleanSequencer", "BooleanToggle", "BooleanTrigger", "Box", "Circle2D", - "Collision", "Color", "ColorInterpolator", "ColorRGBA", "component", "Cone", "connect", - "Contour2D", "ContourPolyline2D", "Coordinate", "CoordinateDouble", "CoordinateInterpolator", - "CoordinateInterpolator2D", "Cylinder", "CylinderSensor", "DirectionalLight", "Disk2D", - "ElevationGrid", "EspduTransform", "EXPORT", "ExternProtoDeclare", "Extrusion", "field", - "fieldValue", "FillProperties", "Fog", "FontStyle", "GeoCoordinate", "GeoElevationGrid", - "GeoLocationLocation", "GeoLOD", "GeoMetadata", "GeoOrigin", "GeoPositionInterpolator", - "GeoTouchSensor", "GeoViewpoint", "Group", "HAnimDisplacer", "HAnimHumanoid", "HAnimJoint", - "HAnimSegment", "HAnimSite", "head", "ImageTexture", "IMPORT", "IndexedFaceSet", - "IndexedLineSet", "IndexedTriangleFanSet", "IndexedTriangleSet", "IndexedTriangleStripSet", - "Inline", "IntegerSequencer", "IntegerTrigger", "IS", "KeySensor", "LineProperties", "LineSet", - "LoadSensor", "LOD", "Material", "meta", "MetadataDouble", "MetadataFloat", "MetadataInteger", - "MetadataSet", "MetadataString", "MovieTexture", "MultiTexture", "MultiTextureCoordinate", - "MultiTextureTransform", "NavigationInfo", "Normal", "NormalInterpolator", "NurbsCurve", - "NurbsCurve2D", "NurbsOrientationInterpolator", "NurbsPatchSurface", - "NurbsPositionInterpolator", "NurbsSet", "NurbsSurfaceInterpolator", "NurbsSweptSurface", - "NurbsSwungSurface", "NurbsTextureCoordinate", "NurbsTrimmedSurface", "OrientationInterpolator", - "PixelTexture", "PlaneSensor", "PointLight", "PointSet", "Polyline2D", "Polypoint2D", - "PositionInterpolator", "PositionInterpolator2D", "ProtoBody", "ProtoDeclare", "ProtoInstance", - "ProtoInterface", "ProximitySensor", "ReceiverPdu", "Rectangle2D", "ROUTE", "ScalarInterpolator", - "Scene", "Script", "Shape", "SignalPdu", "Sound", "Sphere", "SphereSensor", "SpotLight", "StaticGroup", - "StringSensor", "Switch", "Text", "TextureBackground", "TextureCoordinate", "TextureCoordinateGenerator", - "TextureTransform", "TimeSensor", "TimeTrigger", "TouchSensor", "Transform", "TransmitterPdu", - "TriangleFanSet", "TriangleSet", "TriangleSet2D", "TriangleStripSet", "Viewpoint", "VisibilitySensor", - "WorldInfo", "X3D", "XvlShell", "VertexShader", "FragmentShader", "MultiShaderAppearance", "ShaderAppearance"} +x3d_names_reserved = {'Anchor', 'Appearance', 'Arc2D', 'ArcClose2D', 'AudioClip', 'Background', 'Billboard', + 'BooleanFilter', 'BooleanSequencer', 'BooleanToggle', 'BooleanTrigger', 'Box', 'Circle2D', + 'Collision', 'Color', 'ColorInterpolator', 'ColorRGBA', 'component', 'Cone', 'connect', + 'Contour2D', 'ContourPolyline2D', 'Coordinate', 'CoordinateDouble', 'CoordinateInterpolator', + 'CoordinateInterpolator2D', 'Cylinder', 'CylinderSensor', 'DirectionalLight', 'Disk2D', + 'ElevationGrid', 'EspduTransform', 'EXPORT', 'ExternProtoDeclare', 'Extrusion', 'field', + 'fieldValue', 'FillProperties', 'Fog', 'FontStyle', 'GeoCoordinate', 'GeoElevationGrid', + 'GeoLocationLocation', 'GeoLOD', 'GeoMetadata', 'GeoOrigin', 'GeoPositionInterpolator', + 'GeoTouchSensor', 'GeoViewpoint', 'Group', 'HAnimDisplacer', 'HAnimHumanoid', 'HAnimJoint', + 'HAnimSegment', 'HAnimSite', 'head', 'ImageTexture', 'IMPORT', 'IndexedFaceSet', + 'IndexedLineSet', 'IndexedTriangleFanSet', 'IndexedTriangleSet', 'IndexedTriangleStripSet', + 'Inline', 'IntegerSequencer', 'IntegerTrigger', 'IS', 'KeySensor', 'LineProperties', 'LineSet', + 'LoadSensor', 'LOD', 'Material', 'meta', 'MetadataDouble', 'MetadataFloat', 'MetadataInteger', + 'MetadataSet', 'MetadataString', 'MovieTexture', 'MultiTexture', 'MultiTextureCoordinate', + 'MultiTextureTransform', 'NavigationInfo', 'Normal', 'NormalInterpolator', 'NurbsCurve', + 'NurbsCurve2D', 'NurbsOrientationInterpolator', 'NurbsPatchSurface', + 'NurbsPositionInterpolator', 'NurbsSet', 'NurbsSurfaceInterpolator', 'NurbsSweptSurface', + 'NurbsSwungSurface', 'NurbsTextureCoordinate', 'NurbsTrimmedSurface', 'OrientationInterpolator', + 'PixelTexture', 'PlaneSensor', 'PointLight', 'PointSet', 'Polyline2D', 'Polypoint2D', + 'PositionInterpolator', 'PositionInterpolator2D', 'ProtoBody', 'ProtoDeclare', 'ProtoInstance', + 'ProtoInterface', 'ProximitySensor', 'ReceiverPdu', 'Rectangle2D', 'ROUTE', 'ScalarInterpolator', + 'Scene', 'Script', 'Shape', 'SignalPdu', 'Sound', 'Sphere', 'SphereSensor', 'SpotLight', 'StaticGroup', + 'StringSensor', 'Switch', 'Text', 'TextureBackground', 'TextureCoordinate', 'TextureCoordinateGenerator', + 'TextureTransform', 'TimeSensor', 'TimeTrigger', 'TouchSensor', 'Transform', 'TransmitterPdu', + 'TriangleFanSet', 'TriangleSet', 'TriangleSet2D', 'TriangleStripSet', 'Viewpoint', 'VisibilitySensor', + 'WorldInfo', 'X3D', 'XvlShell', 'VertexShader', 'FragmentShader', 'MultiShaderAppearance', 'ShaderAppearance'} def clamp_color(col): @@ -86,10 +86,10 @@ def clean_str(name, prefix='rsvd_'): newName = '%s%s' % (prefix, newName) if newName[0].isdigit(): - newName = "%s%s" % ("_", newName) + newName = '%s%s' % ('_', newName) for bad in [' ', '"', '#', "'", ', ', '.', '[', '\\', ']', '{', '}']: - newName = newName.replace(bad, "_") + newName = newName.replace(bad, '_') return newName @@ -115,7 +115,7 @@ def export(file, if use_h3d: import gpu - gpu_shader_dummy_mat = bpy.data.materials.new("X3D_DYMMY_MAT") + gpu_shader_dummy_mat = bpy.data.materials.new('X3D_DYMMY_MAT') gpu_shader_cache[None] = gpu.export_shader(scene, gpu_shader_dummy_mat) @@ -127,41 +127,41 @@ def export(file, filepath = fw.__self__.name #bfile = sys.expandpath( Blender.Get('filepath') ).replace('<', '<').replace('>', '>') bfile = repr(os.path.basename(filepath).replace('<', '<').replace('>', '>'))[1:-1] # use outfile name - fw("%s\n" % ident) + fw('%s\n' % ident) if use_h3d: - fw("%s\n" % ident) + fw('%s\n' % ident) else: - fw("%s\n" % ident) - fw("%s\n" % ident) - - ident += "\t" - fw("%s\n" % ident) - ident += "\t" - fw("%s\n" % (ident, bfile)) - fw("%s\n" % (ident, bpy.app.version_string)) - fw("%s\n" % ident) + fw('%s\n' % ident) + fw('%s\n' % ident) + + ident += '\t' + fw('%s\n' % ident) + ident += '\t' + fw('%s\n' % (ident, bfile)) + fw('%s\n' % (ident, bpy.app.version_string)) + fw('%s\n' % ident) ident = ident[:-1] - fw("%s\n" % ident) - fw("%s\n" % ident) - ident += "\t" + fw('%s\n' % ident) + fw('%s\n' % ident) + ident += '\t' return ident def writeFooter(ident): ident = ident[:-1] - fw("%s\n" % ident) + fw('%s\n' % ident) ident = ident[:-1] - fw("%s" % ident) + fw('%s' % ident) return ident def writeViewpoint(ident, ob, mat, scene): loc, quat, scale = mat.decompose() - fw("%s\n") + fw('%s\n') def writeFog(ident, world): if world: @@ -171,9 +171,9 @@ def export(file, return if mparam.use_mist: - fw("%s\n" % mparam.depth) + fw('%s\n' % mparam.depth) else: return @@ -201,15 +201,15 @@ def export(file, radius = lamp.distance * math.cos(beamWidth) # radius = lamp.dist*math.cos(beamWidth) - fw("%s\n" % location) + fw('%s\n' % location) def writeDirectionalLight(ident, ob, mtx, lamp, world): safeName = clean_str(ob.name) @@ -225,11 +225,11 @@ def export(file, orientation = matrix_direction_neg_z(mtx) - fw("%s\n" % orientation) + fw('%s\n' % orientation) def writePointLight(ident, ob, mtx, lamp, world): @@ -245,28 +245,28 @@ def export(file, intensity = min(lamp.energy / 1.75, 1.0) location = mtx.to_translation()[:] - fw("%s\n" % location) + fw('intensity="%.4g" ' % intensity) + fw('radius="%.4g" ' % lamp.distance) + fw('location="%.4g %.4g %.4g" />\n' % location) def secureName(name): name = name + str(secureName.nodeID) secureName.nodeID += 1 if len(name) <= 3: - newname = "_" + str(secureName.nodeID) + newname = '_' + str(secureName.nodeID) return "%s" % (newname) else: for bad in ('"', '#', "'", ', ', '.', '[', '\\', ']', '{', '}'): - name = name.replace(bad, "_") + name = name.replace(bad, '_') if name in x3d_names_reserved: - newname = name[0:3] + "_" + str(secureName.nodeID) + newname = name[0:3] + '_' + str(secureName.nodeID) return "%s" % (newname) elif name[0].isdigit(): - newname = "_" + name + str(secureName.nodeID) + newname = '_' + name + str(secureName.nodeID) return "%s" % (newname) else: newname = name @@ -297,17 +297,17 @@ def export(file, # texface_use_object_color |= face.use_object_color if texface_use_halo: - fw("%s\n" % ident) + fw('%s\n' % ident) use_halonode = True - ident += "\t" + ident += '\t' elif texface_use_billboard: - fw("%s\n" % ident) + fw('%s\n' % ident) use_billnode = True - ident += "\t" + ident += '\t' elif texface_use_collision: - fw("%s\n" % ident) + fw('%s\n' % ident) use_collnode = True - ident += "\t" + ident += '\t' del texface_use_halo del texface_use_billboard @@ -316,20 +316,20 @@ def export(file, loc, quat, sca = mtx.decompose() - fw("%s\n") - ident += "\t" + fw('%s\n') + ident += '\t' if mesh.tag: - fw("%s\n" % (ident, mesh_name_x3d)) + fw('%s\n' % (ident, mesh_name_x3d)) else: mesh.tag = True - fw("%s\n" % (ident, mesh_name_x3d)) - ident += "\t" + fw('%s\n' % (ident, mesh_name_x3d)) + ident += '\t' is_uv = bool(mesh.uv_textures.active) # is_col, defined for each material @@ -357,7 +357,7 @@ def export(file, mesh_material_images[i] = image break - mesh_materials_use_face_texture = [getattr(material, "use_face_texture", True) for material in mesh_materials] + mesh_materials_use_face_texture = [getattr(material, 'use_face_texture', True) for material in mesh_materials] # fast access! mesh_vertices = mesh.vertices[:] @@ -387,14 +387,14 @@ def export(file, # same as face_groups.items() but sorted so we can get predictable output. face_groups_items = list(face_groups.items()) - face_groups_items.sort(key=lambda m: (m[0][0], getattr(m[0][1], "name", ""))) + face_groups_items.sort(key=lambda m: (m[0][0], getattr(m[0][1], 'name', ''))) for (material_index, image), face_group in face_groups_items: # face_groups.items() if face_group: material = mesh_materials[material_index] - fw("%s\n" % ident) - ident += "\t" + fw('%s\n' % ident) + ident += '\t' is_smooth = False is_col = (mesh.vertex_colors.active and (material is None or material.use_vertex_color_paint)) @@ -413,7 +413,7 @@ def export(file, if 1: # XXX DEBUG gpu_shader_tmp = gpu.export_shader(scene, material) import pprint - print("\nWRITING MATERIAL:", material.name) + print('\nWRITING MATERIAL:', material.name) del gpu_shader_tmp['fragment'] del gpu_shader_tmp['vertex'] pprint.pprint(gpu_shader_tmp, width=120) @@ -421,15 +421,15 @@ def export(file, del gpu_shader_tmp - fw("%s\n" % ident) - ident += "\t" + fw('%s\n' % ident) + ident += '\t' if image and not use_h3d: writeImageTexture(ident, image) if mesh_materials_use_face_texture[material_index]: if image.use_tiles: - fw("%s\n" % (ident, image.tiles_x, image.tiles_y)) + fw('%s\n' % (ident, image.tiles_x, image.tiles_y)) else: # transform by mtex loc = mesh_material_mtex[material_index].offset[:2] @@ -447,40 +447,40 @@ def export(file, else: rot = 0.0 - fw("%s\n") + fw('%s\n') if use_h3d: mat_tmp = material if material else gpu_shader_dummy_mat - writeMaterialH3D(ident, mat_tmp, clean_str(mat_tmp.name, ""), world, + writeMaterialH3D(ident, mat_tmp, clean_str(mat_tmp.name, ''), world, ob, gpu_shader) del mat_tmp else: - writeMaterial(ident, material, clean_str(material.name, ""), world) + writeMaterial(ident, material, clean_str(material.name, ''), world) ident = ident[:-1] - fw("%s\n" % ident) + fw('%s\n' % ident) mesh_faces_col = mesh.vertex_colors.active.data if is_col else None mesh_faces_uv = mesh.uv_textures.active.data if is_uv else None #-- IndexedFaceSet or IndexedLineSet if use_triangulate: - fw("%s\n") + fw('>\n') - fw("%s\n") + fw('%.6g %.6g %.6g ' % mesh_vertices[x3d_v[1]].co[:]) + fw('" />\n') if use_normals: - fw("%s\n") + fw('%.6g %.6g %.6g ' % mesh_vertices[x3d_v[1]].normal[:]) + fw('" />\n') if is_uv: - fw("%s\n") + fw('%.4g %.4g ' % x3d_v[0][slot_uv]) + fw('" />\n') if is_col: - fw("%s\n") + fw('%.3g %.3g %.3g ' % x3d_v[0][slot_col]) + fw('" />\n') if use_h3d: @@ -592,12 +592,12 @@ def export(file, # UVs if gpu_attr['type'] == gpu.CD_MTFACE: if gpu_attr['datatype'] == gpu.GPU_DATA_2F: - fw("%s\n') else: assert(0) @@ -608,121 +608,121 @@ def export(file, else: assert(0) - fw("%s\n" % ident) + fw('%s\n' % ident) else: - fw("%s\n") + fw('>\n') # --- Write IndexedFaceSet Elements if True: if is_coords_written: - fw("%s\n" % (ident, "coord_", mesh_name_x3d)) + fw('%s\n' % (ident, 'coord_', mesh_name_x3d)) if use_normals: - fw("%s\n" % (ident, "normals_", mesh_name_x3d)) + fw('%s\n' % (ident, 'normals_', mesh_name_x3d)) else: - fw("%s\n") + fw('%.6g %.6g %.6g ' % v.co[:]) + fw('" />\n') is_coords_written = True if use_normals: - fw("%s\n") + fw('%.6g %.6g %.6g ' % v.normal[:]) + fw('" />\n') if is_uv: - fw("%s\n") + fw('" />\n') if is_col: - fw("%s\n") + fw('%.3g %.3g %.3g ' % mesh_faces_col[i].color1[:]) + fw('" />\n') #--- output vertexColors #--- output closing braces ident = ident[:-1] - fw("%s\n" % ident) + fw('%s\n' % ident) ident = ident[:-1] - fw("%s\n" % ident) + fw('%s\n' % ident) ident = ident[:-1] - fw("%s\n" % ident) + fw('%s\n' % ident) ident = ident[:-1] - fw("%s\n" % ident) + fw('%s\n' % ident) if use_halonode: ident = ident[:-1] - fw("%s\n" % ident) + fw('%s\n' % ident) elif use_billnode: ident = ident[:-1] - fw("%s\n" % ident) + fw('%s\n' % ident) elif use_collnode: ident = ident[:-1] - fw("%s\n" % ident) + fw('%s\n' % ident) def writeMaterial(ident, mat, material_id, world): # look up material name, use it if available if mat.tag: - fw("%s\n" % (ident, material_id)) + fw('%s\n' % (ident, material_id)) else: mat.tag = True @@ -744,21 +744,21 @@ def export(file, shininess = 0.0 specColor = emitColor = diffuseColor - fw("%s\n") + fw('%s\n') def writeMaterialH3D(ident, mat, material_id, world, ob, gpu_shader): - fw("%s\n" % ident) + fw('%s\n' % ident) if mat.tag: - fw("%s\n" % (ident, material_id)) + fw('%s\n' % (ident, material_id)) else: mat.tag = True @@ -840,14 +840,14 @@ def export(file, ''' import gpu - fw("%s\n" % (ident, material_id)) - ident += "\t" + fw('%s\n' % (ident, material_id)) + ident += '\t' shader_url_frag = 'shaders/glsl_%s.frag' % material_id shader_url_vert = 'shaders/glsl_%s.vert' % material_id # write files - shader_dir = os.path.join(dirname, "shaders") + shader_dir = os.path.join(dirname, 'shaders') if not os.path.isdir(shader_dir): os.mkdir(shader_dir) @@ -855,11 +855,11 @@ def export(file, if uniform['type'] == gpu.GPU_DYNAMIC_SAMPLER_2DIMAGE: fw('%s\n' % (ident, uniform['varname'])) writeImageTexture(ident + '\t', bpy.data.images[uniform['image']]) - fw("%s\n" % ident) + fw('%s\n' % ident) elif uniform['type'] == gpu.GPU_DYNAMIC_LAMP_DYNCO: if uniform['datatype'] == gpu.GPU_DATA_3F: # should always be true! - value = "%.6g %.6g %.6g" % (global_matrix * bpy.data.objects[uniform['lamp']].matrix_world).to_translation()[:] + value = '%.6g %.6g %.6g' % (global_matrix * bpy.data.objects[uniform['lamp']].matrix_world).to_translation()[:] fw('%s\n' % (ident, uniform['varname'], value)) else: assert(0) @@ -867,7 +867,7 @@ def export(file, elif uniform['type'] == gpu.GPU_DYNAMIC_LAMP_DYNCOL: # odd we have both 3, 4 types. lamp = bpy.data.objects[uniform['lamp']].data - value = "%.6g %.6g %.6g" % (mathutils.Vector(lamp.color) * lamp.energy)[:] + value = '%.6g %.6g %.6g' % (mathutils.Vector(lamp.color) * lamp.energy)[:] if uniform['datatype'] == gpu.GPU_DATA_3F: fw('%s\n' % (ident, uniform['varname'], value)) elif uniform['datatype'] == gpu.GPU_DATA_4F: @@ -877,7 +877,7 @@ def export(file, elif uniform['type'] == gpu.GPU_DYNAMIC_LAMP_DYNVEC: if uniform['datatype'] == gpu.GPU_DATA_3F: - value = "%.6g %.6g %.6g" % (mathutils.Vector((0.0, 0.0, 1.0)) * (global_matrix * bpy.data.objects[uniform['lamp']].matrix_world).to_quaternion()).normalized()[:] + value = '%.6g %.6g %.6g' % (mathutils.Vector((0.0, 0.0, 1.0)) * (global_matrix * bpy.data.objects[uniform['lamp']].matrix_world).to_quaternion()).normalized()[:] fw('%s\n' % (ident, uniform['varname'], value)) else: assert(0) @@ -901,11 +901,11 @@ def export(file, elif uniform['type'] == gpu.GPU_DYNAMIC_SAMPLER_2DSHADOW: pass # XXX, shadow buffers not supported. - file_frag = open(os.path.join(dirname, shader_url_frag), "w") + file_frag = open(os.path.join(dirname, shader_url_frag), 'w') file_frag.write(gpu_shader['fragment']) file_frag.close() - file_vert = open(os.path.join(dirname, shader_url_vert), "w") + file_vert = open(os.path.join(dirname, shader_url_vert), 'w') file_vert.write(gpu_shader['vertex']) file_vert.close() @@ -913,31 +913,30 @@ def export(file, fw('%s\n' % (ident, shader_url_vert)) ident = ident[:-1] - fw("%s\n" % ident) + fw('%s\n' % ident) def writeImageTexture(ident, image): name = image.name if image.tag: - fw("%s\n" % (ident, clean_str(name))) + fw('%s\n' % (ident, clean_str(name))) else: image.tag = True - fw("%s\n" % " ".join(["\"%s\"" % f.replace("\\", "/") for f in images])) + fw("url='%s' />\n" % ' '.join(['"%s"' % f.replace('\\', '/') for f in images])) def writeBackground(ident, world): @@ -952,37 +951,37 @@ def export(file, sky_triple = clamp_color(world.zenith_color) mix_triple = clamp_color((grd_triple[i] + sky_triple[i]) / 2.0 for i in range(3)) - fw("%s\n") + if namemat == 'back': + fw('backUrl="%s" ' % basename) + elif namemat == 'bottom': + fw('bottomUrl="%s" ' % basename) + elif namemat == 'front': + fw('frontUrl="%s" ' % basename) + elif namemat == 'left': + fw('leftUrl="%s" ' % basename) + elif namemat == 'right': + fw('rightUrl="%s" ' % basename) + elif namemat == 'top': + fw('topUrl="%s" ' % basename) + + fw('/>\n') ########################################################## # export routine @@ -1016,15 +1015,15 @@ def export(file, bpy.data.materials.tag(False) bpy.data.images.tag(False) - print("Info: starting X3D export to %r..." % file.name) - ident = "" + print('Info: starting X3D export to %r...' % file.name) + ident = '' ident = writeHeader(ident) writeNavigationInfo(ident, scene) writeBackground(ident, world) writeFog(ident, world) - ident = "\t\t" + ident = '\t\t' if use_selection: objects = (o for o in scene.objects if o.is_visible(scene) and o.select) @@ -1083,7 +1082,7 @@ def export(file, export_main() file.close() - print("Info: finished X3D export to %r" % file.name) + print('Info: finished X3D export to %r' % file.name) ########################################################## @@ -1115,13 +1114,13 @@ def save(operator, context, filepath="", if filepath.lower().endswith('.x3dz'): try: import gzip - file = gzip.open(filepath, "w") + file = gzip.open(filepath, 'w') except: - print("failed to import compression modules, exporting uncompressed") + print('failed to import compression modules, exporting uncompressed') filepath = filepath[:-1] # remove trailing z if file is None: - file = open(filepath, "w") + file = open(filepath, 'w') if global_matrix is None: global_matrix = mathutils.Matrix() -- cgit v1.2.3