Пример #1
0
def removeCustomScriptLink():

	"""
	Removes the custom script link (if it is present) from the
	scene.
	"""
	
	try:
		txt = Text.Get(SCRIPTLINK_NAME)
	except NameError:    # script link not found
		return
	
	scene = Scene.GetCurrent()
	slinks = scene.getScriptLinks('Redraw')
	if slinks is not None:
		scene.clearScriptLinks()
		if SCRIPTLINK_NAME in slinks:
			slinks.remove(SCRIPTLINK_NAME)
		for link in slinks:
			scene.addScriptLink(link, 'Redraw')
	
	Text.unlink(txt)

	# do a full scene update
	Scene.GetCurrent().update(1)
Пример #2
0
def Invoke(exporter=EXPORTER_NAME, use_stored=False, progress_range=None,
		filename = None, selection = None, anims = None, tools = None,
			optparms = None, mextract = False, animonly = False):
	'''
	Invokes Chicken exporter in Forced Background mode
	@param exporter: Specific filename for Chicken, defaults to the version that came with this module
	@param use_stored: Boolean that indicates whether to use stored parameters for export.
	@param progress_range: sequence of 2 floats that defines the range of progress this represents of the total operation
	@param filename: The destination filename. Defaults to working filename
	@param selection: A list of strings containing the names of the selected objects. Defaults to current selection
	@param anims: A list of 4-lists containing [animation-name, fps, start, end]
	@param tools: A 3-tuple containing booleans that indicate whether to invoke pview, egg2bam, and egg-optchar in that order.
	@param optparms: Optional parameters for egg-optchar. Defaults to '-inplace'
	@param mextract: Boolean that indicates whether to attempt motion extraction. Default is False.
	@param animonly: Boolean that indicates that only animation should be exported.
	@return: False if exporter not found, a tuple of the form (pre-export messages, post-export messages)
		if succesful (True is returned if messages were unattainable).
	'''
	result = True
	os.environ[KEY] = 'yes' # arbitrary value, chicken only cares that it is set
	if progress_range and len(progress_range) == 2:
		os.environ[RANGE_KEY] = '%f,%f'%tuple(progress_range)
	if not use_stored:
		# make settings
		settings = Text.New('interface.chicken')
		os.environ[SETTINGS_KEY] = settings.getName()
		settings.write(MakeSettings(filename, selection, anims, tools, optparms, mextract, animonly))
	try:
		Blender.Run(os.path.join(Blender.Get('scriptsdir'),exporter))
	except AttributeError:
		result = False
	if result:
		try:
			msg_txt = Text.Get(os.getenv(MESSAGE_KEY))
		except: pass
		else:
			try:
				msg_str = '\n'.join(msg_txt.asLines())
				import cPickle
				result = cPickle.loads(msg_str)
			except: print sys.exc_info()
			Text.unlink(msg_txt)
	if not use_stored:
		# delete temp settings
		Text.unlink(settings)
		del os.environ[SETTINGS_KEY]
	del os.environ[KEY]
	if os.environ.has_key(MESSAGE_KEY):
		del os.environ[MESSAGE_KEY]
	if os.environ.has_key(RANGE_KEY):
		del os.environ[RANGE_KEY]
	return result
Пример #3
0
def loadmodel(file, words, data):
  def nwprop(file, words, data):
    data['nwnprops'].write('SCENE.%s=%s\n'%(words[0], words[1]))
  modeldict={'beginmodelgeom': loadgeometry, 'donemodel': linereaderbreak,
        'classification': nwprop, 'supermodel': nwprop, 'newanim': loadanim}
  data={'scene': Scene.getCurrent(), 'nwnprops': Text.New('nwnprops'),
          'animnextframe': 2, 'nwnanims': Text.New('nwnanims'), 'fps': 30}
  raise ExitLineReader(linereader(file, modeldict, data))
  # Seems I can't modify the frame settings.
  #data['scene'].startFrame(1)
  #data['scene'].currentFrame(1)
  #data['scene'].endFrame(data['animnextframe']-1)
  data['scene'].update()
Пример #4
0
def parse():
    proptxt = Text.get('nwnprops')
    if not proptxt:
        putlog(
            NBLog.WARNING, "Unable to find the configuration ('nwnprops'.) " +
            "Using defaults...", "Props")
        return
        putlog(NBLog.SPAM, "Found configuration, parsing.", "Props")
    lines = proptxt.asLines()
    for l in lines:
        # Ignore comment lines and empty lines.
        if len(l) == 0:
            continue
        if l[0] == '#':
            continue
        # Find the separators.
        try:
            objectsep = l.index('.')
            valuesep = l.index('=', objectsep)
        except ValueError:
            putlog(NBLog.WARNING,
                   "Ignoring following conf entry " + "(invalid format): " + l,
                   "Props")
            continue
        object = l[0:objectsep]
        property = l[objectsep + 1:valuesep]
        value = l[valuesep + 1:]
        if not nwnprops.has_key(object):
            nwnprops[object] = {}
        nwnprops[object][property] = value
Пример #5
0
def parse():
	proptxt = Text.get('nwnprops')
	if not proptxt:
		putlog(NBLog.WARNING,
		       "Unable to find the configuration ('nwnprops'.) " +
		       "Using defaults...", "Props")
		return
		putlog(NBLog.SPAM, "Found configuration, parsing.", "Props")
	lines = proptxt.asLines()
	for l in lines:
		# Ignore comment lines and empty lines.
		if len(l) == 0:
			continue
		if l[0] == '#':
			continue
		# Find the separators.
		try:
			objectsep=l.index('.')
			valuesep=l.index('=', objectsep)
		except ValueError:
			putlog(NBLog.WARNING,
			       "Ignoring following conf entry " +
			       "(invalid format): " + l, "Props")
			continue
		object = l[0:objectsep]
		property = l[objectsep+1:valuesep]
		value = l[valuesep+1:]
		if not nwnprops.has_key(object):
			nwnprops[object] = {}
		nwnprops[object][property] = value
Пример #6
0
def save_track_metadata():
  global track_info, track_lists
  config = ConfigParser.RawConfigParser()
  # load all the data into the ConfigParser object
  config.add_section("trackinfo")
  for key,value in track_info.iteritems():
    config.set("trackinfo", key, value)
  for track_list in track_lists.keys():
    i = 0
    config.set("trackinfo", "num_%s" % (track_list), len(track_lists[track_list]))
    if track_list == "lap_sequences" or track_list == "road_segments":
      section = track_list
      config.add_section(section)
      for track_list_item in track_lists[track_list]:
        key = "%s_%d" % (track_list.rstrip('s'), i)
        config.set(section, key, track_list_item)
        i += 1
    else:
      for track_list_item in track_lists[track_list]:
        section = "%s.%d" % (track_list, i)
        config.add_section(section)
        keys = []
        if track_list == "surfaces":
          keys = new_track_surface_type("").keys()
        elif track_list == "start_points":
          keys = new_track_start_point("", "").keys()
        for key in keys:
          config.set(section, str(key), track_list_item[key])
        i += 1
  temp_filename = "%s/%s.%s.%s.config" % \
    (tempfile.gettempdir(),
    tempfile.gettempprefix(),
    metadata_text_id,
    time.strftime("%Y%m%d-%H%M"))
  with open(temp_filename, 'wb') as temp_file:
    config.write(temp_file)
  track_metadata_text = Text.Load(temp_filename)
  os.unlink(temp_filename)
  track_metadata_text.fakeUser = True
  t = None
  try:
    t = Text.Get(metadata_text_id)
  except NameError as e:
    pass # doesn't exist, don't need to remove it
  else:
    Text.unlink(t)
  track_metadata_text.setName(metadata_text_id)
Пример #7
0
def addCustomScriptLink():
    """
	Adds a custom script link to the scene so that all script
	windows are redrawn whenever the scene is redrawn.
	"""

    txt = Text.New(SCRIPTLINK_NAME)
    txt.write('import Blender\n')
    txt.write('from Blender import Window\n')
    txt.write('Window.Redraw(Window.Types.SCRIPT)\n')
    Scene.GetCurrent().addScriptLink(SCRIPTLINK_NAME, 'Redraw')

    # do a full scene update
    Scene.GetCurrent().update(1)
Пример #8
0
def removeCustomScriptLink():
    """
	Removes the custom script link (if it is present) from the
	scene.
	"""

    try:
        txt = Text.Get(SCRIPTLINK_NAME)
    except NameError:  # script link not found
        return

    scene = Scene.GetCurrent()
    slinks = scene.getScriptLinks('Redraw')
    if slinks is not None:
        scene.clearScriptLinks()
        if SCRIPTLINK_NAME in slinks:
            slinks.remove(SCRIPTLINK_NAME)
        for link in slinks:
            scene.addScriptLink(link, 'Redraw')

    Text.unlink(txt)

    # do a full scene update
    Scene.GetCurrent().update(1)
Пример #9
0
def Invoke(exporter=EXPORTER_NAME,
           use_stored=False,
           progress_range=None,
           filename=None,
           selection=None,
           anims=None,
           tools=None,
           optparms=None,
           mextract=False,
           animonly=False):
    '''
	Invokes Chicken exporter in Forced Background mode
	@param exporter: Specific filename for Chicken, defaults to the version that came with this module
	@param use_stored: Boolean that indicates whether to use stored parameters for export.
	@param progress_range: sequence of 2 floats that defines the range of progress this represents of the total operation
	@param filename: The destination filename. Defaults to working filename
	@param selection: A list of strings containing the names of the selected objects. Defaults to current selection
	@param anims: A list of 4-lists containing [animation-name, fps, start, end]
	@param tools: A 3-tuple containing booleans that indicate whether to invoke pview, egg2bam, and egg-optchar in that order.
	@param optparms: Optional parameters for egg-optchar. Defaults to '-inplace'
	@param mextract: Boolean that indicates whether to attempt motion extraction. Default is False.
	@param animonly: Boolean that indicates that only animation should be exported.
	@return: False if exporter not found, a tuple of the form (pre-export messages, post-export messages)
		if succesful (True is returned if messages were unattainable).
	'''
    result = True
    os.environ[
        KEY] = 'yes'  # arbitrary value, chicken only cares that it is set
    if progress_range and len(progress_range) == 2:
        os.environ[RANGE_KEY] = '%f,%f' % tuple(progress_range)
    if not use_stored:
        # make settings
        settings = Text.New('interface.chicken')
        os.environ[SETTINGS_KEY] = settings.getName()
        settings.write(
            MakeSettings(filename, selection, anims, tools, optparms, mextract,
                         animonly))
    try:
        Blender.Run(os.path.join(Blender.Get('scriptsdir'), exporter))
    except AttributeError:
        result = False
    if result:
        try:
            msg_txt = Text.Get(os.getenv(MESSAGE_KEY))
        except:
            pass
        else:
            try:
                msg_str = '\n'.join(msg_txt.asLines())
                import cPickle
                result = cPickle.loads(msg_str)
            except:
                print sys.exc_info()
            Text.unlink(msg_txt)
    if not use_stored:
        # delete temp settings
        Text.unlink(settings)
        del os.environ[SETTINGS_KEY]
    del os.environ[KEY]
    if os.environ.has_key(MESSAGE_KEY):
        del os.environ[MESSAGE_KEY]
    if os.environ.has_key(RANGE_KEY):
        del os.environ[RANGE_KEY]
    return result
open the destination blend, paste)

