Skip to content
Snippets Groups Projects
Commit 376fa84e authored by Mikhail Rachinskiy's avatar Mikhail Rachinskiy
Browse files

PLY: code cleanup and PEP8

Unused imports, move rare imports inside functions, comment out unused codeblocks instead of docstring, use bl_description.
parent 5e7df9f7
No related branches found
No related tags found
No related merge requests found
...@@ -21,11 +21,10 @@ ...@@ -21,11 +21,10 @@
bl_info = { bl_info = {
"name": "Stanford PLY format", "name": "Stanford PLY format",
"author": "Bruce Merry, Campbell Barton", "author": "Bruce Merry, Campbell Barton",
"version": (1, 0, 0), "version": (1, 1, 0),
"blender": (2, 81, 6), "blender": (2, 82, 0),
"location": "File > Import-Export", "location": "File > Import-Export",
"description": "Import-Export PLY mesh data with UV's and vertex colors", "description": "Import-Export PLY mesh data with UV's and vertex colors",
"warning": "",
"wiki_url": "https://docs.blender.org/manual/en/latest/addons/io_mesh_ply.html", "wiki_url": "https://docs.blender.org/manual/en/latest/addons/io_mesh_ply.html",
"support": 'OFFICIAL', "support": 'OFFICIAL',
"category": "Import-Export", "category": "Import-Export",
...@@ -34,8 +33,6 @@ bl_info = { ...@@ -34,8 +33,6 @@ bl_info = {
# Copyright (C) 2004, 2005: Bruce Merry, bmerry@cs.uct.ac.za # Copyright (C) 2004, 2005: Bruce Merry, bmerry@cs.uct.ac.za
# Contributors: Bruce Merry, Campbell Barton # Contributors: Bruce Merry, Campbell Barton
# To support reload properly, try to access a package var,
# if it's there, reload everything
if "bpy" in locals(): if "bpy" in locals():
import importlib import importlib
if "export_ply" in locals(): if "export_ply" in locals():
...@@ -44,13 +41,11 @@ if "bpy" in locals(): ...@@ -44,13 +41,11 @@ if "bpy" in locals():
importlib.reload(import_ply) importlib.reload(import_ply)
import os
import bpy import bpy
from bpy.props import ( from bpy.props import (
CollectionProperty, CollectionProperty,
StringProperty, StringProperty,
BoolProperty, BoolProperty,
EnumProperty,
FloatProperty, FloatProperty,
) )
from bpy_extras.io_utils import ( from bpy_extras.io_utils import (
...@@ -81,6 +76,8 @@ class ImportPLY(bpy.types.Operator, ImportHelper): ...@@ -81,6 +76,8 @@ class ImportPLY(bpy.types.Operator, ImportHelper):
filter_glob: StringProperty(default="*.ply", options={'HIDDEN'}) filter_glob: StringProperty(default="*.ply", options={'HIDDEN'})
def execute(self, context): def execute(self, context):
import os
paths = [os.path.join(self.directory, name.name) paths = [os.path.join(self.directory, name.name)
for name in self.files] for name in self.files]
if not paths: if not paths:
...@@ -96,10 +93,9 @@ class ImportPLY(bpy.types.Operator, ImportHelper): ...@@ -96,10 +93,9 @@ class ImportPLY(bpy.types.Operator, ImportHelper):
@orientation_helper(axis_forward='Y', axis_up='Z') @orientation_helper(axis_forward='Y', axis_up='Z')
class ExportPLY(bpy.types.Operator, ExportHelper): class ExportPLY(bpy.types.Operator, ExportHelper):
"""Export a single object as a Stanford PLY with normals, """ \
"""colors and texture coordinates"""
bl_idname = "export_mesh.ply" bl_idname = "export_mesh.ply"
bl_label = "Export PLY" bl_label = "Export PLY"
bl_description = "Export as a Stanford PLY with normals, vertex colors and texture coordinates"
filename_ext = ".ply" filename_ext = ".ply"
filter_glob: StringProperty(default="*.ply", options={'HIDDEN'}) filter_glob: StringProperty(default="*.ply", options={'HIDDEN'})
......
...@@ -21,20 +21,12 @@ ...@@ -21,20 +21,12 @@
""" """
This script exports Stanford PLY files from Blender. It supports normals, This script exports Stanford PLY files from Blender. It supports normals,
colors, and texture coordinates per face or per vertex. colors, and texture coordinates per face or per vertex.
Only one mesh can be exported at a time.
""" """
import bpy
import os
def save_mesh(filepath, mesh, use_normals=True, use_uv_coords=True, use_colors=True):
def save_mesh( import os
filepath, import bpy
mesh,
use_normals=True,
use_uv_coords=True,
use_colors=True,
):
def rvec3d(v): def rvec3d(v):
return round(v[0], 6), round(v[1], 6), round(v[2], 6) return round(v[0], 6), round(v[1], 6), round(v[2], 6)
...@@ -186,16 +178,17 @@ def save_mesh( ...@@ -186,16 +178,17 @@ def save_mesh(
def save( def save(
operator, operator,
context, context,
filepath="", filepath="",
use_selection=False, use_selection=False,
use_mesh_modifiers=True, use_mesh_modifiers=True,
use_normals=True, use_normals=True,
use_uv_coords=True, use_uv_coords=True,
use_colors=True, use_colors=True,
global_matrix=None global_matrix=None
): ):
import bpy
import bmesh import bmesh
if bpy.ops.object.mode_set.poll(): if bpy.ops.object.mode_set.poll():
......
...@@ -18,9 +18,6 @@ ...@@ -18,9 +18,6 @@
# <pep8 compliant> # <pep8 compliant>
import re
import struct
class element_spec(object): class element_spec(object):
__slots__ = ( __slots__ = (
...@@ -59,14 +56,16 @@ class property_spec(object): ...@@ -59,14 +56,16 @@ class property_spec(object):
self.numeric_type = numeric_type self.numeric_type = numeric_type
def read_format(self, format, count, num_type, stream): def read_format(self, format, count, num_type, stream):
import struct
if format == b'ascii': if format == b'ascii':
if num_type == 's': if num_type == 's':
ans = [] ans = []
for i in range(count): for i in range(count):
s = stream[i] s = stream[i]
if not (len(s) >= 2 and s.startswith(b'"') and s.endswith(b'"')): if not (len(s) >= 2 and s.startswith(b'"') and s.endswith(b'"')):
print('Invalid string', s) print("Invalid string", s)
print('Note: ply_import.py does not handle whitespace in strings') print("Note: ply_import.py does not handle whitespace in strings")
return None return None
ans.append(s[1:-1]) ans.append(s[1:-1])
stream[:count] = [] stream[:count] = []
...@@ -104,29 +103,30 @@ class property_spec(object): ...@@ -104,29 +103,30 @@ class property_spec(object):
class object_spec(object): class object_spec(object):
__slots__ = ("specs", __slots__ = ("specs",)
)
'A list of element_specs'
def __init__(self): def __init__(self):
# A list of element_specs
self.specs = [] self.specs = []
def load(self, format, stream): def load(self, format, stream):
return dict([(i.name, [i.load(format, stream) for j in range(i.count)]) for i in self.specs]) return dict([(i.name, [i.load(format, stream) for j in range(i.count)]) for i in self.specs])
'''
# Longhand for above LC # Longhand for above LC
answer = {}
for i in self.specs: # answer = {}
answer[i.name] = [] # for i in self.specs:
for j in range(i.count): # answer[i.name] = []
if not j % 100 and meshtools.show_progress: # for j in range(i.count):
Blender.Window.DrawProgressBar(float(j) / i.count, 'Loading ' + i.name) # if not j % 100 and meshtools.show_progress:
answer[i.name].append(i.load(format, stream)) # Blender.Window.DrawProgressBar(float(j) / i.count, 'Loading ' + i.name)
return answer # answer[i.name].append(i.load(format, stream))
''' # return answer
def read(filepath): def read(filepath):
import re
format = b'' format = b''
texture = b'' texture = b''
version = b'1.0' version = b'1.0'
...@@ -161,7 +161,7 @@ def read(filepath): ...@@ -161,7 +161,7 @@ def read(filepath):
signature = plyf.readline() signature = plyf.readline()
if not signature.startswith(b'ply'): if not signature.startswith(b'ply'):
print('Signature line was invalid') print("Signature line was invalid")
return invalid_ply return invalid_ply
valid_header = False valid_header = False
...@@ -178,7 +178,7 @@ def read(filepath): ...@@ -178,7 +178,7 @@ def read(filepath):
continue continue
elif tokens[1] == b'TextureFile': elif tokens[1] == b'TextureFile':
if len(tokens) < 4: if len(tokens) < 4:
print('Invalid texture line') print("Invalid texture line")
else: else:
texture = tokens[2] texture = tokens[2]
continue continue
...@@ -187,29 +187,29 @@ def read(filepath): ...@@ -187,29 +187,29 @@ def read(filepath):
continue continue
elif tokens[0] == b'format': elif tokens[0] == b'format':
if len(tokens) < 3: if len(tokens) < 3:
print('Invalid format line') print("Invalid format line")
return invalid_ply return invalid_ply
if tokens[1] not in format_specs: if tokens[1] not in format_specs:
print('Unknown format', tokens[1]) print("Unknown format", tokens[1])
return invalid_ply return invalid_ply
try: try:
version_test = float(tokens[2]) version_test = float(tokens[2])
except Exception as ex: except Exception as ex:
print('Unknown version', ex) print("Unknown version", ex)
version_test = None version_test = None
if version_test != float(version): if version_test != float(version):
print('Unknown version', tokens[2]) print("Unknown version", tokens[2])
return invalid_ply return invalid_ply
del version_test del version_test
format = tokens[1] format = tokens[1]
elif tokens[0] == b'element': elif tokens[0] == b'element':
if len(tokens) < 3: if len(tokens) < 3:
print(b'Invalid element line') print("Invalid element line")
return invalid_ply return invalid_ply
obj_spec.specs.append(element_spec(tokens[1], int(tokens[2]))) obj_spec.specs.append(element_spec(tokens[1], int(tokens[2])))
elif tokens[0] == b'property': elif tokens[0] == b'property':
if not len(obj_spec.specs): if not len(obj_spec.specs):
print('Property without element') print("Property without element")
return invalid_ply return invalid_ply
if tokens[1] == b'list': if tokens[1] == b'list':
obj_spec.specs[-1].properties.append(property_spec(tokens[4], type_specs[tokens[2]], type_specs[tokens[3]])) obj_spec.specs[-1].properties.append(property_spec(tokens[4], type_specs[tokens[2]], type_specs[tokens[3]]))
...@@ -224,22 +224,20 @@ def read(filepath): ...@@ -224,22 +224,20 @@ def read(filepath):
return obj_spec, obj, texture return obj_spec, obj, texture
import bpy
def load_ply_mesh(filepath, ply_name): def load_ply_mesh(filepath, ply_name):
from bpy_extras.io_utils import unpack_face_list import bpy
obj_spec, obj, texture = read(filepath) obj_spec, obj, texture = read(filepath)
# XXX28: use texture # XXX28: use texture
if obj is None: if obj is None:
print('Invalid file') print("Invalid file")
return return
uvindices = colindices = None uvindices = colindices = None
colmultiply = None colmultiply = None
# noindices = None # Ignore normals # TODO import normals
# noindices = None
for el in obj_spec.specs: for el in obj_spec.specs:
if el.name == b'vertex': if el.name == b'vertex':
...@@ -376,38 +374,38 @@ def load_ply_mesh(filepath, ply_name): ...@@ -376,38 +374,38 @@ def load_ply_mesh(filepath, ply_name):
if texture and uvindices: if texture and uvindices:
pass pass
# XXX28: add support for using texture. # XXX28: add support for using texture.
'''
import os
import sys
from bpy_extras.image_utils import load_image
encoding = sys.getfilesystemencoding() # import os
encoded_texture = texture.decode(encoding=encoding) # import sys
name = bpy.path.display_name_from_filepath(texture) # from bpy_extras.image_utils import load_image
image = load_image(encoded_texture, os.path.dirname(filepath), recursive=True, place_holder=True)
# encoding = sys.getfilesystemencoding()
# encoded_texture = texture.decode(encoding=encoding)
# name = bpy.path.display_name_from_filepath(texture)
# image = load_image(encoded_texture, os.path.dirname(filepath), recursive=True, place_holder=True)
if image: # if image:
texture = bpy.data.textures.new(name=name, type='IMAGE') # texture = bpy.data.textures.new(name=name, type='IMAGE')
texture.image = image # texture.image = image
material = bpy.data.materials.new(name=name) # material = bpy.data.materials.new(name=name)
material.use_shadeless = True # material.use_shadeless = True
mtex = material.texture_slots.add() # mtex = material.texture_slots.add()
mtex.texture = texture # mtex.texture = texture
mtex.texture_coords = 'UV' # mtex.texture_coords = 'UV'
mtex.use_map_color_diffuse = True # mtex.use_map_color_diffuse = True
mesh.materials.append(material) # mesh.materials.append(material)
for face in mesh.uv_textures[0].data: # for face in mesh.uv_textures[0].data:
face.image = image # face.image = image
'''
return mesh return mesh
def load_ply(filepath): def load_ply(filepath):
import time import time
import bpy
t = time.time() t = time.time()
ply_name = bpy.path.display_name_from_filepath(filepath) ply_name = bpy.path.display_name_from_filepath(filepath)
...@@ -421,7 +419,7 @@ def load_ply(filepath): ...@@ -421,7 +419,7 @@ def load_ply(filepath):
bpy.context.view_layer.objects.active = obj bpy.context.view_layer.objects.active = obj
obj.select_set(True) obj.select_set(True)
print('\nSuccessfully imported %r in %.3f sec' % (filepath, time.time() - t)) print("\nSuccessfully imported %r in %.3f sec" % (filepath, time.time() - t))
return {'FINISHED'} return {'FINISHED'}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment