Added research data, testing blender mesh generation

This commit is contained in:
2021-05-23 15:34:33 -05:00
parent f2efb7c42d
commit 505df54a1e
205 changed files with 124004 additions and 40 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,726 @@
# --------------------------------------------------------------------------
# Illusoft Collada 1.4 plugin for Blender
# --------------------------------------------------------------------------
# ***** BEGIN GPL LICENSE BLOCK *****
#
# Copyright (C) 2006: Illusoft - colladablender@illusoft.com
# 2008.05.08 modif. for debug mode by migius (AKA Remigiusz Fiedler)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ***** END GPL LICENCE BLOCK *****
# --------------------------------------------------------------------------
debug = False #--- debug mode
debprn = False #--- print debug "print 'deb: ..."
_ERROR = False
_PERROR = False
import sys
try:
import Blender
except NameError:
print "Error! Could not find Blender modules!"
_ERROR = True
__version__ = '0.3.162'
# Show the wait cursor in blender
Blender.Window.WaitCursor(1)
# indicates if the user can choose a file to import
useDefaultFile = True
defaultFileUrl = 'animation.DAE'
#defaultFileUrl = 'animation.DAE'
#defaultFileUrl = 'animated_letters.DAE'
#defaultFileUrl = 'animation_robot.DAE'
defaultExportUrl = ''
# Check if full version of python is installed.
try:
import os
import xml
except ImportError:
print"Error! Could not find full version of Python..."
_ERROR = True
if _ERROR:
from sys import version_info
version = '%s.%s' % version_info[0:2]
print """
To run the collada importer and exporter you need to have
Python version %s installed in your system. It can be downloaded from:
http://www.python.org
Notes:
- The minor (third) version number doesn't matter, you can have either
Python %s.1 or %s.2 or higher.
- If you do have Python %s installed and still can't run the scripts, then
make sure Blender's Python interpreter is finding the standalone modules
(run 'System Information' from Blender's Help -> System menu).
""" % (version, version, version, version)
Blender.Draw.PupMenu("Please install full version of python %t | Check the console for more info")
raise StandardError()
else:
# Try to load the Plugin modules
try:
import cutils
except NameError:
print "\nError! Could not find Collada Utils (cutils) module!"
_ERROR = True
try:
import xmlUtils
except NameError:
print "\nError! Could not find XML module!"
_PERROR = True
try:
import collada
except NameError:
print "Error! Could not find Collada(collada.py) module"
_PERROR = True
try:
import translator
except NameError:
print "Error! Could not find Collada Translator (translator.py) module"
_PERROR = True
try:
import helperObjects
except NameError:
print "Error! Could not find Collada helperObjects (helperObjects.py) module"
_PERROR = True
# Try to load extra python modules
try:
import math
except NameError:
print "Error! Could not find math module"
_PERROR = True
if _PERROR:
Blender.Draw.PupMenu("Cannot load plugin modules.")
else:
# A List with al the modules (in the scriptsdir) to be reloaded
modules = [cutils, xmlUtils, collada, helperObjects, translator]
def Main(doImp, scriptsLoc):
global debug, __version__, doImport, scriptsLocation, defaultFilename, valsLoaded
if _ERROR or _PERROR:
return
valsLoaded = False
doImport = doImp
if scriptsLoc == "":
scriptsLoc = Blender.Get('scriptsdir')
if not scriptsLoc: scriptsLoc = Blender.Get('uscriptsdir')
if scriptsLoc:
scriptsLocation = scriptsLoc+Blender.sys.sep+'bpymodules'+Blender.sys.sep+'colladaImEx'+Blender.sys.sep
else:
print 'Could not find a scripts path'
else:
scriptsLocation = scriptsLoc
if not ReloadModules():
print 'cannot reload all modules'
return False
# Clear the console
cutils.ClearConsole()
# set the debuglevel
if debug:
cutils.Debug.SetLevel('DEBUG')
else:
cutils.Debug.SetLevel('FEEDBACK')
cutils.Debug.Debug('Illusoft Collada 1.4 Plugin v%s started'%(__version__),'FEEDBACK')
# Create a Collada <-> Blender Translator
if debug:
print 'keep track of the time to execute this script' #---------
startTime = Blender.sys.time()
##fileurl = scriptsDir
fileurl = ''
if doImport:
fileurl+= defaultFileUrl
else :
fileurl += defaultExportUrl
if debprn: print 'deb: fileurl=',fileurl #-------
useTriangles = False
usePolygons = False
bakeMatrices = False
exportSelection = False
newScene = True
clearScene = False
lookAt = False
usePhysics = True
exportCurrentScene = False
exportRelativePaths = False
useUV = False
sampleAnimation = False
onlyMainScene = False
transl = translator.Translator(doImport,__version__,debug,fileurl, useTriangles, usePolygons, bakeMatrices, exportSelection, newScene, clearScene, lookAt, usePhysics, exportCurrentScene, exportRelativePaths, useUV, sampleAnimation, onlyMainScene)
##transl = translator.Translator(doImport,__version__,debug,fileurl)
##translator = Translator(False,__version__,debug,scriptsDir+defaultExportUrl)
##translator = Translator(True,__version__,debug,scriptsDir+defaultExportUrl)
# Redraw al 3D windows.
if debprn: print 'deb: ---- the end ----' #-----
Blender.Window.RedrawAll()
# calculate the elapsed time
endTime = Blender.sys.time()
elapsedTime = endTime - startTime
cutils.Debug.Debug('FINISHED - time elapsed: %.1f'%(elapsedTime),'FEEDBACK')
# Hide the wait cursor in blender
Blender.Window.WaitCursor(0)
else:
defFilename = Blender.sys.dirname(Blender.sys.progname)+Blender.sys.sep
colladaReg = Blender.Registry.GetKey('collada',True)
if not (colladaReg is None) and 'path' in colladaReg and Blender.sys.exists(colladaReg['path']):
defFilename = colladaReg['path']
elif not (doImport):
defFilename += 'untitled.dae'
defaultFilename = defFilename
Blender.Draw.Register(Gui, Event, ButtonEvent) # registering the 3 callbacks
def ReloadModules():
# Loop through all the modules and try to reload them
for module in modules:
try:
reload(module)
except NameError:
cutils.Debug.Debug('cannot reload module %s' %(module),'ERROR')
return False
return True
def FileSelected(fileName):
global doImport, fileButton
if fileName != '':
# check if file exists
if Blender.sys.exists(fileName) != 1 and doImport:
cutils.Debug.Debug('File(%s) does not exist' % (fileName),'ERROR')
return False
# must the file to import end with .dae or .xml?
## if doImport:
## # Check if the file has a valid extension .DAE or .XML
## extension = fileName.rsplit('.',1)[1].lower()
## if extension != 'xml' and extension != 'dae':
## cutils.Debug.Debug('File(%s) is not a .dae or .xml file' % (fileName),'ERROR')
fileButton.val = fileName
##transl = translator.Translator(doImport,__version__,debug,fileName)
else:
cutils.Debug.Debug('ERROR: filename is empty','ERROR')
toggle = 0
fileButton = None
toggleTriangles = None
togglePolygons = None
toggleExportSelection = None
toggleClearScene = None
toggleNewScene = None
toggleBakeMatrix = None
toggleSampleAnimation = None
toggleLookAt = None
togglePhysics = None
toggleExportCurrentScene = None
toggleExportRelativePaths = None
toggleUseUV = None
toggleSampleAnimation = None
toggleOnlyMainScene = None
toggleApplyModifiers = None
def LoadDefaultVals():
global toggleLookAt, toggleBakeMatrix, toggleSampleAnimation, toggleNewScene, \
toggleClearScene, toggleTriangles, togglePolygons, toggleExportSelection, \
scriptsLocation, doImport, defaultFilename, fileButton, valsLoaded, \
togglePhysics, toggleExportCurrentScene, toggleExportRelativePaths, \
toggleUseUV, toggleOnlyMainScene, toggleApplyModifiers
if valsLoaded:
return None
colladaReg = Blender.Registry.GetKey('collada',True)
if not (colladaReg is None):
fileButton.val = colladaReg.get('path', '')
fileParts = []
filePath = "";
fileParts = fileButton.val.split("\\");
partCount = len(fileParts);
if partCount > 0 :
for i in range(partCount):
if i == 0:
filePath = fileParts[i];
else :
if i != partCount - 1:
filePath = filePath + "\\" + fileParts[i];
else:
filePath = filePath + "\\";
blenderFilename = Blender.Get('filename');
fileParts = []
fileParts = blenderFilename.split("\\");
partCount = len(fileParts);
if partCount > 0 :
blenderFileOnlyName = fileParts[partCount -1];
blenderFileOnlyName = blenderFileOnlyName.replace(".blend", ".dae");
filePath = filePath + blenderFileOnlyName;
else :
filePath = filePath + "untitled.dae";
if len(filePath) > 0 :
fileButton.val = filePath;
if doImport:
toggleOnlyMainScene.val = colladaReg.get('onlyMainScene', False)
toggleNewScene.val = colladaReg.get('newScene', False)
toggleClearScene.val = colladaReg.get('clearScene', False)
else:
##toggleLookAt.val = colladaReg.get('lookAt', False)
toggleBakeMatrix.val = colladaReg.get('bakeMatrices', False)
toggleTriangles.val = colladaReg.get('useTriangles', False)
togglePolygons.val = colladaReg.get('usePolygons', False)
toggleExportSelection.val = colladaReg.get('exportSelection', False)
togglePhysics.val = not colladaReg.get('usePhysics', True)
toggleExportCurrentScene.val = colladaReg.get('exportCurrentScene', False)
toggleExportRelativePaths.val = colladaReg.get('exportRelativePaths', True)
toggleSampleAnimation.val = colladaReg.get('sampleAnimation', False)
toggleUseUV.val = colladaReg.get('useUV', False)
#TODO: "toggleOnlyMainScene" left out intentionally by the original plugin author?
toggleApplyModifiers.val = colladaReg.get('applyModifiers', True)
valsLoaded = True
def Gui():
global toggleLookAt, toggleBakeMatrix, toggleSampleAnimation, toggleNewScene, \
toggleClearScene, toggleTriangles, togglePolygons, toggleExportSelection, \
scriptsLocation, doImport, defaultFilename, fileButton, togglePhysics, \
toggleExportCurrentScene, toggleExportRelativePaths, toggleUseUV, \
toggleOnlyMainScene, toggleApplyModifiers
Blender.BGL.glClearColor(0.898,0.910,0.808,1) # Set BG Color1
Blender.BGL.glClear(Blender.BGL.GL_COLOR_BUFFER_BIT)
Blender.BGL.glColor3f(0.835,0.848,0.745) # BG Color 2
size = Blender.Window.GetAreaSize()
Blender.BGL.glRectd(40,0,200,size[1])
try:
logoImage = Blender.Image.Load(scriptsLocation + 'logo.png')
Blender.BGL.glEnable(Blender.BGL.GL_BLEND ) # Only needed for alpha blending images with background.
Blender.BGL.glBlendFunc(Blender.BGL.GL_SRC_ALPHA, Blender.BGL.GL_ONE_MINUS_SRC_ALPHA)
try: Blender.Draw.Image(logoImage, 45, size[1]-30)
except: pass
Blender.BGL.glDisable(Blender.BGL.GL_BLEND)
except IOError: # image not found
Blender.BGL.glColor3i(0.255,0.255,0.2)
Blender.BGL.glRasterPos2i(45, size[1]-30)
Blender.Draw.Text("Collada 1.4.0 Plugin for Blender", "large")
Blender.BGL.glColor3f(0.255,0.255,0.2)
Blender.BGL.glRasterPos2i(45, size[1]-40)
Blender.Draw.Text("Version: %s"%(__version__),"small")
# Write donation text
donateText1 = "If this plugin is valuable to you or your company, please consider a donation at"
donateText2 = "http://colladablender.illusoft.com to support this plugin. Thanks a lot!"
Blender.BGL.glRasterPos2i(45, size[1]-60)
Blender.Draw.Text(donateText1, "small")
Blender.BGL.glRasterPos2i(45, size[1]-70)
Blender.Draw.Text(donateText2, "small")
# Write import / export text
Blender.BGL.glColor3f(0.9,0.08,0.08)
Blender.BGL.glRasterPos2i(45, size[1]-95)
if doImport:
importExportText = "Import"
else:
importExportText = "Export"
Blender.Draw.Text(importExportText, "normal")
Blender.BGL.glColor3f(0.255,0.255,0.2)
# Create File path input
yval = size[1]-130
Blender.BGL.glRasterPos2i(45, yval)
if fileButton is None or fileButton.val == '':
fileName = defaultFilename
else:
fileName = fileButton.val
Blender.Draw.Text('%s file:'%(importExportText),"normal")
maxWidth = 400
if size[0] - (105 + 35) > maxWidth:
fileWidth = maxWidth
else:
fileWidth = size[0] - (105 + 35)
fileButton = Blender.Draw.String('', 5, 105, yval-5, fileWidth, 20, fileName, 255)
Blender.Draw.PushButton('...', 2, 105 + fileWidth, yval-5, 30, 20, 'browse file')
Blender.Draw.PushButton("Cancel", 3, 45, 10, 55, 20, "Cancel")
Blender.Draw.PushButton(importExportText + ' and Close', 4, 45+55+35, 10, 100, 20, importExportText + ' and close this screen')
# Create Export Options:
if not doImport:
yval = yval - 50
# Create Triangle / Polygons Options
if not (toggleTriangles is None):
toggleTrianglesVal = toggleTriangles.val
else:
toggleTrianglesVal = 0
if not (togglePolygons is None):
togglePolygonsVal = togglePolygons.val
else:
togglePolygonsVal = 0
toggleTriangles = Blender.Draw.Toggle('Triangles',6,45, yval, 60, 20, toggleTrianglesVal, 'Export all geometry as triangles')
togglePolygons = Blender.Draw.Toggle('Polygons',7,45+60 + 30, yval, 60, 20, togglePolygonsVal, 'Export all geometry as polygons')
yval = yval - 40
# Create Export Selection Option
if not (toggleExportSelection is None):
toggleExportSelectionVal = toggleExportSelection.val
else:
toggleExportSelectionVal = 0
toggleExportSelection = Blender.Draw.Toggle('Only Export Selection',8,45, yval, 150, 20, toggleExportSelectionVal, 'Only export selected objects')
yval = yval - 40
# Create Bake Matrix Option
if not (toggleBakeMatrix is None):
toggleBakeMatrixVal = toggleBakeMatrix.val
else:
toggleBakeMatrixVal = 0
toggleBakeMatrix = Blender.Draw.Toggle('Bake Matrices',11,45, yval, 150, 20, toggleBakeMatrixVal, 'Put all transformations in a single matrix')
yval = yval - 40
# Create Sample Anim
if not (toggleSampleAnimation is None):
toggleSampleAnimationVal = toggleSampleAnimation.val
else:
toggleSampleAnimationVal = 0
toggleSampleAnimation = Blender.Draw.Toggle('Sample Animation',16,45, yval, 150, 20, toggleSampleAnimationVal, 'Export information for every frame of animation.')
yval = yval - 40
#Create Physics Option
if not (togglePhysics is None):
togglePhysicsVal = togglePhysics.val
else:
togglePhysicsVal = 0
togglePhysics = Blender.Draw.Toggle('Disable Physics',13,45, yval, 150, 20, togglePhysicsVal, 'Disable Export physics information')
yval = yval - 40
#Create Physics Option
if not (toggleExportCurrentScene is None):
toggleExportCurrentSceneVal = toggleExportCurrentScene.val
else:
toggleExportCurrentSceneVal = 0
toggleExportCurrentScene = Blender.Draw.Toggle('Only Current Scene',14,45, yval, 150, 20, toggleExportCurrentSceneVal, 'Only Export the current scene')
yval = yval - 40
#Create Relative Path's Option
if not (toggleExportRelativePaths is None):
toggleExportRelativePathsVal = toggleExportRelativePaths.val
else:
toggleExportRelativePathsVal = 0
toggleExportRelativePaths = Blender.Draw.Toggle('Use Relative Paths',15,45, yval, 150, 20, toggleExportRelativePathsVal, 'Export paths relative to the collada file')
yval = yval - 40
#Create Relative Path's Option
if not (toggleUseUV is None):
toggleUseUVVal = toggleUseUV.val
else:
toggleUseUVVal = 0
toggleUseUV = Blender.Draw.Toggle('Use UV Image Mats',15,45, yval, 150, 20, toggleUseUVVal, 'Use UV Image instead of the material textures. Use this if you did not use the Material Textures window. Note: If you reimport this file, they will have moved to the materials section!!')
##yval = yval - 40
# Create Lookat Option
if not (toggleLookAt is None):
toggleLookAtVal = toggleLookAt.val
else:
toggleLookAtVal = 0
##toggleLookAt = Blender.Draw.Toggle('Camera as Lookat',14,45, yval, 150, 20, toggleLookAtVal, 'Export the transformation of camera\'s as lookat')
yval = yval - 40
if not (toggleApplyModifiers is None):
toggleApplyModifiersVal = toggleApplyModifiers.val
else:
toggleApplyModifiersVal = 0
toggleApplyModifiers = Blender.Draw.Toggle('Apply modifiers',14,45, yval, 150, 20, toggleApplyModifiersVal, 'Apply modifiers, like mirroring, transformations, etc.')
Blender.Draw.PushButton(importExportText, 12, 45+55+35+100+35, 10, 55, 20, importExportText)
else: # IMPORT GUI
yval = yval - 50
# Create Import To new Scene Options
if not (toggleNewScene is None):
toggleNewSceneVal = toggleNewScene.val
else:
toggleNewSceneVal = 0
if not (toggleClearScene is None):
toggleClearSceneVal = toggleClearScene.val
else:
toggleClearSceneVal = 0
if not (toggleOnlyMainScene is None):
toggleOnlyMainSceneVal = toggleOnlyMainScene.val
else:
toggleOnlyMainSceneVal = 0
if toggleOnlyMainSceneVal == 0:
if toggleClearSceneVal == 0 and toggleNewSceneVal == 0:
toggleNewSceneVal = 1
newSceneText = 'Import file into a new Scene';
newSceneTitle = 'New Scene'
clearSceneText = 'Clear everything on the current scene'
clearSceneTitle = 'Clear Scene'
if toggleOnlyMainSceneVal == 0:
newSceneText = 'Import file into a new Scenes'
newSceneTitle = 'New Scenes'
clearSceneText = 'Delete all the Blender Scenes'
clearSceneTitle = 'Delete Scenes'
toggleOnlyMainScene = Blender.Draw.Toggle('Only Import Main Scene',17,40, yval, 190, 20, toggleOnlyMainSceneVal, 'Only import the main scene from Collada')
yval = yval - 40
toggleNewScene = Blender.Draw.Toggle(newSceneTitle,9,40, yval, 90, 20, toggleNewSceneVal, newSceneText)
toggleClearScene = Blender.Draw.Toggle(clearSceneTitle,10,40+90 + 10, yval, 90, 20, toggleClearSceneVal, clearSceneText)
LoadDefaultVals()
def CalcElapsedTime(startTime):
'''
Calc elapsed time between now and start time.
'''
return Blender.sys.time() - startTime
def Event(evt, val):
pass
def ButtonEvent(evt):
global toggleLookAt, toggleBakeMatrix, toggleExportSelection,toggleNewScene, \
toggleClearScene, toggleTriangles, togglePolygons, doImport, defaultFilename, \
fileSelectorShown, fileButton, valsLoaded, togglePhysics, \
toggleExportCurrentScene, toggleExportRelativePaths, toggleUseUV, \
toggleSampleAnimation, toggleOnlyMainScene
checkImportButtons = False
if evt == 1:
toggle = 1 - toggle
Blender.Draw.Redraw(1)
elif evt == 2: # browse file
browseText = ''
if doImport:
browseText = 'Import .dae'
else:
browseText = 'Export .dae'
Blender.Window.FileSelector(FileSelected,browseText,defaultFilename)
Blender.Draw.Redraw(1)
elif evt == 3:
Blender.Draw.Exit()
elif evt == 4 or evt == 12: # Ok, time to export/import
#keep track of the time to execute this script
startTime = Blender.sys.time()
fileName = fileButton.val
dirName = Blender.sys.dirname(fileName) + Blender.sys.sep
exists = Blender.sys.exists(fileName)
if exists == 1 and not doImport:
overwrite = Blender.Draw.PupMenu( "File Already Exists, Overwrite?%t|Yes%x1|No%x0" )
if not overwrite == 1:
return False
elif exists != 1 and doImport:
Blender.Draw.PupMenu("File does not exist: %t|"+fileName)
cutils.Debug.Debug('File(%s) does not exist' % (fileName),'ERROR')
return False
elif not Blender.sys.exists(dirName):
Blender.Draw.PupMenu("Path is not valid: %t|"+dirName)
cutils.Debug.Debug('Path is not valid: %s' % (dirName),'ERROR')
return False
if toggleTriangles is None:
useTriangles = False
else:
useTriangles = bool(toggleTriangles.val)
if togglePolygons is None:
usePolygons = False
else:
usePolygons = bool(togglePolygons.val)
if toggleBakeMatrix is None:
bakeMatrices = False
else:
bakeMatrices = bool(toggleBakeMatrix.val)
if toggleExportSelection is None:
exportSelection = False
else:
exportSelection = bool(toggleExportSelection.val)
if toggleNewScene is None:
newScene = False
else:
newScene = bool(toggleNewScene.val)
if toggleClearScene is None:
clearScene = False
else:
clearScene = bool(toggleClearScene.val)
if toggleOnlyMainScene is None:
onlyMainScene = False
else:
onlyMainScene = bool(toggleOnlyMainScene.val)
if toggleLookAt is None:
lookAt = False
else:
lookAt = bool(toggleLookAt.val)
if togglePhysics is None:
usePhysics = True
else:
usePhysics = not bool(togglePhysics.val)
if toggleExportCurrentScene is None:
exportCurrentScene = False
else:
exportCurrentScene = bool(toggleExportCurrentScene.val)
if toggleExportRelativePaths is None:
exportRelativePaths = False
else:
exportRelativePaths = bool(toggleExportRelativePaths.val)
if toggleUseUV is None:
useUV = False
else:
useUV = bool(toggleUseUV.val)
if toggleSampleAnimation is None:
sampleAnimation = False
else:
sampleAnimation = bool(toggleSampleAnimation.val)
if toggleApplyModifiers is None:
applyModifiers = False
else:
applyModifiers = bool(toggleApplyModifiers.val)
d = Blender.Registry.GetKey('collada',True)
if d is None:
d = dict()
d['path'] = fileName
if doImport:
d['newScene'] = newScene
d['clearScene'] = clearScene
d['onlyMainScene'] = onlyMainScene
else:
d['useTriangles'] = useTriangles
d['usePolygons'] = usePolygons
d['bakeMatrices'] = bakeMatrices
d['exportSelection'] = exportSelection
d['lookAt'] = lookAt
d['usePhysics'] = usePhysics
d['exportCurrentScene'] = exportCurrentScene
d['exportRelativePaths'] = exportRelativePaths
d['useUV'] = useUV
d['sampleAnimation'] = sampleAnimation
d['applyModifiers'] = applyModifiers
Blender.Registry.SetKey('collada',d, True)
if doImport:
importExportText = "Import"
else:
importExportText = "Export"
try:
transl = translator.Translator(doImport,__version__,debug,fileName, \
useTriangles, usePolygons, bakeMatrices,\
exportSelection, newScene, clearScene, \
lookAt, usePhysics, exportCurrentScene, \
exportRelativePaths, useUV, sampleAnimation, \
onlyMainScene, applyModifiers)
cutils.Debug.Debug('Time to process and save data: %.1f' \
% CalcElapsedTime(startTime), 'FEEDBACK')
# Redraw all 3D windows.
Blender.Window.RedrawAll()
Blender.Draw.PupMenu(importExportText + " Successful %t")
except:
Blender.Draw.PupMenu(importExportText + "ing failed%t | Check the console for more info")
raise # throw the exception
cutils.Debug.Debug('FINISHED - time elapsed: %.1f' % CalcElapsedTime(startTime), \
'FEEDBACK')
# Hide the wait cursor in blender
Blender.Window.WaitCursor(0)
if evt == 4:
Blender.Draw.Exit()
valsLoaded = False
elif evt == 6: # Toggle Triangles
if toggleTriangles.val:
togglePolygons.val = 0
Blender.Draw.Redraw(1)
elif evt == 7: # Toggle Polygons
if togglePolygons.val:
toggleTriangles.val = 0
Blender.Draw.Redraw(1)
elif evt == 9: # Toggle Create new Scene
if toggleNewScene.val:
toggleClearScene.val = 0
checkImportButtons = True
elif evt == 10: # Toggle Clear current Scene
if toggleClearScene.val:
toggleNewScene.val = 0
checkImportButtons = True
elif evt == 17: # Toggle Only Main Scene
checkImportButtons = True
if checkImportButtons:
if not toggleOnlyMainScene.val:
if not toggleClearScene.val and not toggleNewScene.val:
toggleNewScene.val = True
Blender.Draw.Redraw(1)