Save the .blend containing the objects you want to copy first, even if it already has
a filename, only saved objects can be copied (if you had altered something, then save).
"""

import Blender
from Blender import Draw, Text, Library, Object

choice = Draw.PupMenu("Copy object(s) to buffer|Paste object(s) from buffer")
if choice == 1:
    objs = Object.GetSelected()
    if len(objs) == 0:
        Draw.PupMenu("Please select at least 1 object!")
    else:
        txt = open(Blender.Get("datadir") + "/buffer", "w")
        txt.write(Blender.Get("filename") + "\n")
        for item in objs:
            txt.write(item.getName() + "\n")
        txt.close()
elif choice == 2:
    txt = Text.Load(Blender.Get("datadir") + "/buffer")
    buffer = txt.asLines()
    Library.Open(buffer[0])
    buffer.pop(0)
    for item in buffer:
        Library.Load(item, "Object", 0)
    Library.Update()
    Library.Close()
    Text.unlink(txt)
    Blender.Redraw()
Пример #11
0
def buttonEvt(evt):
    global evtExport, evtPathChanged, evtBrows, evtExportSelection, exportSelection, exportNormals, exportTriangulated
    global exportPath
    global guiPopup
    if evt == evtExport:
        i3d = I3d()
        sce = bpy.data.scenes.active
        if exportSelection:
            for obj in sce.objects.selected:
                i3d.addObject(obj)
        else:
            for obj in sce.objects:
                i3d.addObject(obj)
        i3d.printToFile(exportPath.val)

        print("exported to %s" % exportPath.val)
    if evt == evtPathChanged:
        pass
    if evt == evtBrows:
        Window.FileSelector(selectExportFile, "Ok", exportPath.val)
    if evt == evtExportSelection:
        exportSelection = 1 - exportSelection
        Draw.Redraw(1)
    if evt == evtExportNormals:
        exportNormals = 1 - exportNormals
        Draw.Redraw(1)
    if evt == evtExportTriangulated:
        exportTriangulated = 1 - exportTriangulated
        Draw.Redraw(1)
    if evt == evtAddObjExtension:
        activeObj = bpy.data.scenes.active.objects.active
        slName = "%s.i3d" % activeObj.name
        sl = None
        try:
            sl = Text.Get(slName)
        except:
            sl = None
        if not sl is None:
            guiPopup = Draw.PupMenu(
                "%s already exists. Find it in the Text Editor" % slName)
        else:
            sl = Text.New(slName)
            sl.write("""<!--
this describes some i3d properties of the object it is linked to via Script Links.
the name of this text file must end with ".i3d".
all attributes of the SceneType node are copied to the Object in the final i3d.
"i3dNodeId" is replaced by the id the object gets in the i3d scene.
For the UserAttributes to work the attribute nodeId must be "i3dNodeId".
-->
<i3D>
	<Scene>
		<SceneType static="true" dynamic="false" kinematic="false"/>
	</Scene>
	<UserAttributes>
		<UserAttribute nodeId="i3dNodeId">
			<Attribute name="onCreate" type="scriptCallback" value="print"/>
		</UserAttribute>
	</UserAttributes>
</i3D>""")
            activeObj.addScriptLink(sl.getName(), "FrameChanged")
            guiPopup = Draw.PupMenu(
                "Check ScriptLink panel and Text Editor for %s" % sl.getName())
    if evt == evtAddMatExtension:
        activeObj = bpy.data.scenes.active.objects.active
        activeMat = activeObj.getData().materials[activeObj.activeMaterial - 1]
        slName = "%s.i3d" % activeMat.name
        sl = None
        try:
            sl = Text.Get(slName)
        except:
            sl = None
        if not sl is None:
            guiPopup = Draw.PupMenu(
                "%s already exists. Find it in the Text Editor" % slName)
        else:
            sl = Text.New(slName)
            sl.write("""<!--
this describes some i3d properties of the material it is linked to via Script Links.
the name of this text file must end with ".i3d".
all attribute values starting with "assets/" are added to the Files Node and replaced with the id.
in order for file references to work the path must start with "assets/".
-->
<i3D>
	<Materials>
		<Material customShaderId="assets/exampleCustomShader.xml">
			<Custommap name="colorRampTexture" fileId="assets/exampleCustomMap.png"/>
			<CustomParameter name="exampleParameter" value="2 0 0 0"/>	
		</Material>
	</Materials>
</i3D>""")
            activeMat.addScriptLink(sl.getName(), "FrameChanged")
            guiPopup = Draw.PupMenu(
                "Check ScriptLink panel and Text Editor for %s" % sl.getName())
Пример #12
0
    def addMaterial(self, mat):
        tangents = false
        if mat is None:
            if not self.defaultMat:  #create a nice pink default material
                self.lastMaterialId = self.lastMaterialId + 1
                m = self.doc.createElement("Material")
                m.setAttribute("name", "Default")
                #m.setAttribute("materialId", "%i"%self.lastMaterialId)
                m.setAttribute("diffuseColor", "%f %f %f %f" % (1, 0, 1, 1))
                self.materials.appendChild(m)
                self.defaultMat = self.lastMaterialId
            return self.defaultMat, false

        for m in self.materials.getElementsByTagName("Material"):
            if m.getAttribute("name") == mat.getName():
                if len(m.getElementsByTagName("Normalmap")) > 0:
                    tangents = true
                return int(
                    m.getAttribute("materialId")), tangents  #todo: tangents!!!
        m = self.doc.createElement("Material")
        m.setAttribute("name", mat.name)
        self.lastMaterialId = self.lastMaterialId + 1
        #m.setAttribute("materialId", "%i" % self.lastMaterialId)

        m.setAttribute(
            "diffuseColor", "%f %f %f %f" %
            (mat.getRGBCol()[0] * mat.ref, mat.getRGBCol()[1] * mat.ref,
             mat.getRGBCol()[2] * mat.ref, mat.getAlpha()))
        if mat.getAlpha() < 1:
            m.setAttribute("alphaBlending", "true")
        m.setAttribute(
            "specularColor", "%f %f %f" %
            (mat.specR * mat.spec, mat.specG * mat.spec, mat.specB * mat.spec))
        m.setAttribute("cosPower", "%i" % (mat.getHardness()))

        if mat.getMode() & Material.Modes['NOMIST']:
            m.setAttribute("allowFog", "false")

        texturN = 0
        for textur in mat.getTextures():
            texturEnabled = 0
            for t in mat.enabledTextures:
                if t == texturN:
                    texturEnabled = 1
                    break
            if texturEnabled:
                if textur.tex.getImage() is None or textur.tex.getImage(
                ).getFilename() is None:
                    print(
                        "WARNING: cannot export texture named %s, its not an image!"
                        % textur.tex.getName())
                else:
                    path = textur.tex.getImage().getFilename()
                    backslash = path.rfind("/")
                    if not backslash == -1:
                        path = path[
                            backslash +
                            1:]  #cut eveerything infront of the filename. will this work on windows? todo: test

                    #print("path %s" %path)
                    #path = "assets/"+path
                    if textur.mtCol:  #Map To Col
                        i3dTex = self.doc.createElement("Texture")
                        i3dTex.setAttribute("name", "%i" % self.addFile(path))
                        m.appendChild(i3dTex)
                    if textur.mtNor:  #Map To Nor
                        if textur.mtNor == -1:
                            print(
                                "WARNING: normalmap %s cannot be inverted by the exporter"
                                % textur.tex.getName())
                        i3dTex = self.doc.createElement("Normalmap")
                        i3dTex.setAttribute("name", "%i" % self.addFile(path))
                        m.appendChild(i3dTex)
                        tangents = true
                    if textur.mtCsp:  #Map To Spec
                        if textur.mtSpec == -1:
                            print(
                                "WARNING: specularmap %s cannot be inverted by the exporter"
                                % textur.tex.getName())
                        i3dTex = self.doc.createElement("Glossmap")
                        i3dTex.setAttribute("name", "%i" % self.addFile(path))
                        m.appendChild(i3dTex)
                    #todo: other maps
            texturN = texturN + 1

        #parse material ScriptLink file and merge xml into i3d (if it ends with .i3d)
        for sl in mat.getScriptLinks("FrameChanged") + mat.getScriptLinks(
                "Render") + mat.getScriptLinks("Redraw") + mat.getScriptLinks(
                    "ObjectUpdate") + mat.getScriptLinks("ObDataUpdate"):
            if sl.endswith(".i3d"):
                xmlText = ""
                for l in Text.Get(sl).asLines():
                    xmlText = xmlText + l
                slDom = None
                try:
                    slDom = parseString(xmlText)
                except:
                    print "WARNING: cant parse material script link %s" % sl
                    slDom = None
                if not slDom is None:
                    for n in slDom.getElementsByTagName("Material"):
                        i = 0
                        while i < n.attributes.length:  #coppy attributes
                            attr = n.attributes.item(i)
                            if attr.nodeValue.startswith("assets/"):
                                m.setAttribute(
                                    attr.nodeName,
                                    "%i" % self.addFile(attr.nodeValue))
                            else:
                                m.setAttribute(attr.nodeName, attr.nodeValue)
                            i = i + 1
                        for cn in n.childNodes:  #coppy child elements
                            if cn.nodeType == cn.ELEMENT_NODE:
                                #print cn
                                if not cn.attributes is None:
                                    i = 0
                                    while i < cn.attributes.length:
                                        attr = cn.attributes.item(i)
                                        if attr.nodeValue.startswith(
                                                "assets/"):
                                            attr.nodeValue = "%i" % self.addFile(
                                                attr.nodeValue)
                                        i = i + 1
                                m.appendChild(cn)

        self.materials.appendChild(m)
        return self.lastMaterialId, tangents
Пример #13
0
    def addObject(self, obj):  #adds a scene node.
        #print("add object %s" %(obj.getName()))
        node = None
        parentNode = self.scene
        if not obj.getParent() is None:
            #searching parent asuming it is already in i3d (must export ordered by hyrarchie)
            for sceneNode in self.scene.getElementsByTagName("Shape"):
                if sceneNode.getAttribute("name") == obj.getParent().getName():
                    parentNode = sceneNode
                    break
            if parentNode == self.scene:
                for sceneNode in self.scene.getElementsByTagName(
                        "TransformGroup"):
                    if sceneNode.getAttribute(
                            "name") == obj.getParent().getName():
                        parentNode = sceneNode
                        break
            if parentNode == self.scene:
                print("  parent not found!")
        rotX90 = 0

        if obj.type == "Mesh":
            #need armature parent data
            #parentArmBones holds the names of the bones and the i3d nodeId

            node = self.doc.createElement("Shape")
            shapeId, materialIds = self.addMesh(obj.getData(mesh=1),
                                                self.parentArmBones)
            #node.setAttribute("shapeId", "%i" %(shapeId))
            node.setAttribute("ref", "%s" % (obj.getData(mesh=1).name))

            if not self.parentArmBones is None:
                skinBindNodeIds = ""
                for pab in self.parentArmBones:
                    if skinBindNodeIds == "":
                        skinBindNodeIds = "%i" % (pab[1])
                    else:
                        skinBindNodeIds = "%s %i" % (skinBindNodeIds, pab[1])
                node.setAttribute("skinBindNodeIds", skinBindNodeIds)
                self.parentArmBones = None

            #shading propertys stored per object in giants: getting them from first blender material
            if len(obj.getData(mesh=1).materials) > 0:
                if obj.getData(mesh=1).materials[0]:
                    mat = obj.getData(mesh=1).materials[0]
                    if mat.getMode() & Material.Modes['SHADOWBUF']:
                        node.setAttribute("castsShadows", "true")
                    else:
                        node.setAttribute("castsShadows", "false")
                    if mat.getMode() & Material.Modes['SHADOW']:
                        node.setAttribute("receiveShadows", "true")
                    else:
                        node.setAttribute("receiveShadows", "false")
            else:
                node.setAttribute("castsShadows", "false")
                node.setAttribute("receiveShadows", "false")
        elif obj.type == "Empty":
            node = self.doc.createElement("TransformGroup")
        elif obj.type == "Armature":
            node = self.doc.createElement("TransformGroup")
            #self.parentArmBones = self.addArmature(node, obj.getData())
            #self.parentArmBones = self.addArmature(parentNode, obj.getData(), obj)
            self.parentArmBones = self.addArmature(node, obj.getData(), obj)
            #self.armaturesMap.append({0:obj.name, 1:self.parentArmBones})
        elif obj.type == "Camera":
            rotX90 = 1
            node = self.doc.createElement("Camera")
            node.setAttribute("fov", "%f" % (obj.getData().lens))
            node.setAttribute("nearClip", "%f" % (obj.getData().clipStart))
            node.setAttribute("farClip", "%f" % (obj.getData().clipEnd))
        elif obj.type == "Lamp":
            rotX90 = 1
            node = self.doc.createElement("Light")
            lamp = obj.getData()
            lampType = ["point", "directional", "spot", "ambient"]
            if lamp.getType() > 3:
                node.setAttribute("type", lampType[0])
                print("WARNING: lamp type not supported")
            else:
                node.setAttribute("type", lampType[lamp.getType()])
            node.setAttribute(
                "diffuseColor",
                "%f %f %f" % (lamp.R * lamp.energy, lamp.G * lamp.energy,
                              lamp.B * lamp.energy))
            node.setAttribute("emitDiffuse", "true")
            node.setAttribute(
                "specularColor",
                "%f %f %f" % (lamp.R * lamp.energy, lamp.G * lamp.energy,
                              lamp.B * lamp.energy))
            node.setAttribute("emitSpecular", "true")
            node.setAttribute("decayRate", "%f" % (5000 - lamp.getDist()))
            node.setAttribute("range", "500")
            if lamp.getMode() & lamp.Modes['Shadows']:
                node.setAttribute("castShadowMap", "true")
            else:
                node.setAttribute("castShadowMap", "false")
            node.setAttribute("depthMapBias", "%f" % (lamp.bias / 1000))
            node.setAttribute("depthMapResolution", "%i" % lamp.bufferSize)
            node.setAttribute("coneAngle", "%f" % (lamp.getSpotSize()))
            node.setAttribute("dropOff", "%f" %
                              (lamp.getSpotBlend() *
                               5))  #dropOff seems to be between 0 and 5 right?

        if not node is None:
            node.setAttribute("name", obj.getName())
            #self.lastNodeId = self.lastNodeId + 1
            #node.setAttribute("nodeId", "%i" %(self.lastNodeId))

            # getLocation("localspace") seems to be buggy!
            # http://blenderartists.org/forum/showthread.php?t=117421
            localMat = Mathutils.Matrix(obj.matrixLocal)
            #self.setTranslation(node, obj.getLocation("localspace"))
            self.setTranslation(node, localMat.translationPart())
            #self.setRotation(node, localMat.rotationPart().toEuler(), rotX90)
            self.setRotation(node, obj.getEuler("localspace"), rotX90)
            parentNode.appendChild(node)

            #Todo....
            #Export the animations, assuming obj is an armature, hopefully it will also work with objects
            #only the active action (=clip) is exported
            """
			action = obj.getAction()
			if not action is None:
				print("exporting animation: "+action.getName())
				animSet = self.doc.createElement("AnimationSet")
				animSet.setAttribute("name", obj.getName())#AnimationSets are equivalent to blenders NLA, only one per object
				
				clip = self.doc.createElement("Clip")
				clip.setAttribute("name", action.getName())
				print self.parentArmBones
				print action.getFrameNumbers()#the keyframes (would be nice to have them per channel)
				for channel in action.getChannelNames():
					print " "+channel
					key_NodeId = self.lastNodeId
					if not self.parentArmBones is None:
						for nameId in self.parentArmBones:
							if nameId[0] == channel:
								key_NodeId = nameId[1]
					keyframes = self.doc.createElement("Keyframes")
					keyframes.setAttribute("nodeId", "%i"%key_NodeId)
					
					ipo = action.getChannelIpo(channel)
					for curve in ipo:
						print "  "+curve.name
						for bezTri in curve.bezierPoints:
							time, value = bezTri.pt
						#ohoh, now the rotation would have to be calculated from Quats...
						
						#another aproach would be to set the time of the global timeline to the keyframe times
						#and then get the data from the object.getPose() which returns the current pose. (probably eazyer, but might result in redundant data)
						
					clip.appendChild(keyframes)
				#clip.setAttribute("duration", 
				animSet.appendChild(clip)
				#print("chanels: ")
				#print(action.getChannelNames())
				
				self.animationSets.appendChild(animSet)
			"""

            #parse ScriptLink file and merge xml into i3d
            for sl in obj.getScriptLinks("FrameChanged") + obj.getScriptLinks(
                    "Render"
            ) + obj.getScriptLinks("Redraw") + obj.getScriptLinks(
                    "ObjectUpdate") + obj.getScriptLinks("ObDataUpdate"):
                if sl.endswith(".i3d"):
                    xmlText = ""
                    #print Text.Get(sl).asLines()
                    for l in Text.Get(sl).asLines():
                        #print l.replace("i3dNodeId", "%i" %self.lastNodeId)
                        xmlText = xmlText + l.replace("i3dNodeId",
                                                      "%i" % self.lastNodeId)
                    #print "xml: ",xmlText
                    #slDom = parseString(xmlText)
                    slDom = None
                    try:
                        slDom = parseString(xmlText)
                    except:
                        print "WARNING: cant parse %s" % sl
                    if not slDom is None:
                        for ua in slDom.getElementsByTagName("UserAttribute"):
                            self.userAttributes.appendChild(ua)

                        for st in slDom.getElementsByTagName("SceneType"):
                            i = 0
                            while i < st.attributes.length:
                                attr = st.attributes.item(i)
                                node.setAttribute(attr.nodeName,
                                                  attr.nodeValue)
                                i = i + 1
        else:
            print "WARNING: cant export ", obj.type, ": ", obj.getName()
Пример #14
0
def text_for_obj(name):
    all_text = Text.Get()
    for t in all_text:
        if strip_suffix(t.getName()).upper() == strip_suffix(name).upper():
            return t.asLines()
    return []
Пример #15
0
		show = 0
		for objectLayer in object.layers:
			for windowLayer in Window.ViewLayers():
				if objectLayer == windowLayer: show = 1
		if show:
			try:
				if object.getProperty('SpecialType').getData() == 'PhysicProxy':
					if object.getProperty('proxy_type').getData() == 'Box':
						drawPrimitiveCube(object)
					elif object.getProperty('proxy_type').getData() == 'Mesh':
						drawMesh(object)
			except:
				a=1 #for nothing,just a placeholder thingy

# Disable alpha blending and point smoothing.
glDisable(GL_BLEND)
glDisable(GL_POINT_SMOOTH)
"""