View File

@@ -0,0 +1,404 @@
# --------------------------------------------------------------------------
# Illusoft Collada 1.4 plugin for Blender
# --------------------------------------------------------------------------
# ***** BEGIN GPL LICENSE BLOCK *****
#
# Copyright (C) 2006: Illusoft - colladablender@illusoft.com
# 2008.05.08 modif. for debug mode by migius (AKA Remigiusz Fiedler)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ***** END GPL LICENCE BLOCK *****
# --------------------------------------------------------------------------
import sys
import os
import Blender
from Blender.Mathutils import *
import string
'''
Translation map.
Used to translate every COLLADA id to a valid id, no matter what "wrong" letters may be
included. Look at the IDREF XSD declaration for more.
Follows strictly the COLLADA XSD declaration which explicitly allows non-english chars,
like special chars (e.g. micro sign), umlauts and so on.
The COLLADA spec also allows additional chars for member access ('.'), these
must obviously be removed too, otherwise they would be heavily misinterpreted.
'''
translateMap = "" + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(45) + chr(95) + chr(95) + \
chr(48) + chr(49) + chr(50) + chr(51) + chr(52) + chr(53) + chr(54) + chr(55) + \
chr(56) + chr(57) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(65) + chr(66) + chr(67) + chr(68) + chr(69) + chr(70) + chr(71) + \
chr(72) + chr(73) + chr(74) + chr(75) + chr(76) + chr(77) + chr(78) + chr(79) + \
chr(80) + chr(81) + chr(82) + chr(83) + chr(84) + chr(85) + chr(86) + chr(87) + \
chr(88) + chr(89) + chr(90) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(97) + chr(98) + chr(99) + chr(100) + chr(101) + chr(102) + chr(103) + \
chr(104) + chr(105) + chr(106) + chr(107) + chr(108) + chr(109) + chr(110) + chr(111) + \
chr(112) + chr(113) + chr(114) + chr(115) + chr(116) + chr(117) + chr(118) + chr(119) + \
chr(120) + chr(121) + chr(122) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(183) + \
chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + chr(95) + \
chr(192) + chr(193) + chr(194) + chr(195) + chr(196) + chr(197) + chr(198) + chr(199) + \
chr(200) + chr(201) + chr(202) + chr(203) + chr(204) + chr(205) + chr(206) + chr(207) + \
chr(208) + chr(209) + chr(210) + chr(211) + chr(212) + chr(213) + chr(214) + chr(95) + \
chr(216) + chr(217) + chr(218) + chr(219) + chr(220) + chr(221) + chr(222) + chr(223) + \
chr(224) + chr(225) + chr(226) + chr(227) + chr(228) + chr(229) + chr(230) + chr(231) + \
chr(232) + chr(233) + chr(234) + chr(235) + chr(236) + chr(237) + chr(238) + chr(239) + \
chr(240) + chr(241) + chr(242) + chr(243) + chr(244) + chr(245) + chr(246) + chr(95) + \
chr(248) + chr(249) + chr(250) + chr(251) + chr(252) + chr(253) + chr(254) + chr(255)
#---Classes---
class Debug(object):
__debugLevels = ['ALL','DEBUG','FEEDBACK','WARNING','ERROR','NONE']
# the current debugLevel
debugLevel = 'ALL'
# Method: Debug a message
def Debug(message, level):
#print 'deb:', level, message #deb--------
currentLevelIndex = Debug.__debugLevels.index(Debug.debugLevel)
if str(level).isdigit() and level >= currentLevelIndex:
print Debug.__debugLevels[level] + ': ' + message
else:
try:
i = Debug.__debugLevels.index(level)
if i >= currentLevelIndex :
print level + ': ' + str(message)
except:
print 'exception in cutils.py-Debug()'
pass
# make Debug a static method
Debug = staticmethod(Debug)
# Method: Set the Debug Level
def SetLevel(level):
try:
Debug.__debugLevels.index(level)
Debug.debugLevel = level
return True
except:
Debug('Debuglevel not available','WARNING')
return False
# Make SetLevel a static method
SetLevel = staticmethod(SetLevel)
#---Functions----
angleToRadian = 3.1415926 / 180.0
radianToAngle = 180.0 / 3.1415926
# Convert a string to a float if the value exists
def ToFloat(val):
if val is None or val == '':
return None
else:
return float(val)
# Convert a string to a int if the value exists
def ToInt(val):
if val is None or val == '':
return None
else:
return int(val)
# Convert a string to a list of 3 floats e.g '1.0 2.0 3.0' -> [1.0, 2.0, 3.0]
def ToFloat3(stringValue):
if stringValue is None:
return None
split = stringValue.split( )
return [ float( split[ 0 ] ), float( split[ 1 ] ), float( split[ 2 ] ) ]
# Convert a string to a list of 2 floats e.g '1.0 2.0' -> [1.0, 2.0]
def ToFloat2(stringValue, errorText=''):
if stringValue is None:
return None
split = stringValue.split( )
try:
return [ float( split[ 0 ] ), float( split[ 1 ] )]
except IndexError:
print 'Error: ' + errorText
raise
def CreateRelativePath(basePath, filePath):
if basePath is None or basePath is '' or filePath is None or filePath is '':
return ''
try:
if not Blender.sys.exists(filePath):
return ''
except TypeError:
return ''
basePathAr = basePath.lower().split(Blender.sys.sep)
filePathAr = filePath.lower().split(Blender.sys.sep)
filePathLength = len(filePathAr)
if not basePathAr[0] == filePathAr[0]: # Files must have the same root.
return filePath
result = ''
equalIndex = -1
for i in range(len(basePathAr)-1):
if basePathAr[i] == filePathAr[i]:
pass
else:
if equalIndex == -1:
equalIndex = i
result += '..'+ Blender.sys.sep
if equalIndex == -1:
equalIndex = len(basePathAr)-1
for i in range(equalIndex, filePathLength):
result += filePathAr[i]
if not i == filePathLength-1:
result += Blender.sys.sep
return result
def ToList(var):
result = []
if var is None:
return result
split = var.split( )
for i in split:
result.append(i)
return result
# Convert a string or list to a list of floats
def ToFloatList(var):
result = []
if var is None:
return result
if type(var) == list:
for i in var:
result.append(float(i))
else:
split = var.split( )
for i in split:
result.append(float(i))
return result
def ToIntList(lst):
result = []
if lst is None:
return result
if type(lst) == list:
for i in lst:
result.append(int(i))
else:
split = lst.split( )
for i in split:
result.append(int(i))
return result
def ToBoolList(lst):
result = []
if lst is None:
return result
for i in lst:
result.append(bool(i))
return result
# Convert a string to a list of 4 floats e.g '1.0 2.0 3.0 4.0' -> [1.0, 2.0, 3.0, 4.0]
def ToFloat4(stringValue):
split = stringValue.split( )
return [ float( split[ 0 ] ), float( split[ 1 ] ), float( split[ 2 ] ) , float( split[3])]
def ToFloat7(stringValue):
data = stringValue.split( )
return [ float(data[0]), float(data[1]), float(data[2]), float(data[3]), float(data[4]), float(data[5]), float(data[6])]
def AddVec3( vector1, vector2 ):
vector1.x += vector2.x
vector1.y += vector2.y
vector1.z += vector2.z
def ToMatrix4( matrixElement ):
if matrixElement is None:
return None
if not isinstance(matrixElement,list):
data = matrixElement.split( )
vec1 = [ float(data[0]), float(data[4]), float(data[8]), float(data[12]) ]
vec2 = [ float(data[1]), float(data[5]), float(data[9]), float(data[13]) ]
vec3 = [ float(data[2]), float(data[6]), float(data[10]), float(data[14]) ]
vec4 = [ float(data[3]), float(data[7]), float(data[11]), float(data[15]) ]
else:
vec1 = matrixElement[0:4]
vec2 = matrixElement[4:8]
vec3 = matrixElement[8:12]
vec4 = matrixElement[12:16]
return Blender.Mathutils.Matrix( vec1, vec2, vec3, vec4 )
def ToMatrix3(matrixElement):
data = matrixElement.split( )
vec1 = [ float(data[0]), float(data[3]), float(data[6]) ]
vec2 = [ float(data[1]), float(data[4]), float(data[7])]
vec3 = [ float(data[2]), float(data[5]), float(data[8])]
return Blender.Mathutils.Matrix( vec1, vec2, vec3)
def GetVector3( element ):
value = [ float( element[ 0 ] ), float( element[ 1 ] ), float( element[ 2 ] ) ]
return Blender.Mathutils.Vector( value )
def GetEuler( rotateElement ):
euler = [ float( rotateElement[ 0 ] ) * float( rotateElement[ 3 ] ) * angleToRadian,
float( rotateElement[ 1 ] ) * float( rotateElement[ 3 ] ) * angleToRadian,
float( rotateElement[ 2 ] ) * float( rotateElement[ 3 ] ) * angleToRadian ]
return Blender.Mathutils.Euler( euler )
def AddEuler(euler1, euler2):
euler1.x += euler2.x
euler1.y += euler2.y
euler1.z += euler2.z
# Clear the console
def ClearConsole():
if sys.platform == 'linux-i386' or sys.platform == 'linux2':
sysCommand = 'clear'
elif sys.platform == 'win32' or sys.platform == 'dos' or sys.platform[0:5] == 'ms-dos' :
sysCommand = 'cls'
else :
sysCommand = 'unknown'
if sysCommand != 'unknown':
os.system(sysCommand)
def MatrixToString(mat, nDigits):
result = ''
if mat is None:
return result
for vec in mat:
result += '\n\t'
for i in vec:
result += str(round(i, nDigits))+' '
return result+'\n'
def MatrixToList(mat):
result = []
for vec in mat:
result.extend(list(vec))
return result
def RoundList(lst, nDigits):
result = []
for i in lst:
val = round(i, nDigits)
if val < (1.0 / 10**nDigits):
val = 0
result.append(round(i, nDigits))
return result
def ListToString(lst, nDigits = 5):
val = ''
if lst is None:
return val
else:
for i in lst:
if type(i) == list:
val += ListToString(i)+'\n'
elif isinstance(i, float):
f = '%.'+str(nDigits)+'f '
val += f % i
else:
val += str(i)+' '
return val[:-1]
def GetValidFilename(filename):
filename = Blender.sys.expandpath( filename )
filename = filename.replace( "//", "/" )
filename = filename.replace( Blender.sys.sep, "/" )
return "file://" + filename
def GetColumnVector(matrix, colNumber, rowCount):
if rowCount == 4:
return Vector(matrix[0][colNumber], matrix[1][colNumber], matrix[2][colNumber], matrix[3][colNumber])
else:
return Vector(matrix[0][colNumber], matrix[1][colNumber], matrix[2][colNumber])
def PrintTransforms(matrix, name):
print "\n",name, "matrix\n", matrix
newMat = Matrix(matrix).transpose()
print name,"loc: ", newMat.translationPart()
print name,"euler: ", newMat.toEuler()
print name,"scale: ", newMat.scalePart()
def MakeIDXMLConform(id):
'''
Make the name/id COLLADA XML/XSD conform.
See StripString and translateMap docu for more information.
'''
if (len(id) > 0 and id[0] == '#'):
return '#' + string.translate(id[1:], translateMap)
else:
return string.translate(id, translateMap)
def AdjustName(adjustedName):
'''
Make the name/id COLLADA XML/XSD conform.
See StripString and translateMap docu for more information.
'''
if len(adjustedName) > 0 and not adjustedName[0].isalpha():
adjustedName = "i"+adjustedName
return MakeIDXMLConform(adjustedName)
'''
List of error IDs and common strings.
'''
# Expects 1 argument: The mesh name.
# Means that the armature modifier for a mesh couldn't be found,
# probably the parenting is wrong.
ERROR_MESH_ARMATURE_PARENT = 1
MSG_ERROR_FATAL = "Fatal error. Exit script."
def HandleError(failureId, *args):
'''
Prints the error message belonging to the given Id.
May raise an exception if it's a fatal error.
'''
if (failureId == ERROR_MESH_ARMATURE_PARENT):
print("Can't read armature modifier for mesh %s.\n" \
"Most likely your armature isn't correctly parenting the mesh.\n" \
% args[0])
raise MSG_ERROR_FATAL
else:
print("Wrong failure id: %i" % failureId)