try:
    txt = Text.Get("Rastullah Visualizer")
    Text.unlink(txt)
    txt = Text.New("Rastullah Visualizer")
    txt.write(script_text)
except:
    txt = Text.New("Rastullah Visualizer")
    txt.write(script_text)

scene = Scene.GetCurrent()
scene.clearScriptLinks(['Rastullah Visualizer'])
scene.addScriptLink('Rastullah Visualizer', 'Redraw')
Пример #16
0
		show = 0
		for objectLayer in object.layers:
			for windowLayer in Window.ViewLayers():
				if objectLayer == windowLayer: show = 1
		if show:
			try:
				if object.getProperty('SpecialType').getData() == 'PhysicProxy':
					if object.getProperty('proxy_type').getData() == 'Box':
						drawPrimitiveCube(object)
					elif object.getProperty('proxy_type').getData() == 'Mesh':
						drawMesh(object)
			except:
				a=1 #for nothing,just a placeholder thingy

# Disable alpha blending and point smoothing.
glDisable(GL_BLEND)
glDisable(GL_POINT_SMOOTH)
"""

try:
	txt = Text.Get("Rastullah Visualizer")
	Text.unlink(txt)
	txt = Text.New("Rastullah Visualizer")
	txt.write(script_text)
except:
	txt = Text.New("Rastullah Visualizer")
	txt.write(script_text)

scene = Scene.GetCurrent()
scene.clearScriptLinks(['Rastullah Visualizer'])
scene.addScriptLink('Rastullah Visualizer', 'Redraw')