View File

@@ -0,0 +1,305 @@
# --------------------------------------------------------------------------
# Illusoft Collada 1.4 plugin for Blender
# --------------------------------------------------------------------------
# ***** BEGIN GPL LICENSE BLOCK *****
#
# Copyright (C) 2006: Illusoft - colladablender@illusoft.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ***** END GPL LICENCE BLOCK *****
# --------------------------------------------------------------------------
import Blender
import collada
from Blender.Mathutils import *
debprn = 0 #False #--- print debug "print 'deb: ..."
class Armature(object):
# static vars
# A list of all created armatures
_armatures = dict()
def __init__(self, armatureBObject, daeNode):
self.armatureBObject = armatureBObject
self.blenderArmature = Blender.Armature.New()
self.armatureBObject.link(self.blenderArmature)
print self.armatureBObject
self.boneInfos = dict()
self.rootBoneInfos = dict()
# The real blender name of this armature
self.realName = None
self.deaNode = daeNode
def GetBlenderObject(self):
return self.armatureBObject
def GetBlenderArmature(self):
return self.blenderArmature
def HasBone(self, boneName):
return boneName in self.boneInfos
def AddNewBone(self, boneName, parentBoneName, daeNode):
# Create a new Editbone.
editBone = Blender.Armature.Editbone()
# Add the bone to the armature
self.blenderArmature.bones[boneName] = editBone
# Get the boneInfo for the parent of this bone. (if it exists)
parentBoneInfo = None
if not parentBoneName is None and parentBoneName in self.boneInfos:
parentBoneInfo = self.boneInfos[parentBoneName]
# Create a new boneInfo object
boneInfo = BoneInfo(boneName, parentBoneInfo, self, daeNode)
# Store the boneInfo object in the boneInfos collection of this armature.
self.boneInfos[boneName] = boneInfo
# If this bone has a parent, set it.
if not parentBoneName is None and parentBoneName in self.boneInfos:
parentBoneInfo = self.boneInfos[parentBoneName]
parentBoneInfo.childs[boneName] = boneInfo
editBone.parent = self.GetBone(parentBoneName)
##boneInfo.SetConnected()
else:
self.rootBoneInfos[boneName] = boneInfo
return boneInfo
def MakeEditable(self,makeEditable):
if makeEditable:
self.GetBlenderArmature().makeEditable()
else:
self.GetBlenderArmature().update()
def GetBone(self, boneName):
if boneName is None or not (boneName in self.blenderArmature.bones.keys()):
return None
else:
return self.blenderArmature.bones[boneName]
# Get the location of the armature (VECTOR)
def GetLocation(self):
return Vector(self.armatureBObject.loc).resize4D()
def GetTransformation(self):
return self.armatureBObject.matrix
def GetBoneInfo(self, boneName):
if boneName is None:
return None
else:
return self.boneInfos[boneName]
def GetBoneInfoFromJoint(self, jointName):
for boneInfo in self.boneInfos:
if boneInfo.jointName == jointName:
return boneInfo
return None
def GetJointList(self):
result = dict()
for boneInfo in self.boneInfos.values():
result[boneInfo.GetJointName()] = boneInfo
return result
#---CLASSMETHODS
# Factory method
def CreateArmature(cls,objectName,armatureName, realArmatureName, daeNode):
armatureBObject = armature_obj = Blender.Object.New ('Armature', objectName)
armatureBObject.name = str(realArmatureName)
armature = Armature(armatureBObject, daeNode)
armature.name = armatureName
cls._armatures[armatureName] = armature
return armature
CreateArmature = classmethod(CreateArmature)
def GetArmature(cls, armatureName):
return cls._armatures.setdefault(armatureName)
GetArmature = classmethod(GetArmature)
def FindArmatureWithJoint(cls, jointName):
for armature in cls._armatures.values():
jointList = armature.GetJointList()
if jointName in jointList:
return armature
return None
FindArmatureWithJoint = classmethod(FindArmatureWithJoint)
class BoneInfo(object):
def __init__(self, boneName, parentBoneInfo, armature, daeNode):
if debprn: print 'deb:class BoneInfo_INITIALIZE............' #--------
if debprn: print 'deb: boneName=', boneName #--------
if debprn: print 'deb: parentBoneInfo=', #--------
if parentBoneInfo: print parentBoneInfo.name #, parentBoneInfo #--------
else: print parentBoneInfo #--------
#if debprn: print 'deb: armature=', #--------
#if armature: print armature.name #, armature #--------
#else: print armature, #--------
self.name = boneName
self.parent = parentBoneInfo
self.armature = armature
self.childs = dict()
self.daeNode = daeNode
self.headTransformMatrix = None
self.tailTransformMatrix = None
self.localTransformMatrix = Matrix()
self.worldTransformMatrix = Matrix()
def GetBone(self):
return self.armature.GetBone(self.name)
def SetTail(self, tailLocVector):
if len(tailLocVector) == 4:
tailLocVector.resize3D()
self.GetBone().tail = tailLocVector
def GetTail(self):
return self.GetBone().tail
def SetHead(self, headLocVector):
if len(headLocVector) == 4:
headLocVector.resize3D()
self.GetBone().head = headLocVector
def GetHead(self):
return self.GetBone().head
def SetConnected(self):
self.GetBone().options = Blender.Armature.CONNECTED
def IsEnd(self):
return len(self.childs) == 0
def IsRoot(self):
return self.parent is None
def GetTailName(self):
return self.daeNode.name
def GetJointName(self):
return self.name
## if not self.parent is None:
## return self.parent.name
## else:
## return self.armature.name
class AnimationInfo(object):
_animations = dict()
def __init__(self, nodeId):
self.nodeId = nodeId
self.times = dict()
def GetTypes(self, daeNode):
types = []
if len(self.times) > 0:
for target in self.times.values()[0]:
ta = self.GetType(daeNode, target)
if ta[0] == collada.DaeSyntax.TRANSLATE and not Blender.Object.Pose.LOC in types:
types.append(Blender.Object.Pose.LOC)
elif ta[0] == collada.DaeSyntax.ROTATE and not Blender.Object.Pose.ROT in types:
types.append(Blender.Object.Pose.ROT)
#TODO: check if scale correct implemented
elif ta[0] == collada.DaeSyntax.SCALE and not Blender.Object.Pose.SCALE in types:
types.append(Blender.Object.Pose.SCALE)
return types
def GetType(self, daeNode, target):
ta = target.split('.', 1)
for t in daeNode.transforms:
if t[2] == ta[0]:
return [t[0], ta]
def CreateAnimations(cls, animationsLibrary, fps, axiss):
for daeAnimation in animationsLibrary.daeLibrary.items:
for channel in daeAnimation.channels:
# Get the id of the node
targetArray = channel.target.split("/", 1)
nodeId = targetArray[0]
targetId = targetArray[1]
# Get the animationInfo object for this node (or create a new one)
animation = cls._animations.setdefault(nodeId, AnimationInfo(nodeId))
#if debprn: print 'deb:helperObj.py:class AnimationInfo CreateAnimations() dir(animation)', dir(animation) #----------
# loop trough all samplers
sampler = None
if debprn: print 'deb:helperObj.py:class AnimationInfo CreateAnimations() \ndeb: channel.source= ', channel.source #----------
for s in daeAnimation.samplers:
#if debprn: print 'deb: sampler.id = ', s.id #----------
#if debprn: print 'deb: channel.source[1:]= ', channel.source[1:] #----------
#org if s.id == channel.source[1:]:
if s.id == channel.source:
sampler = s
# Get the values for all the inputs
if not sampler is None:
input = sampler.GetInput("INPUT")
inputSource = daeAnimation.GetSource(input.source)
if inputSource.techniqueCommon.accessor.HasParam("TIME") and len(inputSource.techniqueCommon.accessor.params) == 1:
if debprn: print 'deb: DDDDD getting target' #----------
output = sampler.GetInput("OUTPUT")
outputSource = daeAnimation.GetSource(output.source)
outputAccessor = outputSource.techniqueCommon.accessor
accessorCount = outputAccessor.count
accessorStride = outputAccessor.stride
interpolations = sampler.GetInput("INTERPOLATION")
interpolationsSource = daeAnimation.GetSource(interpolations.source)
if 0: #because probably interpolationsAccessor is identical to outputAccessor
interpolationsAccessor = interpolationsSource.techniqueCommon.accessor
accessorCount = interpolationsAccessor.count
accessorStride = interpolationsAccessor.stride
if debprn: print 'deb: outputSource.source.data: ', outputSource.source.data #----------
#if debprn: print 'deb: dir(outputAccessor.params): ', dir(outputAccessor.params) #----------
#if debprn: print 'deb: dir(outputAccessor.params[0]): ', str(outputAccessor.params[0]) #----------
times = [x*fps for x in inputSource.source.data]
if debprn: print 'deb: times=', times #---------
for timeIndex in range(len(times)):
time = animation.times.setdefault(times[timeIndex], dict())
target = time.setdefault(targetId, dict())
#interp = time.setdefault(targetId, dict())
#if debprn: print 'deb: accessorStride=', accessorStride #---------
value = []
for j in range(accessorStride):
#if debprn: print 'deb: timeIndex,j,data=',timeIndex, j, outputSource.source.data[timeIndex*accessorStride + j] #---------
#if debprn: print 'deb: outputAccessor.params[j]=',outputAccessor.params[j] #---------
#target[outputAccessor.params[j]] = outputSource.source.data[timeIndex*accessorStride + j]
value.append(outputSource.source.data[timeIndex*accessorStride + j])
if debprn: print 'deb: value=', value #---------
target[outputAccessor.params[0]] = value
#interp[outputAccessor.params[j]] = interpolationsSource.source.data[timeIndex*accessorStride + j]
if debprn: print 'deb: time=', time #---------
if debprn: print 'deb: target=', target #---------
#if debprn: print 'deb:helperObj.py: X X X X X X X X X class AnimationInfo CreateAnimations() animation=', animation #----------
CreateAnimations = classmethod(CreateAnimations)
def GetAnimationInfo(cls, nodeId):
for animation in cls._animations.values():
if animation.nodeId == nodeId:
return animation
return None
GetAnimationInfo = classmethod(GetAnimationInfo)

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,183 @@
# --------------------------------------------------------------------------
# Illusoft Collada 1.4 plugin for Blender
# --------------------------------------------------------------------------
# ***** BEGIN GPL LICENSE BLOCK *****
#
# Copyright (C) 2006: Illusoft - colladablender@illusoft.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ***** END GPL LICENCE BLOCK *****
# --------------------------------------------------------------------------
from datetime import *
from cutils import *
from xml.dom.minidom import *
debprn = False #--- print debug "print 'deb: ..."
#---XML Utils---
# Returns the first child of the specified type in node
def FindElementByTagName(parentNode, type):
child = parentNode.firstChild
while child != None:
if child.localName == type:
return child
child = child.nextSibling
## childs = parentNode.getElementsByTagName(type)
## if len(childs) > 0:
## return childs[0]
return None
def FindElementsByTagName(parentNode, type):
result = []
child = parentNode.firstChild
while child != None:
if child.localName == type:
result.append(child)
child = child.nextSibling
return result
def ReadAttribute(node,attributeName):
if node != None and attributeName != None:
attribute = node.getAttribute(attributeName)
return attribute
return None
def ReadContents(node):
if node != None:
child = node.firstChild
if child != None and child.nodeType == child.TEXT_NODE:
return child.nodeValue
return None
def ReadDateTime(node):
if node == None:
return None
return GetDateTime(ReadContents(node))
def RemoveWhiteSpace(parent):
for child in list(parent.childNodes):
if child.nodeType==child.TEXT_NODE and child.data.strip()=='':
parent.removeChild(child)
else:
RemoveWhiteSpace(child)
def RemoveWhiteSpaceNode(parent):
for child in list(parent.childNodes):
if child.nodeType == child.TEXT_NODE and child.data.strip()=='':
parent.removeChild(child)
return parent
def RemoveComments(parent):
for child in list(parent.childNodes):
if child.__class__.__name__ == "Comment":
parent.removeChild(child)
return parent
##def RemoveWhiteSpace(node):
## removeList = []
## for child in node.childNodes:
## if child.nodeType == child.TEXT_NODE and not child.data.strip():
## removeList.append(child)
## elif child.hasChildNodes():
## RemoveWhiteSpace(child)
##
## for node in removeList:
## node.parentNode.removeChild(node)
def GetDateTime(xmlvalue):
vals = xmlvalue.split('T')
datestr = vals[0]
timestr = vals[1]
date = datestr.split('-')
time = timestr.split(':')
time[2]=time[2].rstrip('Z')
return datetime(int(date[0]), int(date[1]), int(date[2]),int(time[0]), int(time[1]), int(float(time[2])))
def ToDateTime(val):
return '%s-%s-%sT%s:%s:%sZ'%(val.year,str(val.month).zfill(2),str(val.day).zfill(2), str(val.hour).zfill(2), str(val.minute).zfill(2),str(val.second).zfill(2))
def GetStringArrayFromNodes(xmlNodes):
vals = []
if xmlNodes == None:
return vals
for xmlNode in xmlNodes:
stringvals = ReadContents(xmlNode).split( )
for string in stringvals:
vals.append(string)
return vals
def GetListFromNodes(xmlNodes, cast=None):
result = []
if xmlNodes is None:
return result
for xmlNode in xmlNodes:
val = ReadContents(xmlNode).split( )
if cast == float:
val = ToFloatList(val)
elif cast == int:
val = ToIntList(val)
elif cast == bool:
val = ToBoolList(val)
result.append(val)
return result
def ToXml(xmlNode, indent='\t', newl='\n'):
return '<?xml version="1.0" encoding="utf-8"?>\n%s'%(__ToXml(xmlNode, indent,newl))
def __ToXml(xmlNode, indent='\t',newl='\n',totalIndent=''):
childs = xmlNode.childNodes
if len(childs) > 0:
attrs = ''
attributes = xmlNode.attributes
if attributes != None:
for attr in attributes.keys():
val = attributes[attr].nodeValue
attrs += ' %s="%s"'%(attr,val)
result = '%s<%s%s>'%(totalIndent,xmlNode.localName,attrs)
tempnewl = newl
tempTotIndent = totalIndent
for child in childs:
if child.nodeType == child.TEXT_NODE:
tempnewl = ''
tempTotIndent = ''
result += '%s%s'%(tempnewl,__ToXml(child, indent, newl, totalIndent+indent))
result += '%s%s</%s>'%(tempnewl,tempTotIndent,xmlNode.localName)
return result
else:
if xmlNode.nodeType == xmlNode.TEXT_NODE:
return xmlNode.toxml().replace('\n','\n'+totalIndent[:-1])
else:
return totalIndent+xmlNode.toxml()
def AppendChilds(xmlNode, syntax, lst):
if lst is None or syntax is None or xmlNode is None:
return
for i in lst:
el = Element(syntax)
text = Text()
text.data = ListToString(i)
el.appendChild(text)
xmlNode.appendChild(el)
return xmlNode