code
stringlengths
1
1.72M
language
stringclasses
1 value
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def checkEqualRotate(test, nodeName1, nodeName2, precision): test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.rotateX'), MayaCmds.getAttr(nodeName2 + '.rotateX'), precision) test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.rotateY'), MayaCmds.getAttr(nodeName2 + '.rotateY'), precision) test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.rotateZ'), MayaCmds.getAttr(nodeName2 + '.rotateZ'), precision) def checkEqualTranslate(test, nodeName1, nodeName2, precision): test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.translateX'), MayaCmds.getAttr(nodeName2 + '.translateX'), precision) test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1 + '.translateY'), MayaCmds.getAttr(nodeName2 + '.translateY'), precision) test.failUnlessAlmostEqual(MayaCmds.getAttr(nodeName1+'.translateZ'), MayaCmds.getAttr(nodeName2 + '.translateZ'), precision) def createStaticSolarSystem(): MayaCmds.file(new=True, force=True) moon = MayaCmds.polySphere( radius=0.5, name="moon" )[0] MayaCmds.move( -5, 0.0, 0.0, r=1 ) earth = MayaCmds.polySphere( radius=2, name="earth" )[0] MayaCmds.select( moon, earth ) MayaCmds.group(name='group1') MayaCmds.polySphere( radius=5, name="sun" )[0] MayaCmds.move( 25, 0.0, 0.0, r=1 ) MayaCmds.group(name='group2') def createAnimatedSolarSystem(): MayaCmds.file(new=True, force=True) moon = MayaCmds.polySphere(radius=0.5, name="moon")[0] MayaCmds.move(-5, 0.0, 0.0, r=1) earth = MayaCmds.polySphere(radius=2, name="earth")[0] MayaCmds.select(moon, earth) MayaCmds.group(name='group1') MayaCmds.polySphere(radius=5, name="sun")[0] MayaCmds.move(25, 0.0, 0.0, r=1) MayaCmds.group(name='group2') # the sun's simplified self-rotation MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('sun', at='rotateY', v=0) MayaCmds.currentTime(240, update=True) MayaCmds.setKeyframe('sun', at='rotateY', v=360) # the earth rotate around the sun MayaCmds.expression( s='$angle = (frame-91)/180*3.1415;\n\ earth.translateX = 25+25*sin($angle)') MayaCmds.expression( s='$angle = (frame-91)/180*3.1415;\n\ earth.translateZ = 25*cos($angle)') # the moon rotate around the earth MayaCmds.expression( s='$angle = (frame-91)/180*3.1415+frame;\n\ moon.translateX = earth.translateX+5*sin($angle)') MayaCmds.expression( s='$angle = (frame-91)/180*3.1415+frame;\n\ moon.translateZ = earth.translateZ+5*cos($angle)') class AbcImportSwapTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] # write out an animated Alembic file createAnimatedSolarSystem() self.__files.append(util.expandFileName('testAnimatedSolarSystem.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root group1 -root group2 -file ' + self.__files[-1]) # write out a static Alembic file that's different than the static scene # created by createStaticSolarSystem() MayaCmds.currentTime(12, update=True) self.__files.append(util.expandFileName('testStaticSolarSystem.abc')) MayaCmds.AbcExport(j='-fr 12 12 -root group1 -root group2 -file ' + self.__files[-1]) # write out an animated mesh with animated parent transform node MayaCmds.polyPlane(sx=2, sy=2, w=1, h=1, ch=0, n='polyMesh') MayaCmds.createNode('transform', n='group') MayaCmds.parent('polyMesh', 'group') # key the transform node MayaCmds.setKeyframe('group', attribute='translate', t=[1, 4]) MayaCmds.move(0.36, 0.72, 0.36) MayaCmds.setKeyframe('group', attribute='translate', t=2) #key the mesh node MayaCmds.select('polyMesh.vtx[0:8]') MayaCmds.setKeyframe(t=[1, 4]) MayaCmds.scale(0.1, 0.1, 0.1, r=True) MayaCmds.setKeyframe(t=2) self.__files.append(util.expandFileName('testAnimatedMesh.abc')) MayaCmds.AbcExport(j='-fr 1 4 -root group -file ' + self.__files[-1]) MayaCmds.file(new=True, force=True) def tearDown(self): for f in self.__files : os.remove(f) def testStaticSceneSwapInStaticAlembicTransform(self): createStaticSolarSystem() MayaCmds.AbcImport(self.__files[1], connect='/', debug=False ) # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 16.569, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testStaticSceneSwapInAnimatedAbcTransform(self): createStaticSolarSystem() # swap in the animated hierarchy MayaCmds.AbcImport(self.__files[0], connect='/', debug=False) # this is loaded in for value comparison purpose only MayaCmds.AbcImport(self.__files[0], mode='import') # check the swapped scene at every frame for frame in range(1, 25): MayaCmds.currentTime(frame, update=True) # tranform node moon checkEqualTranslate(self, 'group1|moon', 'group3|moon', 4) # transform node earth checkEqualTranslate(self, 'group1|earth', 'group3|earth', 4) # transform node sun checkEqualRotate(self, 'group2|sun', 'group4|sun', 4) def testAnimatedSceneSwapInStaticAbcTransform(self): createAnimatedSolarSystem() MayaCmds.AbcImport(self.__files[1], connect='/') # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 16.569, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testRemoveIfNoUpdate(self): createStaticSolarSystem() # add a few nodes that don't exist in the Alembic file MayaCmds.createNode('transform', name='saturn') MayaCmds.parent('saturn', 'group1') MayaCmds.createNode('transform', name='venus') MayaCmds.parent('venus', 'group2') MayaCmds.AbcImport(self.__files[1], connect='/', removeIfNoUpdate=True) # check if venus and saturn is deleted self.failUnlessEqual(MayaCmds.objExists('venus'), False) self.failUnlessEqual(MayaCmds.objExists('saturn'), False) # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 16.569, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testCreateIfNotFound(self): createStaticSolarSystem() # delete some nodes MayaCmds.delete( 'sunShape' ) MayaCmds.delete( 'moon' ) MayaCmds.AbcImport(self.__files[1], connect='/', createIfNotFound=True) # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 16.569, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testPartialSwap(self): createStaticSolarSystem() MayaCmds.AbcImport(self.__files[1], connect='group1', createIfNotFound=True) # check the swapped scene is the same as frame #12 # tranform node moon self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateX'), -4.1942, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('moon.translateZ'), 2.9429, 4) # transform node earth self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateX'), 0.4595, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('earth.translateZ'), 4.7712, 4) # transform node sun self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateX'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateY'), 0.0000, 4) self.failUnlessAlmostEqual( MayaCmds.getAttr('sun.rotateZ'), 0.0000, 4) def testAnimatedMeshSwap(self): MayaCmds.polyPlane( sx=2, sy=2, w=1, h=1, ch=0, n='polyMesh') MayaCmds.createNode('transform', n='group') MayaCmds.parent('polyMesh', 'group') MayaCmds.AbcImport(self.__files[2], connect='group') # this is loaded in for value comparison purpose only MayaCmds.AbcImport(self.__files[2], mode='import') # check the swapped scene at every frame for frame in range(1, 4): MayaCmds.currentTime(frame, update=True) # tranform node group checkEqualTranslate(self, 'group', 'group1', 4) # tranform node group checkEqualTranslate(self, 'group|polyMesh', 'group1|polyMesh', 4) # mesh node polyMesh for index in range(0, 9): string1 = 'group|polyMesh.vt[%d]' % index string2 = 'group1|polyMesh.vt[%d]' % index self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][0], MayaCmds.getAttr(string2)[0][0], 4, '%s.x != %s.x' % (string1, string2)) self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][1], MayaCmds.getAttr(string2)[0][1], 4, '%s.y != %s.y' % (string1, string2)) self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][2], MayaCmds.getAttr(string2)[0][2], 4, '%s.z != %s.z' % (string1, string2)) def testMeshTopoChange(self): MayaCmds.polySphere( sx=10, sy=15, r=0, n='polyMesh') MayaCmds.createNode('transform', n='group') MayaCmds.parent('polyMesh', 'group') MayaCmds.AbcImport(self.__files[2], connect='group') # this is loaded in for value comparison purpose only MayaCmds.AbcImport(self.__files[2], mode='import') # check the swapped scene at every frame for frame in range(1, 4): MayaCmds.currentTime(frame, update=True) # tranform node group checkEqualTranslate(self, 'group', 'group1', 4) # tranform node group checkEqualTranslate(self, 'group|polyMesh', 'group1|polyMesh', 4) # mesh node polyMesh for index in range(0, 9): string1 = 'group|polyMesh.vt[%d]' % index string2 = 'group1|polyMesh.vt[%d]' % index self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][0], MayaCmds.getAttr(string2)[0][0], 4, '%s.x != %s.x' % (string1, string2)) self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][1], MayaCmds.getAttr(string2)[0][1], 4, '%s.y != %s.y' % (string1, string2)) self.failUnlessAlmostEqual( MayaCmds.getAttr(string1)[0][2], MayaCmds.getAttr(string2)[0][2], 4, '%s.z != %s.z' % (string1, string2))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class VisibilityTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticVisibility(self): poly1 = MayaCmds.polyPlane(sx=2, sy=2, w=1, h=1, ch=0)[0] group1 = MayaCmds.group() group2 = MayaCmds.createNode("transform") MayaCmds.select(group1, group2) group3 = MayaCmds.group() group4 = (MayaCmds.duplicate(group1, rr=1))[0] group5 = MayaCmds.group() MayaCmds.select(group3, group5) root = MayaCmds.group(name='root') MayaCmds.setAttr(group1 + '.visibility', 0) MayaCmds.setAttr(group2 + '.visibility', 0) MayaCmds.setAttr(group5 + '.visibility', 0) self.__files.append(util.expandFileName('staticVisibilityTest.abc')) MayaCmds.AbcExport(j='-wv -root %s -file %s' % (root, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], m='open') self.failIf(MayaCmds.getAttr(group1+'.visibility')) self.failIf(MayaCmds.getAttr(group2+'.visibility')) self.failIf(MayaCmds.getAttr(group5+'.visibility')) self.failUnless(MayaCmds.getAttr(group1+'|'+poly1+'.visibility')) self.failUnless(MayaCmds.getAttr(group4+'|'+poly1+'.visibility')) self.failUnless(MayaCmds.getAttr(group3+'.visibility')) self.failUnless(MayaCmds.getAttr(group4+'.visibility')) self.failUnless(MayaCmds.getAttr(root+'.visibility')) def testAnimVisibility(self): poly1 = MayaCmds.polyPlane( sx=2, sy=2, w=1, h=1, ch=0)[0] group1 = MayaCmds.group() group2 = MayaCmds.createNode("transform") MayaCmds.select(group1, group2) group3 = MayaCmds.group() group4 = (MayaCmds.duplicate(group1, rr=1))[0] group5 = MayaCmds.group() MayaCmds.select(group3, group5) root = MayaCmds.group(name='root') MayaCmds.setKeyframe(group1 + '.visibility', v=0, t=[1, 4]) MayaCmds.setKeyframe(group2 + '.visibility', v=0, t=[1, 4]) MayaCmds.setKeyframe(group5 + '.visibility', v=0, t=[1, 4]) MayaCmds.setKeyframe(group1 + '.visibility', v=1, t=2) MayaCmds.setKeyframe(group2 + '.visibility', v=1, t=2) MayaCmds.setKeyframe(group5 + '.visibility', v=1, t=2) self.__files.append(util.expandFileName('animVisibilityTest.abc')) MayaCmds.AbcExport(j='-wv -fr 1 4 -root %s -file %s' % (root, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1, update = True) self.failIf(MayaCmds.getAttr(group1 + '.visibility')) self.failIf(MayaCmds.getAttr(group2 + '.visibility')) self.failIf(MayaCmds.getAttr(group5 + '.visibility')) self.failUnless(MayaCmds.getAttr(group1 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group3 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '.visibility')) self.failUnless(MayaCmds.getAttr(root+'.visibility')) MayaCmds.currentTime(2, update = True) self.failUnless(MayaCmds.getAttr(group1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group2 + '.visibility')) self.failUnless(MayaCmds.getAttr(group5 + '.visibility')) self.failUnless(MayaCmds.getAttr(group1 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group3 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '.visibility')) self.failUnless(MayaCmds.getAttr(root + '.visibility')) MayaCmds.currentTime(4, update = True ) self.failIf(MayaCmds.getAttr(group1 + '.visibility')) self.failIf(MayaCmds.getAttr(group2 + '.visibility')) self.failIf(MayaCmds.getAttr(group5 + '.visibility')) self.failUnless(MayaCmds.getAttr(group1 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '|' + poly1 + '.visibility')) self.failUnless(MayaCmds.getAttr(group3 + '.visibility')) self.failUnless(MayaCmds.getAttr(group4 + '.visibility')) self.failUnless(MayaCmds.getAttr(root+'.visibility'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** import maya.cmds as MayaCmds import os import subprocess import unittest import util class AnimTransformTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testAnimTransformReadWrite(self): nodeName = MayaCmds.createNode('transform', n='test') # shear MayaCmds.setKeyframe(nodeName, value=0, attribute='shearXY', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=0, attribute='shearYZ', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=0, attribute='shearXZ', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=1.5, attribute='shearXY', t=12) MayaCmds.setKeyframe(nodeName, value=5, attribute='shearYZ', t=12) MayaCmds.setKeyframe(nodeName, value=2.5, attribute='shearXZ', t=12) # translate MayaCmds.setKeyframe('test', value=0, attribute='translateX', t=[1, 24]) MayaCmds.setKeyframe('test', value=0, attribute='translateY', t=[1, 24]) MayaCmds.setKeyframe('test', value=0, attribute='translateZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.5, attribute='translateX', t=12) MayaCmds.setKeyframe('test', value=5, attribute='translateY', t=12) MayaCmds.setKeyframe('test', value=2.5, attribute='translateZ', t=12) # rotate MayaCmds.setKeyframe('test', value=0, attribute='rotateX', t=[1, 24]) MayaCmds.setKeyframe('test', value=0, attribute='rotateY', t=[1, 24]) MayaCmds.setKeyframe('test', value=0, attribute='rotateZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=24, attribute='rotateX', t=12) MayaCmds.setKeyframe('test', value=53, attribute='rotateY', t=12) MayaCmds.setKeyframe('test', value=90, attribute='rotateZ', t=12) # scale MayaCmds.setKeyframe('test', value=1, attribute='scaleX', t=[1, 24]) MayaCmds.setKeyframe('test', value=1, attribute='scaleY', t=[1, 24]) MayaCmds.setKeyframe('test', value=1, attribute='scaleZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.2, attribute='scaleX', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='scaleY', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='scaleZ', t=12) # rotate pivot MayaCmds.setKeyframe('test', value=0.5, attribute='rotatePivotX', t=[1, 24]) MayaCmds.setKeyframe('test', value=-0.1, attribute='rotatePivotY', t=[1, 24]) MayaCmds.setKeyframe('test', value=1, attribute='rotatePivotZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=0.8, attribute='rotatePivotX', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='rotatePivotY', t=12) MayaCmds.setKeyframe('test', value=-1, attribute='rotatePivotZ', t=12) # scale pivot MayaCmds.setKeyframe('test', value=1.2, attribute='scalePivotX', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.0, attribute='scalePivotY', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.2, attribute='scalePivotZ', t=[1, 24]) MayaCmds.setKeyframe('test', value=1.4, attribute='scalePivotX', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='scalePivotY', t=12) MayaCmds.setKeyframe('test', value=1.5, attribute='scalePivotZ', t=12) self.__files.append(util.expandFileName('testAnimTransformReadWrite.abc')) self.__files.append(util.expandFileName('testAnimTransformReadWrite01_14.abc')) self.__files.append(util.expandFileName('testAnimTransformReadWrite15_24.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root test -file ' + self.__files[-2]) MayaCmds.AbcExport(j='-fr 15 24 -root test -file ' + self.__files[-1]) subprocess.call(self.__abcStitcher + self.__files[-3:]) MayaCmds.AbcImport(self.__files[-3], mode='open') # frame 1 MayaCmds.currentTime(1, update=True) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearXY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearYZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearXZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateX')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateX')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateZ')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleX')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleY')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleZ')) self.failUnlessEqual(0.5, MayaCmds.getAttr('test.rotatePivotX')) self.failUnlessEqual(-0.1, MayaCmds.getAttr('test.rotatePivotY')) self.failUnlessEqual(1, MayaCmds.getAttr('test.rotatePivotZ')) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scalePivotX')) self.failUnlessEqual(1.0, MayaCmds.getAttr('test.scalePivotY')) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scalePivotZ')) # frame 12 MayaCmds.currentTime(12, update=True); abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.dgeval(abcNodeName, verbose=True) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.shearXY')) self.failUnlessEqual(5, MayaCmds.getAttr('test.shearYZ')) self.failUnlessEqual(2.5, MayaCmds.getAttr('test.shearXZ')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.translateX')) self.failUnlessEqual(5, MayaCmds.getAttr('test.translateY')) self.failUnlessEqual(2.5, MayaCmds.getAttr('test.translateZ')) self.failUnlessAlmostEqual(24.0, MayaCmds.getAttr('test.rotateX'), 4) self.failUnlessAlmostEqual(53.0, MayaCmds.getAttr('test.rotateY'), 4) self.failUnlessAlmostEqual(90.0, MayaCmds.getAttr('test.rotateZ'), 4) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scaleX')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.scaleY')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.scaleZ')) self.failUnlessEqual(0.8, MayaCmds.getAttr('test.rotatePivotX')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.rotatePivotY')) self.failUnlessEqual(-1, MayaCmds.getAttr('test.rotatePivotZ')) self.failUnlessEqual(1.4, MayaCmds.getAttr('test.scalePivotX')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.scalePivotY')) self.failUnlessEqual(1.5, MayaCmds.getAttr('test.scalePivotZ')) # frame 24 MayaCmds.currentTime(24, update=True); abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.dgeval(abcNodeName, verbose=True) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearXY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearYZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.shearXZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateX')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.translateZ')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateX')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateY')) self.failUnlessEqual(0, MayaCmds.getAttr('test.rotateZ')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleX')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleY')) self.failUnlessEqual(1, MayaCmds.getAttr('test.scaleZ')) self.failUnlessEqual(0.5, MayaCmds.getAttr('test.rotatePivotX')) self.failUnlessEqual(-0.1, MayaCmds.getAttr('test.rotatePivotY')) self.failUnlessEqual(1, MayaCmds.getAttr('test.rotatePivotZ')) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scalePivotX')) self.failUnlessEqual(1.0, MayaCmds.getAttr('test.scalePivotY')) self.failUnlessEqual(1.2, MayaCmds.getAttr('test.scalePivotZ')) def testSampledConnectionDetectionRW(self): # connect to plugs at parent level and see if when loaded back # the sampled channels are recognized correctly driver = MayaCmds.createNode('transform', n='driverTrans') # shear MayaCmds.setKeyframe(driver, value=0, attribute='shearXY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='shearYZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='shearXZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.5, attribute='shearXY', t=12) MayaCmds.setKeyframe(driver, value=5, attribute='shearYZ', t=12) MayaCmds.setKeyframe(driver, value=2.5, attribute='shearXZ', t=12) # translate MayaCmds.setKeyframe(driver, value=0, attribute='translateX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='translateY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='translateZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.5, attribute='translateX', t=12) MayaCmds.setKeyframe(driver, value=5, attribute='translateY', t=12) MayaCmds.setKeyframe(driver, value=2.5, attribute='translateZ', t=12) # rotate MayaCmds.setKeyframe(driver, value=0, attribute='rotateX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='rotateY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0, attribute='rotateZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=24, attribute='rotateX', t=12) MayaCmds.setKeyframe(driver, value=53, attribute='rotateY', t=12) MayaCmds.setKeyframe(driver, value=90, attribute='rotateZ', t=12) # scale MayaCmds.setKeyframe(driver, value=1, attribute='scaleX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1, attribute='scaleY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1, attribute='scaleZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.2, attribute='scaleX', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='scaleY', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='scaleZ', t=12) # rotate pivot MayaCmds.setKeyframe(driver, value=0.5, attribute='rotatePivotX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=-0.1, attribute='rotatePivotY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1, attribute='rotatePivotZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=0.8, attribute='rotatePivotX', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='rotatePivotY', t=12) MayaCmds.setKeyframe(driver, value=-1, attribute='rotatePivotZ', t=12) # scale pivot MayaCmds.setKeyframe(driver, value=1.2, attribute='scalePivotX', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.0, attribute='scalePivotY', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.2, attribute='scalePivotZ', t=[1, 24]) MayaCmds.setKeyframe(driver, value=1.4, attribute='scalePivotX', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='scalePivotY', t=12) MayaCmds.setKeyframe(driver, value=1.5, attribute='scalePivotZ', t=12) # create the transform node that's been driven by the connections driven = MayaCmds.createNode('transform', n = 'drivenTrans') MayaCmds.connectAttr(driver+'.translate', driven+'.translate') MayaCmds.connectAttr(driver+'.scale', driven+'.scale') MayaCmds.connectAttr(driver+'.rotate', driven+'.rotate') MayaCmds.connectAttr(driver+'.shear', driven+'.shear') MayaCmds.connectAttr(driver+'.rotatePivot', driven+'.rotatePivot') MayaCmds.connectAttr(driver+'.scalePivot', driven+'.scalePivot') self.__files.append(util.expandFileName('testSampledTransformDetection.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root drivenTrans -file ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') # frame 1 MayaCmds.currentTime(1, update=True) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearXY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearYZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearXZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateX')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateX')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateZ')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleX')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleY')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleZ')) self.failUnlessEqual(0.5, MayaCmds.getAttr(driven+'.rotatePivotX')) self.failUnlessEqual(-0.1, MayaCmds.getAttr(driven+'.rotatePivotY')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.rotatePivotZ')) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scalePivotX')) self.failUnlessEqual(1.0, MayaCmds.getAttr(driven+'.scalePivotY')) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scalePivotZ')) # frame 12 MayaCmds.currentTime(12, update=True); abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.dgeval(abcNodeName, verbose=True) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.shearXY')) self.failUnlessEqual(5, MayaCmds.getAttr(driven+'.shearYZ')) self.failUnlessEqual(2.5, MayaCmds.getAttr(driven+'.shearXZ')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.translateX')) self.failUnlessEqual(5, MayaCmds.getAttr(driven+'.translateY')) self.failUnlessEqual(2.5, MayaCmds.getAttr(driven+'.translateZ')) self.failUnlessAlmostEqual(24.0, MayaCmds.getAttr(driven+'.rotateX'), 4) self.failUnlessAlmostEqual(53.0, MayaCmds.getAttr(driven+'.rotateY'), 4) self.failUnlessAlmostEqual(90.0, MayaCmds.getAttr(driven+'.rotateZ'), 4) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scaleX')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.scaleY')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.scaleZ')) self.failUnlessEqual(0.8, MayaCmds.getAttr(driven+'.rotatePivotX')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.rotatePivotY')) self.failUnlessEqual(-1, MayaCmds.getAttr(driven+'.rotatePivotZ')) self.failUnlessEqual(1.4, MayaCmds.getAttr(driven+'.scalePivotX')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.scalePivotY')) self.failUnlessEqual(1.5, MayaCmds.getAttr(driven+'.scalePivotZ')) # frame 24 MayaCmds.currentTime(24, update=True); abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.dgeval(abcNodeName, verbose=True) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearXY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearYZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.shearXZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateX')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.translateZ')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateX')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateY')) self.failUnlessEqual(0, MayaCmds.getAttr(driven+'.rotateZ')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleX')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleY')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.scaleZ')) self.failUnlessEqual(0.5, MayaCmds.getAttr(driven+'.rotatePivotX')) self.failUnlessEqual(-0.1, MayaCmds.getAttr(driven+'.rotatePivotY')) self.failUnlessEqual(1, MayaCmds.getAttr(driven+'.rotatePivotZ')) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scalePivotX')) self.failUnlessEqual(1.0, MayaCmds.getAttr(driven+'.scalePivotY')) self.failUnlessEqual(1.2, MayaCmds.getAttr(driven+'.scalePivotZ'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def makeRobot(): MayaCmds.polyCube(name="head") MayaCmds.move(0, 4, 0, r=1) MayaCmds.polyCube(name="chest") MayaCmds.scale(2, 2.5, 1) MayaCmds.move(0, 2, 0, r=1) MayaCmds.polyCube(name="leftArm") MayaCmds.move(0, 3, 0, r=1) MayaCmds.scale(2, 0.5, 1, r=1) MayaCmds.duplicate(name="rightArm") MayaCmds.select("leftArm") MayaCmds.move(1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, 32, r=1, os=1) MayaCmds.select("rightArm") MayaCmds.move(-1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, -32, r=1, os=1) MayaCmds.select("rightArm", "leftArm", "chest", r=1) MayaCmds.group(name="body") MayaCmds.polyCube(name="bottom") MayaCmds.scale(2, 0.5, 1) MayaCmds.move(0, 0.5, 0, r=1) MayaCmds.polyCube(name="leftLeg") MayaCmds.scale(0.65, 2.8, 1, r=1) MayaCmds.move(-0.5, -1, 0, r=1) MayaCmds.duplicate(name="rightLeg") MayaCmds.move(1, 0, 0, r=1) MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1) MayaCmds.group(name="lower") MayaCmds.select("head", "body", "lower", r=1) MayaCmds.group(name="robot") class selectionTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testSelectionNamespace(self): nodes = MayaCmds.polyCube() MayaCmds.namespace(add="potato") MayaCmds.rename(nodes[0], "potato:" + nodes[0]) MayaCmds.select(MayaCmds.ls(type="mesh")) self.__files.append(util.expandFileName('selectionTest_namespace.abc')) MayaCmds.AbcExport(j='-sl -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') self.failUnless(MayaCmds.ls(type="mesh") != 1) def testSelectionFlag(self): makeRobot() MayaCmds.select('bottom', 'leftArm', 'head') self.__files.append(util.expandFileName('selectionTest_partial.abc')) MayaCmds.AbcExport(j='-sl -root head -root body -root lower -file ' + self.__files[-1]) self.__files.append(util.expandFileName('selectionTest.abc')) MayaCmds.AbcExport(j='-sl -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') self.failUnless(MayaCmds.objExists("robot|head")) self.failUnless(MayaCmds.objExists("robot|body|leftArm")) self.failUnless(MayaCmds.objExists("robot|lower|bottom")) self.failIf(MayaCmds.objExists("robot|body|rightArm")) self.failIf(MayaCmds.objExists("robot|body|chest")) self.failIf(MayaCmds.objExists("robot|lower|rightLeg")) self.failIf(MayaCmds.objExists("robot|lower|leftLeg")) MayaCmds.AbcImport(self.__files[-2], m='open') self.failUnless(MayaCmds.objExists("head")) self.failUnless(MayaCmds.objExists("body|leftArm")) self.failUnless(MayaCmds.objExists("lower|bottom")) # we didnt actually select any meshes so there shouldnt # be any in the scene self.failIf(MayaCmds.ls(type='mesh'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds from maya.mel import eval as MelEval import os import maya.OpenMaya as OpenMaya import unittest import util class StaticMeshTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticMeshReadWrite(self): numFaces = 6 numVertices = 8 numFaceConnects = 24 vtx_1 = OpenMaya.MFloatPoint(-0.5, -0.5, -0.5) vtx_2 = OpenMaya.MFloatPoint( 0.5, -0.5, -0.5) vtx_3 = OpenMaya.MFloatPoint( 0.5, -0.5, 0.5) vtx_4 = OpenMaya.MFloatPoint(-0.5, -0.5, 0.5) vtx_5 = OpenMaya.MFloatPoint(-0.5, 0.5, -0.5) vtx_6 = OpenMaya.MFloatPoint(-0.5, 0.5, 0.5) vtx_7 = OpenMaya.MFloatPoint( 0.5, 0.5, 0.5) vtx_8 = OpenMaya.MFloatPoint( 0.5, 0.5, -0.5) points = OpenMaya.MFloatPointArray() points.setLength(8) points.set(vtx_1, 0) points.set(vtx_2, 1) points.set(vtx_3, 2) points.set(vtx_4, 3) points.set(vtx_5, 4) points.set(vtx_6, 5) points.set(vtx_7, 6) points.set(vtx_8, 7) faceConnects = OpenMaya.MIntArray() faceConnects.setLength(numFaceConnects) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) faceConnects.set(4, 4) faceConnects.set(5, 5) faceConnects.set(6, 6) faceConnects.set(7, 7) faceConnects.set(3, 8) faceConnects.set(2, 9) faceConnects.set(6, 10) faceConnects.set(5, 11) faceConnects.set(0, 12) faceConnects.set(3, 13) faceConnects.set(5, 14) faceConnects.set(4, 15) faceConnects.set(0, 16) faceConnects.set(4, 17) faceConnects.set(7, 18) faceConnects.set(1, 19) faceConnects.set(1, 20) faceConnects.set(7, 21) faceConnects.set(6, 22) faceConnects.set(2, 23) faceCounts = OpenMaya.MIntArray() faceCounts.setLength(6) faceCounts.set(4, 0) faceCounts.set(4, 1) faceCounts.set(4, 2) faceCounts.set(4, 3) faceCounts.set(4, 4) faceCounts.set(4, 5) transFn = OpenMaya.MFnTransform() parent = transFn.create() transFn.setName('mesh') meshFn = OpenMaya.MFnMesh() meshFn.create(numVertices, numFaces, points, faceCounts, faceConnects, parent) meshFn.setName("meshShape"); self.__files.append(util.expandFileName('testStaticMeshReadWrite.abc')) MayaCmds.AbcExport(j='-root mesh -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') sList = OpenMaya.MSelectionList() sList.add('meshShape') meshObj = OpenMaya.MObject() sList.getDependNode(0, meshObj) meshFn = OpenMaya.MFnMesh(meshObj) # check the point list meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints); self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7]) # check the polygonvertices list vertexList = OpenMaya.MIntArray() faceConnects = OpenMaya.MIntArray() faceConnects.setLength(4) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) meshFn.getPolygonVertices(0, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(4, 0) faceConnects.set(5, 1) faceConnects.set(6, 2) faceConnects.set(7, 3) meshFn.getPolygonVertices(1, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(3, 0) faceConnects.set(2, 1) faceConnects.set(6, 2) faceConnects.set(5, 3) meshFn.getPolygonVertices(2, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(3, 1) faceConnects.set(5, 2) faceConnects.set(4, 3) meshFn.getPolygonVertices(3, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(4, 1) faceConnects.set(7, 2) faceConnects.set(1, 3) meshFn.getPolygonVertices(4, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(1, 0) faceConnects.set(7, 1) faceConnects.set(6, 2) faceConnects.set(2, 3) meshFn.getPolygonVertices(5, vertexList) self.failUnlessEqual(faceConnects, vertexList)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class LoadWorldSpaceTranslateJobTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticLoadWorldSpaceTranslateJobReadWrite(self): nodeName = MayaCmds.polyCube(n='cube') root = nodeName[0] MayaCmds.setAttr(root+'.rotateX', 45) MayaCmds.setAttr(root+'.scaleX', 1.5) MayaCmds.setAttr(root+'.translateY', -1.95443) nodeName = MayaCmds.group() MayaCmds.setAttr(nodeName+'.rotateY', 15) MayaCmds.setAttr(nodeName+'.translateY', -3.95443) nodeName = MayaCmds.group() MayaCmds.setAttr(nodeName+'.rotateZ',-90) MayaCmds.setAttr(nodeName+'.shearXZ',2.555) self.__files.append(util.expandFileName('testStaticLoadWorldSpaceTranslateJob.abc')) MayaCmds.AbcExport(j='-ws -root %s -file %s' % (root, self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateX'), 3) self.failUnlessAlmostEqual(-5.909, MayaCmds.getAttr(root+'.translateY'), 3) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateZ'), 3) self.failUnlessAlmostEqual(68.211, MayaCmds.getAttr(root+'.rotateX'), 3) self.failUnlessAlmostEqual(40.351, MayaCmds.getAttr(root+'.rotateY'), 3) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr(root+'.rotateZ'), 3) self.failUnlessAlmostEqual(0.600, MayaCmds.getAttr(root+'.scaleX'), 3) self.failUnlessAlmostEqual(1.905, MayaCmds.getAttr(root+'.scaleY'), 3) self.failUnlessAlmostEqual(1.313, MayaCmds.getAttr(root+'.scaleZ'), 3) self.failUnlessAlmostEqual(0.539, MayaCmds.getAttr(root+'.shearXY'), 3) self.failUnlessAlmostEqual(0.782, MayaCmds.getAttr(root+'.shearXZ'), 3) self.failUnlessAlmostEqual(1.051, MayaCmds.getAttr(root+'.shearYZ'), 3) def testAnimLoadWorldSpaceTranslateJobReadWrite(self): nodeName = MayaCmds.polyCube(n='cube') root = nodeName[0] MayaCmds.setAttr(root+'.rotateX', 45) MayaCmds.setAttr(root+'.scaleX', 1.5) MayaCmds.setAttr(root+'.translateY', -1.95443) MayaCmds.setKeyframe(root, value=0, attribute='translateX', t=[1, 24]) MayaCmds.setKeyframe(root, value=1, attribute='translateX', t=12) nodeName = MayaCmds.group() MayaCmds.setAttr(nodeName+'.rotateY', 15) MayaCmds.setAttr(nodeName+'.translateY', -3.95443) nodeName = MayaCmds.group() MayaCmds.setAttr(nodeName+'.rotateZ',-90) MayaCmds.setAttr(nodeName+'.shearXZ',2.555) self.__files.append(util.expandFileName('testAnimLoadWorldSpaceTranslateJob.abc')) MayaCmds.AbcExport(j='-fr 1 24 -ws -root %s -file %s' % (root, self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') # frame 1 MayaCmds.currentTime(1, update=True) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateX'), 3) self.failUnlessAlmostEqual(-5.909, MayaCmds.getAttr(root+'.translateY'), 3) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateZ'), 3) self.failUnlessAlmostEqual(68.211, MayaCmds.getAttr(root+'.rotateX'), 3) self.failUnlessAlmostEqual(40.351, MayaCmds.getAttr(root+'.rotateY'), 3) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr(root+'.rotateZ'), 3) self.failUnlessAlmostEqual(0.600, MayaCmds.getAttr(root+'.scaleX'), 3) self.failUnlessAlmostEqual(1.905, MayaCmds.getAttr(root+'.scaleY'), 3) self.failUnlessAlmostEqual(1.313, MayaCmds.getAttr(root+'.scaleZ'), 3) self.failUnlessAlmostEqual(0.539, MayaCmds.getAttr(root+'.shearXY'), 3) self.failUnlessAlmostEqual(0.782, MayaCmds.getAttr(root+'.shearXZ'), 3) self.failUnlessAlmostEqual(1.051, MayaCmds.getAttr(root+'.shearYZ'), 3) # frame 12 MayaCmds.currentTime(12, update=True) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateX'), 3) self.failUnlessAlmostEqual(-6.2135, MayaCmds.getAttr(root+'.translateY'), 3) self.failUnlessAlmostEqual(-0.258819, MayaCmds.getAttr(root+'.translateZ'), 3) self.failUnlessAlmostEqual(68.211, MayaCmds.getAttr(root+'.rotateX'), 3) self.failUnlessAlmostEqual(40.351, MayaCmds.getAttr(root+'.rotateY'), 3) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr(root+'.rotateZ'), 3) self.failUnlessAlmostEqual(0.600, MayaCmds.getAttr(root+'.scaleX'), 3) self.failUnlessAlmostEqual(1.905, MayaCmds.getAttr(root+'.scaleY'), 3) self.failUnlessAlmostEqual(1.313, MayaCmds.getAttr(root+'.scaleZ'), 3) self.failUnlessAlmostEqual(0.539, MayaCmds.getAttr(root+'.shearXY'), 3) self.failUnlessAlmostEqual(0.782, MayaCmds.getAttr(root+'.shearXZ'), 3) self.failUnlessAlmostEqual(1.051, MayaCmds.getAttr(root+'.shearYZ'), 3) # frame 24 MayaCmds.currentTime(24, update=True) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateX'), 3) self.failUnlessAlmostEqual(-5.909, MayaCmds.getAttr(root+'.translateY'), 3) self.failUnlessAlmostEqual(0, MayaCmds.getAttr(root+'.translateZ'), 3) self.failUnlessAlmostEqual(68.211, MayaCmds.getAttr(root+'.rotateX'), 3) self.failUnlessAlmostEqual(40.351, MayaCmds.getAttr(root+'.rotateY'), 3) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr(root+'.rotateZ'), 3) self.failUnlessAlmostEqual(0.600, MayaCmds.getAttr(root+'.scaleX'), 3) self.failUnlessAlmostEqual(1.905, MayaCmds.getAttr(root+'.scaleY'), 3) self.failUnlessAlmostEqual(1.313, MayaCmds.getAttr(root+'.scaleZ'), 3) self.failUnlessAlmostEqual(0.539, MayaCmds.getAttr(root+'.shearXY'), 3) self.failUnlessAlmostEqual(0.782, MayaCmds.getAttr(root+'.shearXZ'), 3) self.failUnlessAlmostEqual(1.051, MayaCmds.getAttr(root+'.shearYZ'), 3)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util class MayaReloadTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) # this test makes sure that not just the vertex positions but the # connection info is all correct def testAnimMeshReload(self): MayaCmds.polyCube( name = 'mesh') MayaCmds.setKeyframe('meshShape.vtx[0:7]', time=[1, 24]) MayaCmds.setKeyframe('meshShape.vtx[0:7]') MayaCmds.currentTime(12, update=True) MayaCmds.select('meshShape.vtx[0:7]') MayaCmds.scale(5, 5, 5, r=True) MayaCmds.setKeyframe('meshShape.vtx[0:7]', time=[12]) self.__files.append(util.expandFileName('testAnimMeshReadWrite.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root mesh -f ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') # save as a maya file self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # reload as a maya file MayaCmds.file(self.__files[-1], open=True) MayaCmds.AbcImport(self.__files[-2], mode='import') retVal = True mesh1 = '|mesh|meshShape' mesh2 = '|mesh1|meshShape' for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareMesh( mesh1, mesh2 ): self.fail('%s and %s were not equal at frame %d' % (mesh1, mesh2, t)) #------------------------------------------------------------------------------- # The following tests each creates four animated nodes of the same data # type, writes out to Abc file, loads back the file and deletes one node. # Then the scene is saved as a Maya file, and load back to check if the # reload works as expected #------------------------------------------------------------------------------- def testAnimPolyDeleteReload(self): # create a poly cube and animate shapeName = 'pCube' MayaCmds.polyCube( name=shapeName ) MayaCmds.move(5, 0, 0, r=True) MayaCmds.setKeyframe( shapeName+'.vtx[2:5]', time=[1, 24] ) MayaCmds.currentTime( 12 ) MayaCmds.select( shapeName+'.vtx[2:5]',replace=True ) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe( shapeName+'.vtx[2:5]', time=[12] ) # create a poly sphere and animate shapeName = 'pSphere' MayaCmds.polySphere( name=shapeName ) MayaCmds.move(-5, 0, 0, r=True) MayaCmds.setKeyframe( shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select( shapeName+'.vtx[200:379]', shapeName+'.vtx[381]',replace=True) MayaCmds.scale(0.5, 0.5, 0.5, relative=True) MayaCmds.setKeyframe( shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', time=[12]) MayaCmds.currentTime(1) # create a poly torus and animate shapeName = 'pTorus' MayaCmds.polyTorus(name=shapeName) MayaCmds.setKeyframe(shapeName+'.vtx[200:219]',time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[200:219]',replace=True) MayaCmds.scale(2, 1, 2, relative=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:219]', time=[12]) # create a poly cone and animate shapeName = 'pCone' MayaCmds.polyCone(name=shapeName) MayaCmds.move(0, 0, -5, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[20]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[20]',replace=True) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[20]', time=[12]) # write it out to Abc file and load back in self.__files.append(util.expandFileName('testPolyReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root pCube -root pSphere -root pTorus -root pCone -file %s' % self.__files[-1]) # load back the Abc file, delete the sphere and save to a maya file MayaCmds.AbcImport( self.__files[-1], mode='open') MayaCmds.delete('pSphere') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('pCube', 'pTorus', 'pCone', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') shapeList = MayaCmds.ls(type='mesh') self.failUnlessEqual(len(shapeList), 7) meshes = [('|pCube|pCubeShape', '|ReloadGrp|pCube|pCubeShape'), ('|pTorus|pTorusShape', '|ReloadGrp|pTorus|pTorusShape'), ('|pCone|pConeShape', '|ReloadGrp|pCone|pConeShape')] for m in meshes: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareMesh(m[0], m[1]): self.fail('%s and %s are not the same at frame %d' % (m[0], m[1], t)) def testAnimSubDDeleteReload(self): # create a subD cube and animate shapeName = 'cube' MayaCmds.polyCube( name=shapeName ) MayaCmds.select('cubeShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.move(5, 0, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[2:5]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[2:5]',replace=True) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[2:5]', time=[12]) # create a subD sphere and animate shapeName = 'sphere' MayaCmds.polySphere(name=shapeName) MayaCmds.select('sphereShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.move(-5, 0, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', replace=True) MayaCmds.scale(0.5, 0.5, 0.5, relative=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:379]', shapeName+'.vtx[381]', time=[12]) MayaCmds.currentTime(1) # create a subD torus and animate shapeName = 'torus' MayaCmds.polyTorus(name=shapeName) MayaCmds.select('torusShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:219]',time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[200:219]',replace=True) MayaCmds.scale(2, 1, 2, relative=True) MayaCmds.setKeyframe(shapeName+'.vtx[200:219]', time=[12]) # create a subD cone and animate shapeName = 'cone' MayaCmds.polyCone( name=shapeName ) MayaCmds.select('coneShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.move(0, 0, -5, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[20]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[20]',replace=True) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[20]', time=[12]) self.__files.append(util.expandFileName('testSubDReload.abc')) # write it out to Abc file and load back in MayaCmds.AbcExport(j='-fr 1 24 -root cube -root sphere -root torus -root cone -file ' + self.__files[-1]) # load back the Abc file, delete the sphere and save to a maya file MayaCmds.AbcImport( self.__files[-1], mode='open' ) MayaCmds.delete('sphere') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('cube', 'torus', 'cone', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') shapeList = MayaCmds.ls(type='mesh') self.failUnlessEqual(len(shapeList), 7) # test the equality of cubes meshes = [('|cube|cubeShape', '|ReloadGrp|cube|cubeShape'), ('|torus|torusShape', '|ReloadGrp|torus|torusShape'), ('|cone|coneShape', '|ReloadGrp|cone|coneShape')] for m in meshes: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareMesh(m[0], m[1]): self.fail('%s and %s are not the same at frame %d' % (m[0], m[1], t)) def testAnimNSurfaceDeleteReload(self): # create an animated Nurbs sphere MayaCmds.sphere(ch=False, name='nSphere') MayaCmds.move(5, 0, 0, relative=True) MayaCmds.select('nSphere.cv[0:1][0:7]', 'nSphere.cv[5:6][0:7]', replace=True) MayaCmds.setKeyframe(time=[1, 24]) MayaCmds.currentTime(12, update=True) MayaCmds.scale(1.5, 1, 1, relative=True) MayaCmds.setKeyframe(time=12) # create an animated Nurbs torus MayaCmds.torus(ch=False, name='nTorus') MayaCmds.move(-5, 0, 0, relative=True) MayaCmds.select('nTorus.cv[0][0:7]', 'nTorus.cv[2][0:7]', replace=True) MayaCmds.setKeyframe(time=[1, 24]) MayaCmds.currentTime(12, update=True) MayaCmds.scale(1, 2, 2, relative=True) MayaCmds.setKeyframe(time=12) # create an animated Nurbs plane # should add the trim curve test on this surface, will be easier # than the rest MayaCmds.nurbsPlane(ch=False, name='nPlane') MayaCmds.move(-5, 5, 0, relative=True) MayaCmds.select('nPlane.cv[0:3][0:3]', replace=True) MayaCmds.setKeyframe(time=1) MayaCmds.currentTime(12, update=True) MayaCmds.rotate(0, 0, 90, relative=True) MayaCmds.setKeyframe(time=12) MayaCmds.currentTime(24, update=True) MayaCmds.rotate(0, 0, 90, relative=True) MayaCmds.setKeyframe(time=24) # create an animated Nurbs cylinder MayaCmds.cylinder(ch=False, name='nCylinder') MayaCmds.select('nCylinder.cv[0][0:7]', replace=True) MayaCmds.setKeyframe(time=[1, 24]) MayaCmds.currentTime(12, update=True) MayaCmds.move(-3, 0, 0, relative=True) MayaCmds.setKeyframe(time=12) # write it out to Abc file and load back in self.__files.append(util.expandFileName('testNSurfaceReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root nSphere -root nTorus -root nPlane -root nCylinder -file ' + self.__files[-1]) # load back the Abc file, delete the torus and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.delete('nTorus') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('nSphere', 'nPlane', 'nCylinder', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') surfaceList = MayaCmds.ls(type='nurbsSurface') self.failUnlessEqual(len(surfaceList), 7) surfaces = [('|nSphere|nSphereShape', '|ReloadGrp|nSphere|nSphereShape'), ('|nPlane|nPlaneShape', '|ReloadGrp|nPlane|nPlaneShape'), ('|nCylinder|nCylinderShape', '|ReloadGrp|nCylinder|nCylinderShape')] for s in surfaces: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareNurbsSurface(s[0], s[1]): self.fail('%s and %s are not the same at frame %d' % (s[0], s[1], t)) def testAnimNSurfaceAndPolyDeleteReload(self): # create a poly cube and animate shapeName = 'pCube' MayaCmds.polyCube(name=shapeName) MayaCmds.move(5, 0, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[2:5]', time=[1, 24]) MayaCmds.currentTime(12) MayaCmds.select(shapeName+'.vtx[2:5]',replace=True) MayaCmds.move(0, 4, 0, r=True) MayaCmds.setKeyframe(shapeName+'.vtx[2:5]', time=[12]) # create an animated Nurbs plane MayaCmds.nurbsPlane(ch=False, name='nPlane') MayaCmds.move(-5, 5, 0, relative=True) MayaCmds.select('nPlane.cv[0:3][0:3]', replace=True) MayaCmds.setKeyframe(time=1) MayaCmds.currentTime(12, update=True) MayaCmds.rotate(0, 0, 90, relative=True) MayaCmds.setKeyframe(time=12) MayaCmds.currentTime(24, update=True) MayaCmds.rotate(0, 0, 90, relative=True) MayaCmds.setKeyframe(time=24) # write it out to Abc file and load back in self.__files.append(util.expandFileName('testNSurfaceAndPolyReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root pCube -root nPlane -file ' + self.__files[-1]) # load back the Abc file, delete the cube and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.delete('pCube') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('nPlane', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') shapeList = MayaCmds.ls(type='mesh') self.failUnlessEqual(len(shapeList), 1) surfaceList = MayaCmds.ls(type='nurbsSurface') self.failUnlessEqual(len(surfaceList), 2) # test the equality of plane surface1 = '|nPlane|nPlaneShape' surface2 = '|ReloadGrp|nPlane|nPlaneShape' for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareNurbsSurface( surface1, surface2 ): self.fail('%s and %s are not the same at frame %d' % (surface1, surface2, t)) def testAnimCameraDeleteReload(self): # cam1 MayaCmds.camera(name='cam1') MayaCmds.setAttr('cam1Shape1.horizontalFilmAperture', 0.962) MayaCmds.setAttr('cam1Shape1.verticalFilmAperture', 0.731) MayaCmds.setAttr('cam1Shape1.focalLength', 50) MayaCmds.setAttr('cam1Shape1.focusDistance', 5) MayaCmds.setAttr('cam1Shape1.shutterAngle', 144) MayaCmds.setAttr('cam1Shape1.centerOfInterest', 1384.825) # cam2 MayaCmds.duplicate('cam1', returnRootsOnly=True) # cam3 MayaCmds.duplicate('cam1', returnRootsOnly=True) # cam4 MayaCmds.duplicate('cam1', returnRootsOnly=True) # animate each camera slightly different MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('cam1Shape1', attribute='horizontalFilmAperture') MayaCmds.setKeyframe('cam2Shape', attribute='focalLength') MayaCmds.setKeyframe('cam3Shape', attribute='focusDistance') MayaCmds.setKeyframe('cam4Shape', attribute='shutterAngle') MayaCmds.setKeyframe('cam4Shape', attribute='centerOfInterest') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe('cam1Shape1', attribute='horizontalFilmAperture', value=0.95) MayaCmds.setKeyframe('cam2Shape', attribute='focalLength', value=40) MayaCmds.setKeyframe('cam3Shape', attribute='focusDistance', value=5.4) MayaCmds.setKeyframe('cam4Shape', attribute='shutterAngle', value=174.94) MayaCmds.setKeyframe('cam4Shape', attribute='centerOfInterest', value=67.418) # write them out to an Abc file and load back in self.__files.append(util.expandFileName('testCamReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root cam1 -root cam2 -root cam3 -root cam4 -file ' + self.__files[-1]) # load back the Abc file, delete the 2nd camera and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.delete('cam2') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('cam1', 'cam3', 'cam4', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') camList = MayaCmds.ls(type='camera') # should be 7, but this query will return the four standard cameras in # the scene too self.failUnlessEqual(len(camList), 11) # test the equality of cameras cameras = [('|cam1|cam1Shape1', '|ReloadGrp|cam1|cam1Shape1'), ('|cam3|cam3Shape', '|ReloadGrp|cam3|cam3Shape'), ('|cam4|cam4Shape', '|ReloadGrp|cam4|cam4Shape')] for c in cameras: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareCamera(c[0], c[1]): self.fail('%s and %s are not the same at frame %d' % (c[0], c[1], t)) def testAnimNCurvesDeleteReload(self): # create some animated curves MayaCmds.textCurves(ch=False, t='Maya', name='Curves', font='Courier') MayaCmds.currentTime(1, update=True) MayaCmds.select('curve1.cv[0:27]', 'curve2.cv[0:45]', 'curve3.cv[0:15]', 'curve4.cv[0:19]', 'curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.setKeyframe() MayaCmds.currentTime(24, update=True) MayaCmds.select('curve1.cv[0:27]', replace=True) MayaCmds.move(-3, 3, 0, relative=True) MayaCmds.select('curve2.cv[0:45]', 'curve3.cv[0:15]', replace=True) MayaCmds.scale(1.5, 1.5, 1.5, relative=True) MayaCmds.select('curve4.cv[0:19]', replace=True) MayaCmds.move(1.5, 0, 0, relative=True) MayaCmds.rotate(0, 90, 0, relative=True) MayaCmds.select('curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.move(3, 0, 0, relative=True) MayaCmds.select('curve1.cv[0:27]', 'curve2.cv[0:45]', 'curve3.cv[0:15]', 'curve4.cv[0:19]', 'curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.setKeyframe() # write them out to an Abc file and load back in self.__files.append(util.expandFileName('testNCurvesReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root CurvesShape -file ' + self.__files[-1]) # load back the Abc file, delete the 2nd letter and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') # delete letter "a" which has two curves MayaCmds.delete('Char_a_1') self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('CurvesShape', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') curveList = MayaCmds.ls(type='nurbsCurve') self.failUnlessEqual(len(curveList), 10) # test the equality of curves curves = [('|CurvesShape|Char_M_1|curve1|curveShape1', '|ReloadGrp|CurvesShape|Char_M_1|curve1|curveShape1'), ('|CurvesShape|Char_y_1|curve4|curveShape4', '|ReloadGrp|CurvesShape|Char_y_1|curve4|curveShape4'), ('|CurvesShape|Char_a_2|curve5|curveShape5', '|ReloadGrp|CurvesShape|Char_a_2|curve5|curveShape5'), ('|CurvesShape|Char_a_2|curve6|curveShape6', '|ReloadGrp|CurvesShape|Char_a_2|curve6|curveShape6')] for c in curves: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareNurbsCurve(c[0], c[1]): self.fail('%s and %s are not the same at frame %d' % (c[0], c[1], t)) #------------------------------------------------------------------------- def testAnimNCurveGrpDeleteReload(self): # create an animated curves group MayaCmds.textCurves(ch=False, t='haka', name='Curves', font='Courier') MayaCmds.addAttr(longName='riCurves', at='bool', dv=True) MayaCmds.currentTime(1, update=True) MayaCmds.select('curve1.cv[0:27]', 'curve2.cv[0:45]', 'curve3.cv[0:15]', 'curve4.cv[0:19]', 'curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.setKeyframe() MayaCmds.currentTime(24, update=True) MayaCmds.select('curve1.cv[0:27]', replace=True) MayaCmds.move(-3, 3, 0, relative=True) MayaCmds.select('curve2.cv[0:45]', 'curve3.cv[0:15]', replace=True) MayaCmds.scale(1.5, 1.5, 1.5, relative=True) MayaCmds.select('curve4.cv[0:19]', replace=True) MayaCmds.move(1.5, 0, 0, relative=True) MayaCmds.rotate(0, 90, 0, relative=True) MayaCmds.select('curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.move(3, 0, 0, relative=True) MayaCmds.select('curve1.cv[0:27]', 'curve2.cv[0:45]', 'curve3.cv[0:15]', 'curve4.cv[0:19]', 'curve5.cv[0:45]', 'curve6.cv[0:15]', replace=True) MayaCmds.setKeyframe() # write them out to an Abc file and load back in self.__files.append(util.expandFileName('testNCurveGrpReload.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root CurvesShape -file ' + self.__files[-1]) # load back the Abc file, delete the 2nd letter and save to a maya file MayaCmds.AbcImport(self.__files[-1], mode='open') # delete letter "a" which has two curves, but as a curve group. # the curve shapes are renamed under the group node MayaCmds.delete('CurvesShape1') MayaCmds.delete('CurvesShape2') self.__files.append(util.expandFileName('testCurves.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('|CurvesShape', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') curveList = MayaCmds.ls(type='nurbsCurve') self.failUnlessEqual(len(curveList), 10) curves = [('|CurvesShape|CurvesShape', '|ReloadGrp|CurvesShape|CurvesShape'), ('|CurvesShape|CurvesShape8', '|ReloadGrp|CurvesShape|CurvesShape3'), ('|CurvesShape|CurvesShape9', '|ReloadGrp|CurvesShape|CurvesShape4'), ('|CurvesShape|CurvesShape10', '|ReloadGrp|CurvesShape|CurvesShape5')] for c in curves: for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareNurbsCurve(c[0], c[1]): self.fail('%s and %s are not the same at frame %d' % (c[0], c[1], t)) def testAnimPropDeleteReload(self): # create some animated properties on a transform node ( could be any type ) nodeName = MayaCmds.polyPrism(ch=False, name = 'prism') MayaCmds.addAttr(longName='SPT_int8', defaultValue=0, attributeType='byte', keyable=True) MayaCmds.addAttr(longName='SPT_int16', defaultValue=100, attributeType='short', keyable=True) MayaCmds.addAttr(longName='SPT_int32', defaultValue=1000, attributeType='long', keyable=True) MayaCmds.addAttr(longName='SPT_float', defaultValue=0.57777777, attributeType='float', keyable=True) MayaCmds.addAttr(longName='SPT_double', defaultValue=5.0456435, attributeType='double', keyable=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(nodeName, attribute='SPT_int8') MayaCmds.setKeyframe(nodeName, attribute='SPT_int16') MayaCmds.setKeyframe(nodeName, attribute='SPT_int32') MayaCmds.setKeyframe(nodeName, attribute='SPT_float') MayaCmds.setKeyframe(nodeName, attribute='SPT_double') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(nodeName, attribute='SPT_int8', value=8) MayaCmds.setKeyframe(nodeName, attribute='SPT_int16', value=16) MayaCmds.setKeyframe(nodeName, attribute='SPT_int32', value=32) MayaCmds.setKeyframe(nodeName, attribute='SPT_float', value=5.24847) MayaCmds.setKeyframe(nodeName, attribute='SPT_double', value=3.14154) # create SPT_HWColor on the shape node MayaCmds.select('prismShape') MayaCmds.addAttr(longName='SPT_HwColorR', defaultValue=1.0, minValue=0.0, maxValue=1.0) MayaCmds.addAttr(longName='SPT_HwColorG', defaultValue=1.0, minValue=0.0, maxValue=1.0) MayaCmds.addAttr(longName='SPT_HwColorB', defaultValue=1.0, minValue=0.0, maxValue=1.0) MayaCmds.addAttr( longName='SPT_HwColor', usedAsColor=True, attributeType='float3') MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(at='SPT_HwColorR') MayaCmds.setKeyframe(at='SPT_HwColorG') MayaCmds.setKeyframe(at='SPT_HwColorB') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(at='SPT_HwColorR', value=0.5) MayaCmds.setKeyframe(at='SPT_HwColorG', value=0.15) MayaCmds.setKeyframe(at='SPT_HwColorB', value=0.75) # write them out to an Abc file and load back in self.__files.append(util.expandFileName('testPropReload.abc')) MayaCmds.AbcExport(j='-atp SPT_ -fr 1 24 -root prism -file ' + self.__files[-1]) # load back the Abc file, delete the 2nd letter and save to a maya file abcNode = MayaCmds.AbcImport( self.__files[-1], mode='open' ) # delete connections to animated props prop = MayaCmds.listConnections('|prism.SPT_float', p=True)[0] MayaCmds.disconnectAttr(prop, '|prism.SPT_float') attr = '|prism|prismShape.SPT_HwColorG' prop = MayaCmds.listConnections(attr, p=True)[0] MayaCmds.disconnectAttr(prop, attr) self.__files.append(util.expandFileName('test.mb')) MayaCmds.file(rename=self.__files[-1]) MayaCmds.file(save=True) # import the saved maya file to compare with the original scene MayaCmds.file(self.__files[-1], open=True) MayaCmds.select('prism', replace=True) MayaCmds.group(name='ReloadGrp') MayaCmds.AbcImport(self.__files[-2], mode='import') # test the equality of props for t in range(1, 25): MayaCmds.currentTime(t, update=True) self.failUnlessEqual(MayaCmds.getAttr('|prism.SPT_int8'), MayaCmds.getAttr('|ReloadGrp|prism.SPT_int8'), 'prism.SPT_int8 not equal' ) self.failUnlessEqual(MayaCmds.getAttr('|prism.SPT_int16'), MayaCmds.getAttr('|ReloadGrp|prism.SPT_int16'), 'prism.SPT_int16 not equal') self.failUnlessEqual(MayaCmds.getAttr('|prism.SPT_int32'), MayaCmds.getAttr('|ReloadGrp|prism.SPT_int32'), 'prism.SPT_int32 not equal') self.failUnlessAlmostEqual(MayaCmds.getAttr('|prism.SPT_double'), MayaCmds.getAttr('|ReloadGrp|prism.SPT_double'), 4, 'prism.SPT_double not equal') self.failUnlessAlmostEqual( MayaCmds.getAttr('|prism|prismShape.SPT_HwColorR'), MayaCmds.getAttr('|ReloadGrp|prism|prismShape.SPT_HwColorR'), 4, 'prismShape.SPT_HwColorR not equal') self.failUnlessAlmostEqual( MayaCmds.getAttr('|prism|prismShape.SPT_HwColorB'), MayaCmds.getAttr('|ReloadGrp|prism|prismShape.SPT_HwColorB'), 4, 'prismShape.SPT_HwColorB not equal')
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class TransformTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticTransformReadWrite(self): nodeName1 = MayaCmds.polyCube() nodeName2 = MayaCmds.duplicate() nodeName3 = MayaCmds.duplicate() self.__files.append(util.expandFileName('reparentflag.abc')) MayaCmds.AbcExport(j='-root %s -root %s -root %s -file %s' % (nodeName1[0], nodeName2[0], nodeName3[0], self.__files[-1])) # reading test MayaCmds.file(new=True, force=True) MayaCmds.createNode('transform', n='root') MayaCmds.AbcImport(self.__files[-1], mode='import', reparent='root') self.failUnlessEqual(MayaCmds.objExists('root|'+nodeName1[0]), 1) self.failUnlessEqual(MayaCmds.objExists('root|'+nodeName2[0]), 1) self.failUnlessEqual(MayaCmds.objExists('root|'+nodeName3[0]), 1)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import subprocess import unittest import util def createCamera(): name = MayaCmds.camera() MayaCmds.setAttr(name[1]+'.horizontalFilmAperture', 0.962) MayaCmds.setAttr(name[1]+'.verticalFilmAperture', 0.731) MayaCmds.setAttr(name[1]+'.focalLength', 50) MayaCmds.setAttr(name[1]+'.focusDistance', 5) MayaCmds.setAttr(name[1]+'.shutterAngle', 144) return name class cameraTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] self.__abcStitcher = [os.environ['AbcStitcher']] def tearDown(self): for f in self.__files: os.remove(f) def testStaticCameraReadWrite(self): name = createCamera() # write to file self.__files.append(util.expandFileName('testStaticCameraReadWrite.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (name[0], self.__files[-1])) # read from file MayaCmds.AbcImport(self.__files[-1], mode='import') camList = MayaCmds.ls(type='camera') self.failUnless(util.compareCamera(camList[0], camList[1])) def testAnimCameraReadWrite(self): name = createCamera() MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(name[1], attribute='horizontalFilmAperture') MayaCmds.setKeyframe(name[1], attribute='focalLength') MayaCmds.setKeyframe(name[1], attribute='focusDistance') MayaCmds.setKeyframe(name[1], attribute='shutterAngle') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(name[1], attribute='horizontalFilmAperture', value=0.95) MayaCmds.setKeyframe(name[1], attribute='focalLength', value=40) MayaCmds.setKeyframe(name[1], attribute='focusDistance', value=5.4) MayaCmds.setKeyframe(name[1], attribute='shutterAngle', value=174.94) self.__files.append(util.expandFileName('testAnimCameraReadWrite.abc')) self.__files.append(util.expandFileName('testAnimCameraReadWrite01_14.abc')) self.__files.append(util.expandFileName('testAnimCameraReadWrite15-24.abc')) # write to files MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name[0], self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name[0], self.__files[-1])) subprocess.call(self.__abcStitcher + self.__files[-3:]) # read from file MayaCmds.AbcImport(self.__files[-3], mode='import') camList = MayaCmds.ls(type='camera') for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareCamera(camList[0], camList[1]): self.fail('%s and %s are not the same at frame %d' % (camList[0], camList[1], t))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import math # adds the current working directory so tools don't get confused about where we # are storing files def expandFileName(name): return os.getcwd() + os.path.sep + name # compare the two floating point values def floatDiff(val1, val2, tolerance): diff = math.fabs(val1 - val2) if diff < math.pow(10, -tolerance): return True return False # function that returns a node object given a name def getObjFromName(nodeName): selectionList = OpenMaya.MSelectionList() selectionList.add( nodeName ) obj = OpenMaya.MObject() selectionList.getDependNode(0, obj) return obj # function that finds a plug given a node object and plug name def getPlugFromName(attrName, nodeObj): fnDepNode = OpenMaya.MFnDependencyNode(nodeObj) attrObj = fnDepNode.attribute(attrName) plug = OpenMaya.MPlug(nodeObj, attrObj) return plug # meaning of return value: # 0 if array1 = array2 # 1 if array1 and array2 are of the same length, array1[i] == array2[i] for 0<=i<m<len, and array1[m] < array2[m] # -1 if array1 and array2 are of the same length, array1[i] == array2[i] for 0<=i<m<len, and array1[m] > array2[m] # 2 if array1.length() < array2.length() # -2 if array1.length() > array2.length() def compareArray(array1, array2): len1 = array1.length() len2 = array2.length() if len1 > len2 : return -2 if len1 < len2 : return 2 for i in range(0, len1): if array1[i] < array2[i] : return 1 if array1[i] > array2[i] : return -1 return 0 # return True if the two point arrays are exactly the same def comparePointArray(array1, array2): len1 = array1.length() len2 = array2.length() if len1 != len2 : return False for i in range(0, len1): if not array1[i].isEquivalent(array2[i], 1e-6): return False return True # return True if the two meshes are identical def compareMesh( nodeName1, nodeName2 ): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kMesh): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kMesh): return False polyIt1 = OpenMaya.MItMeshPolygon( obj1 ) polyIt2 = OpenMaya.MItMeshPolygon( obj2 ) if polyIt1.count() != polyIt2.count(): return False if polyIt1.polygonVertexCount() != polyIt2.polygonVertexCount(): return False vertices1 = OpenMaya.MIntArray() vertices2 = OpenMaya.MIntArray() pointArray1 = OpenMaya.MPointArray() pointArray2 = OpenMaya.MPointArray() while polyIt1.isDone()==False and polyIt2.isDone()==False : # compare vertex indices polyIt1.getVertices(vertices1) polyIt2.getVertices(vertices2) if compareArray(vertices1, vertices2) != 0: return False # compare vertex positions polyIt1.getPoints(pointArray1) polyIt2.getPoints(pointArray2) if not comparePointArray( pointArray1, pointArray2 ): return False polyIt1.next() polyIt2.next() if polyIt1.isDone() and polyIt2.isDone() : return True return False # return True if the two Nurbs Surfaces are identical def compareNurbsSurface(nodeName1, nodeName2): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kNurbsSurface): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kNurbsSurface): return False fn1 = OpenMaya.MFnNurbsSurface(obj1) fn2 = OpenMaya.MFnNurbsSurface(obj2) # degree if fn1.degreeU() != fn2.degreeU(): return False if fn1.degreeV() != fn2.degreeV(): return False # span if fn1.numSpansInU() != fn2.numSpansInU(): return False if fn1.numSpansInV() != fn2.numSpansInV(): return False # form if fn1.formInU() != fn2.formInU(): return False if fn1.formInV() != fn2.formInV(): return False # control points if fn1.numCVsInU() != fn2.numCVsInU(): return False if fn1.numCVsInV() != fn2.numCVsInV(): return False cv1 = OpenMaya.MPointArray() fn1.getCVs(cv1) cv2 = OpenMaya.MPointArray() fn2.getCVs(cv2) if not comparePointArray(cv1, cv2): return False # knots if fn1.numKnotsInU() != fn2.numKnotsInU(): return False if fn1.numKnotsInV() != fn2.numKnotsInV(): return False knotsU1 = OpenMaya.MDoubleArray() fn1.getKnotsInU(knotsU1) knotsV1 = OpenMaya.MDoubleArray() fn1.getKnotsInV(knotsV1) knotsU2 = OpenMaya.MDoubleArray() fn2.getKnotsInU(knotsU2) knotsV2 = OpenMaya.MDoubleArray() fn2.getKnotsInV(knotsV2) if compareArray( knotsU1, knotsU2 ) != 0: return False if compareArray( knotsV1, knotsV2 ) != 0: return False # trim curves if fn1.isTrimmedSurface() != fn2.isTrimmedSurface(): return False # may need to add more trim checks return True # return True if the two locators are idential def compareLocator(nodeName1, nodeName2): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kLocator): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kLocator): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localPositionX'), MayaCmds.getAttr(nodeName2+'.localPositionX'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localPositionY'), MayaCmds.getAttr(nodeName2+'.localPositionY'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localPositionZ'), MayaCmds.getAttr(nodeName2+'.localPositionZ'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localScaleX'), MayaCmds.getAttr(nodeName2+'.localScaleX'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localScaleY'), MayaCmds.getAttr(nodeName2+'.localScaleY'), 4): return False if not floatDiff(MayaCmds.getAttr(nodeName1+'.localScaleZ'), MayaCmds.getAttr(nodeName2+'.localScaleZ'), 4): return False return True # return True if the two cameras are identical def compareCamera( nodeName1, nodeName2 ): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kCamera): return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kCamera): return False fn1 = OpenMaya.MFnCamera( obj1 ) fn2 = OpenMaya.MFnCamera( obj2 ) if fn1.filmFit() != fn2.filmFit(): print "differ in filmFit" return False if not floatDiff(fn1.filmFitOffset(), fn2.filmFitOffset(), 4): print "differ in filmFitOffset" return False if fn1.isOrtho() != fn2.isOrtho(): print "differ in isOrtho" return False if not floatDiff(fn1.orthoWidth(), fn2.orthoWidth(), 4): print "differ in orthoWidth" return False if not floatDiff(fn1.focalLength(), fn2.focalLength(), 4): print "differ in focalLength" return False if not floatDiff(fn1.lensSqueezeRatio(), fn2.lensSqueezeRatio(), 4): print "differ in lensSqueezeRatio" return False if not floatDiff(fn1.cameraScale(), fn2.cameraScale(), 4): print "differ in cameraScale" return False if not floatDiff(fn1.horizontalFilmAperture(), fn2.horizontalFilmAperture(), 4): print "differ in horizontalFilmAperture" return False if not floatDiff(fn1.verticalFilmAperture(), fn2.verticalFilmAperture(), 4): print "differ in verticalFilmAperture" return False if not floatDiff(fn1.horizontalFilmOffset(), fn2.horizontalFilmOffset(), 4): print "differ in horizontalFilmOffset" return False if not floatDiff(fn1.verticalFilmOffset(), fn2.verticalFilmOffset(), 4): print "differ in verticalFilmOffset" return False if not floatDiff(fn1.overscan(), fn2.overscan(), 4): print "differ in overscan" return False if not floatDiff(fn1.nearClippingPlane(), fn2.nearClippingPlane(), 4): print "differ in nearClippingPlane" return False if not floatDiff(fn1.farClippingPlane(), fn2.farClippingPlane(), 4): print "differ in farClippingPlane" return False if not floatDiff(fn1.preScale(), fn2.preScale(), 4): print "differ in preScale" return False if not floatDiff(fn1.postScale(), fn2.postScale(), 4): print "differ in postScale" return False if not floatDiff(fn1.filmTranslateH(), fn2.filmTranslateH(), 4): print "differ in filmTranslateH" return False if not floatDiff(fn1.filmTranslateV(), fn2.filmTranslateV(), 4): print "differ in filmTranslateV" return False if not floatDiff(fn1.horizontalRollPivot(), fn2.horizontalRollPivot(), 4): print "differ in horizontalRollPivot" return False if not floatDiff(fn1.verticalRollPivot(), fn2.verticalRollPivot(), 4): print "differ in verticalRollPivot" return False if fn1.filmRollOrder() != fn2.filmRollOrder(): print "differ in filmRollOrder" return False if not floatDiff(fn1.filmRollValue(), fn2.filmRollValue(), 4): print "differ in filmRollValue" return False if not floatDiff(fn1.fStop(), fn2.fStop(), 4): print "differ in fStop" return False if not floatDiff(fn1.focusDistance(), fn2.focusDistance(), 4,): print "differ in focusDistance" return False if not floatDiff(fn1.shutterAngle(), fn2.shutterAngle(), 4): print "differ in shutterAngle" return False if fn1.usePivotAsLocalSpace() != fn2.usePivotAsLocalSpace(): print "differ in usePivotAsLocalSpace" return False if fn1.tumblePivot() != fn2.tumblePivot(): print "differ in tumblePivot" return False return True # return True if the two Nurbs curves are identical def compareNurbsCurve(nodeName1, nodeName2): # basic error checking obj1 = getObjFromName(nodeName1) if not obj1.hasFn(OpenMaya.MFn.kNurbsCurve): print nodeName1, "not a curve." return False obj2 = getObjFromName(nodeName2) if not obj2.hasFn(OpenMaya.MFn.kNurbsCurve): print nodeName2, "not a curve." return False fn1 = OpenMaya.MFnNurbsCurve(obj1) fn2 = OpenMaya.MFnNurbsCurve(obj2) if fn1.degree() != fn2.degree(): print nodeName1, nodeName2, "degrees differ." return False if fn1.numCVs() != fn2.numCVs(): print nodeName1, nodeName2, "numCVs differ." return False if fn1.numSpans() != fn2.numSpans(): print nodeName1, nodeName2, "spans differ." return False if fn1.numKnots() != fn2.numKnots(): print nodeName1, nodeName2, "numKnots differ." return False if fn1.form() != fn2.form(): print nodeName1, nodeName2, "form differ." return False cv1 = OpenMaya.MPointArray() fn1.getCVs(cv1) cv2 = OpenMaya.MPointArray() fn2.getCVs(cv2) if not comparePointArray(cv1, cv2): print nodeName1, nodeName2, "points differ." return False # we do not need to compare knots, since they aren't stored in Alembic # and are currently recreated as uniformly distributed between 0 and 1 return True
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest class AbcExport_dupRootsTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) def testStaticTransformReadWrite(self): MayaCmds.polyCube(n='cube') MayaCmds.group(n='group1') MayaCmds.duplicate() self.failUnlessRaises(RuntimeError, MayaCmds.AbcExport, j='-root group1|cube -root group2|cube -f dupRoots.abc') # the abc file shouldn't exist self.failUnless(not os.path.isfile('dupRoots.abc'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import subprocess import unittest import util class AnimNurbsSurfaceTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testAnimNurbsPlaneWrite(self): ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0) name = ret[0] MayaCmds.lattice(name, dv=(4, 5, 4), oc=True) MayaCmds.select('ffd1Lattice.pt[1:2][0:4][1:2]', r=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(12, update=True) MayaCmds.move( 0, 0.18, 0, r=True) MayaCmds.scale( 2.5, 1.0, 2.5, r=True) MayaCmds.setKeyframe() MayaCmds.curveOnSurface(name, uv=((0.597523,0), (0.600359,0.271782), (0.538598,0.564218), (0.496932,0.779936), (0.672153,1)), k=(0,0,0,0.263463,0.530094,0.530094,0.530094)) curvename = MayaCmds.curveOnSurface(name, uv=((0.170718,0.565967), (0.0685088,0.393034), (0.141997,0.206296), (0.95,0.230359), (0.36264,0.441381), (0.251243,0.569889)), k=(0,0,0,0.200545,0.404853,0.598957,0.598957,0.598957)) MayaCmds.closeCurve(curvename, ch=1, ps=1, rpo=1, bb=0.5, bki=0, p=0.1, cos=1) MayaCmds.trim(name, lu=0.23, lv=0.39) degreeU = MayaCmds.getAttr(name+'.degreeU') degreeV = MayaCmds.getAttr(name+'.degreeV') spansU = MayaCmds.getAttr(name+'.spansU') spansV = MayaCmds.getAttr(name+'.spansV') formU = MayaCmds.getAttr(name+'.formU') formV = MayaCmds.getAttr(name+'.formV') minU = MayaCmds.getAttr(name+'.minValueU') maxU = MayaCmds.getAttr(name+'.maxValueU') minV = MayaCmds.getAttr(name+'.minValueV') maxV = MayaCmds.getAttr(name+'.maxValueV') MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface', force=True) MayaCmds.currentTime(1, update=True) controlPoints = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]') knotsU = MayaCmds.getAttr('surfaceInfo1.knotsU[*]') knotsV = MayaCmds.getAttr('surfaceInfo1.knotsV[*]') MayaCmds.currentTime(12, update=True) controlPoints2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]') knotsU2 = MayaCmds.getAttr('surfaceInfo1.knotsU[*]') knotsV2 = MayaCmds.getAttr('surfaceInfo1.knotsV[*]') self.__files.append(util.expandFileName('testAnimNurbsPlane.abc')) self.__files.append(util.expandFileName('testAnimNurbsPlane01_14.abc')) self.__files.append(util.expandFileName('testAnimNurbsPlane15_24.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name, self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name, self.__files[-1])) # use AbcStitcher to combine two files into one subprocess.call(self.__abcStitcher + self.__files[-3:]) # reading test MayaCmds.AbcImport(self.__files[-3], mode='open') self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU')) self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV')) self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU')) self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV')) self.failUnlessEqual(formU, MayaCmds.getAttr(name+'.formU')) self.failUnlessEqual(formV, MayaCmds.getAttr(name+'.formV')) self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU')) self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU')) self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV')) self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV')) MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface', force=True) MayaCmds.currentTime(1, update=True) errmsg = "At frame #1, Nurbs Plane's control point #%d.%s not equal" for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i)) self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x')) self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y')) self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z')) errmsg = "At frame #1, Nurbs Plane's control knotsU #%d not equal" for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i)) self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i)) errmsg = "At frame #1, Nurbs Plane's control knotsV #%d not equal" for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i)) self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i)) MayaCmds.currentTime(12, update=True) errmsg = "At frame #12, Nurbs Plane's control point #%d.%s not equal" for i in range(0, len(controlPoints2)): cp1 = controlPoints2[i] cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i)) self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x')) self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y')) self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z')) errmsg = "At frame #12, Nurbs Plane's control knotsU #%d not equal" for i in range(0, len(knotsU2)): ku1 = knotsU2[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i)) self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i)) errmsg = "At frame #12, Nurbs Plane's control knotsV #%d not equal" for i in range(0, len(knotsV2)): kv1 = knotsV2[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i)) self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i)) MayaCmds.currentTime(24, update=True) errmsg = "At frame #24, Nurbs Plane's control point #%d.%s not equal" for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % (i)) self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, errmsg % (i, 'x')) self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, errmsg % (i, 'y')) self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, errmsg % (i, 'z')) errmsg = "At frame #24, Nurbs Plane's control knotsU #%d not equal" for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % (i)) self.failUnlessAlmostEqual(ku1, ku2, 3, errmsg % (i)) errmsg = "At frame #24, Nurbs Plane's control knotsV #%d not equal" for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % (i)) self.failUnlessAlmostEqual(kv1, kv2, 3, errmsg % (i))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class renderableOnlyTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testRenderableOnly(self): MayaCmds.polyPlane(name='potato') MayaCmds.polyPlane(name='hidden') MayaCmds.setAttr("hidden.visibility", 0) self.__files.append(util.expandFileName('renderableOnlyTest.abc')) MayaCmds.AbcExport(j='-renderableOnly -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') self.failUnless(MayaCmds.objExists('potato')) self.failIf(MayaCmds.objExists('hidden'))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util def getObjFromName( nodeName ): selectionList = OpenMaya.MSelectionList() selectionList.add( nodeName ) obj = OpenMaya.MObject() selectionList.getDependNode(0, obj) return obj class MeshUVsTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) # we only support writing out the most basic uv sets (and static only) def testPolyUVs(self): MayaCmds.polyCube(name = 'cube') cubeObj = getObjFromName('cubeShape') fnMesh = OpenMaya.MFnMesh(cubeObj) # get the name of the current UV set uvSetName = fnMesh.currentUVSetName() uArray = OpenMaya.MFloatArray() vArray = OpenMaya.MFloatArray() fnMesh.getUVs(uArray, vArray, uvSetName) newUArray = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 2, -1, -1] newVArray = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 0, 1 , 0, 1] for i in range(0, 14): uArray[i] = newUArray[i] vArray[i] = newVArray[i] fnMesh.setUVs(uArray, vArray, uvSetName) self.__files.append(util.expandFileName('polyUvsTest.abc')) MayaCmds.AbcExport(j='-uv -root cube -file ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.select('cube.map[0:13]', replace=True) uvs = MayaCmds.polyEditUV(query=True) for i in range(0, 14): self.failUnlessAlmostEqual(newUArray[i], uvs[2*i], 4, 'map[%d].u is not the same' % i) self.failUnlessAlmostEqual(newVArray[i], uvs[2*i+1], 4, 'map[%d].v is not the same' % i)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util class AnimMeshTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] self.__abcStitcherExe = os.environ['AbcStitcher'] + ' ' def tearDown(self): for f in self.__files : os.remove(f) def testAnimPolyReadWrite(self): numFaces = 6 numVertices = 8 numFaceConnects = 24 vtx_1 = OpenMaya.MFloatPoint(-0.5, -0.5, -0.5) vtx_2 = OpenMaya.MFloatPoint( 0.5, -0.5, -0.5) vtx_3 = OpenMaya.MFloatPoint( 0.5, -0.5, 0.5) vtx_4 = OpenMaya.MFloatPoint(-0.5, -0.5, 0.5) vtx_5 = OpenMaya.MFloatPoint(-0.5, 0.5, -0.5) vtx_6 = OpenMaya.MFloatPoint(-0.5, 0.5, 0.5) vtx_7 = OpenMaya.MFloatPoint( 0.5, 0.5, 0.5) vtx_8 = OpenMaya.MFloatPoint( 0.5, 0.5, -0.5) points = OpenMaya.MFloatPointArray() points.setLength(8) points.set(vtx_1, 0) points.set(vtx_2, 1) points.set(vtx_3, 2) points.set(vtx_4, 3) points.set(vtx_5, 4) points.set(vtx_6, 5) points.set(vtx_7, 6) points.set(vtx_8, 7) faceConnects = OpenMaya.MIntArray() faceConnects.setLength(numFaceConnects) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) faceConnects.set(4, 4) faceConnects.set(5, 5) faceConnects.set(6, 6) faceConnects.set(7, 7) faceConnects.set(3, 8) faceConnects.set(2, 9) faceConnects.set(6, 10) faceConnects.set(5, 11) faceConnects.set(0, 12) faceConnects.set(3, 13) faceConnects.set(5, 14) faceConnects.set(4, 15) faceConnects.set(0, 16) faceConnects.set(4, 17) faceConnects.set(7, 18) faceConnects.set(1, 19) faceConnects.set(1, 20) faceConnects.set(7, 21) faceConnects.set(6, 22) faceConnects.set(2, 23) faceCounts = OpenMaya.MIntArray() faceCounts.setLength(6) faceCounts.set(4, 0) faceCounts.set(4, 1) faceCounts.set(4, 2) faceCounts.set(4, 3) faceCounts.set(4, 4) faceCounts.set(4, 5) transFn = OpenMaya.MFnTransform() parent = transFn.create() transFn.setName('poly') meshFn = OpenMaya.MFnMesh() meshFn.create(numVertices, numFaces, points, faceCounts, faceConnects, parent) meshFn.setName("polyShape"); MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('polyShape.vtx[0:7]') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe('polyShape.vtx[0:7]') MayaCmds.currentTime(12, update=True) vtx_11 = OpenMaya.MFloatPoint(-1, -1, -1) vtx_22 = OpenMaya.MFloatPoint( 1, -1, -1) vtx_33 = OpenMaya.MFloatPoint( 1, -1, 1) vtx_44 = OpenMaya.MFloatPoint(-1, -1, 1) vtx_55 = OpenMaya.MFloatPoint(-1, 1, -1) vtx_66 = OpenMaya.MFloatPoint(-1, 1, 1) vtx_77 = OpenMaya.MFloatPoint( 1, 1, 1) vtx_88 = OpenMaya.MFloatPoint( 1, 1, -1) points.set(vtx_11, 0) points.set(vtx_22, 1) points.set(vtx_33, 2) points.set(vtx_44, 3) points.set(vtx_55, 4) points.set(vtx_66, 5) points.set(vtx_77, 6) points.set(vtx_88, 7) meshFn.setPoints(points) MayaCmds.setKeyframe('polyShape.vtx[0:7]') self.__files.append(util.expandFileName('animPoly.abc')) self.__files.append(util.expandFileName('animPoly01_14.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root poly -file ' + self.__files[-1]) self.__files.append(util.expandFileName('animPoly15_24.abc')) MayaCmds.AbcExport(j='-fr 15 24 -root poly -file ' + self.__files[-1]) # use AbcStitcher to combine two files into one os.system(self.__abcStitcherExe + ' '.join(self.__files[-3:])) # reading test MayaCmds.AbcImport(self.__files[-3], mode='open') MayaCmds.currentTime(1, update=True) sList = OpenMaya.MSelectionList(); sList.add('polyShape'); meshObj = OpenMaya.MObject(); sList.getDependNode(0, meshObj); meshFn = OpenMaya.MFnMesh(meshObj) # check the point list meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7]) # check the polygonvertices list vertexList = OpenMaya.MIntArray() faceConnects = OpenMaya.MIntArray() faceConnects.setLength(4) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) meshFn.getPolygonVertices(0, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(4, 0) faceConnects.set(5, 1) faceConnects.set(6, 2) faceConnects.set(7, 3) meshFn.getPolygonVertices(1, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(3, 0) faceConnects.set(2, 1) faceConnects.set(6, 2) faceConnects.set(5, 3) meshFn.getPolygonVertices(2, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(3, 1) faceConnects.set(5, 2) faceConnects.set(4, 3) meshFn.getPolygonVertices(3, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(4, 1) faceConnects.set(7, 2) faceConnects.set(1, 3) meshFn.getPolygonVertices(4, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(1, 0) faceConnects.set(7, 1) faceConnects.set(6, 2) faceConnects.set(2, 3) meshFn.getPolygonVertices(5, vertexList) self.failUnlessEqual(faceConnects, vertexList) MayaCmds.currentTime(12, update=True) meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_11, meshPoints[0]) self.failUnlessEqual(vtx_22, meshPoints[1]) self.failUnlessEqual(vtx_33, meshPoints[2]) self.failUnlessEqual(vtx_44, meshPoints[3]) self.failUnlessEqual(vtx_55, meshPoints[4]) self.failUnlessEqual(vtx_66, meshPoints[5]) self.failUnlessEqual(vtx_77, meshPoints[6]) self.failUnlessEqual(vtx_88, meshPoints[7]) MayaCmds.currentTime(24, update=True) meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7]) def testAnimSubDReadWrite(self): numFaces = 6 numVertices = 8 numFaceConnects = 24 vtx_1 = OpenMaya.MFloatPoint(-0.5, -0.5, -0.5) vtx_2 = OpenMaya.MFloatPoint( 0.5, -0.5, -0.5) vtx_3 = OpenMaya.MFloatPoint( 0.5, -0.5, 0.5) vtx_4 = OpenMaya.MFloatPoint(-0.5, -0.5, 0.5) vtx_5 = OpenMaya.MFloatPoint(-0.5, 0.5, -0.5) vtx_6 = OpenMaya.MFloatPoint(-0.5, 0.5, 0.5) vtx_7 = OpenMaya.MFloatPoint( 0.5, 0.5, 0.5) vtx_8 = OpenMaya.MFloatPoint( 0.5, 0.5, -0.5) points = OpenMaya.MFloatPointArray() points.setLength(8) points.set(vtx_1, 0) points.set(vtx_2, 1) points.set(vtx_3, 2) points.set(vtx_4, 3) points.set(vtx_5, 4) points.set(vtx_6, 5) points.set(vtx_7, 6) points.set(vtx_8, 7) faceConnects = OpenMaya.MIntArray() faceConnects.setLength(numFaceConnects) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) faceConnects.set(4, 4) faceConnects.set(5, 5) faceConnects.set(6, 6) faceConnects.set(7, 7) faceConnects.set(3, 8) faceConnects.set(2, 9) faceConnects.set(6, 10) faceConnects.set(5, 11) faceConnects.set(0, 12) faceConnects.set(3, 13) faceConnects.set(5, 14) faceConnects.set(4, 15) faceConnects.set(0, 16) faceConnects.set(4, 17) faceConnects.set(7, 18) faceConnects.set(1, 19) faceConnects.set(1, 20) faceConnects.set(7, 21) faceConnects.set(6, 22) faceConnects.set(2, 23) faceCounts = OpenMaya.MIntArray() faceCounts.setLength(6) faceCounts.set(4, 0) faceCounts.set(4, 1) faceCounts.set(4, 2) faceCounts.set(4, 3) faceCounts.set(4, 4) faceCounts.set(4, 5) transFn = OpenMaya.MFnTransform() parent = transFn.create() transFn.setName('subD') meshFn = OpenMaya.MFnMesh() meshFn.create(numVertices, numFaces, points, faceCounts, faceConnects, parent) meshFn.setName("subDShape"); MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe('subDShape.vtx[0:7]') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe('subDShape.vtx[0:7]') MayaCmds.currentTime(12, update=True) vtx_11 = OpenMaya.MFloatPoint(-1, -1, -1) vtx_22 = OpenMaya.MFloatPoint( 1, -1, -1) vtx_33 = OpenMaya.MFloatPoint( 1, -1, 1) vtx_44 = OpenMaya.MFloatPoint(-1, -1, 1) vtx_55 = OpenMaya.MFloatPoint(-1, 1, -1) vtx_66 = OpenMaya.MFloatPoint(-1, 1, 1) vtx_77 = OpenMaya.MFloatPoint( 1, 1, 1) vtx_88 = OpenMaya.MFloatPoint( 1, 1, -1) points.set(vtx_11, 0) points.set(vtx_22, 1) points.set(vtx_33, 2) points.set(vtx_44, 3) points.set(vtx_55, 4) points.set(vtx_66, 5) points.set(vtx_77, 6) points.set(vtx_88, 7) meshFn.setPoints(points) MayaCmds.setKeyframe('subDShape.vtx[0:7]') # mark the mesh as a subD MayaCmds.select('subDShape') MayaCmds.addAttr(attributeType='bool', defaultValue=1, keyable=True, longName='SubDivisionMesh') self.__files.append(util.expandFileName('animSubD.abc')) self.__files.append(util.expandFileName('animSubD01_14.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root subD -file ' + self.__files[-1]) self.__files.append(util.expandFileName('animSubD15_24.abc')) MayaCmds.AbcExport(j='-fr 15 24 -root subD -file ' + self.__files[-1]) # use AbcStitcher to combine two files into one os.system(self.__abcStitcherExe + ' '.join(self.__files[-3:])) # reading test MayaCmds.AbcImport(self.__files[-3], mode='open') MayaCmds.currentTime(1, update=True) sList = OpenMaya.MSelectionList() sList.add('subDShape') meshObj = OpenMaya.MObject() sList.getDependNode(0, meshObj) meshFn = OpenMaya.MFnMesh(meshObj) # check the point list meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7]) # check the polygonvertices list vertexList = OpenMaya.MIntArray() faceConnects = OpenMaya.MIntArray() faceConnects.setLength(4) faceConnects.set(0, 0) faceConnects.set(1, 1) faceConnects.set(2, 2) faceConnects.set(3, 3) meshFn.getPolygonVertices(0, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(4, 0) faceConnects.set(5, 1) faceConnects.set(6, 2) faceConnects.set(7, 3) meshFn.getPolygonVertices(1, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(3, 0) faceConnects.set(2, 1) faceConnects.set(6, 2) faceConnects.set(5, 3) meshFn.getPolygonVertices(2, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(3, 1) faceConnects.set(5, 2) faceConnects.set(4, 3) meshFn.getPolygonVertices(3, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(0, 0) faceConnects.set(4, 1) faceConnects.set(7, 2) faceConnects.set(1, 3) meshFn.getPolygonVertices(4, vertexList) self.failUnlessEqual(faceConnects, vertexList) faceConnects.set(1, 0) faceConnects.set(7, 1) faceConnects.set(6, 2) faceConnects.set(2, 3) meshFn.getPolygonVertices(5, vertexList) self.failUnlessEqual(faceConnects, vertexList) MayaCmds.currentTime(12, update=True) meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_11, meshPoints[0]) self.failUnlessEqual(vtx_22, meshPoints[1]) self.failUnlessEqual(vtx_33, meshPoints[2]) self.failUnlessEqual(vtx_44, meshPoints[3]) self.failUnlessEqual(vtx_55, meshPoints[4]) self.failUnlessEqual(vtx_66, meshPoints[5]) self.failUnlessEqual(vtx_77, meshPoints[6]) self.failUnlessEqual(vtx_88, meshPoints[7]) MayaCmds.currentTime(24, update=True) meshPoints = OpenMaya.MFloatPointArray() meshFn.getPoints(meshPoints) self.failUnlessEqual(vtx_1, meshPoints[0]) self.failUnlessEqual(vtx_2, meshPoints[1]) self.failUnlessEqual(vtx_3, meshPoints[2]) self.failUnlessEqual(vtx_4, meshPoints[3]) self.failUnlessEqual(vtx_5, meshPoints[4]) self.failUnlessEqual(vtx_6, meshPoints[5]) self.failUnlessEqual(vtx_7, meshPoints[6]) self.failUnlessEqual(vtx_8, meshPoints[7])
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class StaticPointPrimitiveTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testPointPrimitiveReadWrite(self): # Creates a particle object with four particles name = MayaCmds.particle( p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9)]) posVec = [0, 0, 0, 3, 5, 6, 5, 6, 7, 9, 9, 9] self.__files.append(util.expandFileName('testPointPrimitiveReadWrite.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name[0], self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') pos = MayaCmds.getAttr(name[1] + '.position') ids = MayaCmds.getAttr(name[1] + '.particleId') self.failUnlessEqual(len(ids), 4) for i in range(0, 4): index = 3*i self.failUnlessAlmostEqual(pos[i][0], posVec[index], 4) self.failUnlessAlmostEqual(pos[i][1], posVec[index+1], 4) self.failUnlessAlmostEqual(pos[i][2], posVec[index+2], 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import subprocess import unittest import util def createLocator(): shape = MayaCmds.createNode("locator") name = MayaCmds.pickWalk(shape, d="up") MayaCmds.setAttr(shape+'.localPositionX', 0.962) MayaCmds.setAttr(shape+'.localPositionY', 0.731) MayaCmds.setAttr(shape+'.localPositionZ', 5.114) MayaCmds.setAttr(shape+'.localScaleX', 5) MayaCmds.setAttr(shape+'.localScaleY', 1.44) MayaCmds.setAttr(shape+'.localScaleZ', 1.38) return name[0], shape class locatorTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] self.__abcStitcher = [os.environ['AbcStitcher']] def tearDown(self): for f in self.__files: os.remove(f) def testStaticLocatorRW(self): name = createLocator() # write to file self.__files.append(util.expandFileName('testStaticLocatorRW.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (name[0], self.__files[-1])) # read from file MayaCmds.AbcImport(self.__files[-1], mode='import') locatorList = MayaCmds.ls(type='locator') self.failUnless(util.compareLocator(locatorList[0], locatorList[1])) def testAnimLocatorRW(self): name = createLocator() MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(name[1], attribute='localPositionX') MayaCmds.setKeyframe(name[1], attribute='localPositionY') MayaCmds.setKeyframe(name[1], attribute='localPositionZ') MayaCmds.setKeyframe(name[1], attribute='localScaleX') MayaCmds.setKeyframe(name[1], attribute='localScaleY') MayaCmds.setKeyframe(name[1], attribute='localScaleZ') MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe(name[1], attribute='localPositionX', value=0.0) MayaCmds.setKeyframe(name[1], attribute='localPositionY', value=0.0) MayaCmds.setKeyframe(name[1], attribute='localPositionZ', value=0.0) MayaCmds.setKeyframe(name[1], attribute='localScaleX', value=1.0) MayaCmds.setKeyframe(name[1], attribute='localScaleY', value=1.0) MayaCmds.setKeyframe(name[1], attribute='localScaleZ', value=1.0) self.__files.append(util.expandFileName('testAnimLocatorRW.abc')) self.__files.append(util.expandFileName('testAnimLocatorRW01_14.abc')) self.__files.append(util.expandFileName('testAnimLocatorRW15-24.abc')) # write to files MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name[0], self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name[0], self.__files[-1])) subprocess.call(self.__abcStitcher + self.__files[-3:]) # read from file MayaCmds.AbcImport(self.__files[-3], mode='import') locatorList = MayaCmds.ls(type='locator') for t in range(1, 25): MayaCmds.currentTime(t, update=True) if not util.compareLocator(locatorList[0], locatorList[1]): self.fail('%s and %s are not the same at frame %d' % (locatorList[0], locatorList[1], t))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def testStaticNurbsWithoutTrim(self, surfacetype, abcFileName): if (surfacetype == 0): ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0) errmsg = 'Nurbs Plane' elif (surfacetype == 1): ret = MayaCmds.sphere(p=(0, 0, 0), ax=(0, 1, 0), ssw=0, esw=360, r=1, d=3, ut=0, tol=0.01, s=8, nsp=4, ch=0) errmsg = 'Nurbs Sphere' elif (surfacetype == 2): ret = MayaCmds.torus(p=(0, 0, 0), ax=(0, 1, 0), ssw=0, esw=360, msw=360, r=1, hr=0.5, ch=0) errmsg = 'Nurbs Torus' name = ret[0] degreeU = MayaCmds.getAttr(name+'.degreeU') degreeV = MayaCmds.getAttr(name+'.degreeV') spansU = MayaCmds.getAttr(name+'.spansU') spansV = MayaCmds.getAttr(name+'.spansV') minU = MayaCmds.getAttr(name+'.minValueU') maxU = MayaCmds.getAttr(name+'.maxValueU') minV = MayaCmds.getAttr(name+'.minValueV') maxV = MayaCmds.getAttr(name+'.maxValueV') surfaceInfoNode = MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', surfaceInfoNode+'.inputSurface', force=True) controlPoints = MayaCmds.getAttr(surfaceInfoNode+'.controlPoints[*]') knotsU = MayaCmds.getAttr(surfaceInfoNode+'.knotsU[*]') knotsV = MayaCmds.getAttr(surfaceInfoNode+'.knotsV[*]') MayaCmds.AbcExport(j='-root %s -f %s' % (name, abcFileName)) # reading test MayaCmds.AbcImport(abcFileName, mode='open') self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU')) self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV')) self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU')) self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV')) self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU')) self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU')) self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV')) self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV')) # form will always be open self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formU')) self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formV')) surfaceInfoNode = MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', surfaceInfoNode+'.inputSurface', force=True) controlPoints2 = MayaCmds.getAttr(surfaceInfoNode + '.controlPoints[*]') self.failUnlessEqual(len(controlPoints), len(controlPoints2)) for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = controlPoints2[i] self.failUnlessAlmostEqual(cp1[0], cp2[0], 3, 'cp[%d].x not equal' % i) self.failUnlessAlmostEqual(cp1[1], cp2[1], 3, 'cp[%d].y not equal' % i) self.failUnlessAlmostEqual(cp1[2], cp2[2], 3, 'cp[%d].z not equal' % i) for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % i) self.failUnlessAlmostEqual(ku1, ku2, 3, 'control knotsU # %d not equal' % i) for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % i) self.failUnlessAlmostEqual(kv1, kv2, 3, 'control knotsV # %d not equal' % i) def testStaticNurbsWithOneCloseCurveTrim(self, surfacetype, abcFileName, trimtype): if (surfacetype == 0): ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0) elif (surfacetype == 1): ret = MayaCmds.sphere(p=(0, 0, 0), ax=(0, 1, 0), ssw=0, esw=360, r=1, d=3, ut=0, tol=0.01, s=8, nsp=4, ch=0) elif (surfacetype == 2): ret = MayaCmds.torus(p=(0, 0, 0), ax=(0, 1, 0), ssw=0, esw=360, msw=360, r=1, hr=0.5, ch=0) name = ret[0] MayaCmds.curveOnSurface(name, uv=((0.170718,0.565967), (0.0685088,0.393034), (0.141997,0.206296), (0.95,0.230359), (0.36264,0.441381), (0.251243,0.569889)), k=(0,0,0,0.200545,0.404853,0.598957,0.598957,0.598957)) MayaCmds.closeCurve(name+'->curve1', ch=1, ps=1, rpo=1, bb=0.5, bki=0, p=0.1, cos=1) if trimtype == 0 : MayaCmds.trim(name, lu=0.68, lv=0.39) elif 1 : MayaCmds.trim(name, lu=0.267062, lv=0.39475) degreeU = MayaCmds.getAttr(name+'.degreeU') degreeV = MayaCmds.getAttr(name+'.degreeV') spansU = MayaCmds.getAttr(name+'.spansU') spansV = MayaCmds.getAttr(name+'.spansV') formU = MayaCmds.getAttr(name+'.formU') formV = MayaCmds.getAttr(name+'.formV') minU = MayaCmds.getAttr(name+'.minValueU') maxU = MayaCmds.getAttr(name+'.maxValueU') minV = MayaCmds.getAttr(name+'.minValueV') maxV = MayaCmds.getAttr(name+'.maxValueV') surfaceInfoNode = MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', surfaceInfoNode+'.inputSurface', force=True) controlPoints = MayaCmds.getAttr(surfaceInfoNode+'.controlPoints[*]') knotsU = MayaCmds.getAttr(surfaceInfoNode+'.knotsU[*]') knotsV = MayaCmds.getAttr(surfaceInfoNode+'.knotsV[*]') MayaCmds.AbcExport(j='-root %s -f %s' % (name, abcFileName)) MayaCmds.AbcImport(abcFileName, mode='open') self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU')) self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV')) self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU')) self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV')) self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU')) self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU')) self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV')) self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV')) surfaceInfoNode = MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', surfaceInfoNode+'.inputSurface', force=True) controlPoints2 = MayaCmds.getAttr( surfaceInfoNode + '.controlPoints[*]') self.failUnlessEqual(len(controlPoints), len(controlPoints2)) for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = controlPoints2[i] self.failUnlessAlmostEqual(cp1[0], cp2[0], 3, 'cp[%d].x not equal' % i) self.failUnlessAlmostEqual(cp1[1], cp2[1], 3, 'cp[%d].y not equal' % i) self.failUnlessAlmostEqual(cp1[2], cp2[2], 3, 'cp[%d].z not equal' % i) for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % i) self.failUnlessAlmostEqual(ku1, ku2, 3, 'control knotsU # %d not equal' % i) for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % i) self.failUnlessAlmostEqual(kv1, kv2, 3, 'control knotsV # %d not equal' % i) class StaticNurbsSurfaceTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticNurbsSurfaceWithoutTrimReadWrite(self): # open - open surface self.__files.append(util.expandFileName('testStaticNurbsPlaneWithoutTrim.abc')) testStaticNurbsWithoutTrim(self, 0, self.__files[-1]) # open - periodic surface self.__files.append(util.expandFileName('testStaticNurbsSphereWithoutTrim.abc')) testStaticNurbsWithoutTrim(self, 1, self.__files[-1]) # periodic - periodic surface self.__files.append(util.expandFileName('testStaticNurbsTorusWithoutTrim.abc')) testStaticNurbsWithoutTrim(self, 2 , self.__files[-1]) def testStaticNurbsSurfaceWithOneCloseCurveTrimInsideReadWrite(self): # open - open surface self.__files.append(util.expandFileName('testStaticNurbsPlaneWithOneCloseCurveTrimInside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 0 , self.__files[-1], 0) # open - periodic surface self.__files.append(util.expandFileName('testStaticNurbsSphereWithOneCloseCurveTrimInside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 1, self.__files[-1], 0) # periodic - periodic surface self.__files.append(util.expandFileName('testStaticNurbsTorusWithOneCloseCurveTrimInside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 2, self.__files[-1], 0) def testStaticNurbsSurfaceWithOneCloseCurveTrimOutsideReadWrite(self): # open - open surface self.__files.append(util.expandFileName('testStaticNurbsPlaneWithOneCloseCurveTrimOutside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 0, self.__files[-1], 1) # open - periodic surface self.__files.append(util.expandFileName('testStaticNurbsSphereWithOneCloseCurveTrimOutside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 1, self.__files[-1], 1) # periodic - periodic surface self.__files.append(util.expandFileName('testStaticNurbsTorusWithOneCloseCurveTrimOutside.abc')) testStaticNurbsWithOneCloseCurveTrim(self, 2, self.__files[-1], 1) def testStaticNurbsPlaneWithOneSegmentTrimReadWrite(self): ret = MayaCmds.nurbsPlane(p=(0, 0, 0), ax=(0, 1, 0), w=1, lr=1, d=3, u=5, v=5, ch=0) name = ret[0] MayaCmds.curveOnSurface(name, uv=((0.597523,0), (0.600359,0.271782), (0.538598,0.564218), (0.496932,0.779936), (0.672153,1)), k=(0,0,0,0.263463,0.530094,0.530094,0.530094)) MayaCmds.trim(name, lu=0.68, lv=0.39) degreeU = MayaCmds.getAttr(name+'.degreeU') degreeV = MayaCmds.getAttr(name+'.degreeV') spansU = MayaCmds.getAttr(name+'.spansU') spansV = MayaCmds.getAttr(name+'.spansV') minU = MayaCmds.getAttr(name+'.minValueU') maxU = MayaCmds.getAttr(name+'.maxValueU') minV = MayaCmds.getAttr(name+'.minValueV') maxV = MayaCmds.getAttr(name+'.maxValueV') MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface', force=True) controlPoints = MayaCmds.getAttr('surfaceInfo1.controlPoints[*]') knotsU = MayaCmds.getAttr('surfaceInfo1.knotsU[*]') knotsV = MayaCmds.getAttr('surfaceInfo1.knotsV[*]') self.__files.append(util.expandFileName('testStaticNurbsPlaneWithOneSegmentTrim.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name, self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessEqual(degreeU, MayaCmds.getAttr(name+'.degreeU')) self.failUnlessEqual(degreeV, MayaCmds.getAttr(name+'.degreeV')) self.failUnlessEqual(spansU, MayaCmds.getAttr(name+'.spansU')) self.failUnlessEqual(spansV, MayaCmds.getAttr(name+'.spansV')) self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formU')) self.failUnlessEqual(0, MayaCmds.getAttr(name+'.formV')) self.failUnlessEqual(minU, MayaCmds.getAttr(name+'.minValueU')) self.failUnlessEqual(maxU, MayaCmds.getAttr(name+'.maxValueU')) self.failUnlessEqual(minV, MayaCmds.getAttr(name+'.minValueV')) self.failUnlessEqual(maxV, MayaCmds.getAttr(name+'.maxValueV')) MayaCmds.createNode('surfaceInfo') MayaCmds.connectAttr(name+'.worldSpace', 'surfaceInfo1.inputSurface', force=True) for i in range(0, len(controlPoints)): cp1 = controlPoints[i] cp2 = MayaCmds.getAttr('surfaceInfo1.controlPoints[%d]' % i) self.failUnlessAlmostEqual(cp1[0], cp2[0][0], 3, 'control point [%d].x not equal' % i) self.failUnlessAlmostEqual(cp1[1], cp2[0][1], 3, 'control point [%d].y not equal' % i) self.failUnlessAlmostEqual(cp1[2], cp2[0][2], 3, 'control point [%d].z not equal' % i) for i in range(0, len(knotsU)): ku1 = knotsU[i] ku2 = MayaCmds.getAttr('surfaceInfo1.knotsU[%d]' % i) self.failUnlessAlmostEqual(ku1, ku2, 3, 'control knotsU # %d not equal' % i) for i in range(0, len(knotsV)): kv1 = knotsV[i] kv2 = MayaCmds.getAttr('surfaceInfo1.knotsV[%d]' % i) self.failUnlessAlmostEqual(kv1, kv2, 3, 'control knotsV # %d not equal' % i)
Python
# # Copyright (c) 2010 Sony Pictures Imageworks Inc. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the # distribution. Neither the name of Sony Pictures Imageworks nor the # names of its contributors may be used to endorse or promote # products derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. from maya import cmds as MayaCmds from maya import mel as Mel import os import unittest import util def makeRobot(): MayaCmds.polyCube(name="head") MayaCmds.move(0, 4, 0, r=1) MayaCmds.polyCube(name="chest") MayaCmds.scale(2, 2.5, 1) MayaCmds.move(0, 2, 0, r=1) MayaCmds.polyCube(name="leftArm") MayaCmds.move(0, 3, 0, r=1) MayaCmds.scale(2, 0.5, 1, r=1) MayaCmds.duplicate(name="rightArm") MayaCmds.select("leftArm") MayaCmds.move(1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, 32, r=1, os=1) MayaCmds.select("rightArm") MayaCmds.move(-1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, -32, r=1, os=1) MayaCmds.select("rightArm", "leftArm", "chest", r=1) MayaCmds.group(name="body") MayaCmds.polyCube(name="bottom") MayaCmds.scale(2, 0.5, 1) MayaCmds.move(0, 0.5, 0, r=1) MayaCmds.polyCube(name="leftLeg") MayaCmds.scale(0.65, 2.8, 1, r=1) MayaCmds.move(-0.5, -1, 0, r=1) MayaCmds.duplicate(name="rightLeg") MayaCmds.move(1, 0, 0, r=1) MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1) MayaCmds.group(name="lower") MayaCmds.select("head", "body", "lower", r=1) MayaCmds.group(name="robot") def makeRobotAnimated(): makeRobot() #change pivot point of arms and legs MayaCmds.move(0.65, -0.40, 0, 'rightArm.scalePivot', 'rightArm.rotatePivot', relative=True) MayaCmds.move(-0.65, -0.40, 0, 'leftArm.scalePivot', 'leftArm.rotatePivot', relative=True) MayaCmds.move(0, 1.12, 0, 'rightLeg.scalePivot', 'rightLeg.rotatePivot', relative=True) MayaCmds.move(0, 1.12, 0, 'leftLeg.scalePivot', 'leftLeg.rotatePivot', relative=True) MayaCmds.setKeyframe('leftLeg', at='rotateX', value=25, t=[1, 12]) MayaCmds.setKeyframe('leftLeg', at='rotateX', value=-40, t=[6]) MayaCmds.setKeyframe('rightLeg', at='scaleY', value=2.8, t=[1, 12]) MayaCmds.setKeyframe('rightLeg', at='scaleY', value=5.0, t=[6]) MayaCmds.setKeyframe('leftArm', at='rotateZ', value=55, t=[1, 12]) MayaCmds.setKeyframe('leftArm', at='rotateZ', value=-50, t=[6]) MayaCmds.setKeyframe('rightArm', at='scaleX', value=0.5, t=[1, 12]) MayaCmds.setKeyframe('rightArm', at='scaleX', value=3.6, t=[6]) class AbcNodeNameTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testReturnAbcNodeName(self): makeRobotAnimated() self.__files.append(util.expandFileName('returnAlembicNodeNameTest.abc')) MayaCmds.AbcExport(j='-fr 1 12 -root robot -file ' + self.__files[-1]) ret = MayaCmds.AbcImport(self.__files[-1], mode='open') ret1 = MayaCmds.AbcImport(self.__files[-1], mode='import') self.failUnless(MayaCmds.objExists(ret)) self.failUnless(MayaCmds.objExists(ret1)) self.failIf(ret == ret1)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import unittest import util class ColorSetsTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticMeshStaticColor(self): red_array = OpenMaya.MColorArray() red_array.append(1.0, 0.0, 0.0) blue_array = OpenMaya.MColorArray() blue_array.append(0.0, 0.0, 1.0) single_indices = OpenMaya.MIntArray(4, 0) mixed_colors = [[1.0, 1.0, 0.0, 1.0], [0.0, 1.0, 1.0, 0.75], [1.0, 0.0, 1.0, 0.5], [1.0, 1.0, 1.0, 0.25]] mixed_array = OpenMaya.MColorArray() for x in mixed_colors: mixed_array.append(x[0], x[1], x[2], x[3]) mixed_indices = OpenMaya.MIntArray() for i in range(4): mixed_indices.append(i) MayaCmds.polyPlane(sx=1, sy=1, name='poly') MayaCmds.select('polyShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) fn.createColorSetWithName('reds') fn.createColorSetWithName('mixed') fn.setColors(red_array, 'reds', OpenMaya.MFnMesh.kRGB) fn.assignColors(single_indices, 'reds') fn.setColors(mixed_array, 'mixed', OpenMaya.MFnMesh.kRGBA) fn.assignColors(mixed_indices, 'mixed') fn.setCurrentColorSetName('mixed') MayaCmds.polyPlane(sx=1, sy=1, name='subd') MayaCmds.select('subdShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) fn.createColorSetWithName('blues') fn.createColorSetWithName('mixed') fn.setColors(blue_array, 'blues', OpenMaya.MFnMesh.kRGB) fn.assignColors(single_indices, 'blues') fn.setColors(mixed_array, 'mixed', OpenMaya.MFnMesh.kRGBA) fn.assignColors(mixed_indices, 'mixed') fn.setCurrentColorSetName('blues') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) self.__files.append(util.expandFileName('staticColorSets.abc')) MayaCmds.AbcExport(j='-root poly -root subd -wcs -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.select('polyShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) self.failUnless(fn.currentColorSetName() == 'mixed') setNames = [] fn.getColorSetNames(setNames) self.failUnless(len(setNames) == 2) self.failUnless(setNames.count('mixed') == 1) self.failUnless(setNames.count('reds') == 1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray, 'reds') self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == 1) self.failUnless(colArray[x].g == 0) self.failUnless(colArray[x].b == 0) fn.getFaceVertexColors(colArray, 'mixed') self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == mixed_colors[x][0]) self.failUnless(colArray[x].g == mixed_colors[x][1]) self.failUnless(colArray[x].b == mixed_colors[x][2]) self.failUnless(colArray[x].a == mixed_colors[x][3]) MayaCmds.select('subdShape') self.failUnless(MayaCmds.getAttr('subdShape.SubDivisionMesh') == 1) sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) self.failUnless(fn.currentColorSetName() == 'blues') setNames = [] fn.getColorSetNames(setNames) self.failUnless(len(setNames) == 2) self.failUnless(setNames.count('mixed') == 1) self.failUnless(setNames.count('blues') == 1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray, 'blues') self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == 0) self.failUnless(colArray[x].g == 0) self.failUnless(colArray[x].b == 1) fn.getFaceVertexColors(colArray, 'mixed') self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == mixed_colors[x][0]) self.failUnless(colArray[x].g == mixed_colors[x][1]) self.failUnless(colArray[x].b == mixed_colors[x][2]) self.failUnless(colArray[x].a == mixed_colors[x][3]) def testStaticMeshAnimColor(self): MayaCmds.currentTime(1) MayaCmds.polyPlane(sx=1, sy=1, name='poly') MayaCmds.polyColorPerVertex(r=0.0,g=1.0,b=0.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex1"]) MayaCmds.currentTime(10) MayaCmds.polyColorPerVertex(r=0.0,g=0.0,b=1.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex1"]) MayaCmds.currentTime(1) MayaCmds.polyPlane(sx=1, sy=1, name='subd') MayaCmds.select('subdShape') MayaCmds.addAttr(longName='SubDivisionMesh', attributeType='bool', defaultValue=True) MayaCmds.polyColorPerVertex(r=1.0,g=1.0,b=0.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex2"]) MayaCmds.currentTime(10) MayaCmds.polyColorPerVertex(r=1.0,g=0.0,b=0.0, cdo=True) MayaCmds.setKeyframe(["polyColorPerVertex2"]) self.__files.append(util.expandFileName('animColorSets.abc')) MayaCmds.AbcExport(j='-fr 1 10 -root poly -root subd -wcs -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.select('polyShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) MayaCmds.currentTime(1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 0) self.failUnlessAlmostEqual(colArray[x].g, 1) self.failUnlessAlmostEqual(colArray[x].b, 0) MayaCmds.currentTime(5) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnless(colArray[x].r == 0) self.failUnlessAlmostEqual(colArray[x].g, 0.555555582047) self.failUnlessAlmostEqual(colArray[x].b, 0.444444447756) MayaCmds.currentTime(10) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 0) self.failUnlessAlmostEqual(colArray[x].g, 0) self.failUnlessAlmostEqual(colArray[x].b, 1) self.failUnless(MayaCmds.getAttr('subdShape.SubDivisionMesh') == 1) MayaCmds.select('subdShape') sel = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(sel) obj = OpenMaya.MObject() sel.getDependNode(0, obj) fn = OpenMaya.MFnMesh(obj) MayaCmds.currentTime(1) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 1) self.failUnlessAlmostEqual(colArray[x].g, 1) self.failUnlessAlmostEqual(colArray[x].b, 0) MayaCmds.currentTime(5) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 1) self.failUnlessAlmostEqual(colArray[x].g, 0.555555582047) self.failUnlessAlmostEqual(colArray[x].b, 0) MayaCmds.currentTime(10) colArray = OpenMaya.MColorArray() fn.getFaceVertexColors(colArray) self.failUnless(colArray.length() == 4) for x in range(colArray.length()): self.failUnlessAlmostEqual(colArray[x].r, 1) self.failUnlessAlmostEqual(colArray[x].g, 0) self.failUnlessAlmostEqual(colArray[x].b, 0)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def makeRobot(): MayaCmds.polyCube(name="head") MayaCmds.move(0, 4, 0, r=1) MayaCmds.polyCube(name="chest") MayaCmds.scale(2, 2.5, 1) MayaCmds.move(0, 2, 0, r=1) MayaCmds.polyCube(name="leftArm") MayaCmds.move(0, 3, 0, r=1) MayaCmds.scale(2, 0.5, 1, r=1) MayaCmds.duplicate(name="rightArm") MayaCmds.select("leftArm") MayaCmds.move(1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, 32, r=1, os=1) MayaCmds.select("rightArm") MayaCmds.move(-1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, -32, r=1, os=1) MayaCmds.select("rightArm", "leftArm", "chest", r=1) MayaCmds.group(name="body") MayaCmds.polyCube(name="bottom") MayaCmds.scale(2, 0.5, 1) MayaCmds.move(0, 0.5, 0, r=1) MayaCmds.polyCube(name="leftLeg") MayaCmds.scale(0.65, 2.8, 1, r=1) MayaCmds.move(-0.5, -1, 0, r=1) MayaCmds.duplicate(name="rightLeg") MayaCmds.move(1, 0, 0, r=1) MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1) MayaCmds.group(name="lower") MayaCmds.select("head", "body", "lower", r=1) MayaCmds.group(name="robot") class selectionTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testWriteMultipleRoots(self): makeRobot() MayaCmds.duplicate("robot", name="dupRobot") self.__files.append(util.expandFileName('writeMultipleRootsTest.abc')) MayaCmds.AbcExport(j='-root dupRobot -root head -root lower -root chest -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') self.failUnless(MayaCmds.objExists("dupRobot")) self.failUnless(MayaCmds.objExists("head")) self.failUnless(MayaCmds.objExists("lower")) self.failUnless(MayaCmds.objExists("chest")) self.failIf(MayaCmds.objExists("robot")) self.failIf(MayaCmds.objExists("robot|body"))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import unittest import util import os class interpolationTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testSubD(self): trans = MayaCmds.polyPlane(n='plane', sx=1, sy=1, ch=False)[0] shape = MayaCmds.pickWalk(d='down')[0] MayaCmds.addAttr(attributeType='bool', defaultValue=1, keyable=True, longName='SubDivisionMesh') MayaCmds.select(trans+'.vtx[0:3]', r=True) MayaCmds.move(0, 1, 0, r=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(2, update=True) MayaCmds.move(0, 5, 0, r=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testSubDInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -root %s -file %s' % (trans, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1.004, update=True) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(1.02, ty) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(ty, (1-alpha)*1.0+alpha*6.0, 3) def testPoly(self): trans = MayaCmds.polyPlane(n='plane', sx=1, sy=1, ch=False)[0] shape = MayaCmds.pickWalk(d='down')[0] MayaCmds.select(trans+'.vtx[0:3]', r=True) MayaCmds.move(0, 1, 0, r=True) MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() MayaCmds.currentTime(2, update=True) MayaCmds.move(0, 5, 0, r=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testPolyInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -root %s -file %s' % (trans, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1.004, update=True) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(1.02, ty) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) ty = MayaCmds.getAttr(shape+'.vt[0]')[0][1] self.failUnlessAlmostEqual(ty, (1-alpha)*1.0+alpha*6.0, 3) def testTransOp(self): nodeName = MayaCmds.createNode('transform', n='test') # shear MayaCmds.setKeyframe(nodeName, value=0, attribute='shearXY', t=1) MayaCmds.setKeyframe(nodeName, value=0, attribute='shearYZ', t=1) MayaCmds.setKeyframe(nodeName, value=0, attribute='shearXZ', t=1) MayaCmds.setKeyframe(nodeName, value=1.5, attribute='shearXY', t=2) MayaCmds.setKeyframe(nodeName, value=5, attribute='shearYZ', t=2) MayaCmds.setKeyframe(nodeName, value=2.5, attribute='shearXZ', t=2) # translate MayaCmds.setKeyframe('test', value=0, attribute='translateX', t=1) MayaCmds.setKeyframe('test', value=0, attribute='translateY', t=1) MayaCmds.setKeyframe('test', value=0, attribute='translateZ', t=1) MayaCmds.setKeyframe('test', value=1.5, attribute='translateX', t=2) MayaCmds.setKeyframe('test', value=5, attribute='translateY', t=2) MayaCmds.setKeyframe('test', value=2.5, attribute='translateZ', t=2) # rotate MayaCmds.setKeyframe('test', value=0, attribute='rotateX', t=1) MayaCmds.setKeyframe('test', value=0, attribute='rotateY', t=1) MayaCmds.setKeyframe('test', value=0, attribute='rotateZ', t=1) MayaCmds.setKeyframe('test', value=24, attribute='rotateX', t=2) MayaCmds.setKeyframe('test', value=53, attribute='rotateY', t=2) MayaCmds.setKeyframe('test', value=90, attribute='rotateZ', t=2) # scale MayaCmds.setKeyframe('test', value=1, attribute='scaleX', t=1) MayaCmds.setKeyframe('test', value=1, attribute='scaleY', t=1) MayaCmds.setKeyframe('test', value=1, attribute='scaleZ', t=1) MayaCmds.setKeyframe('test', value=1.2, attribute='scaleX', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='scaleY', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='scaleZ', t=2) # rotate pivot MayaCmds.setKeyframe('test', value=0.5, attribute='rotatePivotX', t=1) MayaCmds.setKeyframe('test', value=-0.1, attribute='rotatePivotY', t=1) MayaCmds.setKeyframe('test', value=1, attribute='rotatePivotZ', t=1) MayaCmds.setKeyframe('test', value=0.8, attribute='rotatePivotX', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='rotatePivotY', t=2) MayaCmds.setKeyframe('test', value=-1, attribute='rotatePivotZ', t=2) # scale pivot MayaCmds.setKeyframe('test', value=1.2, attribute='scalePivotX', t=1) MayaCmds.setKeyframe('test', value=1.0, attribute='scalePivotY', t=1) MayaCmds.setKeyframe('test', value=1.2, attribute='scalePivotZ', t=1) MayaCmds.setKeyframe('test', value=1.4, attribute='scalePivotX', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='scalePivotY', t=2) MayaCmds.setKeyframe('test', value=1.5, attribute='scalePivotZ', t=2) self.__files.append(util.expandFileName('testTransOpInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -root %s -f %s' % (nodeName, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') MayaCmds.currentTime(1.004, update=True) # should read the content of frame #1 self.failUnlessAlmostEqual(0.006, MayaCmds.getAttr('test.shearXY')) self.failUnlessAlmostEqual(0.02, MayaCmds.getAttr('test.shearYZ')) self.failUnlessAlmostEqual(0.01, MayaCmds.getAttr('test.shearXZ')) self.failUnlessAlmostEqual(0.006, MayaCmds.getAttr('test.translateX')) self.failUnlessAlmostEqual(0.02, MayaCmds.getAttr('test.translateY')) self.failUnlessAlmostEqual(0.01, MayaCmds.getAttr('test.translateZ')) self.failUnlessAlmostEqual(0.096, MayaCmds.getAttr('test.rotateX')) self.failUnlessAlmostEqual(0.212, MayaCmds.getAttr('test.rotateY')) self.failUnlessAlmostEqual(0.36, MayaCmds.getAttr('test.rotateZ')) self.failUnlessAlmostEqual(1.0008, MayaCmds.getAttr('test.scaleX')) self.failUnlessAlmostEqual(1.002, MayaCmds.getAttr('test.scaleY')) self.failUnlessAlmostEqual(1.002, MayaCmds.getAttr('test.scaleZ')) self.failUnlessAlmostEqual(0.5012, MayaCmds.getAttr('test.rotatePivotX')) self.failUnlessAlmostEqual(-0.0936, MayaCmds.getAttr('test.rotatePivotY')) self.failUnlessAlmostEqual(0.992, MayaCmds.getAttr('test.rotatePivotZ')) self.failUnlessAlmostEqual(1.2008, MayaCmds.getAttr('test.scalePivotX')) self.failUnlessAlmostEqual(1.002, MayaCmds.getAttr('test.scalePivotY')) self.failUnlessAlmostEqual(1.2012, MayaCmds.getAttr('test.scalePivotZ')) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) # should interpolate the content of frame #3 and frame #4 self.failUnlessAlmostEqual(MayaCmds.getAttr('test.shearXY'), (1-alpha)*0+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.shearYZ'), (1-alpha)*0+alpha*5.0) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.shearXZ'), (1-alpha)*0+alpha*2.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.translateX'), (1-alpha)*0+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.translateY'), (1-alpha)*0+alpha*5.0) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.translateZ'), (1-alpha)*0+alpha*2.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotateX'), (1-alpha)*0+alpha*24) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotateY'), (1-alpha)*0+alpha*53) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotateZ'), (1-alpha)*0+alpha*90) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scaleX'), (1-alpha)*1+alpha*1.2) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scaleY'), (1-alpha)*1+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scaleZ'), (1-alpha)*1+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotatePivotX'), (1-alpha)*0.5+alpha*0.8) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotatePivotY'), (1-alpha)*(-0.1)+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.rotatePivotZ'), (1-alpha)*1.0+alpha*(-1.0)) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scalePivotX'), (1-alpha)*1.2+alpha*1.4) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scalePivotY'), (1-alpha)*1.0+alpha*1.5) self.failUnlessAlmostEqual(MayaCmds.getAttr('test.scalePivotZ'), (1-alpha)*1.2+alpha*1.5) def testCamera(self): # create an animated camera and write out name = MayaCmds.camera() MayaCmds.setAttr(name[1]+'.horizontalFilmAperture', 0.962) MayaCmds.setAttr(name[1]+'.verticalFilmAperture', 0.731) MayaCmds.setAttr(name[1]+'.focalLength', 50) MayaCmds.setAttr(name[1]+'.focusDistance', 5) MayaCmds.setAttr(name[1]+'.shutterAngle', 144) # animate the camera MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(name[1], attribute='horizontalFilmAperture') MayaCmds.setKeyframe(name[1], attribute='focalLength') MayaCmds.setKeyframe(name[1], attribute='focusDistance') MayaCmds.setKeyframe(name[1], attribute='shutterAngle') MayaCmds.currentTime(6, update=True) MayaCmds.setKeyframe(name[1], attribute='horizontalFilmAperture', value=0.95) MayaCmds.setKeyframe(name[1], attribute='focalLength', value=40) MayaCmds.setKeyframe(name[1], attribute='focusDistance', value=5.4) MayaCmds.setKeyframe(name[1], attribute='shutterAngle', value=174.94) self.__files.append(util.expandFileName('testCameraInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 6 -root %s -f %s' % (name[0], self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='import') camList = MayaCmds.ls(type='camera') t = 1.004 MayaCmds.currentTime(t, update=True) self.failUnlessAlmostEqual(MayaCmds.getAttr(camList[0]+'.horizontalFilmAperture'), 0.962, 3) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) if not util.compareCamera(camList[0], camList[1]): self.fail('%s and %s are not the same at frame %d' % (camList[0], camList[1], t)) def testProp(self): trans = MayaCmds.createNode("transform") # create animated props MayaCmds.select(trans) MayaCmds.addAttr(longName='SPT_int8', dv=0, attributeType='byte', keyable=True) MayaCmds.addAttr(longName='SPT_int16', dv=0, attributeType='short', keyable=True) MayaCmds.addAttr(longName='SPT_int32', dv=0, attributeType='long', keyable=True) MayaCmds.addAttr(longName='SPT_float', dv=0, attributeType='float', keyable=True) MayaCmds.addAttr(longName='SPT_double', dv=0, attributeType='double', keyable=True) MayaCmds.setKeyframe(trans, value=0, attribute='SPT_int8', t=1) MayaCmds.setKeyframe(trans, value=100, attribute='SPT_int16', t=1) MayaCmds.setKeyframe(trans, value=1000, attribute='SPT_int32', t=1) MayaCmds.setKeyframe(trans, value=0.57777777, attribute='SPT_float', t=1) MayaCmds.setKeyframe(trans, value=5.045643545457, attribute='SPT_double', t=1) MayaCmds.setKeyframe(trans, value=8, attribute='SPT_int8', t=2) MayaCmds.setKeyframe(trans, value=16, attribute='SPT_int16', t=2) MayaCmds.setKeyframe(trans, value=32, attribute='SPT_int32', t=2) MayaCmds.setKeyframe(trans, value=3.141592654, attribute='SPT_float', t=2) MayaCmds.setKeyframe(trans, value=3.141592654, attribute='SPT_double', t=2) self.__files.append(util.expandFileName('testPropInterpolation.abc')) MayaCmds.AbcExport(j='-fr 1 2 -atp SPT_ -root %s -f %s' % (trans, self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') t = 1.004 MayaCmds.currentTime(t, update=True) self.failUnlessEqual(MayaCmds.getAttr(trans+'.SPT_int8'), 0) self.failUnlessEqual(MayaCmds.getAttr(trans+'.SPT_int16'), 99) self.failUnlessEqual(MayaCmds.getAttr(trans+'.SPT_int32'), 996) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_float'), 0.5880330295359999, 7) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_double'), 5.038027341891171, 7) setTime = MayaCmds.currentTime(1.422, update=True) alpha = (setTime - 1) / (2 - 1) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_int8'), (1-alpha)*0+alpha*8, -1) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_int16'), (1-alpha)*100+alpha*16, -1) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_int32'), (1-alpha)*1000+alpha*32, -1) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_float'), (1-alpha)*0.57777777+alpha*3.141592654, 6) self.failUnlessAlmostEqual(MayaCmds.getAttr(trans+'.SPT_double'), (1-alpha)* 5.045643545457+alpha*3.141592654, 6)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import maya.OpenMaya as OpenMaya import os import subprocess import unittest import util def createJoints(): name = MayaCmds.joint(position=(0, 0, 0)) MayaCmds.rotate(33.694356, 4.000428, 61.426019, r=True, ws=True) MayaCmds.joint(position=(0, 4, 0), orientation=(0.0, 45.0, 90.0)) MayaCmds.rotate(62.153171, 0.0, 0.0, r=True, os=True) MayaCmds.joint(position=(0, 8, -1), orientation=(90.0, 0.0, 0.0)) MayaCmds.rotate(70.245162, -33.242019, 41.673097, r=True, os=True) MayaCmds.joint(position=(0, 12, 3)) MayaCmds.rotate(0.0, 0.0, -58.973851, r=True, os=True) return name class JointTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] self.__abcStitcher = [os.environ['AbcStitcher']] def tearDown(self): for f in self.__files: os.remove(f) def testStaticJointRW(self): name = createJoints() # write to file self.__files.append(util.expandFileName('testStaticJoints.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (name, self.__files[-1])) MayaCmds.select(name) MayaCmds.group(name='original') # read from file MayaCmds.AbcImport(self.__files[-1], mode='import') # make sure the translate and rotation are the same nodes1 = ["|original|joint1", "|original|joint1|joint2", "|original|joint1|joint2|joint3", "|original|joint1|joint2|joint3|joint4"] nodes2 = ["|joint1", "|joint1|joint2", "|joint1|joint2|joint3", "|joint1|joint2|joint3|joint4"] for i in range(0, 4): self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tx'), MayaCmds.getAttr(nodes2[i]+'.tx'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.ty'), MayaCmds.getAttr(nodes2[i]+'.ty'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tz'), MayaCmds.getAttr(nodes2[i]+'.tz'), 4) def testStaticIKRW(self): name = createJoints() MayaCmds.ikHandle(sj=name, ee='joint4') MayaCmds.move(-1.040057, -7.278225, 6.498725, r=True) # write to file self.__files.append(util.expandFileName('testStaticIK.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name, self.__files[-1])) MayaCmds.select(name) MayaCmds.group(name='original') # read from file MayaCmds.AbcImport(self.__files[-1], mode='import') # make sure the translate and rotation are the same nodes1 = ["|original|joint1", "|original|joint1|joint2", "|original|joint1|joint2|joint3", "|original|joint1|joint2|joint3|joint4"] nodes2 = ["|joint1", "|joint1|joint2", "|joint1|joint2|joint3", "|joint1|joint2|joint3|joint4"] for i in range(0, 4): self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tx'), MayaCmds.getAttr(nodes2[i]+'.tx'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.ty'), MayaCmds.getAttr(nodes2[i]+'.ty'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tz'), MayaCmds.getAttr(nodes2[i]+'.tz'), 4) def testAnimIKRW(self): name = createJoints() handleName = MayaCmds.ikHandle(sj=name, ee='joint4')[0] MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe(handleName, breakdown=0, hierarchy='none', controlPoints=False, shape=False) MayaCmds.currentTime(16, update=True) MayaCmds.move(-1.040057, -7.278225, 6.498725, r=True) MayaCmds.setKeyframe(handleName, breakdown=0, hierarchy='none', controlPoints=False, shape=False) self.__files.append(util.expandFileName('testAnimIKRW.abc')) self.__files.append(util.expandFileName('testAnimIKRW01_08.abc')) self.__files.append(util.expandFileName('testAnimIKRW09-16.abc')) # write to files MayaCmds.AbcExport(j='-fr 1 8 -root %s -f %s' % (name, self.__files[-2])) MayaCmds.AbcExport(j='-fr 9 16 -root %s -f %s' % (name, self.__files[-1])) MayaCmds.select(name) MayaCmds.group(name='original') subprocess.call(self.__abcStitcher + self.__files[-3:]) # read from file MayaCmds.AbcImport(self.__files[-3], mode='import') # make sure the translate and rotation are the same nodes1 = ["|original|joint1", "|original|joint1|joint2", "|original|joint1|joint2|joint3", "|original|joint1|joint2|joint3|joint4"] nodes2 = ["|joint1", "|joint1|joint2", "|joint1|joint2|joint3", "|joint1|joint2|joint3|joint4"] for t in range(1, 25): MayaCmds.currentTime(t, update=True) for i in range(0, 4): self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tx'), MayaCmds.getAttr(nodes2[i]+'.tx'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.ty'), MayaCmds.getAttr(nodes2[i]+'.ty'), 4) self.failUnlessAlmostEqual(MayaCmds.getAttr(nodes1[i]+'.tz'), MayaCmds.getAttr(nodes2[i]+'.tz'), 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds from maya import mel as Mel import os import unittest import util def makeRobot(): MayaCmds.polyCube(name="head") MayaCmds.move(0, 4, 0, r=1) MayaCmds.polyCube(name="chest") MayaCmds.scale(2, 2.5, 1) MayaCmds.move(0, 2, 0, r=1) MayaCmds.polyCube(name="leftArm") MayaCmds.move(0, 3, 0, r=1) MayaCmds.scale(2, 0.5, 1, r=1) MayaCmds.duplicate(name="rightArm") MayaCmds.select("leftArm") MayaCmds.move(1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, 32, r=1, os=1) MayaCmds.select("rightArm") MayaCmds.move(-1.25, 0, 0, r=1) MayaCmds.rotate(0, 0, -32, r=1, os=1) MayaCmds.select("rightArm", "leftArm", "chest", r=1) MayaCmds.group(name="body") MayaCmds.polyCube(name="bottom") MayaCmds.scale(2, 0.5, 1) MayaCmds.move(0, 0.5, 0, r=1) MayaCmds.polyCube(name="leftLeg") MayaCmds.scale(0.65, 2.8, 1, r=1) MayaCmds.move(-0.5, -1, 0, r=1) MayaCmds.duplicate(name="rightLeg") MayaCmds.move(1, 0, 0, r=1) MayaCmds.select("rightLeg", "leftLeg", "bottom", r=1) MayaCmds.group(name="lower") MayaCmds.select("head", "body", "lower", r=1) MayaCmds.group(name="robot") def makeRobotAnimated(): makeRobot() #change pivot point of arms and legs MayaCmds.move(0.65, -0.40, 0, 'rightArm.scalePivot', 'rightArm.rotatePivot', relative=True) MayaCmds.move(-0.65, -0.40, 0, 'leftArm.scalePivot', 'leftArm.rotatePivot', relative=True) MayaCmds.move(0, 1.12, 0, 'rightLeg.scalePivot', 'rightLeg.rotatePivot', relative=True) MayaCmds.move(0, 1.12, 0, 'leftLeg.scalePivot', 'leftLeg.rotatePivot', relative=True) MayaCmds.setKeyframe('leftLeg', at='rotateX', value=25, t=[1, 12]) MayaCmds.setKeyframe('leftLeg', at='rotateX', value=-40, t=[6]) MayaCmds.setKeyframe('rightLeg', at='scaleY', value=2.8, t=[1, 12]) MayaCmds.setKeyframe('rightLeg', at='scaleY', value=5.0, t=[6]) MayaCmds.setKeyframe('leftArm', at='rotateZ', value=55, t=[1, 12]) MayaCmds.setKeyframe('leftArm', at='rotateZ', value=-50, t=[6]) MayaCmds.setKeyframe('rightArm', at='scaleX', value=0.5, t=[1, 12]) MayaCmds.setKeyframe('rightArm', at='scaleX', value=3.6, t=[6]) def drawBBox(llx, lly, llz, urx, ury, urz): # delete the old bounding box if MayaCmds.objExists('bbox'): MayaCmds.delete('bbox') p0 = (llx, lly, urz) p1 = (urx, lly, urz) p2 = (urx, lly, llz) p3 = (llx, lly, llz) p4 = (llx, ury, urz) p5 = (urx, ury, urz) p6 = (urx, ury, llz) p7 = (llx, ury, llz) MayaCmds.curve(d=1, p=[p0, p1]) MayaCmds.curve(d=1, p=[p1, p2]) MayaCmds.curve(d=1, p=[p2, p3]) MayaCmds.curve(d=1, p=[p3, p0]) MayaCmds.curve(d=1, p=[p4, p5]) MayaCmds.curve(d=1, p=[p5, p6]) MayaCmds.curve(d=1, p=[p6, p7]) MayaCmds.curve(d=1, p=[p7, p4]) MayaCmds.curve(d=1, p=[p0, p4]) MayaCmds.curve(d=1, p=[p1, p5]) MayaCmds.curve(d=1, p=[p2, p6]) MayaCmds.curve(d=1, p=[p3, p7]) MayaCmds.select(MayaCmds.ls("curve?")) MayaCmds.select(MayaCmds.ls("curve??"), add=True) MayaCmds.group(name="bbox") class callbackTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testMelPerFrameCallbackFlag(self): makeRobotAnimated() # make a non-zero transform on top of it MayaCmds.select('robot') MayaCmds.group(n='parent') MayaCmds.setAttr('parent.tx', 5) MayaCmds.setAttr('parent.ty', 3.15) MayaCmds.setAttr('parent.tz', 0.8) MayaCmds.setAttr('parent.rx', 2) MayaCmds.setAttr('parent.ry', 90) MayaCmds.setAttr('parent.rz', 1) MayaCmds.setAttr('parent.sx', 0.9) MayaCmds.setAttr('parent.sy', 1.1) MayaCmds.setAttr('parent.sz', 0.5) # create a camera looking at the robot camNames = MayaCmds.camera() MayaCmds.move(50.107, 20.968, 5.802, r=True) MayaCmds.rotate(-22.635, 83.6, 0, r=True) MayaCmds.camera(camNames[1], e=True, centerOfInterest=55.336, focalLength=50, horizontalFilmAperture=0.962, verticalFilmAperture=0.731) MayaCmds.rename(camNames[0], "cam_master") MayaCmds.setKeyframe('cam_master', t=[1, 12]) __builtins__['bboxDict'] = {} self.__files.append(util.expandFileName('pyPerFrameTest.abc')) MayaCmds.AbcExport(j='-fr 1 12 -pfc bboxDict[#FRAME#]=#BOUNDSARRAY# -root robot -file ' + self.__files[-1]) # push the numbers into a flat list array = [] for i in range(1, 13): array.append(bboxDict[i][0]) array.append(bboxDict[i][1]) array.append(bboxDict[i][2]) array.append(bboxDict[i][3]) array.append(bboxDict[i][4]) array.append(bboxDict[i][5]) bboxList_worldSpaceOff = [ -1.10907, -2.4, -1.51815, 1.8204, 4.5, 0.571487, -1.64677, -2.85936, -0.926652, 2.24711, 4.5, 0.540761, -2.25864, -3.38208, -0.531301, 2.37391, 4.5, 0.813599, -2.83342, -3.87312, -0.570038, 2.3177, 4.5, 1.45821, -3.25988, -4.23744, -0.569848, 2.06639, 4.5, 1.86489, -3.42675, -4.38, -0.563003, 1.92087, 4.5, 2.00285, -3.30872, -4.27917, -0.568236, 2.02633, 4.5, 1.9066, -2.99755, -4.01333, -0.572918, 2.24279, 4.5, 1.62326, -2.55762, -3.6375, -0.556938, 2.3781, 4.5, 1.16026, -2.05331, -3.20667, -0.507072, 2.37727, 4.5, 0.564985, -1.549, -2.77583, -1.04022, 2.18975, 4.5, 0.549216, -1.10907, -2.4, -1.51815, 1.8204, 4.5, 0.571487] self.failUnlessEqual(len(array), len(bboxList_worldSpaceOff)) for i in range(0, len(array)): self.failUnlessAlmostEqual(array[i], bboxList_worldSpaceOff[i], 4, '%d element in bbox array does not match.' % i) # test the bounding box calculation when worldSpace flag is on __builtins__['bboxDict'] = {} self.__files.append(util.expandFileName('pyPerFrameWorldspaceTest.abc')) MayaCmds.AbcExport(j='-fr 1 12 -ws -pfc bboxDict[#FRAME#]=#BOUNDSARRAY# -root robot -file ' + self.__files[-1]) # push the numbers into a flat list array = [] for i in range(1, 13): array.append(bboxDict[i][0]) array.append(bboxDict[i][1]) array.append(bboxDict[i][2]) array.append(bboxDict[i][3]) array.append(bboxDict[i][4]) array.append(bboxDict[i][5]) bboxList_worldSpaceOn = [ 4.77569, 0.397085, -0.991594, 5.90849, 7.99465, 1.64493, 5.06518, -0.108135, -1.37563, 5.90849, 7.99465, 2.12886, 5.25725, -0.683039, -1.48975, 5.9344, 7.99465, 2.67954, 5.24782, -1.223100, -1.43916, 6.26283, 7.99465, 3.19685, 5.24083, -1.62379, -1.21298, 6.47282, 7.99465, 3.58066, 5.23809, -1.78058, -1.08202, 6.54482, 7.99465, 3.73084, 5.24003, -1.66968, -1.17693, 6.49454, 7.99465, 3.62461, 5.24513, -1.37731, -1.37175, 6.34772, 7.99465, 3.34456, 5.25234, -0.963958, -1.49352, 6.11048, 7.99465, 2.94862, 5.26062, -0.490114, -1.49277, 5.90849, 7.99465, 2.49475, 5.00931, -0.0162691, -1.32401, 5.90849, 7.99465, 2.04087, 4.77569, 0.397085, -0.991594, 5.90849, 7.99465, 1.64493] self.failUnlessEqual(len(array), len(bboxList_worldSpaceOn)) for i in range(0, len(array)): self.failUnlessAlmostEqual(array[i], bboxList_worldSpaceOn[i], 4, '%d element in bbox array does not match.' % i) # test the bounding box calculation for camera __builtins__['bboxDict'] = {} self.__files.append(util.expandFileName('camPyPerFrameTest.abc')) MayaCmds.AbcExport(j='-fr 1 12 -pfc bboxDict[#FRAME#]=#BOUNDSARRAY# -root cam_master -file ' + self.__files[-1]) # push the numbers into a flat list ( since each frame is the same ) array = [] array.append(bboxDict[1][0]) array.append(bboxDict[1][1]) array.append(bboxDict[1][2]) array.append(bboxDict[1][3]) array.append(bboxDict[1][4]) array.append(bboxDict[1][5]) # cameras aren't included in the bounds bboxList_CAM = [0, 0, 0, 0, 0, 0] for i in range(0, len(array)): self.failUnlessAlmostEqual(array[i], bboxList_CAM[i], 4, '%d element in camera bbox array does not match.' % i)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class TransformTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files : os.remove(f) def testStaticTransformReadWrite(self): nodeName = MayaCmds.polyCube(n='cube') MayaCmds.setAttr('cube.translate', 2.456, -3.95443, 0, type="double3") MayaCmds.setAttr('cube.rotate', 45, 15, -90, type="double3") MayaCmds.setAttr('cube.rotateOrder', 4) MayaCmds.setAttr('cube.scale', 1.5, 5, 1, type="double3") MayaCmds.setAttr('cube.shearXY',1) MayaCmds.setAttr('cube.rotatePivot', 13.52, 0.0, 20.25, type="double3") MayaCmds.setAttr('cube.rotatePivotTranslate', 0.5, 0.0, 0.25, type="double3") MayaCmds.setAttr('cube.scalePivot', 10.7, 2.612, 0.2, type="double3") MayaCmds.setAttr('cube.scalePivotTranslate', 0.0, 0.0, 0.25, type="double3") MayaCmds.setAttr('cube.inheritsTransform', 0) self.__files.append(util.expandFileName('testStaticTransformReadWrite.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (nodeName[0], self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessAlmostEqual(2.456, MayaCmds.getAttr('cube.translateX'), 4) self.failUnlessAlmostEqual(-3.95443, MayaCmds.getAttr('cube.translateY'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.translateZ'), 4) self.failUnlessAlmostEqual(45, MayaCmds.getAttr('cube.rotateX'), 4) self.failUnlessAlmostEqual(15, MayaCmds.getAttr('cube.rotateY'), 4) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr('cube.rotateZ'), 4) self.failUnlessEqual(4, MayaCmds.getAttr('cube.rotateOrder')) self.failUnlessAlmostEqual(1.5, MayaCmds.getAttr('cube.scaleX'), 4) self.failUnlessAlmostEqual(5, MayaCmds.getAttr('cube.scaleY'), 4) self.failUnlessAlmostEqual(1, MayaCmds.getAttr('cube.scaleZ'), 4) self.failUnlessAlmostEqual(1, MayaCmds.getAttr('cube.shearXY'), 4) self.failUnlessAlmostEqual(13.52, MayaCmds.getAttr('cube.rotatePivotX'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.rotatePivotY'), 4) self.failUnlessAlmostEqual(20.25, MayaCmds.getAttr('cube.rotatePivotZ'), 4) self.failUnlessAlmostEqual(0.5, MayaCmds.getAttr('cube.rotatePivotTranslateX'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.rotatePivotTranslateY'), 4) self.failUnlessAlmostEqual(0.25, MayaCmds.getAttr('cube.rotatePivotTranslateZ'), 4) self.failUnlessAlmostEqual(10.7, MayaCmds.getAttr('cube.scalePivotX'), 4) self.failUnlessAlmostEqual(2.612, MayaCmds.getAttr('cube.scalePivotY'), 4) self.failUnlessAlmostEqual(0.2, MayaCmds.getAttr('cube.scalePivotZ'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.scalePivotTranslateX'), 4) self.failUnlessAlmostEqual(0.0, MayaCmds.getAttr('cube.scalePivotTranslateY'), 4) self.failUnlessAlmostEqual(0.25, MayaCmds.getAttr('cube.scalePivotTranslateZ'), 4) self.failUnlessEqual(0, MayaCmds.getAttr('cube.inheritsTransform')) def testStaticTransformRotateOrder(self): nodeName = MayaCmds.polyCube(n='cube') MayaCmds.setAttr('cube.rotate', 45, 1, -90, type="double3") MayaCmds.setAttr('cube.rotateOrder', 5) self.__files.append(util.expandFileName('testStaticTransformRotateOrder.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (nodeName[0], self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessEqual(5, MayaCmds.getAttr('cube.rotateOrder')) self.failUnlessAlmostEqual(45, MayaCmds.getAttr('cube.rotateX'), 4) self.failUnlessAlmostEqual(1, MayaCmds.getAttr('cube.rotateY'), 4) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr('cube.rotateZ'), 4) def testStaticTransformRotateOrder2(self): nodeName = MayaCmds.polyCube(n='cube') MayaCmds.setAttr('cube.rotate', 45, 0, -90, type="double3") MayaCmds.setAttr('cube.rotateOrder', 5) self.__files.append(util.expandFileName('testStaticTransformRotateOrder2.abc')) MayaCmds.AbcExport(j='-root %s -file %s' % (nodeName[0], self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') self.failUnlessEqual(5, MayaCmds.getAttr('cube.rotateOrder')) self.failUnlessAlmostEqual(45, MayaCmds.getAttr('cube.rotateX'), 4) self.failUnlessAlmostEqual(0, MayaCmds.getAttr('cube.rotateY'), 4) self.failUnlessAlmostEqual(-90, MayaCmds.getAttr('cube.rotateZ'), 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util def testNurbsCurveRW( self, isGroup, abcFileName, inText): MayaCmds.file(new=True, force=True) name = MayaCmds.textCurves( font='Courier', text=inText ) if isGroup == True : MayaCmds.addAttr(name[0], longName='riCurves', at='bool', dv=True) shapeNames = MayaCmds.ls(type='nurbsCurve') miscinfo=[] cv=[] knot=[] curveInfoNode = MayaCmds.createNode('curveInfo') for i in range(0, len(shapeNames)) : shapeName = shapeNames[i] MayaCmds.connectAttr(shapeName+'.worldSpace', curveInfoNode+'.inputCurve', force=True) controlPoints = MayaCmds.getAttr(curveInfoNode + '.controlPoints[*]') cv.append(controlPoints) numCV = len(controlPoints) spans = MayaCmds.getAttr(shapeName+'.spans') degree = MayaCmds.getAttr(shapeName+'.degree') form = MayaCmds.getAttr(shapeName+'.form') minVal = MayaCmds.getAttr(shapeName+'.minValue') maxVal = MayaCmds.getAttr(shapeName+'.maxValue') misc = [numCV, spans, degree, form, minVal, maxVal] miscinfo.append(misc) knots = MayaCmds.getAttr(curveInfoNode + '.knots[*]') knot.append(knots) MayaCmds.AbcExport(j='-root %s -f %s' % (name[0], abcFileName)) # reading test MayaCmds.AbcImport(abcFileName, mode='open') if isGroup == True: shapeNames = MayaCmds.ls(exactType='nurbsCurve') self.failUnless(MayaCmds.getAttr(name[0]+'.riCurves')) miscinfo2 = [] cv2 = [] knot2 = [] curveInfoNode = MayaCmds.createNode('curveInfo') for i in range(0, len(shapeNames)): name = shapeNames[i] MayaCmds.connectAttr(name+'.worldSpace', curveInfoNode+'.inputCurve', force=True) controlPoints = MayaCmds.getAttr(curveInfoNode + '.controlPoints[*]') cv2.append(controlPoints) numCV = len(controlPoints) spans = MayaCmds.getAttr(name+'.spans') degree = MayaCmds.getAttr(name+'.degree') form = MayaCmds.getAttr(name+'.form') minVal = MayaCmds.getAttr(name+'.minValue') maxVal = MayaCmds.getAttr(name+'.maxValue') misc = [numCV, spans, degree, form, minVal, maxVal] miscinfo2.append(misc) knots = MayaCmds.getAttr(curveInfoNode + '.knots[*]') knot2.append(knots) for i in range(0, len(shapeNames)) : name = shapeNames[i] self.failUnlessEqual(len(cv[i]), len(cv2[i])) for j in range(0, len(cv[i])) : cp1 = cv[i][j] cp2 = cv2[i][j] self.failUnlessAlmostEqual(cp1[0], cp2[0], 3, 'curve[%d].cp[%d].x not equal' % (i,j)) self.failUnlessAlmostEqual(cp1[1], cp2[1], 3, 'curve[%d].cp[%d].y not equal' % (i,j)) self.failUnlessAlmostEqual(cp1[2], cp2[2], 3, 'curve[%d].cp[%d].z not equal' % (i,j)) class StaticNurbsCurveTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testNurbsSingleCurveReadWrite(self): name = MayaCmds.curve(d=3, p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9), (12, 10, 2)], k=[0,0,0,1,2,2,2]) self.__files.append(util.expandFileName('testStaticNurbsSingleCurve.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name, self.__files[-1])) # reading test MayaCmds.AbcImport(self.__files[-1], mode='import') shapeNames = MayaCmds.ls(exactType='nurbsCurve') self.failUnless(util.compareNurbsCurve(shapeNames[0], shapeNames[1])) def testNurbsCurveGrpReadWrite(self): # test w/r of simple Nurbs Curve self.__files.append(util.expandFileName('testStaticNurbsCurves.abc')) testNurbsCurveRW(self, False, self.__files[-1], 'haka') self.__files.append(util.expandFileName('testStaticNurbsCurveGrp.abc')) testNurbsCurveRW(self, True, self.__files[-1], 'haka') # test if some curves have different degree or close states information MayaCmds.file(new=True, force=True) name = MayaCmds.textCurves(font='Courier', text='Maya') MayaCmds.addAttr(name[0], longName='riCurves', at='bool', dv=True) self.__files.append(util.expandFileName('testStaticNurbsCurveGrp2.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (name[0], self.__files[-1])) MayaCmds.AbcImport(self.__files[-1], mode='open') if 'riCurves' in MayaCmds.listAttr(name[0]): self.fail(name[0]+".riCurves shouldn't exist") def testNurbsSingleCurveWidthReadWrite(self): MayaCmds.file(new=True, force=True) # single curve with no width information MayaCmds.curve(d=3, p=[(0, 0, 0), (3, 5, 0), (5, 6, 0), (9, 9, 0), (12, 10, 0)], k=[0,0,0,1,2,2,2], name='curve1') # single curve with constant width information MayaCmds.curve(d=3, p=[(0, 0, 3), (3, 5, 3), (5, 6, 3), (9, 9, 3), (12, 10, 3)], k=[0,0,0,1,2,2,2], name='curve2') MayaCmds.select('curveShape2') MayaCmds.addAttr(longName='width', attributeType='double', dv=0.75) # single open curve with width information MayaCmds.curve(d=3, p=[(0, 0, 6), (3, 5, 6), (5, 6, 6), (9, 9, 6), (12, 10, 6)], k=[0,0,0,1,2,2,2], name='curve3') MayaCmds.select('curveShape3') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape3.width', [0.2, 0.4, 0.6, 0.8, 1.0], type='doubleArray') # single open curve with wrong width information MayaCmds.curve(d=3, p=[(0, 0, 9), (3, 5, 9), (5, 6, 9), (9, 9, 9), (12, 10, 9)], k=[0,0,0,1,2,2,2], name='curve4') MayaCmds.select('curveShape4') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape4.width', [0.12, 1.4, 0.37], type='doubleArray') # single curve circle with width information MayaCmds.circle(ch=False, name='curve5') MayaCmds.select('curve5Shape') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curve5Shape.width', [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1], type='doubleArray') # single curve circle with wrong width information MayaCmds.circle(ch=False, name='curve6') MayaCmds.select('curve6Shape') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curve6Shape.width', [0.12, 1.4, 0.37], type='doubleArray') self.__files.append(util.expandFileName('testStaticNurbsCurveWidthTest.abc')) MayaCmds.AbcExport(j='-root curve1 -root curve2 -root curve3 -root curve4 -root curve5 -root curve6 -f ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') # check the width # curve 1 self.failUnless('width' in MayaCmds.listAttr('curveShape1')) self.failUnlessAlmostEqual( MayaCmds.getAttr('curveShape1.width'), 0.1, 4) # curve 2 self.failUnless('width' in MayaCmds.listAttr('curveShape2')) self.failUnlessAlmostEqual( MayaCmds.getAttr('curveShape2.width'), 0.75, 4) # curve 3 width = MayaCmds.getAttr('curveShape3.width') for i in range(5): self.failUnlessAlmostEqual(width[i], 0.2*i+0.2, 4) # curve 4 (bad width defaults to 0.1) self.failUnless('width' in MayaCmds.listAttr('curveShape4')) width = MayaCmds.getAttr('curveShape4.width') self.failUnlessAlmostEqual( MayaCmds.getAttr('curveShape4.width'), 0.1, 4) # curve 5 self.failUnlessEqual('width' in MayaCmds.listAttr('curve5Shape'), True) width = MayaCmds.getAttr('curve5Shape.width') for i in range(11): self.failUnlessAlmostEqual(width[i], 0.1*i+0.1, 4) # curve 6 (bad width defaults to 0.1) self.failUnless('width' in MayaCmds.listAttr('curve6Shape')) self.failUnlessAlmostEqual( MayaCmds.getAttr('curve6Shape.width'), 0.1, 4) def testNurbsCurveGrpWidthRW1(self): widthVecs = [[0.11, 0.12, 0.13, 0.14, 0.15], [0.1, 0.3, 0.5, 0.7, 0.9], [0.2, 0.3, 0.4, 0.5, 0.6]] MayaCmds.curve(d=3, p=[(0, 0, 0), (3, 5, 0), (5, 6, 0), (9, 9, 0), (12, 10, 0)], k=[0,0,0,1,2,2,2], name='curve1') MayaCmds.select('curveShape1') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape1.width', widthVecs[0], type='doubleArray') MayaCmds.curve(d=3, p=[(0, 0, 3), (3, 5, 3), (5, 6, 3), (9, 9, 3), (12, 10, 3)], k=[0,0,0,1,2,2,2], name='curve2') MayaCmds.select('curveShape2') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape2.width', widthVecs[1], type='doubleArray') MayaCmds.curve(d=3, p=[(0, 0, 6), (3, 5, 6), (5, 6, 6), (9, 9, 6), (12, 10, 6)], k=[0,0,0,1,2,2,2], name='curve3') MayaCmds.select('curveShape3') MayaCmds.addAttr(longName='width', dataType='doubleArray') MayaCmds.setAttr('curveShape3.width', widthVecs[2], type='doubleArray') MayaCmds.group('curve1', 'curve2', 'curve3', name='group') MayaCmds.addAttr('group', longName='riCurves', at='bool', dv=True) self.__files.append(util.expandFileName('testStaticNurbsCurveGrpWidthTest1.abc')) MayaCmds.AbcExport(j='-root group -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') # width check for i in range(0,3): shapeName = '|group|group' if i > 0: shapeName = shapeName + str(i) self.failUnless('width' in MayaCmds.listAttr(shapeName)) width = MayaCmds.getAttr(shapeName + '.width') for j in range(len(widthVecs[i])): self.failUnlessAlmostEqual(width[j], widthVecs[i][j], 4) def testNurbsCurveGrpWidthRW2(self): MayaCmds.curve(d=3, p=[(0, 0, 0), (3, 5, 0), (5, 6, 0), (9, 9, 0), (12, 10, 0)], k=[0,0,0,1,2,2,2], name='curve1') MayaCmds.select('curveShape1') MayaCmds.curve(d=3, p=[(0, 0, 3), (3, 5, 3), (5, 6, 3), (9, 9, 3), (12, 10, 3)], k=[0,0,0,1,2,2,2], name='curve2') MayaCmds.curve(d=3, p=[(0, 0, 6), (3, 5, 6), (5, 6, 6), (9, 9, 6), (12, 10, 6)], k=[0,0,0,1,2,2,2], name='curve3') MayaCmds.select('curveShape3') MayaCmds.group('curve1', 'curve2', 'curve3', name='group') MayaCmds.addAttr('group', longName='riCurves', at='bool', dv=True) MayaCmds.addAttr('group', longName='width', attributeType='double', dv=0.75) self.__files.append(util.expandFileName('testStaticNurbsCurveGrpWidthTest2.abc')) MayaCmds.AbcExport(j='-root group -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], mode='open') # constant width check self.failUnless('width' in MayaCmds.listAttr('|group')) self.failUnlessAlmostEqual(MayaCmds.getAttr('|group.width'), 0.75, 4)
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import subprocess import unittest import util class subframesTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testRangeFlag(self): MayaCmds.createNode('transform', name='node') MayaCmds.setKeyframe('node.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe('node.translateX', time=11.0, v=11.0) self.__files.append(util.expandFileName('rangeTest.abc')) MayaCmds.AbcExport(j='-fr 1 11 -step 0.25 -root node -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') MayaCmds.currentTime(0, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 1) MayaCmds.currentTime(1, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 1) MayaCmds.currentTime(1.0003, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 1) MayaCmds.currentTime(1.333333, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.translateX'), 1.333333333, 2) MayaCmds.currentTime(9.66667, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.translateX'), 9.6666666666, 2) MayaCmds.currentTime(11, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 11) MayaCmds.currentTime(12, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.translateX'), 11) def testPreRollStartFrameFlag(self): MayaCmds.createNode('transform', name='node') MayaCmds.setAttr('node.tx', 0.0) MayaCmds.expression( string="if(time==0)\n\tnode.tx=0;\n\nif (time*24 > 6 && node.tx > 0.8)\n\tnode.tx = 10;\n\nnode.tx = node.tx + time;\n", name="startAtExp", ae=1, uc=all) self.__files.append(util.expandFileName('startAtTest.abc')) MayaCmds.AbcExport(j='-fr 1 10 -root node -file ' + self.__files[-1], prs=0, duf=True) MayaCmds.AbcImport(self.__files[-1], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') # if the evaluation doesn't start at frame 0, node.tx < 10 MayaCmds.currentTime(10, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnless(MayaCmds.getAttr('node.translateX')-10 > 0) def testSkipFrames(self): MayaCmds.createNode('transform', name='node') MayaCmds.setKeyframe('node.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe('node.translateX', time=10.0, v=10.0) MayaCmds.duplicate(name='dupNode') MayaCmds.setAttr('dupNode.tx', 0.0) MayaCmds.expression( string="if(time==11)\n\tdupNode.tx=-50;\n\ndupNode.tx = dupNode.tx + time;\n", name="startAtExp", ae=1, uc=all) self.__files.append(util.expandFileName('skipFrameTest1.abc')) self.__files.append(util.expandFileName('skipFrameTest2.abc')) MayaCmds.AbcExport(j=['-fr 1 10 -root node -file ' + self.__files[-2], '-fr 20 25 -root dupNode -file ' + self.__files[-1]]) MayaCmds.AbcImport(self.__files[-2], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') # make sure all the frames needed are written out and correctly for val in range(1, 11): MayaCmds.currentTime(val, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.tx'), val, 3) # also make sure nothing extra gets written out MayaCmds.currentTime(11, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessEqual(MayaCmds.getAttr('node.tx'), 10.0) MayaCmds.AbcImport(self.__files[-1], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') # if dontSkipFrames flag is not set maya would evaluate frame 11 and # set dupNode.tx to a big negative number MayaCmds.currentTime(20, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnless(MayaCmds.getAttr('dupNode.tx') > 0) def testWholeFrameGeoFlag(self): MayaCmds.polyCube(name='node') MayaCmds.setKeyframe('node.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe('node.translateX', time=2.0, v=-3.0) MayaCmds.setKeyframe('node.translateX', time=5.0, v=9.0) MayaCmds.select('node.vtx[0:8]') MayaCmds.setKeyframe(time=1.0) MayaCmds.scale(1.5, 1.5, 1.8) MayaCmds.setKeyframe(time=5.0) self.__files.append(util.expandFileName('noSampleGeoTest.abc')) MayaCmds.AbcExport(j='-fr 1 5 -wfg -frs 0 -frs 0.9 -root node -file ' + self.__files[-1]) MayaCmds.AbcImport(self.__files[-1], m='open') abcNodeName = MayaCmds.ls(exactType='AlembicNode') setTime = MayaCmds.currentTime(1, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) val_1 = MayaCmds.getAttr('node.vt[0]')[0][0] MayaCmds.currentTime(2.0, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) MayaCmds.getAttr('node.vt[0]') val_2 = MayaCmds.getAttr('node.vt[0]')[0][0] self.failUnlessAlmostEqual(val_2, -0.5625, 3) setTime = MayaCmds.currentTime(1.9, update=True) MayaCmds.dgeval(abcNodeName, verbose=False) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.tx'), -3.086, 3) # the vertex will get linearly interpolated alpha = (setTime - 1) / (2 - 1) self.failUnlessAlmostEqual(MayaCmds.getAttr('node.vt[0]')[0][0], (1-alpha)*val_1+alpha*val_2, 3) # convenience functions for the tests following def noFrameRangeExists(self, fileName): retVal = subprocess.call(['h5dump', '--attribute=1.time', fileName]) self.failUnless(retVal != 0) def isFrameRangeExists(self, fileName): retVal = subprocess.call(['h5dump', '--attribute=2.time', fileName]) self.failUnless(retVal != 0) retVal = subprocess.call(['h5dump', '--attribute=1.time', fileName]) self.failUnless(retVal == 0) def isFrameRangeTransAndFrameRangeShapeExists(self, fileName): retVal = subprocess.call(['h5dump', '--attribute=2.time', fileName]) self.failUnless(retVal == 0) retVal = subprocess.call(['h5dump', '--attribute=1.time', fileName]) self.failUnless(retVal == 0) def test_agat(self): # animated geometry, animated transform node nodename = 'agat_node' MayaCmds.polyCube(name=nodename) MayaCmds.setKeyframe(nodename+'.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe(nodename+'.translateX', time=5.0, v=10.0) MayaCmds.select(nodename+'.vtx[0:8]') MayaCmds.setKeyframe(time=1.0) MayaCmds.scale(1.5, 1.5, 1.8) MayaCmds.setKeyframe(time=5.0) self.__files.append(util.expandFileName('agat_motionblur_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -wfg -step 0.5 -root %s -file %s' % ( nodename, self.__files[-1])) # frameRangeShape: 1, 2, 3, 4, 5, 6 # frameRangeTrans: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeTransAndFrameRangeShapeExists(self.__files[-1]) self.__files.append(util.expandFileName('agat_motionblur_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -root %s -file %s' % ( nodename, self.__files[-1])) # frameRange: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeExists(self.__files[-1]) self.__files.append(util.expandFileName('agat_norange_Test.abc')) MayaCmds.AbcExport(j='-root %s -f %s' % (nodename,self.__files[-1])) # no frameRange self.noFrameRangeExists(self.__files[-1]) def test_agst(self): # animated geometry, static transform node nodename = 'agst_node' MayaCmds.polyCube(name=nodename) MayaCmds.select(nodename+'.vtx[0:8]') MayaCmds.setKeyframe(time=1.0) MayaCmds.scale(1.5, 1.5, 1.8) MayaCmds.setKeyframe(time=5.0) self.__files.append(util.expandFileName('agst_motionblur_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -wfg -root %s -file %s' % ( nodename, self.__files[-1])) # frameRange: 1, 2, 3, 4, 5, 6 self.isFrameRangeTransAndFrameRangeShapeExists(self.__files[-1]) self.__files.append(util.expandFileName('agst_motionblur_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -root %s -f %s' % ( nodename, self.__files[-1])) # frameRange: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeExists(self.__files[-1]) self.__files.append(util.expandFileName('agst_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -wfg -root %s -f %s' % (nodename, self.__files[-1])) # frameRange: 1, 2, 3, 4, 5 self.isFrameRangeExists(self.__files[-1]) def test_sgat(self): # static geometry, animated transform node nodename = 'sgat_node' MayaCmds.polyCube(name=nodename) MayaCmds.setKeyframe(nodename+'.translateX', time=1.0, v=1.0) MayaCmds.setKeyframe(nodename+'.translateX', time=5.0, v=10.0) self.__files.append(util.expandFileName('sgat_motionblur_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -wfg -root %s -f %s' % ( nodename, self.__files[-1])) # frameRange: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeTransAndFrameRangeShapeExists(self.__files[-1]) self.__files.append(util.expandFileName('sgat_motionblur_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -root %s -f %s ' % ( nodename, self.__files[-1])) # frameRange: 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6 self.isFrameRangeExists(self.__files[-1]) def test_sgst(self): # static geometry, static transform node nodename = 'sgst_node' MayaCmds.polyCube(name=nodename) self.__files.append(util.expandFileName('sgst_motionblur_noSampleGeo_Test.abc')) MayaCmds.AbcExport(j='-fr 1 5 -step 0.5 -wfg -root %s -file %s ' % ( nodename, self.__files[-1])) self.failIf(MayaCmds.AbcImport(self.__files[-1]) != "") self.__files.append(util.expandFileName('sgst_moblur_noSampleGeo_norange_Test.abc')) MayaCmds.AbcExport(j='-step 0.5 -wfg -root %s -file %s' % ( nodename, self.__files[-1])) # frameRange: NA self.noFrameRangeExists(self.__files[-1])
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import subprocess import unittest import util class AnimNurbsCurveTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) # a test for animated non-curve group Nurbs Curve def testAnimSimpleNurbsCurveRW(self): # create the Nurbs Curve name = MayaCmds.curve( d=3, p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9), (12, 10, 2)], k=[0,0,0,1,2,2,2] ) MayaCmds.select(name+'.cv[0:4]') # frame 1 MayaCmds.currentTime(1, update=True) MayaCmds.setKeyframe() # frame 24 MayaCmds.currentTime(24, update=True) MayaCmds.setKeyframe() # frame 12 MayaCmds.currentTime(12, update=True) MayaCmds.move(3, 0, 0, r=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testAnimNurbsSingleCurve.abc')) self.__files.append(util.expandFileName('testAnimNurbsSingleCurve01_14.abc')) self.__files.append(util.expandFileName('testAnimNurbsSingleCurve15_24.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % (name, self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % (name, self.__files[-1])) # use AbcStitcher to combine two files into one subprocess.call(self.__abcStitcher + self.__files[-3:]) MayaCmds.AbcImport(self.__files[-3], mode='import') shapeNames = MayaCmds.ls(exactType='nurbsCurve') MayaCmds.currentTime(1, update=True) self.failUnless(util.compareNurbsCurve(shapeNames[0], shapeNames[1])) MayaCmds.currentTime(12, update=True) self.failUnless(util.compareNurbsCurve(shapeNames[0], shapeNames[1])) MayaCmds.currentTime(24, update=True) self.failUnless(util.compareNurbsCurve(shapeNames[0], shapeNames[1])) def testAnimNurbsCurveGrpRW(self): # create Nurbs Curve group knotVec = [0,0,0,1,2,2,2] curve1CV = [(0, 0, 0), (3, 5, 0), (5, 6, 0), (9, 9, 0), (12, 10, 0)] curve2CV = [(0, 0, 3), (3, 5, 3), (5, 6, 3), (9, 9, 3), (12, 10, 3)] curve3CV = [(0, 0, 6), (3, 5, 6), (5, 6, 6), (9, 9, 6), (12, 10, 6)] MayaCmds.curve(d=3, p=curve1CV, k=knotVec, name='curve1') MayaCmds.curve(d=3, p=curve2CV, k=knotVec, name='curve2') MayaCmds.curve(d=3, p=curve3CV, k=knotVec, name='curve3') MayaCmds.group('curve1', 'curve2', 'curve3', name='group') MayaCmds.addAttr('group', longName='riCurves', at='bool', dv=True) # frame 1 MayaCmds.currentTime(1, update=True) MayaCmds.select('curve1.cv[0:4]', 'curve2.cv[0:4]', 'curve3.cv[0:4]', replace=True) MayaCmds.setKeyframe() # frame 24 MayaCmds.currentTime(24, update=True) MayaCmds.select('curve1.cv[0:4]') MayaCmds.rotate(0.0, '90deg', 0.0, relative=True ) MayaCmds.select('curve2.cv[0:4]') MayaCmds.move(0.0, 0.5, 0.0, relative=True ) MayaCmds.select('curve3.cv[0:4]') MayaCmds.scale(1.0, 0.5, 1.0, relative=True ) MayaCmds.select('curve1.cv[0:4]', 'curve2.cv[0:4]', 'curve3.cv[0:4]', replace=True) MayaCmds.setKeyframe() self.__files.append(util.expandFileName('testAnimNCGrp.abc')) self.__files.append(util.expandFileName('testAnimNCGrp01_14.abc')) self.__files.append(util.expandFileName('testAnimNCGrp15_24.abc')) MayaCmds.AbcExport(j='-fr 1 14 -root %s -file %s' % ('group', self.__files[-2])) MayaCmds.AbcExport(j='-fr 15 24 -root %s -file %s' % ('group', self.__files[-1])) # use AbcStitcher to combine two files into one subprocess.call(self.__abcStitcher + self.__files[-3:]) # reading test MayaCmds.AbcImport(self.__files[-3], mode='import') shapeNames = MayaCmds.ls(exactType='nurbsCurve') MayaCmds.currentTime(1, update=True) for i in range(0, 3): self.failUnless( util.compareNurbsCurve(shapeNames[i], shapeNames[i+3])) MayaCmds.currentTime(12, update=True) for i in range(0, 3): self.failUnless( util.compareNurbsCurve(shapeNames[i], shapeNames[i+3])) MayaCmds.currentTime(24, update=True) for i in range(0, 3): self.failUnless( util.compareNurbsCurve(shapeNames[i], shapeNames[i+3]))
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from maya import cmds as MayaCmds import os import unittest import util class AnimPointPrimitiveTest(unittest.TestCase): def setUp(self): MayaCmds.file(new=True, force=True) self.__files = [] def tearDown(self): for f in self.__files: os.remove(f) def testAnimPointPrimitiveReadWrite(self): # Creates a point emitter. MayaCmds.emitter(dx=1, dy=0, dz=0, sp=0.33, pos=(1, 1, 1), n='myEmitter') MayaCmds.particle(n='emittedParticles') MayaCmds.setAttr('emittedParticles.lfm', 2) MayaCmds.setAttr('emittedParticles.lifespan', 50) MayaCmds.setAttr('emittedParticles.lifespanRandom', 2) MayaCmds.connectDynamic('emittedParticles', em='myEmitter') self.__files.append(util.expandFileName('testAnimParticleReadWrite.abc')) MayaCmds.AbcExport(j='-fr 1 24 -root emittedParticles -file ' + self.__files[-1]) # reading test MayaCmds.AbcImport(self.__files[-1], mode='open') # reading animated point clouds into Maya aren't fully supported # yet which is why we don't have any checks on the data here
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** import maya.cmds as MayaCmds import os import subprocess import unittest import util class animPropTest(unittest.TestCase): #------------------------------------------------------------------------- def setUp(self): MayaCmds.file(new=True, force=True) self.__abcStitcher = [os.environ['AbcStitcher']] self.__files = [util.expandFileName('animProp.abc'), util.expandFileName('animProp01_14.abc'), util.expandFileName('animProp15_24.abc')] #------------------------------------------------------------------------- def tearDown(self): for f in self.__files : os.remove(f) #------------------------------------------------------------------------- def setAndKeyProps( self, nodeName ): MayaCmds.select(nodeName) MayaCmds.addAttr(longName='SPT_int8', defaultValue=0, attributeType='byte', keyable=True) MayaCmds.addAttr(longName='SPT_int16', defaultValue=0, attributeType='short', keyable=True) MayaCmds.addAttr(longName='SPT_int32', defaultValue=0, attributeType='long', keyable=True) MayaCmds.addAttr(longName='SPT_float', defaultValue=0, attributeType='float', keyable=True) MayaCmds.addAttr(longName='SPT_double', defaultValue=0, attributeType='double', keyable=True) MayaCmds.setKeyframe(nodeName, value=0, attribute='SPT_int8', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=100, attribute='SPT_int16', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=1000, attribute='SPT_int32', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=0.57777777, attribute='SPT_float', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=5.045643545457, attribute='SPT_double', t=[1, 24]) MayaCmds.setKeyframe(nodeName, value=8, attribute='SPT_int8', t=12) MayaCmds.setKeyframe(nodeName, value=16, attribute='SPT_int16', t=12) MayaCmds.setKeyframe(nodeName, value=32, attribute='SPT_int32', t=12) MayaCmds.setKeyframe(nodeName, value=3.141592654, attribute='SPT_float', t=12) MayaCmds.setKeyframe(nodeName, value=3.141592654, attribute='SPT_double', t=12) def verifyProps( self, root, nodeName ): # write to files MayaCmds.AbcExport(j='-atp SPT_ -fr 1 14 -root %s -file %s' % (root, self.__files[1])) MayaCmds.AbcExport(j='-atp SPT_ -fr 15 24 -root %s -file %s' % (root, self.__files[2])) subprocess.call(self.__abcStitcher + self.__files) # read file and verify data MayaCmds.AbcImport(self.__files[0], mode='open') t = 1 # frame 1 MayaCmds.currentTime(t, update=True) self.failUnlessEqual(0, MayaCmds.getAttr(nodeName+'.SPT_int8'), '%s.SPT_int8 != 0 at frame %d' %( nodeName, t)) self.failUnlessEqual(100, MayaCmds.getAttr(nodeName+'.SPT_int16'), '%s.SPT_int16 != 100 at frame %d' %( nodeName, t)) self.failUnlessEqual(1000, MayaCmds.getAttr(nodeName+'.SPT_int32'), '%s.SPT_int32 != 1000 at frame %d' %( nodeName, t)) self.failUnlessAlmostEqual(0.57777777, MayaCmds.getAttr(nodeName+'.SPT_float'), 4, '%s.SPT_float != 0.57777777 at frame %d' %( nodeName, t)) self.failUnlessAlmostEqual(5.045643545457, MayaCmds.getAttr(nodeName+'.SPT_double'), 7, '%s.SPT_double != 5.045643545457 at frame %d' %( nodeName, t)) t = 12 # frame 12 MayaCmds.currentTime(t, update=True) self.failUnlessEqual(8, MayaCmds.getAttr(nodeName+'.SPT_int8'), '%s.SPT_int8 != 8 at frame %d' %( nodeName, t)) self.failUnlessEqual(16, MayaCmds.getAttr(nodeName+'.SPT_int16'), '%s.SPT_int16 != 16 at frame %d' %( nodeName, t)) self.failUnlessEqual(32, MayaCmds.getAttr(nodeName+'.SPT_int32'), '%s.SPT_int32 != 32 at frame %d' %( nodeName, t)) self.failUnlessAlmostEqual(3.141592654, MayaCmds.getAttr(nodeName+'.SPT_float'), 4, '%s.SPT_float != 3.141592654 at frame %d' %( nodeName, t)) self.failUnlessAlmostEqual(3.1415926547, MayaCmds.getAttr(nodeName+'.SPT_double'), 7, '%s.SPT_double != 3.141592654 at frame %d' %( nodeName, t)) t = 24 # frame 24 MayaCmds.currentTime(t, update=True) self.failUnlessEqual(0,MayaCmds.getAttr(nodeName+'.SPT_int8'), '%s.SPT_int8 != 0 at frame %d' % (nodeName, t)) self.failUnlessEqual(100, MayaCmds.getAttr(nodeName+'.SPT_int16'), '%s.SPT_int16 != 100 at frame %d' % (nodeName, t)) self.failUnlessEqual(1000, MayaCmds.getAttr(nodeName+'.SPT_int32'), '%s.SPT_int32 != 1000 at frame %d' % (nodeName, t)) self.failUnlessAlmostEqual(0.57777777, MayaCmds.getAttr(nodeName+'.SPT_float'), 4, '%s.SPT_float != 0.57777777 at frame %d' % (nodeName, t)) self.failUnlessAlmostEqual(5.045643545457, MayaCmds.getAttr(nodeName+'.SPT_double'), 7, '%s.SPT_double != 5.045643545457 at frame %d' % (nodeName, t)) def testAnimTransformProp(self): nodeName = MayaCmds.createNode('transform') self.setAndKeyProps(nodeName) self.verifyProps(nodeName, nodeName) def testAnimCameraProp(self): root = MayaCmds.camera() nodeName = root[0] shapeName = root[1] self.setAndKeyProps(shapeName) self.verifyProps(nodeName, shapeName) def testAnimMeshProp(self): nodeName = 'polyCube' shapeName = 'polyCubeShape' MayaCmds.polyCube(name=nodeName, ch=False) self.setAndKeyProps(shapeName) self.verifyProps(nodeName, shapeName) def testAnimNurbsCurvePropReadWrite(self): nodeName = 'nCurve' shapeName = 'curveShape1' MayaCmds.curve(p=[(0, 0, 0), (3, 5, 6), (5, 6, 7), (9, 9, 9)], name=nodeName) self.setAndKeyProps(shapeName) self.verifyProps(nodeName, shapeName) def testAnimNurbsSurfaceProp(self): nodeName = MayaCmds.sphere(ch=False)[0] nodeNameList = MayaCmds.pickWalk(d='down') shapeName = nodeNameList[0] self.setAndKeyProps(shapeName) self.verifyProps(nodeName, shapeName)
Python
#!/usr/bin/env mayapy ##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** # run this via mayapy # runs the test suite import glob import os import sys import time import unittest import maya.standalone maya.standalone.initialize(name='python') from maya import cmds as MayaCmds from maya.mel import eval as MelEval usage = """ Usage: mayapy RunTests.py AbcExport AbcImport AbcStitcher [tests.py] Where: AbcExport is the location of the AbcExport Maya plugin to load. AbcImport is the location of the AbcImport Maya plugin to load. AbcStitcher is the location of the AbcStitcher command to use. If no specific python tests are specified, all python files named *_test.py in the same directory as this file are used. """ if len(sys.argv) < 4: raise RuntimeError(usage) MayaCmds.loadPlugin(sys.argv[1]) print 'LOADED', sys.argv[1] MayaCmds.loadPlugin(sys.argv[2]) print 'LOADED', sys.argv[2] if not os.path.exists(sys.argv[3]): raise RuntimeError (sys.argv[3] + ' does not exist') else: os.environ['AbcStitcher'] = sys.argv[3] suite = unittest.TestSuite() main_dir = os.path.dirname(os.path.abspath(__file__)) os.chdir( main_dir ) MelEval('chdir "%s"' % main_dir ) # For now, hack the path (so the import below works) sys.path.append("..") # Load all the tests specified by the command line or *_test.py testFiles = sys.argv[4:] if not testFiles: testFiles = glob.glob('*_test.py') for file in testFiles: name = os.path.splitext(file)[0] __import__(name) test = unittest.defaultTestLoader.loadTestsFromName(name) suite.addTest(test) # Run the tests runner = unittest.TextTestRunner(verbosity=2) runner.run(suite)
Python
#!/usr/bin/env python2.5 #-*- mode: python -*- ##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Industrial Light & Magic nor the names of ## its contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** import os, sys class Path( object ): """The Path class simplifies filesystem path manipulation. If you wish to use a Path object as an argument to standard Python path functions such as os.path.*, open(), etc., you must first cast it to a string like "str( myPathObject )".""" def __init__( self, path=None ): if path != None: path = str( path ) self._isabs = os.path.isabs( path ) self._orig = path self._path = os.path.normpath( os.path.expanduser( path ) ) else: self._isabs = False self._path = '' self._orig = '' if self._isabs: self._root = os.sep else: if self._orig == '': self._root = None else: self._root = os.curdir self._plist = filter( lambda x: x and x != os.curdir, self._path.split( os.sep )) self._len = len( self._plist ) self._isempty = self._root == None and self._len == 0 self._maxindex = self._len - 1 self._maxsliceindex = self._len def __reinit__( self, new ): self._len = len( new._plist ) self._plist = new._plist[:] self._isempty = 0 == new._len self._maxindex = new._len - 1 self._maxsliceindex = new._len self._path = new._path self._orig = new._orig self._isabs = new._isabs self._root = new._root def __repr__( self ): return self._path def __str__( self ): return self.__repr__() def __contains__( self, other ): return other in self._plist def __len__( self ): return self._len def __add__( self, other ): return Path( os.path.join( str( self ), str( other ) ) ) def __radd__( self, other ): return Path( other ) + self def __iter__( self ): self._iterindex = 0 return self def __eq__( self, other ): return str( self ) == str( other ) def __ne__( self, other ): return str( self ) != str( other ) def __cmp__( self, other ): _, p1, p2 = self.common( other ) return len( p1 ) - len( p2 ) def __nonzero__( self ): if not self.isabs() and len( self ) == 0: return False else: return True def __hash__( self ): return hash( str( self )) def __getitem__( self, n ): if isinstance( n, slice ): path = None plist = self._plist[n.start:n.stop:n.step] returnabs = self._isabs and n.start < 1 if len( plist ) > 0: path = os.sep.join( plist ) else: path = os.curdir path = Path( path ) if returnabs: path = self.root() + path else: pass return path else: return self._plist[n] def __setitem__( self, key, value ): try: key = int( key ) except ValueError: raise ValueError, "You must use an integer to refer to a path element." if key > abs( self._maxindex ): raise IndexError, "Maximum index is +/- %s." % self._maxindex self._plist[key] = value self._path = str( self[:] ) def __delitem__( self, n ): try: n = int( n ) except ValueError: raise ValueError, "You must use an integer to refer to a path element." try: del( self._plist[n] ) t = Path( self[:] ) self.__reinit__( t ) except IndexError: raise IndexError, "Maximum index is +/- %s" & self._maxindex def rindex( self, val ): if val in self: return len( self._plist ) - \ list( reversed( self._plist ) ).index( val ) - 1 else: raise ValueError, "%s is not in path." % val def index( self, val ): if val in self: return self._plist.index( val ) else: raise ValueError, "%s is not in path." % val def common( self, other, cmn=None ): cmn = Path( cmn ) other = Path( str( other ) ) if self.isempty() or other.isempty(): return cmn, self, other elif (self[0] != other[0]) or (self.root() != other.root()): return cmn, self, other else: return self[1:].common( other[1:], self.root() + cmn + self[0] ) def relative( self, other ): cmn, p1, p2 = self.common( other ) relhead = Path() if len( p1 ) > 0: relhead = Path( (os.pardir + os.sep) * len( p1 )) return relhead + p2 def join( self, *others ): t = self[:] for o in others: t = t + o return t def split( self ): head = self[:-1] tail = None if not head.isempty(): tail = Path( self[-1] ) else: tail = self if not head.isabs() and head.isempty(): head = Path( None ) if head.isabs() and len( tail ) == 1: tail = tail[-1] return ( head, tail ) def splitext( self ): head, tail = os.path.splitext( self._path ) return Path( head ), tail def next( self ): if self._iterindex > self._maxindex: raise StopIteration else: i = self._iterindex self._iterindex += 1 return self[i] def subpaths( self ): sliceind = 0 while sliceind < self._maxsliceindex: sliceind += 1 yield self[:sliceind] def append( self, *others ): t = self[:] for o in others: t = t + o self.__reinit__( t ) def root( self ): return Path( self._root ) def elems( self ): return self._plist def path( self ): return self._path def exists( self ): return os.path.exists( self._path ) def isempty( self ): return self._isempty def isabs( self ): return self._isabs def islink( self ): return os.path.islink( self._path ) def isdir( self ): return os.path.isdir( self._path ) def isfile( self ): return os.path.isfile( self._path ) def readlink( self ): if self.islink(): return Path( os.readlink( self._orig ) ) else: return self def dirname( self ): return self[:-1] def basename( self ): return self.dirname() def startswith( self, other ): return self._path.startswith( other ) def makeabs( self ): t = self[:] t._root = os.sep t._isabs = True t._path = os.path.join( os.sep, self._path ) self.__reinit__( t ) def makerel( self ): t = self[:] t._root = os.curdir t._isabs = False t._path = os.sep.join( t._plist ) self.__reinit__( t ) def toabs( self ): return Path( os.path.abspath( self._path ) ) def torel( self ): t = self[:] t.makerel() return t ##-***************************************************************************** def mapFSTree( root, path, dirs=set(), links={} ): """Create a sparse map of the filesystem graph from the root node to the path node.""" root = Path( root ) path = Path( path ) for sp in path.subpaths(): if sp.isabs(): full = sp else: full = sp.toabs() head = full.dirname() if full.islink(): target = full.readlink() if target.isabs(): newpath = target else: newpath = head + target # make sure there are no cycles if full in links: continue links[full] = newpath _dirs, _links = mapFSTree( full, newpath, dirs, links ) dirs.update( _dirs ) links.update( _links ) elif full.isdir(): if full in dirs: continue else: dirs.add( full ) elif full.isfile(): break #pass else: print "QOI??? %s" % full return dirs, links ##-***************************************************************************** def main(): try: arg = Path( sys.argv[1] ) except IndexError: print "Please supply a directory to analyze." return 1 dirs, links = mapFSTree( Path( os.getcwd() ), arg ) print print "Directories traversed to get to %s\n" % arg for d in sorted( list( dirs ) ): print d print print "Symlinks in traversed directories for %s\n" % arg for k in links: print "%s: %s" % ( k, links[k] ) print return 0 ##-***************************************************************************** if __name__ == "__main__": sys.exit( main() )
Python
#!/usr/bin/env python2.6 #-*- mode: python -*- ##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Industrial Light & Magic nor the names of ## its contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from __future__ import with_statement import os, sys, re from Path import Path ##-***************************************************************************** COMMENT = re.compile( r"//|#" ) WS = re.compile( r"\s" ) ##-***************************************************************************** class CacheEntry( object ): def __init__( self, _line ): line = WS.sub( "", str( _line ) ) if not line: return None elif COMMENT.match( line ): return None else: # get rid of comments at the end of the line line = COMMENT.split( line, 1 )[0].strip() try: name_type, value = line.split( '=' ) self._value = value.strip() if self._value == '': self._value = None name, typ = name_type.split( ':' ) self._name = name.strip() self._type = typ.strip() except ValueError: sys.stderr.write( "Could not parse line '%s'\n" % _line ) self._value = None self._name = None self._type = None def __str__( self ): val = "" typ = "" if self._value != None: val = self._value if self._type != None: typ = self._type if self._name == None: return "" else: s = "%s:%s=%s" % ( self._name, typ, val ) return s.strip() def __eq__( self, other ): return str( self ) == str( other ) def __nonzero__( self ): try: return self._name != None and self._value != None except AttributeError: return False def name( self ): return self._name def value( self, newval = None ): if newval != None: self._value = newval else: return self._value def hint( self ): """Return the CMakeCache TYPE of the entry; used as a hint to CMake GUIs.""" return self._type ##-***************************************************************************** class CMakeCache( object ): """This class is used to read in and get programmatic access to the variables in a CMakeCache.txt file, manipulate them, and then write the cache back out.""" def __init__( self, path=None ): self._cachefile = Path( path ) _cachefile = str( self._cachefile ) self._entries = {} if self._cachefile.exists(): with open( _cachefile ) as c: entries = filter( None, map( lambda x: CacheEntry( x ), c.readlines() ) ) entries = filter( lambda x: x.value() != None, entries ) for i in entries: self._entries[i.name()] = i def __contains__( self, thingy ): try: return thingy in self.names() except TypeError: return thingy in self._entries.values() def __iter__( self ): return self._entries def __nonzero__( self ): return len( self._entries ) > 0 def __str__( self ): return os.linesep.join( map( lambda x: str( x ), self.entries() ) ) def add( self, entry ): e = CacheEntry( entry ) if e: if not e in self: self._entries[e.name()] = e else: sys.stderr.write( "Entry for '%s' is already in the cache.\n" % \ e.name() ) else: sys.stderr.write( "Could not create cache entry for '%s'\n" % e ) def update( self, entry ): e = CacheEntry( entry ) if e: self._entries[e.name()] = e else: sys.stderr.write( "Could not create cache entry for '%s'\n" % e ) def names( self ): return self._entries.keys() def entries( self ): return self._entries.values() def get( self, name ): return self._entries[name] def cachefile( self ): return self._cachefile def refresh( self ): self.__init__( self._cachefile ) def write( self, newfile = None ): if newfile == None: newfile = self._cachefile with open( newfile, 'w' ) as f: for e in self.entries(): f.write( str( e ) + os.linesep )
Python
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Sony Pictures Imageworks, nor ## Industrial Light & Magic, nor the names of their contributors may be used ## to endorse or promote products derived from this software without specific ## prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## ##-***************************************************************************** from Path import Path from CMakeCache import CMakeCache, CacheEntry
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Datastore model classes for the members. # # Created on 2008-10-28. # $Id: models.py 29 2009-09-23 21:22:49Z guolin.mobi $ # import logging import datetime from google.appengine.ext import db from google.appengine.api import users from afcpweb.apps.common import utils from afcpweb.apps.members import paristech class AFCPUserProfile(db.Model): """This class represents a profile of an AFCP member. The key name of the entity is the Google account email address. """ MEMBER_ROLE = "member" EDITOR_ROLE = "editor" PENDING_STATUS = "pending" APPROVED_STATUS = "approved" uid = db.StringProperty(required=True) name = db.StringProperty(required=True) name_zh = db.StringProperty() sex = db.StringProperty(choices=["male", "female", "unknown"], default="unknown") birthday = db.DateTimeProperty() promo = db.IntegerProperty() ecole_id = db.StringProperty() univ_id = db.StringProperty() alt_email = db.StringProperty() tel = db.StringProperty() photo_type = db.StringProperty() photo_data = db.BlobProperty() # cv_en = props.CurriculumVitaeProperty(default=props.CurriculumVitae()) # cv_fr = props.CurriculumVitaeProperty(default=props.CurriculumVitae()) # cv_zh = props.CurriculumVitaeProperty(default=props.CurriculumVitae()) status = db.StringProperty(default=PENDING_STATUS) deleted = db.BooleanProperty(default=False) create_date = db.DateTimeProperty(auto_now_add=True) last_login = db.DateTimeProperty(auto_now_add=True) login_count = db.IntegerProperty(default=0) roles = db.StringListProperty(default=[]) def __unicode__(self): return self.user() def user(self): return users.User(self.key().name()) def is_current_user_owner(self): user = users.get_current_user() return user == self.user() def google_account(self): return self.user().email() def names(self): names = self.name if self.name_zh is not None: names += " (%s)" % self.name_zh return names def email(self): if self.alt_email is None: return self.key().name() else: return self.alt_email def munging_google_account(self): return utils.munge_email(self.google_account()) def munging_alt_email(self): return utils.munge_email(self.alt_email) def munging_email(self): return utils.munge_email(self.email()) def ecole(self): return paristech.ECOLES.get(self.ecole_id) def university(self): return paristech.UNIVERSITIES.get(self.univ_id) def has_photo(self): return self.photo_type is not None and self.photo_data is not None def is_member(self): return AFCPUserProfile.MEMBER_ROLE in self.roles def is_editor(self): return AFCPUserProfile.EDITOR_ROLE in self.roles def add_editor(self): if AFCPUserProfile.EDITOR_ROLE not in self.roles: self.roles.append(AFCPUserProfile.EDITOR_ROLE) def count_login(self): self.last_login = datetime.datetime.utcnow() self.login_count += 1 def put(self): # Set default value to login count. if self.login_count is None: self.login_count = 1 # If the user is an AFCP member, add the member role. Otherwise, remove the member role. if self.roles is None: self.roles = [] if self.ecole_id is not None: if AFCPUserProfile.MEMBER_ROLE not in self.roles: self.roles.append(AFCPUserProfile.MEMBER_ROLE) else: if AFCPUserProfile.MEMBER_ROLE in self.roles: self.roles.remove(AFCPUserProfile.MEMBER_ROLE) # Put the entity to datastore. return super(AFCPUserProfile, self).put() #--------------------------------------------------------------------------------------------------- # AFCPUser: a wrapper around google.appengine.api.users.User #--------------------------------------------------------------------------------------------------- class AFCPUser(object): def __init__(self, user): self._user = user if self._user: self._profile = AFCPUserProfile.get_by_key_name(self._user.email()) else: self._profile = None def profile(self): return self._profile def google_user(self): return self._user def nickname(self): if self._profile: return self._profile.name elif self._user: return self._user.nickname() else: return None def email(self): if self._user: return self._user.email() else: return None def is_anonymous(self): return self._user is None def is_authenticated(self): return self._user is not None def __nonzero__(self): return self.is_authenticated() def get_current_user(): google_user = users.get_current_user() return AFCPUser(google_user) def create_login_url(redirect_url): return users.create_login_url(redirect_url) def create_logout_url(redirect_url): return users.create_logout_url(redirect_url) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Views for the members app. # # Created on 2008-10-28. # $Id: views.py 40 2010-03-08 23:05:09Z guolin.mobi $ # import logging import urllib from django.template import loader from django.template import Context from django.http import HttpResponseRedirect from django.http import HttpResponse from afcpweb.apps.common.actions import get_common_data from afcpweb.apps.common import utils from afcpweb.apps.members.config import Config from afcpweb.apps.members import paristech from afcpweb.apps.members.models import get_current_user from afcpweb.apps.members.models import AFCPUserProfile def view_members(request): """Displays the AFCP members list.""" MEMBERS_PER_PAGE = 10 query = AFCPUserProfile.gql("WHERE deleted=:deleted ORDER BY name", deleted=False) page_number = utils.get_param(request.REQUEST, "page") members = utils.EntityPage(query, MEMBERS_PER_PAGE, page_number) ctxt_dict = { "members" : members, "has_previous" : members.has_previous(), "has_next" : members.has_next(), "previous_page" : members.previous_page_number(), "next_page" : members.next_page_number(),} ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/members.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) def my_profile(request): """If current user already has a profile, redirect to the profile page; otherwise, display the create profile page. """ # Anonymous user should not have arrived to this page. user = get_current_user() if not user: return HttpResponseRedirect("%s/" % Config.URL_PREFIX) # If the user already has a profile, redirect to the profile page. if user.profile() is not None: return HttpResponseRedirect("%s/profile/%s/" % (Config.URL_PREFIX, user.profile().uid)) # Create profile for the current user. if request.method == "GET": # Return the create profile form. ctxt_dict = { "error" : utils.get_param(request.GET, "error"), "ecoles" : paristech.ECOLES.values(), "universities" : paristech.UNIVERSITIES.values(), } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/create_profile.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) elif request.method == "POST": # Create a profile for the current user. try: key_name = user.email() logging.info(key_name) uid = utils.generate_random_id("U") logging.info(uid) name = utils.get_param(request.POST, "name") logging.info(name) name_zh = utils.get_param(request.POST, "name_zh") logging.info(name_zh) status = AFCPUserProfile.PENDING_STATUS profile = AFCPUserProfile( key_name=key_name, uid=uid, name=name, name_zh=name_zh, status=status ) profile.put() return HttpResponseRedirect("%s/profile/%s/" % (Config.URL_PREFIX, profile.uid)) except Exception, ex: error = "Failed to create user profile: %s" % str(ex) logging.error(error) params = { "error" : error, } return HttpResponseRedirect("%s?%s" % (request.path, urllib.urlencode(params))) def profile(request, uid): """Displays the member profile by UID.""" profile = AFCPUserProfile.gql("WHERE uid=:uid", uid=uid).get() if profile is None: return not_found(request) if request.method == "GET": ctxt_dict = { "info" : utils.get_param(request.GET, "info"), "error" : utils.get_param(request.GET, "error"), "uid" : uid, "profile" : profile, "ecoles" : paristech.ECOLES.values(), "universities" : paristech.UNIVERSITIES.values(), } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/profile.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) elif request.method == "POST": params = {} action = utils.get_param(request.POST, "action") try: if action == "edit": # Update basic information. profile.name = utils.get_param(request.POST, "name") profile.name_zh = utils.get_param(request.POST, "name_zh") profile.sex = utils.get_param(request.POST, "sex") birthday_str = utils.get_param(request.POST, "birthday") if birthday_str is not None: profile.birthday = datetime.datetime.strptime(birthday_str, "%Y-%m-%d") else: profile.birthday = None promo_str = utils.get_param(request.POST, "promo") if promo_str is not None: profile.promo = int(promo_str) else: profile.promo = None profile.ecole_id = utils.get_param(request.POST, "ecole_id") profile.univ_id = utils.get_param(request.POST, "univ_id") profile.alt_email = utils.get_param(request.POST, "alt_email") profile.tel = utils.get_param(request.POST, "tel") # Update profile photo. """ query_dict = request.POST.copy() query_dict.update(request.FILES) photo_dict = query_dict.get("photo", None) if photo_dict is not None: profile.photo_type = utils.get_param(photo_dict, "content-type") profile.photo_data = photo_dict.get("content") elif utils.get_param(request.POST, "delete_photo") == "1": profile.photo_type = None profile.photo_data = None """ # Update profile in datastore. profile.put() params["info"] = "Profile updated successfully." elif action == "delete": profile.deleted = True profile.put() params["info"] = "Profile deleted successfully." elif action == "restore": profile.deleted = False profile.put() params["info"] = "Profile restored successfully." else: raise Exception, "Unknown action '%s'." % action except Exception, ex: error = "Failed to perform action '%s': %s" % (action, str(ex)) logging.error(error) params["error"] = error return HttpResponseRedirect("%s?%s" % (request.path, urllib.urlencode(params))) def profile_photo(request, uid): profile = AFCPUserProfile.gql("WHERE uid=:uid", uid=uid).get() if profile is None: return not_found(request) if request.method == "GET": if profile.has_photo(): return HttpResponse(profile.photo_data, mimetype=profile.photo_type) else: return not_found(request) def random_profile(request): # TODO: count() and fetch() cannot handle a large amount of results. # This function should be redesigned to be more scalable. query = AFCPUserProfile.gql("") count = query.count() if count <= 0: return not_found(request) random_offset = random.choice(range(0, count)) profile_list = query.fetch(1, random_offset) if not profile_list: return not_found(request) else: profile_uid = profile_list[0].uid return HttpResponseRedirect("%s/profile/%s/" % (Config.URL_PREFIX, profile_uid)) #--------------------------------------------------------------------------------------------------- def ecole(request, acronym): if request.method == "GET": MEMBERS_PER_PAGE = 20 query = AFCPUserProfile.gql( "WHERE ecole_id=:acronym AND deleted=:deleted ORDER BY name", acronym=acronym, deleted=False ) page_number = utils.get_param(request.REQUEST, "page") members = utils.EntityPage(query, MEMBERS_PER_PAGE, page_number) ctxt_dict = { "members" : members, "ecole" : paristech.ECOLES.get(acronym), "ecoles" : paristech.ECOLES.values(), } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/ecole.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) def university(request, acronym): if request.method == "GET": MEMBERS_PER_PAGE = 20 query = AFCPUserProfile.gql( "WHERE univ_id=:acronym AND deleted=:deleted ORDER BY name", acronym=acronym, deleted=False ) page_number = utils.get_param(request.REQUEST, "page") members = utils.EntityPage(query, MEMBERS_PER_PAGE, page_number) ctxt_dict = { "members" : members, "university" : paristech.UNIVERSITIES.get(acronym), "universities" : paristech.UNIVERSITIES.values(), } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/university.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2008-10-28 # $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $ #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # all info about Paristech ecole and universities in China # Created on 2008-11-19. # $Id: paristech.py 26 2009-08-04 22:06:00Z guolin.mobi $ # class Ecole(object): def __init__(self, acronym, name, website, desc=None): self.acronym = acronym self.name = name self.website = website self.desc = desc class University(object): def __init__(self, acronym, name, name_en, website, desc=None): self.acronym = acronym self.name = name self.name_en = name_en self.website = website self.desc = desc ECOLES = { "ENPC" : Ecole( acronym="ENPC", name="Ecole Nationale des Ponts et Chaussées", website="http://www.enpc.fr/" ), "ENST" : Ecole( acronym="ENST", name="Ecole Nationale Supérieure des Télécommunications (aka. Télécom ParisTech)", website="http://www.enst.fr/" ), "ENSAE" : Ecole( acronym="ENSAE", name="Ecole Nationale de la Statistique et de l'Administration", website="http://www.ensae.fr/" ), "ENSTA" : Ecole( acronym="ENSTA", name="Ecole Nationale Supérieure de Techniques Avancées", website="http://www.ensta.fr/" ), "ENSAM" : Ecole( acronym="ENSAM", name="Ecole Nationale Supérieure d'Arts et Métiers", website="http://www.ensam.fr/" ), "X" : Ecole( acronym="X", name="Ecole Polytechnique", website="http://www.polytechnique.fr/" ), "ENSCP" : Ecole( acronym="ENSCP", name="Ecole Nationale Supérieure de Chimie de Paris", website="http://www.enscp.fr/" ), "ESPCI" : Ecole( acronym="ESPCI", name="Ecole Supérieure de Physique et de Chimie Industrielles de la Ville de Paris", website="http://www.espci.fr/" ), "ENSMP" : Ecole( acronym="ENSMP", name="Ecole Nationale Supérieure des Mines de Paris", website="http://www.ensmp.fr/" ), "AgroParisTech" : Ecole( acronym="AgroParisTech", name="AgroParisTech (INA P-G, ENGREF, ENSIA)", website="http://www.agroparistech.fr/" ), "HEC" : Ecole( acronym="HEC", name="Ecole des Hautes Etudes Commerciales", website="http://www.hec.fr/" ), # Add an ecole here: # "Acronym" : # Ecole( acronym="Acronym", # name="Ecole Name", # website="Ecole Website URL" ), } # ECOLES UNIVERSITIES = { "PKU" : University( acronym="PKU", name="北京大学", name_en="Peking University", website="http://www.pku.edu.cn/" ), "Tsinghua" : University( acronym="Tsinghua", name="清华大学", name_en="Tsinghua University", website="http://www.tsinghua.edu.cn/" ), "CAU" : University( acronym="CAU", name="中国农业大学", name_en="China Agricultural University", website="http://www.cau.edu.cn/" ), "NJU" : University( acronym="NJU", name="南京大学", name_en="Nanjing University", website="http://www.nju.edu.cn/" ), "SEU" : University( acronym="SEU", name="东南大学", name_en="Southeast University", website="http://www.seu.edu.cn/" ), "NJAU" : University( acronym="NJAU", name="南京农业大学", name_en="Nanjing Agricultural University", website="http://www.njau.edu.cn/" ), "Tongji" : University( acronym="Tongji", name="同济大学", name_en="Tongji University", website="http://www.tongji.edu.cn/" ), "Fudan" : University( acronym="Fudan", name="复旦大学", name_en="Fudan University", website="http://www.fudan.edu.cn/" ), "SJTU" : University( acronym="SJTU", name="上海交通大学", name_en="Shanghai Jiao Tong University", website="http://www.sjtu.edu.cn/" ), "ZJU" : University( acronym="ZJU", name="浙江大学", name_en="Zhe Jiang University", website="http://www.zju.edu.cn/" ), # Add a Chinese university here: # "Acronym" : # University( acronym="Acronym", # name="University Name", # name_en="University Name in English", # website="University Website URL" ), } # UNIVERSITIES
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Datastore model classes for the members. # # Created on 2008-10-28. # $Id: models.py 29 2009-09-23 21:22:49Z guolin.mobi $ # import logging import datetime from google.appengine.ext import db from google.appengine.api import users from afcpweb.apps.common import utils from afcpweb.apps.members import paristech class AFCPUserProfile(db.Model): """This class represents a profile of an AFCP member. The key name of the entity is the Google account email address. """ MEMBER_ROLE = "member" EDITOR_ROLE = "editor" PENDING_STATUS = "pending" APPROVED_STATUS = "approved" uid = db.StringProperty(required=True) name = db.StringProperty(required=True) name_zh = db.StringProperty() sex = db.StringProperty(choices=["male", "female", "unknown"], default="unknown") birthday = db.DateTimeProperty() promo = db.IntegerProperty() ecole_id = db.StringProperty() univ_id = db.StringProperty() alt_email = db.StringProperty() tel = db.StringProperty() photo_type = db.StringProperty() photo_data = db.BlobProperty() # cv_en = props.CurriculumVitaeProperty(default=props.CurriculumVitae()) # cv_fr = props.CurriculumVitaeProperty(default=props.CurriculumVitae()) # cv_zh = props.CurriculumVitaeProperty(default=props.CurriculumVitae()) status = db.StringProperty(default=PENDING_STATUS) deleted = db.BooleanProperty(default=False) create_date = db.DateTimeProperty(auto_now_add=True) last_login = db.DateTimeProperty(auto_now_add=True) login_count = db.IntegerProperty(default=0) roles = db.StringListProperty(default=[]) def __unicode__(self): return self.user() def user(self): return users.User(self.key().name()) def is_current_user_owner(self): user = users.get_current_user() return user == self.user() def google_account(self): return self.user().email() def names(self): names = self.name if self.name_zh is not None: names += " (%s)" % self.name_zh return names def email(self): if self.alt_email is None: return self.key().name() else: return self.alt_email def munging_google_account(self): return utils.munge_email(self.google_account()) def munging_alt_email(self): return utils.munge_email(self.alt_email) def munging_email(self): return utils.munge_email(self.email()) def ecole(self): return paristech.ECOLES.get(self.ecole_id) def university(self): return paristech.UNIVERSITIES.get(self.univ_id) def has_photo(self): return self.photo_type is not None and self.photo_data is not None def is_member(self): return AFCPUserProfile.MEMBER_ROLE in self.roles def is_editor(self): return AFCPUserProfile.EDITOR_ROLE in self.roles def add_editor(self): if AFCPUserProfile.EDITOR_ROLE not in self.roles: self.roles.append(AFCPUserProfile.EDITOR_ROLE) def count_login(self): self.last_login = datetime.datetime.utcnow() self.login_count += 1 def put(self): # Set default value to login count. if self.login_count is None: self.login_count = 1 # If the user is an AFCP member, add the member role. Otherwise, remove the member role. if self.roles is None: self.roles = [] if self.ecole_id is not None: if AFCPUserProfile.MEMBER_ROLE not in self.roles: self.roles.append(AFCPUserProfile.MEMBER_ROLE) else: if AFCPUserProfile.MEMBER_ROLE in self.roles: self.roles.remove(AFCPUserProfile.MEMBER_ROLE) # Put the entity to datastore. return super(AFCPUserProfile, self).put() #--------------------------------------------------------------------------------------------------- # AFCPUser: a wrapper around google.appengine.api.users.User #--------------------------------------------------------------------------------------------------- class AFCPUser(object): def __init__(self, user): self._user = user if self._user: self._profile = AFCPUserProfile.get_by_key_name(self._user.email()) else: self._profile = None def profile(self): return self._profile def google_user(self): return self._user def nickname(self): if self._profile: return self._profile.name elif self._user: return self._user.nickname() else: return None def email(self): if self._user: return self._user.email() else: return None def is_anonymous(self): return self._user is None def is_authenticated(self): return self._user is not None def __nonzero__(self): return self.is_authenticated() def get_current_user(): google_user = users.get_current_user() return AFCPUser(google_user) def create_login_url(redirect_url): return users.create_login_url(redirect_url) def create_logout_url(redirect_url): return users.create_logout_url(redirect_url) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Inscription app URL mappings. # # Created on 2008-10-28. # $Id: urls.py 26 2009-08-04 22:06:00Z guolin.mobi $ # from django.conf.urls.defaults import patterns urlpatterns = patterns( "afcpweb.apps.members.views", ( r"^$" , "view_members" ), ( r"^my_profile/$" , "my_profile" ), ( r"^profile/(?P<uid>\w+)/$" , "profile" ), ( r"^profile/(?P<uid>\w+)/photo/$" , "profile_photo" ), ( r"^random_profile/$" , "random_profile" ), ( r"^ecole/(?P<acronym>\w+)/$" , "ecole" ), ( r"^university/(?P<acronym>\w+)/$" , "university" ), ) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Config for the members app. # # Created on 2008-10-28. # $Id: views.py 40 2010-03-08 23:05:09Z guolin.mobi $ # class Config(object): """This class contains constants for the inscription app.""" APP_NAME = "members" URL_PREFIX = "/members"
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Inscription app URL mappings. # # Created on 2008-10-28. # $Id: urls.py 26 2009-08-04 22:06:00Z guolin.mobi $ # from django.conf.urls.defaults import patterns urlpatterns = patterns( "afcpweb.apps.members.views", ( r"^$" , "view_members" ), ( r"^my_profile/$" , "my_profile" ), ( r"^profile/(?P<uid>\w+)/$" , "profile" ), ( r"^profile/(?P<uid>\w+)/photo/$" , "profile_photo" ), ( r"^random_profile/$" , "random_profile" ), ( r"^ecole/(?P<acronym>\w+)/$" , "ecole" ), ( r"^university/(?P<acronym>\w+)/$" , "university" ), ) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # all info about Paristech ecole and universities in China # Created on 2008-11-19. # $Id: paristech.py 26 2009-08-04 22:06:00Z guolin.mobi $ # class Ecole(object): def __init__(self, acronym, name, website, desc=None): self.acronym = acronym self.name = name self.website = website self.desc = desc class University(object): def __init__(self, acronym, name, name_en, website, desc=None): self.acronym = acronym self.name = name self.name_en = name_en self.website = website self.desc = desc ECOLES = { "ENPC" : Ecole( acronym="ENPC", name="Ecole Nationale des Ponts et Chaussées", website="http://www.enpc.fr/" ), "ENST" : Ecole( acronym="ENST", name="Ecole Nationale Supérieure des Télécommunications (aka. Télécom ParisTech)", website="http://www.enst.fr/" ), "ENSAE" : Ecole( acronym="ENSAE", name="Ecole Nationale de la Statistique et de l'Administration", website="http://www.ensae.fr/" ), "ENSTA" : Ecole( acronym="ENSTA", name="Ecole Nationale Supérieure de Techniques Avancées", website="http://www.ensta.fr/" ), "ENSAM" : Ecole( acronym="ENSAM", name="Ecole Nationale Supérieure d'Arts et Métiers", website="http://www.ensam.fr/" ), "X" : Ecole( acronym="X", name="Ecole Polytechnique", website="http://www.polytechnique.fr/" ), "ENSCP" : Ecole( acronym="ENSCP", name="Ecole Nationale Supérieure de Chimie de Paris", website="http://www.enscp.fr/" ), "ESPCI" : Ecole( acronym="ESPCI", name="Ecole Supérieure de Physique et de Chimie Industrielles de la Ville de Paris", website="http://www.espci.fr/" ), "ENSMP" : Ecole( acronym="ENSMP", name="Ecole Nationale Supérieure des Mines de Paris", website="http://www.ensmp.fr/" ), "AgroParisTech" : Ecole( acronym="AgroParisTech", name="AgroParisTech (INA P-G, ENGREF, ENSIA)", website="http://www.agroparistech.fr/" ), "HEC" : Ecole( acronym="HEC", name="Ecole des Hautes Etudes Commerciales", website="http://www.hec.fr/" ), # Add an ecole here: # "Acronym" : # Ecole( acronym="Acronym", # name="Ecole Name", # website="Ecole Website URL" ), } # ECOLES UNIVERSITIES = { "PKU" : University( acronym="PKU", name="北京大学", name_en="Peking University", website="http://www.pku.edu.cn/" ), "Tsinghua" : University( acronym="Tsinghua", name="清华大学", name_en="Tsinghua University", website="http://www.tsinghua.edu.cn/" ), "CAU" : University( acronym="CAU", name="中国农业大学", name_en="China Agricultural University", website="http://www.cau.edu.cn/" ), "NJU" : University( acronym="NJU", name="南京大学", name_en="Nanjing University", website="http://www.nju.edu.cn/" ), "SEU" : University( acronym="SEU", name="东南大学", name_en="Southeast University", website="http://www.seu.edu.cn/" ), "NJAU" : University( acronym="NJAU", name="南京农业大学", name_en="Nanjing Agricultural University", website="http://www.njau.edu.cn/" ), "Tongji" : University( acronym="Tongji", name="同济大学", name_en="Tongji University", website="http://www.tongji.edu.cn/" ), "Fudan" : University( acronym="Fudan", name="复旦大学", name_en="Fudan University", website="http://www.fudan.edu.cn/" ), "SJTU" : University( acronym="SJTU", name="上海交通大学", name_en="Shanghai Jiao Tong University", website="http://www.sjtu.edu.cn/" ), "ZJU" : University( acronym="ZJU", name="浙江大学", name_en="Zhe Jiang University", website="http://www.zju.edu.cn/" ), # Add a Chinese university here: # "Acronym" : # University( acronym="Acronym", # name="University Name", # name_en="University Name in English", # website="University Website URL" ), } # UNIVERSITIES
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2008-10-28 # $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $ #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Views for the members app. # # Created on 2008-10-28. # $Id: views.py 40 2010-03-08 23:05:09Z guolin.mobi $ # import logging import urllib from django.template import loader from django.template import Context from django.http import HttpResponseRedirect from django.http import HttpResponse from afcpweb.apps.common.actions import get_common_data from afcpweb.apps.common import utils from afcpweb.apps.members.config import Config from afcpweb.apps.members import paristech from afcpweb.apps.members.models import get_current_user from afcpweb.apps.members.models import AFCPUserProfile def view_members(request): """Displays the AFCP members list.""" MEMBERS_PER_PAGE = 10 query = AFCPUserProfile.gql("WHERE deleted=:deleted ORDER BY name", deleted=False) page_number = utils.get_param(request.REQUEST, "page") members = utils.EntityPage(query, MEMBERS_PER_PAGE, page_number) ctxt_dict = { "members" : members, "has_previous" : members.has_previous(), "has_next" : members.has_next(), "previous_page" : members.previous_page_number(), "next_page" : members.next_page_number(),} ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/members.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) def my_profile(request): """If current user already has a profile, redirect to the profile page; otherwise, display the create profile page. """ # Anonymous user should not have arrived to this page. user = get_current_user() if not user: return HttpResponseRedirect("%s/" % Config.URL_PREFIX) # If the user already has a profile, redirect to the profile page. if user.profile() is not None: return HttpResponseRedirect("%s/profile/%s/" % (Config.URL_PREFIX, user.profile().uid)) # Create profile for the current user. if request.method == "GET": # Return the create profile form. ctxt_dict = { "error" : utils.get_param(request.GET, "error"), "ecoles" : paristech.ECOLES.values(), "universities" : paristech.UNIVERSITIES.values(), } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/create_profile.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) elif request.method == "POST": # Create a profile for the current user. try: key_name = user.email() logging.info(key_name) uid = utils.generate_random_id("U") logging.info(uid) name = utils.get_param(request.POST, "name") logging.info(name) name_zh = utils.get_param(request.POST, "name_zh") logging.info(name_zh) status = AFCPUserProfile.PENDING_STATUS profile = AFCPUserProfile( key_name=key_name, uid=uid, name=name, name_zh=name_zh, status=status ) profile.put() return HttpResponseRedirect("%s/profile/%s/" % (Config.URL_PREFIX, profile.uid)) except Exception, ex: error = "Failed to create user profile: %s" % str(ex) logging.error(error) params = { "error" : error, } return HttpResponseRedirect("%s?%s" % (request.path, urllib.urlencode(params))) def profile(request, uid): """Displays the member profile by UID.""" profile = AFCPUserProfile.gql("WHERE uid=:uid", uid=uid).get() if profile is None: return not_found(request) if request.method == "GET": ctxt_dict = { "info" : utils.get_param(request.GET, "info"), "error" : utils.get_param(request.GET, "error"), "uid" : uid, "profile" : profile, "ecoles" : paristech.ECOLES.values(), "universities" : paristech.UNIVERSITIES.values(), } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/profile.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) elif request.method == "POST": params = {} action = utils.get_param(request.POST, "action") try: if action == "edit": # Update basic information. profile.name = utils.get_param(request.POST, "name") profile.name_zh = utils.get_param(request.POST, "name_zh") profile.sex = utils.get_param(request.POST, "sex") birthday_str = utils.get_param(request.POST, "birthday") if birthday_str is not None: profile.birthday = datetime.datetime.strptime(birthday_str, "%Y-%m-%d") else: profile.birthday = None promo_str = utils.get_param(request.POST, "promo") if promo_str is not None: profile.promo = int(promo_str) else: profile.promo = None profile.ecole_id = utils.get_param(request.POST, "ecole_id") profile.univ_id = utils.get_param(request.POST, "univ_id") profile.alt_email = utils.get_param(request.POST, "alt_email") profile.tel = utils.get_param(request.POST, "tel") # Update profile photo. """ query_dict = request.POST.copy() query_dict.update(request.FILES) photo_dict = query_dict.get("photo", None) if photo_dict is not None: profile.photo_type = utils.get_param(photo_dict, "content-type") profile.photo_data = photo_dict.get("content") elif utils.get_param(request.POST, "delete_photo") == "1": profile.photo_type = None profile.photo_data = None """ # Update profile in datastore. profile.put() params["info"] = "Profile updated successfully." elif action == "delete": profile.deleted = True profile.put() params["info"] = "Profile deleted successfully." elif action == "restore": profile.deleted = False profile.put() params["info"] = "Profile restored successfully." else: raise Exception, "Unknown action '%s'." % action except Exception, ex: error = "Failed to perform action '%s': %s" % (action, str(ex)) logging.error(error) params["error"] = error return HttpResponseRedirect("%s?%s" % (request.path, urllib.urlencode(params))) def profile_photo(request, uid): profile = AFCPUserProfile.gql("WHERE uid=:uid", uid=uid).get() if profile is None: return not_found(request) if request.method == "GET": if profile.has_photo(): return HttpResponse(profile.photo_data, mimetype=profile.photo_type) else: return not_found(request) def random_profile(request): # TODO: count() and fetch() cannot handle a large amount of results. # This function should be redesigned to be more scalable. query = AFCPUserProfile.gql("") count = query.count() if count <= 0: return not_found(request) random_offset = random.choice(range(0, count)) profile_list = query.fetch(1, random_offset) if not profile_list: return not_found(request) else: profile_uid = profile_list[0].uid return HttpResponseRedirect("%s/profile/%s/" % (Config.URL_PREFIX, profile_uid)) #--------------------------------------------------------------------------------------------------- def ecole(request, acronym): if request.method == "GET": MEMBERS_PER_PAGE = 20 query = AFCPUserProfile.gql( "WHERE ecole_id=:acronym AND deleted=:deleted ORDER BY name", acronym=acronym, deleted=False ) page_number = utils.get_param(request.REQUEST, "page") members = utils.EntityPage(query, MEMBERS_PER_PAGE, page_number) ctxt_dict = { "members" : members, "ecole" : paristech.ECOLES.get(acronym), "ecoles" : paristech.ECOLES.values(), } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/ecole.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) def university(request, acronym): if request.method == "GET": MEMBERS_PER_PAGE = 20 query = AFCPUserProfile.gql( "WHERE univ_id=:acronym AND deleted=:deleted ORDER BY name", acronym=acronym, deleted=False ) page_number = utils.get_param(request.REQUEST, "page") members = utils.EntityPage(query, MEMBERS_PER_PAGE, page_number) ctxt_dict = { "members" : members, "university" : paristech.UNIVERSITIES.get(acronym), "universities" : paristech.UNIVERSITIES.values(), } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/university.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Config for the members app. # # Created on 2008-10-28. # $Id: views.py 40 2010-03-08 23:05:09Z guolin.mobi $ # class Config(object): """This class contains constants for the inscription app.""" APP_NAME = "members" URL_PREFIX = "/members"
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Views for the members app. # # Created on 2008-10-28. # $Id: views.py 40 2010-03-08 23:05:09Z guolin.mobi $ # from afcpweb.apps.common import utils from afcpweb.apps.common.actions import get_common_data from afcpweb.apps.members import paristech from afcpweb.apps.members.config import Config from afcpweb.apps.members.models import AFCPUserProfile, get_current_user from django.http import HttpResponse, HttpResponseRedirect from django.template import Context, loader import logging import urllib APP_NAME = "test" HTML_PAGE = "test.html" def view_test(request): """Displays a test page""" ctxt_dict = { } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/%s" % (APP_NAME, HTML_PAGE)) return HttpResponse(tmpl.render(ctxt))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2008-10-28 # $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $ #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Inscription app URL mappings. # # Created on 2008-10-28. # $Id: urls.py 26 2009-08-04 22:06:00Z guolin.mobi $ # from django.conf.urls.defaults import patterns urlpatterns = patterns( "afcpweb.apps.test.views", ( r"^$" , "view_test" ), ) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Inscription app URL mappings. # # Created on 2008-10-28. # $Id: urls.py 26 2009-08-04 22:06:00Z guolin.mobi $ # from django.conf.urls.defaults import patterns urlpatterns = patterns( "afcpweb.apps.test.views", ( r"^$" , "view_test" ), ) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2008-10-28 # $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $ #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Views for the members app. # # Created on 2008-10-28. # $Id: views.py 40 2010-03-08 23:05:09Z guolin.mobi $ # from afcpweb.apps.common import utils from afcpweb.apps.common.actions import get_common_data from afcpweb.apps.members import paristech from afcpweb.apps.members.config import Config from afcpweb.apps.members.models import AFCPUserProfile, get_current_user from django.http import HttpResponse, HttpResponseRedirect from django.template import Context, loader import logging import urllib APP_NAME = "test" HTML_PAGE = "test.html" def view_test(request): """Displays a test page""" ctxt_dict = { } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/%s" % (APP_NAME, HTML_PAGE)) return HttpResponse(tmpl.render(ctxt))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Datastore model classes for admin app. # # Created on 2010-07-18. # $Id: models.py 29 2010-07-18 21:22:49Z guolin.mobi $ # from google.appengine.ext import db class AFCPActivity(db.Model): "This class represents an Activity" uid = db.StringProperty(required=True) name = db.StringProperty(required=True) subject = db.StringProperty() date = db.DateTimeProperty() address = db.StringProperty() spreadsheet_link = db.StringProperty() create_date = db.DateTimeProperty(auto_now_add=True) is_closed = db.StringProperty(choices=["yes", "no"], default="no") @classmethod def find_all(cls, **kwargs): query = cls.all() return query @classmethod def get_unique(cls, uid): instance = cls.gql("WHERE uid=:uid", uid=uid).get() return instance #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Access for admin app. # # Created on 2010-07-18. # $Id: models.py 29 2010-07-18 21:22:49Z guolin.mobi $ # from afcpweb.apps.common.access import Access class AdminAccess(Access): def can_consult(self): return is_webmaster(self._user) def can_edit(self): return is_webmaster(self._user) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Views for the admin app. # # Created on 2008-10-28. # $Id: views.py 40 2010-03-08 23:05:09Z guolin.mobi $ # import urllib import logging import datetime from django.template import loader from django.template import Context from django.http import HttpResponse from django.http import HttpResponseRedirect from afcpweb.apps.common import utils from afcpweb.apps.common.actions import get_common_data from afcpweb.apps.members.models import get_current_user from afcpweb.apps.admin.access import AdminAccess from afcpweb.apps.admin.config import Config from afcpweb.apps.activities.models import AFCPActivity def admin(request): return view_all_activity(request) def get_activity_data(request): ctxt_dict = { "page_name" : "activity",} ctxt_dict.update(get_common_data(request)) return ctxt_dict def view_all_activity(request): "Displays the admin console and handles the admin request." user = get_current_user() access = AdminAccess(user) if not access.can_consult: return HttpResponseRedirect("/afcp/") error = utils.get_param(request.GET, "error") info = utils.get_param(request.GET, "info" ) ACTIVITY_PER_PAGE = 8 #query = AFCPActivity.gql("") query = AFCPActivity.find_all() page_number = utils.get_param(request.REQUEST, "page") activities = utils.EntityPage(query, ACTIVITY_PER_PAGE, page_number) ctxt_dict = { "info" : info, "error" : error, "activities" : activities, "has_previous" : activities.has_previous(), "has_next" : activities.has_next(), "previous_page": activities.previous_page_number(), "next_page" : activities.next_page_number(),} ctxt_dict.update(get_activity_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/admin_activities.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) def create_activity(request, uid=None): activity = AFCPActivity.get_unique(uid) if request.method == "GET": if activity is None: isUpdateMode = False else : isUpdateMode = True # enter the information ctxt_dict = { "isUpdateMode" : isUpdateMode, "info" : utils.get_param(request.GET, "info"), "error" : utils.get_param(request.GET, "error"), "activity" : activity,} ctxt_dict.update(get_activity_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/activity/create_activity.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) elif request.method == "POST": # Create an activity for the current user. try: date_str = utils.get_param(request.POST, "date") if date_str is not None: date = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M") else: date = None if uid is None: uid = utils.generate_random_id("U") name = utils.get_param(request.POST, "name") subject = utils.get_param(request.POST, "subject") address = utils.get_param(request.POST, "address") spreadsheet_link = utils.get_param(request.POST, "spreadsheet_link") activity = AFCPActivity( uid=uid, name=name, subject=subject, address=address, spreadsheet_link=spreadsheet_link, date= date, is_closed = "no" ) else: activity = AFCPActivity.get_unique(uid) activity.name = utils.get_param(request.POST, "name") activity.subject = utils.get_param(request.POST, "subject") activity.address = utils.get_param(request.POST, "address") activity.spreadsheet_link = utils.get_param(request.POST, "spreadsheet_link") activity.is_closed = utils.get_param(request.POST, "is_closed") activity.date = date activity.put() ctxt_dict = { "info" : utils.get_param(request.GET, "info"), "error" : utils.get_param(request.GET, "error"), "activity" : activity,} ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/activity/view_activity.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) except Exception, ex: error = "Failed to create an activity: %s" % str(ex) logging.error(error) params = { "error" : error, "activity" : activity, } return HttpResponseRedirect("%s?%s" % (request.path, urllib.urlencode(params))) def view_activity(request,uid): activity = AFCPActivity.get_unique(uid) if request.method == "GET": ctxt_dict = { "info" : utils.get_param(request.GET, "info"), "error" : utils.get_param(request.GET, "error"), "activity" : activity,} ctxt_dict.update(get_activity_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/activity/view_activity.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) else : return not_found(request) def delete_activity(request, uid): activity = AFCPActivity.get_unique(uid) if request.method == "GET": ctxt_dict = { "info" : utils.get_param(request.GET, "info"), "error" : utils.get_param(request.GET, "error"), "activity" : activity,} ctxt_dict.update(get_activity_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/activity/delete_activity.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) elif request.method == "POST": activity.delete() info = "Success to delete activity." logging.info(info) params = { "info" : info, } return HttpResponseRedirect("/admin/activity/?%s" % urllib.urlencode(params) ) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Access for admin app. # # Created on 2010-07-18. # $Id: models.py 29 2010-07-18 21:22:49Z guolin.mobi $ # from afcpweb.apps.common.access import Access class AdminAccess(Access): def can_consult(self): return is_webmaster(self._user) def can_edit(self): return is_webmaster(self._user) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Datastore model classes for admin app. # # Created on 2010-07-18. # $Id: models.py 29 2010-07-18 21:22:49Z guolin.mobi $ # from google.appengine.ext import db class AFCPActivity(db.Model): "This class represents an Activity" uid = db.StringProperty(required=True) name = db.StringProperty(required=True) subject = db.StringProperty() date = db.DateTimeProperty() address = db.StringProperty() spreadsheet_link = db.StringProperty() create_date = db.DateTimeProperty(auto_now_add=True) is_closed = db.StringProperty(choices=["yes", "no"], default="no") @classmethod def find_all(cls, **kwargs): query = cls.all() return query @classmethod def get_unique(cls, uid): instance = cls.gql("WHERE uid=:uid", uid=uid).get() return instance #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Admin app URL mappings. # # Created on 2008-10-28. # $Id: urls.py 40 2010-03-08 23:05:09Z guolin.mobi $ # from django.conf.urls.defaults import patterns urlpatterns = patterns( "afcpweb.apps.admin.views", ( r"^$" , "admin" ), ( r"^activity/$" , "view_all_activity" ), ( r"^activity/create/$" , "create_activity" ), ( r"^activity/create/(?P<uid>\w+)/$" , "create_activity" ), ( r"^activity/delete/(?P<uid>\w+)/$" , "delete_activity" ), ( r"^activity/(?P<uid>\w+)/$" , "view_activity" ), ) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2008-05-06. # $Id: views.py 26 2009-08-04 22:06:00Z guolin.mobi $ # class Config(object): """This class contains constants for the admin app.""" APP_NAME = "admin" URL_PREFIX = "/admin"
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Admin app URL mappings. # # Created on 2008-10-28. # $Id: urls.py 40 2010-03-08 23:05:09Z guolin.mobi $ # from django.conf.urls.defaults import patterns urlpatterns = patterns( "afcpweb.apps.admin.views", ( r"^$" , "admin" ), ( r"^activity/$" , "view_all_activity" ), ( r"^activity/create/$" , "create_activity" ), ( r"^activity/create/(?P<uid>\w+)/$" , "create_activity" ), ( r"^activity/delete/(?P<uid>\w+)/$" , "delete_activity" ), ( r"^activity/(?P<uid>\w+)/$" , "view_activity" ), ) #
Python
# !/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2008-04-28 # $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $ #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Views for the admin app. # # Created on 2008-10-28. # $Id: views.py 40 2010-03-08 23:05:09Z guolin.mobi $ # import urllib import logging import datetime from django.template import loader from django.template import Context from django.http import HttpResponse from django.http import HttpResponseRedirect from afcpweb.apps.common import utils from afcpweb.apps.common.actions import get_common_data from afcpweb.apps.members.models import get_current_user from afcpweb.apps.admin.access import AdminAccess from afcpweb.apps.admin.config import Config from afcpweb.apps.activities.models import AFCPActivity def admin(request): return view_all_activity(request) def get_activity_data(request): ctxt_dict = { "page_name" : "activity",} ctxt_dict.update(get_common_data(request)) return ctxt_dict def view_all_activity(request): "Displays the admin console and handles the admin request." user = get_current_user() access = AdminAccess(user) if not access.can_consult: return HttpResponseRedirect("/afcp/") error = utils.get_param(request.GET, "error") info = utils.get_param(request.GET, "info" ) ACTIVITY_PER_PAGE = 8 #query = AFCPActivity.gql("") query = AFCPActivity.find_all() page_number = utils.get_param(request.REQUEST, "page") activities = utils.EntityPage(query, ACTIVITY_PER_PAGE, page_number) ctxt_dict = { "info" : info, "error" : error, "activities" : activities, "has_previous" : activities.has_previous(), "has_next" : activities.has_next(), "previous_page": activities.previous_page_number(), "next_page" : activities.next_page_number(),} ctxt_dict.update(get_activity_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/admin_activities.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) def create_activity(request, uid=None): activity = AFCPActivity.get_unique(uid) if request.method == "GET": if activity is None: isUpdateMode = False else : isUpdateMode = True # enter the information ctxt_dict = { "isUpdateMode" : isUpdateMode, "info" : utils.get_param(request.GET, "info"), "error" : utils.get_param(request.GET, "error"), "activity" : activity,} ctxt_dict.update(get_activity_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/activity/create_activity.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) elif request.method == "POST": # Create an activity for the current user. try: date_str = utils.get_param(request.POST, "date") if date_str is not None: date = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M") else: date = None if uid is None: uid = utils.generate_random_id("U") name = utils.get_param(request.POST, "name") subject = utils.get_param(request.POST, "subject") address = utils.get_param(request.POST, "address") spreadsheet_link = utils.get_param(request.POST, "spreadsheet_link") activity = AFCPActivity( uid=uid, name=name, subject=subject, address=address, spreadsheet_link=spreadsheet_link, date= date, is_closed = "no" ) else: activity = AFCPActivity.get_unique(uid) activity.name = utils.get_param(request.POST, "name") activity.subject = utils.get_param(request.POST, "subject") activity.address = utils.get_param(request.POST, "address") activity.spreadsheet_link = utils.get_param(request.POST, "spreadsheet_link") activity.is_closed = utils.get_param(request.POST, "is_closed") activity.date = date activity.put() ctxt_dict = { "info" : utils.get_param(request.GET, "info"), "error" : utils.get_param(request.GET, "error"), "activity" : activity,} ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/activity/view_activity.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) except Exception, ex: error = "Failed to create an activity: %s" % str(ex) logging.error(error) params = { "error" : error, "activity" : activity, } return HttpResponseRedirect("%s?%s" % (request.path, urllib.urlencode(params))) def view_activity(request,uid): activity = AFCPActivity.get_unique(uid) if request.method == "GET": ctxt_dict = { "info" : utils.get_param(request.GET, "info"), "error" : utils.get_param(request.GET, "error"), "activity" : activity,} ctxt_dict.update(get_activity_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/activity/view_activity.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) else : return not_found(request) def delete_activity(request, uid): activity = AFCPActivity.get_unique(uid) if request.method == "GET": ctxt_dict = { "info" : utils.get_param(request.GET, "info"), "error" : utils.get_param(request.GET, "error"), "activity" : activity,} ctxt_dict.update(get_activity_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("%s/activity/delete_activity.html" % Config.APP_NAME) return HttpResponse(tmpl.render(ctxt)) elif request.method == "POST": activity.delete() info = "Success to delete activity." logging.info(info) params = { "info" : info, } return HttpResponseRedirect("/admin/activity/?%s" % urllib.urlencode(params) ) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2008-05-06. # $Id: views.py 26 2009-08-04 22:06:00Z guolin.mobi $ # class Config(object): """This class contains constants for the admin app.""" APP_NAME = "admin" URL_PREFIX = "/admin"
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2008-05-06. # $Id: views.py 26 2009-08-04 22:06:00Z guolin.mobi $ # import logging from django.template import loader from django.template import Context from django.http import HttpRequest from django.http import HttpResponse from django.http import HttpResponseRedirect from google.appengine.api import users from afcpweb.apps.common.actions import get_common_data #--------------------------------------------------------------------------------------------------- # Sub-webapp homepages #--------------------------------------------------------------------------------------------------- def _redirect_to_error_page(error): params = { "error" : error, } url = "/error/?%s" % ( urllib.urlencode(params)) return HttpResponseRedirect(url) def _afcp_home(request): return HttpResponseRedirect("/home/fr/") def _default_home(request): return _afcp_home(request) HOME_HANDLER_MAPPINGS = { "afcp" : _afcp_home, } SERVER_HANDLER_MAPPINGS = { "www.afcp-paristech.org" : _afcp_home, "beta.afcp-paristech.org" : _afcp_home, "afcp.appspot.com" : _afcp_home, } #--------------------------------------------------------------------------------------------------- # Homepage handler #--------------------------------------------------------------------------------------------------- def home(request): home = request.REQUEST.get("home") handler = HOME_HANDLER_MAPPINGS.get(home, None) if handler is not None: return handler(request) else: server = request.META.get("SERVER_NAME") handler = SERVER_HANDLER_MAPPINGS.get(server, None) if handler is not None: return handler(request) else: return _default_home(request) def not_found(request): "Renders the 404 not-found page." logging.info("The requested page '%s' does not exist." % request.path) # uri path without host: request.path ctxt_dict = { "url": request.build_absolute_uri(), } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("not_found.html") return HttpResponse(tmpl.render(ctxt)) def error_page(request): "Displays the error page." ctxt_dict = { "error" : utils.get_param(request.REQUEST, "error"), } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("error.html") return HttpResponse(tmpl.render(ctxt)) def generateSitemap(request): "Generates a new sitemap" #TODO: écrire le code de génération du sitemap. #
Python
# !/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2008-10-28 # $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $ #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2008-05-06. # $Id: views.py 26 2009-08-04 22:06:00Z guolin.mobi $ # import logging from django.template import loader from django.template import Context from django.http import HttpRequest from django.http import HttpResponse from django.http import HttpResponseRedirect from google.appengine.api import users from afcpweb.apps.common.actions import get_common_data #--------------------------------------------------------------------------------------------------- # Sub-webapp homepages #--------------------------------------------------------------------------------------------------- def _redirect_to_error_page(error): params = { "error" : error, } url = "/error/?%s" % ( urllib.urlencode(params)) return HttpResponseRedirect(url) def _afcp_home(request): return HttpResponseRedirect("/home/fr/") def _default_home(request): return _afcp_home(request) HOME_HANDLER_MAPPINGS = { "afcp" : _afcp_home, } SERVER_HANDLER_MAPPINGS = { "www.afcp-paristech.org" : _afcp_home, "beta.afcp-paristech.org" : _afcp_home, "afcp.appspot.com" : _afcp_home, } #--------------------------------------------------------------------------------------------------- # Homepage handler #--------------------------------------------------------------------------------------------------- def home(request): home = request.REQUEST.get("home") handler = HOME_HANDLER_MAPPINGS.get(home, None) if handler is not None: return handler(request) else: server = request.META.get("SERVER_NAME") handler = SERVER_HANDLER_MAPPINGS.get(server, None) if handler is not None: return handler(request) else: return _default_home(request) def not_found(request): "Renders the 404 not-found page." logging.info("The requested page '%s' does not exist." % request.path) # uri path without host: request.path ctxt_dict = { "url": request.build_absolute_uri(), } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("not_found.html") return HttpResponse(tmpl.render(ctxt)) def error_page(request): "Displays the error page." ctxt_dict = { "error" : utils.get_param(request.REQUEST, "error"), } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("error.html") return HttpResponse(tmpl.render(ctxt)) def generateSitemap(request): "Generates a new sitemap" #TODO: écrire le code de génération du sitemap. #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Views for the Forum webapp. # # Created on 2008-10-28. # $Id: views.py 41 2010-07-21 10:33:30Z guolin.mobi $ # from afcpweb.apps.common import utils from afcpweb.apps.common.actions import get_common_data from afcpweb.apps.forum import resources from afcpweb.apps.forum.config import Config from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect, HttpRequest from django.template import Context, loader, TemplateDoesNotExist from google.appengine.api import mail from google.appengine.ext import db from os.path import splitext import datetime import random #from django.utils.translation import gettext_lazy as _ from django.utils.translation import ugettext as _, activate from django.conf import settings import logging #from google.appengine.api import users #--------------------------------------------------------------------------------------------------- # Home page, 404 not-found page, error page and static pages #--------------------------------------------------------------------------------------------------- def _redirect(supage_name, name, lang, defaultName, subPage = None): if name is None: name = defaultName if lang is None: lang = defaultLanguage if supage_name is None: supage_name = "" else: supage_name = "/" + supage_name if not subPage is None: name += "/" + subPage return HttpResponseRedirect(supage_name + "/" + name + "/" + lang + "/") defaultLanguage = settings.LANGUAGE_CODE #defaultLanguage = "zh-cn" def home(request, lang=None): "Displays the Forum home page." supage_name = "home" if lang is None: #return _redirect(None, None, lang, "home") lang = defaultLanguage activate(lang) ctxt_dict = { "supage_name": supage_name, # "page_name" : "/" + name, "url" : request.path, "lang_code" : lang, "banner_image" : random.choice(resources.BANNER_IMAGES) } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/home.html" % (Config.APP_NAME, lang) ) except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) def home_with_args(request, lang=None): "Displays the root page, supposed to be the home page" if lang is None: return _redirect(None, None, lang, "home") elif lang == defaultLanguage: return HttpResponseRedirect("/") else: return home(request, lang) def visitor(request, name=None, lang=None): "Displays the Forum visitor page" supage_name = "visitors" if name is None or lang is None: return _redirect(supage_name, name, lang, "program") activate(lang) ctxt_dict = { "supage_name": supage_name, "page_name" : "/" + name, "url" : request.path, "lang_code" : lang, "thispage" : "entry_" + supage_name + "_" + name ,"ext" : "forum/"+lang+"/static/base-visitors.html" } ctxt_dict.update(get_common_data(request)) if name == "workpermit" and request.method == 'POST': msg = sendWorkPermitComment(request) if msg != '': ctxt_dict["errmsg"] = msg else: ctxt_dict["msgok"] = True if name == "sendmail": return_code = sendmail(request, lang) if return_code != OK: ctxt_dict.update({"error_code" : return_code}) name = "nosendmail" if name == "applications": c = Candidate.all() results = c.fetch(100000) ctxt_dict["application"] = results ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/static/visitors/%s.html" % (Config.APP_NAME, lang, name) ) except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) # Class used for google datastore (list of applications done) class Candidate(db.Model): lastname = db.StringProperty(required=True) firstname = db.StringProperty(required=True) email = db.StringProperty(required=True) application_date = db.DateProperty(required=True) company = db.StringProperty(required=True) job = db.StringProperty(required=True) OK = 0 INVALID_MAIL = 1 MISSING_ATTACHMENT = 2 REQUIRED_FIELD = 3 INVALID_EXT = 4 TOO_LARGE_ATTACHMENT = 5 EMPTY_REQUIRED_FIELD = 6 def sendmail(request, lang): if not mail.is_email_valid(request.POST['email']): return INVALID_MAIL # if len(request.POST) != 6: # return REQUIRED_FIELD id = unicode(request.POST.get('id', '')) prenom = unicode(request.POST.get('prenom', '')).capitalize() nom = unicode(request.POST.get('nom', '')).upper() email = unicode(request.POST.get('email', '')) company = unicode(request.POST.get('company', '')) job = unicode(request.POST.get('jobname', '')) if (len(id) == 0 or len(prenom) == 0 or len(nom) == 0 or len(email) == 0 or (company) == 0 or len(job) == 0): return EMPTY_REQUIRED_FIELD addressee = resources.company_emails[id] # numberOfAttachmentsAllowed = resources.attachments.get(id, resources.defaultAttachmentsNumber) numberOfAttachmentsSents = len(request.FILES) if numberOfAttachmentsSents < addressee.minattach or numberOfAttachmentsSents > addressee.maxattach: return MISSING_ATTACHMENT totalSize = 0 for f in request.FILES.values(): path, ext = splitext(f.name) if ext != '.doc' and ext != '.pdf': return INVALID_EXT totalSize += f.size #if totalSize > 1048576: # Max 1 Mo # Max 0.5 Mo * nombre de pièces jointes ou 10 Mo (un peu moins pour le corps du mail) if totalSize > numberOfAttachmentsSents * 524288 or totalSize > 10000000: return TOO_LARGE_ATTACHMENT tmpl = loader.get_template("%s/%s/mail/application_subject.txt" % (Config.APP_NAME, lang) ) mail_subject = tmpl.render(Context(get_common_data(request))) % job message = mail.EmailMessage(sender=resources.sender, # subject=u"%s : Nouvelle candidature envoyée par le site de l'AFCP" % job) subject=mail_subject) message.to = unicode(addressee.email) if id != 'test': message.cc = resources.application_cc # message.body = u""" #Madame, Monsieur, # #Une nouvelle candidature pour le poste %s a été envoyée par l'intermédiaire du site de l'AFCP, l'offre y étant publiée. # #Veuillez trouver ci-joint le CV et la lettre de motivation de %s %s pour cette candidature. Vous pouvez le joindre à l'adresse e-mail %s # #Bien à vous, # #L'équipe AFCP #""" % (job, prenom, nom, email) tmpl = loader.get_template("%s/%s/mail/application.txt" % (Config.APP_NAME, lang) ) message.body = tmpl.render(Context(get_common_data(request))) % (job, prenom, nom, email) # message.html = u""" #<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><br/> #Madame, Monsieur,<br/> #<br/> #Une nouvelle candidature pour le poste %s a été envoyée par l'intermédiaire du site de l'AFCP, l'offre y étant publiée.<br/> #<br/> #Veuillez trouver ci-joint le CV et la lettre de motivation de %s %s pour cette candidature. Vous pouvez le joindre à l'adresse e-mail <a href="mailto:%s">%s</a>.<br/> #<br/> #Bien à vous,<br/> #<br/> #L'équipe AFCP<br/> #</body></html> #""" % (job, prenom, nom, email, email) tmpl = loader.get_template("%s/%s/mail/application.html" % (Config.APP_NAME, lang) ) message.html = tmpl.render(Context(get_common_data(request))) % (job, prenom, nom, email, email) # message.attachments = request.FILES.items() #message.attachments = [(filename + u"__" + replaceForbiddenCharacters(f.name), f.read()) for filename, f in request.FILES.items()] message.attachments = [(f.name, f.read()) for filename, f in request.FILES.items()] message.send() e = Candidate( lastname = nom, firstname = prenom, email = email, application_date = datetime.datetime.now().date(), company = company, job = job ) e.put() return OK #def replaceForbiddenCharacters(s): # p = re.compile('(\\|\/|\:|\*|\?|\"|\<|\>|\|)') # return p.sub('_', s) def sendWorkPermitComment(request): msg = request.POST.get('message', '') email = request.POST.get('email', '') firstname = request.POST.get('firstname', '') firstname = firstname[:1].upper() + firstname[1:] # Capitalize lastname = request.POST.get('lastname', '') if firstname == '': return u"Veuillez indiquer votre prénom." if lastname == '': return u"Veuillez indiquer votre nom." if email == '' and msg == '': return u"Veuillez indiquer un e-mail auquel vous répondre et rédiger un message avant d'envoyer." if email == '': return u"Veuillez indiquer un e-mail auquel vous répondre." if msg == '': return u"Procédez dans l'ordre et rédigez un message avant de l'envoyer :)" message = mail.EmailMessage(sender=resources.sender, subject=u"Commentaire envoyé par le formulaire Permis de Travail du site du Forum") message.to = resources.workpermit_comments_to message.cc = resources.workpermit_comments_cc message.reply_to = email message.body = u"Message envoyé par le formulaire Permis de Travail, par <strong>%s %s</strong> (%s) :\n\n%s" % (firstname, lastname.upper(), email, msg) message.send() return '' def exhibitor(request, name=None, lang=None): "Display the Forum visitor page" supage_name = "exhibitors" if name is None or lang is None: return _redirect(supage_name, name, lang, "visitors") activate(lang) ctxt_dict = { "url" : request.path, "lang_code" : lang, "supage_name": supage_name, "page_name" : "/" + name, "thispage" : "entry_" + supage_name + "_" + name ,"ext" : "forum/"+lang+"/static/base-exhibitors.html" } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/static/exhibitors/%s.html" % (Config.APP_NAME, lang, name) ) except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) VISITORS = 0 EXHIBITORS = 1 def contactVisitors(request, name=None, lang=None): # logging.error("supage_name:%s - nameisNone:%s - langisNone:%s"%("visitors",(name is None),(lang is None))) # if not name is None: # logging.error("name:%s"%name) # if not lang is None: # logging.error("lang:%s"%lang) return contact(request, name, lang, VISITORS) def contactExhibitors(request, name=None, lang=None): return contact(request, name, lang, EXHIBITORS) def contact(request, name, lang, source): "Display the Forum contact page." if source == VISITORS: supage_name = "visitors" else: supage_name = "exhibitors" # logging.error("supage_name:%s - nameisNone:%s - langisNone:%s"%(supage_name,(name is None),(lang is None))) # if not name is None: # logging.error("name:%s"%name) # if not lang is None: # logging.error("lang:%s"%lang) if name is None or lang is None: return _redirect(supage_name, name, lang, "contact", "contact") activate(lang) if source == VISITORS: ext = "forum/"+lang+"/static/base-visitors.html" else: ext = "forum/"+lang+"/static/base-exhibitors.html" ctxt_dict = {"url" : request.path, "lang_code" : lang, "supage_name" : supage_name, "page_name" : "/contact/" + name, "thispage" : "entry_" + supage_name + "_" + name ,"ext" : ext } ctxt_dict.update(get_common_data(request)) if name == "contact" and request.method == 'POST': msg = sendMailToAfcp(request) if msg != '': ctxt_dict["errmsg"] = msg else: ctxt_dict["msgok"] = True ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/static/contact/%s.html" % (Config.APP_NAME, lang, name)); except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) def sendMailToAfcp(request): msg = request.POST.get('message', '') email = request.POST.get('email', '') fromArg = request.POST.get('from', '') if email == '' and msg == '': return u"Veuillez indiquer un e-mail auquel vous répondre et rédiger un message avant d'envoyer." if email == '': return u"Veuillez indiquer un e-mail auquel vous répondre." if msg == '': return u"Procédez dans l'ordre et rédigez un message avant de l'envoyer :)" if fromArg == '': return u"Emplacement du formulaire sur le site non précisé." message = mail.EmailMessage(sender=resources.sender, subject=u"Message envoyé par le formulaire de contact du site de l'AFCP, section %s" % fromArg) message.to = resources.contactus_emails message.reply_to = email message.body = u"Message envoyé par le formulaire de contact, par %s :\n\n%s" % (email, msg) message.send() return '' def inscript(request, name=None, lang=None): "Display the Inscription Page." supage_name = "visitors" logging.error("supage_name:%s - nameisNone:%s - langisNone:%s"%(supage_name,(name is None),(lang is None))) if not name is None: logging.error("name:%s"%name) if not lang is None: logging.error("lang:%s"%lang) if name is None or lang is None: return _redirect(supage_name, name, lang, "forum2013", "inscript") activate(lang) ctxt_dict = {"url" : request.path, "lang_code" : lang, "supage_name" : supage_name, "subpage" : "inscript", "page_name" : "/" + name, "thispage" : "entry_" + supage_name + "_inscription" #Exception pour le menu à gauche ,"ext" : "forum/"+lang+"/static/base-visitors.html" } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/static/inscription/%s.html" % (Config.APP_NAME, lang, name)); except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) def saint_gobain(request, name=None, lang=None): "Display the Inscription Page." supage_name = "inscript" if name is None or lang is None: return _redirect(supage_name, name, lang, "test") activate(lang) ctxt_dict = {"url" : request.path, "lang_code" : lang, "supage_name" : supage_name, "page_name" : "/" + name, "thispage" : "entry_" + supage_name + "_" + name} ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/static/inscription/%s.html" % (Config.APP_NAME, lang, name)); except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) def inscription(request, name=None, lang=None): "Display the Inscription Page." supage_name = "inscript" if name is None or lang is None: return _redirect(supage_name, name, lang, "inscription") activate(lang) ctxt_dict = {"url" : request.path, "lang_code" : lang, "supage_name" : supage_name, "page_name" : "/" + name, "thispage" : "entry_" + supage_name + "_" + name} ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/static/visitors/%s.html" % (Config.APP_NAME, lang, name)); except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) def not_found(request): "Displays the 404 not-found page." ctxt_dict = { "url" : request.path, } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("not_found.html") return HttpResponseNotFound(tmpl.render(ctxt))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com> # - http://heavyz.blogspot.com/ # - http://buggarden.blogspot.com/ # # Created on 2008-12-08. # $Id: resources.py 26 2009-08-04 22:06:00Z guolin.mobi $ # class BannerImage(object): def __init__(self, id, url, title, desc): self.id = id self.url = url self.title = title self.desc = desc HOME_URL = "/" BANNER_IMAGES = ( BannerImage( id="Forum_Horizon_Chine_2010_1", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_2", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_3", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_4", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_5", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_6", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_7", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_8", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_9", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_10", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2011_11", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2011-05-12" ), BannerImage( id="Forum_Horizon_Chine_2011_12", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2011-05-12" ), BannerImage( id="Forum_Horizon_Chine_2011_13", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2011-05-12" ), BannerImage( id="Forum_Horizon_Chine_2011_14", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2011-05-12" ), BannerImage( id="Forum_Horizon_Chine_2011_15", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2011-05-12" ), BannerImage( id="Forum_Horizon_Chine_2011_16", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2011-05-12" ), # Add a banner image here: # BannerImage( id="id (static image file base name)", # url="external url", # title="image title", # desc="description" ), ) # BANNER_IMAGES # Liste des adresses e-mail des contacts des entreprises à qui les candidatures sont envoyées. # L'id correspond à l'id indiquée dans les formulaires de postulation # Exemple : #company_emails = { # '1': "architruc <archi.truc@yahoo.fr>, aol emd <antoine.ory-lamballe@mines-paristech.fr>" # } sender = u'Forum Horizon Chine <admin@forumhorizonchine.com>' defaultAttachmentsNumber = 2 # Number of attachments required for applications. # The identifier used is the same as company_emails (following) #attachments = { # 'huawei': 4, # 'huawei2': 4, # 'test': 4, #} class CompanyDetails(object): """ Properties: company email (email), minimal number of attachment (minattach), maximal number of attachment (maxattach). If no minattach is defined, it is set to resources.defaultAttachmentsNumber (2). If no maxattach is defined, it is set to minattach value. """ def __init__(self, email, minattach=defaultAttachmentsNumber, maxattach=None): self.email = email self.minattach = minattach if maxattach is None: self.maxattach = minattach else: self.maxattach = maxattach company_emails = { 'test': CompanyDetails('Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr>', 2, 4), # formulaire de test # 'huawei': CompanyDetails('recuit@huawei.com', 2, 4), # Huawei - recrutement # 'huawei2': CompanyDetails("ricky@huawei.com, francehr@huawei.com", 2, 4), # Huawei - Ingénieur Support Expert Datacom 'bmwbj': CompanyDetails('careerbj@bmw-brilliance.cn'), # BMW - recrutement bj 'bmwsy': CompanyDetails('careersy@bmw-brilliance.cn'), # BMW - recrutement sy # 'tbsmarketing': CompanyDetails('Sallytbsdtv@gmail.com, kerong.cao@gmail.com'), # TBS Europe - Chargé(e) de mission - Marketing 'lyxorquant': CompanyDetails('jean-charles.richard@lyxor.com'), # Lyxor Asset Management - Quant R&D # 'bmwbj': CompanyDetails('antoine.orylamballe@yahoo.fr'), # BMW - recrutement bj # 'bmwsy': CompanyDetails('antoine.orylamballe@yahoo.fr'), # BMW - recrutement sy # 'jpm': CompanyDetails('fei.shi@jpmchase.com'), # Lyxor Asset Management - Quant R&D 'michelin': CompanyDetails('assistant.recruiting@cn.michelin.com'), # Michelin 'boc': CompanyDetails('hrceximbank@gmail.com'), # Bank of China # 'bureauveritas': CompanyDetails('thomas.zhu2008@gmail.com'), # Bureau Veritas China 'haygroup': CompanyDetails('xiajiaojiao428@gmail.com'), # Hay Group 'devialet': CompanyDetails('julien.bergere@devialet.com'), # Devialet 'diam': CompanyDetails('raphaele.briand@diaminter.com, dan.xu@diaminter.com'), # Diam } #application_cc = u'AFCP <AFCParisTech@gmail.com>, Antoine ORY-LAMBALLE <antoine.ory-lamballe@mines-paristech.fr>, ZHENG Ban <ban.zheng.x2005@gmail.com>' #application_cc = u'ZHU Qi <realzhq@gmail.com>, LI Zheng <zheng.li@polytechnique.edu>, ZHANG Nan <nan.zhann@gmail.com>, DENG Ken <dengken524@live.cn>, Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr>, ZHU Tong <zhutong0114@gmail.com>' application_cc = u'ZHU Qi <realzhq@gmail.com>, LI Zheng <zheng.li@polytechnique.edu>, DENG Ken <dengken524@live.cn>, Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr>, ZHU Tong <zhutong0114@gmail.com>' #contactus_emails = u'AFCP <AFCParisTech@gmail.com>, ban.zheng.x2005@gmail.com, luoyudenis@gmail.com' #contactus_emails = u'ZHU Qi <realzhq@gmail.com>, LI Zheng <zheng.li@polytechnique.edu>, ZHANG Nan <nan.zhann@gmail.com>, DENG Ken <dengken524@live.cn>, Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr>, ZHU Tong <zhutong0114@gmail.com>' contactus_emails = u'ZHU Qi <realzhq@gmail.com>, LI Zheng <zheng.li@polytechnique.edu>, DENG Ken <dengken524@live.cn>, Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr>, ZHU Tong <zhutong0114@gmail.com>' workpermit_comments_to = u'AFCP <afcparistech@gmail.com' #workpermit_comments_to = u'Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr' workpermit_comments_cc = u'Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr'
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # # Forum app URL mappings. # # Created on 2008-10-28. # $Id: urls.py 41 2010-07-21 10:33:30Z guolin.mobi $ # from django.conf.urls.defaults import patterns, include urlpatterns = patterns("afcpweb.apps.forum.views", ( r"^lang/$" , "change_language" ), ( r"^$" , "home" ), ( r"^home/$" , "home_with_args" ), ( r"^home/(?P<lang>.+)/$" , "home_with_args" ), # ( r"^inscription/$" , "inscription" ), # ( r"^inscription$" , "inscription" ), ( r"^visitors/contact/(?P<name>\w+)/(?P<lang>.+)/$" , "contactVisitors" ), ( r"^visitors/contact/(?P<name>\w+)/$" , "contactVisitors" ), ( r"^visitors/contact/$" , "contactVisitors" ), ( r"^exhibitors/contact/(?P<name>\w+)/(?P<lang>.+)/$" , "contactExhibitors" ), ( r"^exhibitors/contact/(?P<name>\w+)/$" , "contactExhibitors" ), ( r"^exhibitors/contact/$" , "contactExhibitors" ), ( r"^visitors/inscript/(?P<name>\w+)/(?P<lang>.+)/$" , "inscript" ), ( r"^visitors/inscript/(?P<name>\w+)/$" , "inscript" ), ( r"^visitors/inscript/$" , "inscript" ), #( r"^visitors/(?P<name>\w+)$" , "visitor" ), ( r"^visitors/(?P<name>\w+)/(?P<lang>.+)/$" , "visitor" ), ( r"^visitors/(?P<name>\w+)/$" , "visitor" ), ( r"^visitors/$" , "visitor" ), ( r"^exhibitors/(?P<name>\w+)/(?P<lang>.+)/$" , "exhibitor" ), ( r"^exhibitors/(?P<name>\w+)/$" , "exhibitor" ), ( r"^exhibitors/$" , "exhibitor" ), #( r"^inscript/$" , "saint_gobain"), # ( r"^inscript/(?P<name>\w+)/(?P<lang>.+)/$" , "inscript"), # ( r"^inscript/(?P<name>\w+)/$" , "inscript"), (r'^i18n/', include('django.conf.urls.i18n')), ) urlpatterns += patterns( "afcpweb.apps.misc.views", # 404 not-found: must be the last URL pattern. ( r"^.*$" , "not_found" ), )
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Forum app global configurations. # # Created on 2008-10-28. # $Id: config.py 41 2010-07-21 10:33:30Z guolin.mobi $ # class Config(object): """This class contains constants for the AFCP webapp.""" APP_NAME = "forum" URL_PREFIX = "/forum" #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # # Forum app URL mappings. # # Created on 2008-10-28. # $Id: urls.py 41 2010-07-21 10:33:30Z guolin.mobi $ # from django.conf.urls.defaults import patterns, include urlpatterns = patterns("afcpweb.apps.forum.views", ( r"^lang/$" , "change_language" ), ( r"^$" , "home" ), ( r"^home/$" , "home_with_args" ), ( r"^home/(?P<lang>.+)/$" , "home_with_args" ), # ( r"^inscription/$" , "inscription" ), # ( r"^inscription$" , "inscription" ), ( r"^visitors/contact/(?P<name>\w+)/(?P<lang>.+)/$" , "contactVisitors" ), ( r"^visitors/contact/(?P<name>\w+)/$" , "contactVisitors" ), ( r"^visitors/contact/$" , "contactVisitors" ), ( r"^exhibitors/contact/(?P<name>\w+)/(?P<lang>.+)/$" , "contactExhibitors" ), ( r"^exhibitors/contact/(?P<name>\w+)/$" , "contactExhibitors" ), ( r"^exhibitors/contact/$" , "contactExhibitors" ), ( r"^visitors/inscript/(?P<name>\w+)/(?P<lang>.+)/$" , "inscript" ), ( r"^visitors/inscript/(?P<name>\w+)/$" , "inscript" ), ( r"^visitors/inscript/$" , "inscript" ), #( r"^visitors/(?P<name>\w+)$" , "visitor" ), ( r"^visitors/(?P<name>\w+)/(?P<lang>.+)/$" , "visitor" ), ( r"^visitors/(?P<name>\w+)/$" , "visitor" ), ( r"^visitors/$" , "visitor" ), ( r"^exhibitors/(?P<name>\w+)/(?P<lang>.+)/$" , "exhibitor" ), ( r"^exhibitors/(?P<name>\w+)/$" , "exhibitor" ), ( r"^exhibitors/$" , "exhibitor" ), #( r"^inscript/$" , "saint_gobain"), # ( r"^inscript/(?P<name>\w+)/(?P<lang>.+)/$" , "inscript"), # ( r"^inscript/(?P<name>\w+)/$" , "inscript"), (r'^i18n/', include('django.conf.urls.i18n')), ) urlpatterns += patterns( "afcpweb.apps.misc.views", # 404 not-found: must be the last URL pattern. ( r"^.*$" , "not_found" ), )
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com> # - http://heavyz.blogspot.com/ # - http://buggarden.blogspot.com/ # # Created on 2008-04-28 # $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $ #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Views for the Forum webapp. # # Created on 2008-10-28. # $Id: views.py 41 2010-07-21 10:33:30Z guolin.mobi $ # from afcpweb.apps.common import utils from afcpweb.apps.common.actions import get_common_data from afcpweb.apps.forum import resources from afcpweb.apps.forum.config import Config from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect, HttpRequest from django.template import Context, loader, TemplateDoesNotExist from google.appengine.api import mail from google.appengine.ext import db from os.path import splitext import datetime import random #from django.utils.translation import gettext_lazy as _ from django.utils.translation import ugettext as _, activate from django.conf import settings import logging #from google.appengine.api import users #--------------------------------------------------------------------------------------------------- # Home page, 404 not-found page, error page and static pages #--------------------------------------------------------------------------------------------------- def _redirect(supage_name, name, lang, defaultName, subPage = None): if name is None: name = defaultName if lang is None: lang = defaultLanguage if supage_name is None: supage_name = "" else: supage_name = "/" + supage_name if not subPage is None: name += "/" + subPage return HttpResponseRedirect(supage_name + "/" + name + "/" + lang + "/") defaultLanguage = settings.LANGUAGE_CODE #defaultLanguage = "zh-cn" def home(request, lang=None): "Displays the Forum home page." supage_name = "home" if lang is None: #return _redirect(None, None, lang, "home") lang = defaultLanguage activate(lang) ctxt_dict = { "supage_name": supage_name, # "page_name" : "/" + name, "url" : request.path, "lang_code" : lang, "banner_image" : random.choice(resources.BANNER_IMAGES) } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/home.html" % (Config.APP_NAME, lang) ) except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) def home_with_args(request, lang=None): "Displays the root page, supposed to be the home page" if lang is None: return _redirect(None, None, lang, "home") elif lang == defaultLanguage: return HttpResponseRedirect("/") else: return home(request, lang) def visitor(request, name=None, lang=None): "Displays the Forum visitor page" supage_name = "visitors" if name is None or lang is None: return _redirect(supage_name, name, lang, "program") activate(lang) ctxt_dict = { "supage_name": supage_name, "page_name" : "/" + name, "url" : request.path, "lang_code" : lang, "thispage" : "entry_" + supage_name + "_" + name ,"ext" : "forum/"+lang+"/static/base-visitors.html" } ctxt_dict.update(get_common_data(request)) if name == "workpermit" and request.method == 'POST': msg = sendWorkPermitComment(request) if msg != '': ctxt_dict["errmsg"] = msg else: ctxt_dict["msgok"] = True if name == "sendmail": return_code = sendmail(request, lang) if return_code != OK: ctxt_dict.update({"error_code" : return_code}) name = "nosendmail" if name == "applications": c = Candidate.all() results = c.fetch(100000) ctxt_dict["application"] = results ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/static/visitors/%s.html" % (Config.APP_NAME, lang, name) ) except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) # Class used for google datastore (list of applications done) class Candidate(db.Model): lastname = db.StringProperty(required=True) firstname = db.StringProperty(required=True) email = db.StringProperty(required=True) application_date = db.DateProperty(required=True) company = db.StringProperty(required=True) job = db.StringProperty(required=True) OK = 0 INVALID_MAIL = 1 MISSING_ATTACHMENT = 2 REQUIRED_FIELD = 3 INVALID_EXT = 4 TOO_LARGE_ATTACHMENT = 5 EMPTY_REQUIRED_FIELD = 6 def sendmail(request, lang): if not mail.is_email_valid(request.POST['email']): return INVALID_MAIL # if len(request.POST) != 6: # return REQUIRED_FIELD id = unicode(request.POST.get('id', '')) prenom = unicode(request.POST.get('prenom', '')).capitalize() nom = unicode(request.POST.get('nom', '')).upper() email = unicode(request.POST.get('email', '')) company = unicode(request.POST.get('company', '')) job = unicode(request.POST.get('jobname', '')) if (len(id) == 0 or len(prenom) == 0 or len(nom) == 0 or len(email) == 0 or (company) == 0 or len(job) == 0): return EMPTY_REQUIRED_FIELD addressee = resources.company_emails[id] # numberOfAttachmentsAllowed = resources.attachments.get(id, resources.defaultAttachmentsNumber) numberOfAttachmentsSents = len(request.FILES) if numberOfAttachmentsSents < addressee.minattach or numberOfAttachmentsSents > addressee.maxattach: return MISSING_ATTACHMENT totalSize = 0 for f in request.FILES.values(): path, ext = splitext(f.name) if ext != '.doc' and ext != '.pdf': return INVALID_EXT totalSize += f.size #if totalSize > 1048576: # Max 1 Mo # Max 0.5 Mo * nombre de pièces jointes ou 10 Mo (un peu moins pour le corps du mail) if totalSize > numberOfAttachmentsSents * 524288 or totalSize > 10000000: return TOO_LARGE_ATTACHMENT tmpl = loader.get_template("%s/%s/mail/application_subject.txt" % (Config.APP_NAME, lang) ) mail_subject = tmpl.render(Context(get_common_data(request))) % job message = mail.EmailMessage(sender=resources.sender, # subject=u"%s : Nouvelle candidature envoyée par le site de l'AFCP" % job) subject=mail_subject) message.to = unicode(addressee.email) if id != 'test': message.cc = resources.application_cc # message.body = u""" #Madame, Monsieur, # #Une nouvelle candidature pour le poste %s a été envoyée par l'intermédiaire du site de l'AFCP, l'offre y étant publiée. # #Veuillez trouver ci-joint le CV et la lettre de motivation de %s %s pour cette candidature. Vous pouvez le joindre à l'adresse e-mail %s # #Bien à vous, # #L'équipe AFCP #""" % (job, prenom, nom, email) tmpl = loader.get_template("%s/%s/mail/application.txt" % (Config.APP_NAME, lang) ) message.body = tmpl.render(Context(get_common_data(request))) % (job, prenom, nom, email) # message.html = u""" #<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><br/> #Madame, Monsieur,<br/> #<br/> #Une nouvelle candidature pour le poste %s a été envoyée par l'intermédiaire du site de l'AFCP, l'offre y étant publiée.<br/> #<br/> #Veuillez trouver ci-joint le CV et la lettre de motivation de %s %s pour cette candidature. Vous pouvez le joindre à l'adresse e-mail <a href="mailto:%s">%s</a>.<br/> #<br/> #Bien à vous,<br/> #<br/> #L'équipe AFCP<br/> #</body></html> #""" % (job, prenom, nom, email, email) tmpl = loader.get_template("%s/%s/mail/application.html" % (Config.APP_NAME, lang) ) message.html = tmpl.render(Context(get_common_data(request))) % (job, prenom, nom, email, email) # message.attachments = request.FILES.items() #message.attachments = [(filename + u"__" + replaceForbiddenCharacters(f.name), f.read()) for filename, f in request.FILES.items()] message.attachments = [(f.name, f.read()) for filename, f in request.FILES.items()] message.send() e = Candidate( lastname = nom, firstname = prenom, email = email, application_date = datetime.datetime.now().date(), company = company, job = job ) e.put() return OK #def replaceForbiddenCharacters(s): # p = re.compile('(\\|\/|\:|\*|\?|\"|\<|\>|\|)') # return p.sub('_', s) def sendWorkPermitComment(request): msg = request.POST.get('message', '') email = request.POST.get('email', '') firstname = request.POST.get('firstname', '') firstname = firstname[:1].upper() + firstname[1:] # Capitalize lastname = request.POST.get('lastname', '') if firstname == '': return u"Veuillez indiquer votre prénom." if lastname == '': return u"Veuillez indiquer votre nom." if email == '' and msg == '': return u"Veuillez indiquer un e-mail auquel vous répondre et rédiger un message avant d'envoyer." if email == '': return u"Veuillez indiquer un e-mail auquel vous répondre." if msg == '': return u"Procédez dans l'ordre et rédigez un message avant de l'envoyer :)" message = mail.EmailMessage(sender=resources.sender, subject=u"Commentaire envoyé par le formulaire Permis de Travail du site du Forum") message.to = resources.workpermit_comments_to message.cc = resources.workpermit_comments_cc message.reply_to = email message.body = u"Message envoyé par le formulaire Permis de Travail, par <strong>%s %s</strong> (%s) :\n\n%s" % (firstname, lastname.upper(), email, msg) message.send() return '' def exhibitor(request, name=None, lang=None): "Display the Forum visitor page" supage_name = "exhibitors" if name is None or lang is None: return _redirect(supage_name, name, lang, "visitors") activate(lang) ctxt_dict = { "url" : request.path, "lang_code" : lang, "supage_name": supage_name, "page_name" : "/" + name, "thispage" : "entry_" + supage_name + "_" + name ,"ext" : "forum/"+lang+"/static/base-exhibitors.html" } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/static/exhibitors/%s.html" % (Config.APP_NAME, lang, name) ) except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) VISITORS = 0 EXHIBITORS = 1 def contactVisitors(request, name=None, lang=None): # logging.error("supage_name:%s - nameisNone:%s - langisNone:%s"%("visitors",(name is None),(lang is None))) # if not name is None: # logging.error("name:%s"%name) # if not lang is None: # logging.error("lang:%s"%lang) return contact(request, name, lang, VISITORS) def contactExhibitors(request, name=None, lang=None): return contact(request, name, lang, EXHIBITORS) def contact(request, name, lang, source): "Display the Forum contact page." if source == VISITORS: supage_name = "visitors" else: supage_name = "exhibitors" # logging.error("supage_name:%s - nameisNone:%s - langisNone:%s"%(supage_name,(name is None),(lang is None))) # if not name is None: # logging.error("name:%s"%name) # if not lang is None: # logging.error("lang:%s"%lang) if name is None or lang is None: return _redirect(supage_name, name, lang, "contact", "contact") activate(lang) if source == VISITORS: ext = "forum/"+lang+"/static/base-visitors.html" else: ext = "forum/"+lang+"/static/base-exhibitors.html" ctxt_dict = {"url" : request.path, "lang_code" : lang, "supage_name" : supage_name, "page_name" : "/contact/" + name, "thispage" : "entry_" + supage_name + "_" + name ,"ext" : ext } ctxt_dict.update(get_common_data(request)) if name == "contact" and request.method == 'POST': msg = sendMailToAfcp(request) if msg != '': ctxt_dict["errmsg"] = msg else: ctxt_dict["msgok"] = True ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/static/contact/%s.html" % (Config.APP_NAME, lang, name)); except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) def sendMailToAfcp(request): msg = request.POST.get('message', '') email = request.POST.get('email', '') fromArg = request.POST.get('from', '') if email == '' and msg == '': return u"Veuillez indiquer un e-mail auquel vous répondre et rédiger un message avant d'envoyer." if email == '': return u"Veuillez indiquer un e-mail auquel vous répondre." if msg == '': return u"Procédez dans l'ordre et rédigez un message avant de l'envoyer :)" if fromArg == '': return u"Emplacement du formulaire sur le site non précisé." message = mail.EmailMessage(sender=resources.sender, subject=u"Message envoyé par le formulaire de contact du site de l'AFCP, section %s" % fromArg) message.to = resources.contactus_emails message.reply_to = email message.body = u"Message envoyé par le formulaire de contact, par %s :\n\n%s" % (email, msg) message.send() return '' def inscript(request, name=None, lang=None): "Display the Inscription Page." supage_name = "visitors" logging.error("supage_name:%s - nameisNone:%s - langisNone:%s"%(supage_name,(name is None),(lang is None))) if not name is None: logging.error("name:%s"%name) if not lang is None: logging.error("lang:%s"%lang) if name is None or lang is None: return _redirect(supage_name, name, lang, "forum2013", "inscript") activate(lang) ctxt_dict = {"url" : request.path, "lang_code" : lang, "supage_name" : supage_name, "subpage" : "inscript", "page_name" : "/" + name, "thispage" : "entry_" + supage_name + "_inscription" #Exception pour le menu à gauche ,"ext" : "forum/"+lang+"/static/base-visitors.html" } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/static/inscription/%s.html" % (Config.APP_NAME, lang, name)); except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) def saint_gobain(request, name=None, lang=None): "Display the Inscription Page." supage_name = "inscript" if name is None or lang is None: return _redirect(supage_name, name, lang, "test") activate(lang) ctxt_dict = {"url" : request.path, "lang_code" : lang, "supage_name" : supage_name, "page_name" : "/" + name, "thispage" : "entry_" + supage_name + "_" + name} ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/static/inscription/%s.html" % (Config.APP_NAME, lang, name)); except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) def inscription(request, name=None, lang=None): "Display the Inscription Page." supage_name = "inscript" if name is None or lang is None: return _redirect(supage_name, name, lang, "inscription") activate(lang) ctxt_dict = {"url" : request.path, "lang_code" : lang, "supage_name" : supage_name, "page_name" : "/" + name, "thispage" : "entry_" + supage_name + "_" + name} ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) try: tmpl = loader.get_template("%s/%s/static/visitors/%s.html" % (Config.APP_NAME, lang, name)); except TemplateDoesNotExist: return not_found(request) return HttpResponse(tmpl.render(ctxt)) def not_found(request): "Displays the 404 not-found page." ctxt_dict = { "url" : request.path, } ctxt_dict.update(get_common_data(request)) ctxt = Context(ctxt_dict) tmpl = loader.get_template("not_found.html") return HttpResponseNotFound(tmpl.render(ctxt))
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Forum app global configurations. # # Created on 2008-10-28. # $Id: config.py 41 2010-07-21 10:33:30Z guolin.mobi $ # class Config(object): """This class contains constants for the AFCP webapp.""" APP_NAME = "forum" URL_PREFIX = "/forum" #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com> # - http://heavyz.blogspot.com/ # - http://buggarden.blogspot.com/ # # Created on 2008-12-08. # $Id: resources.py 26 2009-08-04 22:06:00Z guolin.mobi $ # class BannerImage(object): def __init__(self, id, url, title, desc): self.id = id self.url = url self.title = title self.desc = desc HOME_URL = "/" BANNER_IMAGES = ( BannerImage( id="Forum_Horizon_Chine_2010_1", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_2", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_3", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_4", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_5", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_6", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_7", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_8", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_9", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2010_10", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2010-05-20" ), BannerImage( id="Forum_Horizon_Chine_2011_11", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2011-05-12" ), BannerImage( id="Forum_Horizon_Chine_2011_12", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2011-05-12" ), BannerImage( id="Forum_Horizon_Chine_2011_13", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2011-05-12" ), BannerImage( id="Forum_Horizon_Chine_2011_14", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2011-05-12" ), BannerImage( id="Forum_Horizon_Chine_2011_15", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2011-05-12" ), BannerImage( id="Forum_Horizon_Chine_2011_16", url=HOME_URL, title="Forum Horizon Chine,", desc="Taken by AFCP on 2011-05-12" ), # Add a banner image here: # BannerImage( id="id (static image file base name)", # url="external url", # title="image title", # desc="description" ), ) # BANNER_IMAGES # Liste des adresses e-mail des contacts des entreprises à qui les candidatures sont envoyées. # L'id correspond à l'id indiquée dans les formulaires de postulation # Exemple : #company_emails = { # '1': "architruc <archi.truc@yahoo.fr>, aol emd <antoine.ory-lamballe@mines-paristech.fr>" # } sender = u'Forum Horizon Chine <admin@forumhorizonchine.com>' defaultAttachmentsNumber = 2 # Number of attachments required for applications. # The identifier used is the same as company_emails (following) #attachments = { # 'huawei': 4, # 'huawei2': 4, # 'test': 4, #} class CompanyDetails(object): """ Properties: company email (email), minimal number of attachment (minattach), maximal number of attachment (maxattach). If no minattach is defined, it is set to resources.defaultAttachmentsNumber (2). If no maxattach is defined, it is set to minattach value. """ def __init__(self, email, minattach=defaultAttachmentsNumber, maxattach=None): self.email = email self.minattach = minattach if maxattach is None: self.maxattach = minattach else: self.maxattach = maxattach company_emails = { 'test': CompanyDetails('Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr>', 2, 4), # formulaire de test # 'huawei': CompanyDetails('recuit@huawei.com', 2, 4), # Huawei - recrutement # 'huawei2': CompanyDetails("ricky@huawei.com, francehr@huawei.com", 2, 4), # Huawei - Ingénieur Support Expert Datacom 'bmwbj': CompanyDetails('careerbj@bmw-brilliance.cn'), # BMW - recrutement bj 'bmwsy': CompanyDetails('careersy@bmw-brilliance.cn'), # BMW - recrutement sy # 'tbsmarketing': CompanyDetails('Sallytbsdtv@gmail.com, kerong.cao@gmail.com'), # TBS Europe - Chargé(e) de mission - Marketing 'lyxorquant': CompanyDetails('jean-charles.richard@lyxor.com'), # Lyxor Asset Management - Quant R&D # 'bmwbj': CompanyDetails('antoine.orylamballe@yahoo.fr'), # BMW - recrutement bj # 'bmwsy': CompanyDetails('antoine.orylamballe@yahoo.fr'), # BMW - recrutement sy # 'jpm': CompanyDetails('fei.shi@jpmchase.com'), # Lyxor Asset Management - Quant R&D 'michelin': CompanyDetails('assistant.recruiting@cn.michelin.com'), # Michelin 'boc': CompanyDetails('hrceximbank@gmail.com'), # Bank of China # 'bureauveritas': CompanyDetails('thomas.zhu2008@gmail.com'), # Bureau Veritas China 'haygroup': CompanyDetails('xiajiaojiao428@gmail.com'), # Hay Group 'devialet': CompanyDetails('julien.bergere@devialet.com'), # Devialet 'diam': CompanyDetails('raphaele.briand@diaminter.com, dan.xu@diaminter.com'), # Diam } #application_cc = u'AFCP <AFCParisTech@gmail.com>, Antoine ORY-LAMBALLE <antoine.ory-lamballe@mines-paristech.fr>, ZHENG Ban <ban.zheng.x2005@gmail.com>' #application_cc = u'ZHU Qi <realzhq@gmail.com>, LI Zheng <zheng.li@polytechnique.edu>, ZHANG Nan <nan.zhann@gmail.com>, DENG Ken <dengken524@live.cn>, Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr>, ZHU Tong <zhutong0114@gmail.com>' application_cc = u'ZHU Qi <realzhq@gmail.com>, LI Zheng <zheng.li@polytechnique.edu>, DENG Ken <dengken524@live.cn>, Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr>, ZHU Tong <zhutong0114@gmail.com>' #contactus_emails = u'AFCP <AFCParisTech@gmail.com>, ban.zheng.x2005@gmail.com, luoyudenis@gmail.com' #contactus_emails = u'ZHU Qi <realzhq@gmail.com>, LI Zheng <zheng.li@polytechnique.edu>, ZHANG Nan <nan.zhann@gmail.com>, DENG Ken <dengken524@live.cn>, Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr>, ZHU Tong <zhutong0114@gmail.com>' contactus_emails = u'ZHU Qi <realzhq@gmail.com>, LI Zheng <zheng.li@polytechnique.edu>, DENG Ken <dengken524@live.cn>, Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr>, ZHU Tong <zhutong0114@gmail.com>' workpermit_comments_to = u'AFCP <afcparistech@gmail.com' #workpermit_comments_to = u'Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr' workpermit_comments_cc = u'Antoine ORY-LAMBALLE <antoine.orylamballe@yahoo.fr'
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2008-04-28 # $Id: __init__.py 49 2010-07-21 15:54:10Z guolin.mobi $ #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com> # - http://heavyz.blogspot.com/ # - http://buggarden.blogspot.com/ # # Modified Django session middleware classes for Google App Engine. This middleware uses google's # memcache instead of relational database to save session. # # Created on 2008-11-13. # $Id: sessions.py 26 2009-08-04 22:06:00Z guolin.mobi $ # import datetime import random import logging from django.conf import settings from django.utils.cache import patch_vary_headers from google.appengine.api import memcache #--------------------------------------------------------------------------------------------------- class SessionWrapper(object): def __init__(self, session_key): self._session_cache = None self.session_key = session_key self.accessed = False self.modified = False def __contains__(self, key): return key in self._session def __getitem__(self, key): return self._session[key] def __setitem__(self, key, value): self._session[key] = value self.modified = True def __delitem__(self, key): del self._session[key] self.modified = True def keys(self): return self._session.keys() def items(self): return self._session.items() def get(self, key, default=None): return self._session.get(key, default) def get_or_create_session_key(self, request): if self.session_key is None: ip_addr = request.META.get("REMOTE_ADDR", "unknown_ip") timestamp = datetime.datetime.strftime(datetime.datetime.utcnow(), "%Y%m%d%H%M%S") suffix = "%x" % (random.random() * 65536) self.session_key = "session_" + ip_addr + "_" + timestamp + "_" + suffix return self.session_key def _get_session(self): self.accessed = True if self._session_cache is None: if self.session_key is None: self._session_cache = {} else: self._session_cache = memcache.get(self.session_key) if self._session_cache is None: self._session_cache = {} self.session_key = None return self._session_cache _session = property(_get_session) #--------------------------------------------------------------------------------------------------- class SessionMiddleware(object): """Session middleware based on memcache. """ def process_request(self, request): request.session = SessionWrapper(request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)) def process_response(self, request, response): """If session was modified, save those changes and set a session cookie. """ try: accessed = request.session.accessed modified = request.session.modified except AttributeError, ex: logging.error("Failed to get session attribute: %s" % str(ex)) else: if accessed: patch_vary_headers(response, ("Cookie",)) if request.session.modified or settings.SESSION_SAVE_EVERY_REQUEST: # Get or create the session key. session_key = request.session.get_or_create_session_key(request) # Update the session dictionary object in memcache. memcache.set(session_key, request.session._session, settings.SESSION_COOKIE_AGE) # Set the session key in the cookie. if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE: max_age = None expires = None else: max_age = settings.SESSION_COOKIE_AGE expires_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age) expires = datetime.datetime.strftime(expires_time, "%a, %d-%b-%Y %H:%M:%S GMT") response.set_cookie( settings.SESSION_COOKIE_NAME, session_key, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None ) return response
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com> # - http://heavyz.blogspot.com/ # - http://buggarden.blogspot.com/ # # Django common middleware classes for the Bug Garden webapp. # # Created on 2008-10-20. # $Id: common.py 26 2009-08-04 22:06:00Z guolin.mobi $ # import logging from django.http import HttpRequest from django.http import HttpResponse from google.appengine.api import users #--------------------------------------------------------------------------------------------------- # DummyMiddleware #--------------------------------------------------------------------------------------------------- class DummyMiddleware(object): def __init__(self): """Most middleware classes won't need an initializer since middleware classes are essentially placeholders for the process_* methods. If you do need some global state you may use __init__ to set up. However, keep in mind a couple of caveats: * Django initializes your middleware without any arguments, so you can't define __init__ as requiring any arguments. * Unlike the process_* methods which get called once per request, __init__ gets called only once, when the web server starts up. """ pass def process_request(self, request): """This function is called on each request, before Django decides which view to execute. This function should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won't bother calling ANY other request, view or exception middleware, or the appropriate view; it'll return that HttpResponse. Response middleware is always called on every response. """ return None def process_view(self, request, view_func, view_args, view_kwargs): """This function is called just before Django calls the view. It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won't bother calling ANY other request, view or exception middleware, or the appropriate view; it'll return that HttpResponse. Response middleware is always called on every response. """ return None def process_response(self, request, response): """This function should return an HttpResponse object. It could alter the given response, or it could create and return a brand-new HttpResponse. """ return response def process_exception(self, request, exception): """This function is called when a view raises an exception. This function should return either None or an HttpResponse object. If it returns an HttpResponse object, the response will be returned to the browser. Otherwise, default exception handling kicks in. """ return None #--------------------------------------------------------------------------------------------------- # LogErrorMiddleware #--------------------------------------------------------------------------------------------------- class LogErrorMiddleware(object): def process_exception(self, request, exception): logging.error( "Error occurred: (%s) %s" % (type(exception), str(exception)) ) return None
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com> # - http://heavyz.blogspot.com/ # - http://buggarden.blogspot.com/ # # Modified Django session middleware classes for Google App Engine. This middleware uses google's # memcache instead of relational database to save session. # # Created on 2008-11-13. # $Id: sessions.py 26 2009-08-04 22:06:00Z guolin.mobi $ # import datetime import random import logging from django.conf import settings from django.utils.cache import patch_vary_headers from google.appengine.api import memcache #--------------------------------------------------------------------------------------------------- class SessionWrapper(object): def __init__(self, session_key): self._session_cache = None self.session_key = session_key self.accessed = False self.modified = False def __contains__(self, key): return key in self._session def __getitem__(self, key): return self._session[key] def __setitem__(self, key, value): self._session[key] = value self.modified = True def __delitem__(self, key): del self._session[key] self.modified = True def keys(self): return self._session.keys() def items(self): return self._session.items() def get(self, key, default=None): return self._session.get(key, default) def get_or_create_session_key(self, request): if self.session_key is None: ip_addr = request.META.get("REMOTE_ADDR", "unknown_ip") timestamp = datetime.datetime.strftime(datetime.datetime.utcnow(), "%Y%m%d%H%M%S") suffix = "%x" % (random.random() * 65536) self.session_key = "session_" + ip_addr + "_" + timestamp + "_" + suffix return self.session_key def _get_session(self): self.accessed = True if self._session_cache is None: if self.session_key is None: self._session_cache = {} else: self._session_cache = memcache.get(self.session_key) if self._session_cache is None: self._session_cache = {} self.session_key = None return self._session_cache _session = property(_get_session) #--------------------------------------------------------------------------------------------------- class SessionMiddleware(object): """Session middleware based on memcache. """ def process_request(self, request): request.session = SessionWrapper(request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)) def process_response(self, request, response): """If session was modified, save those changes and set a session cookie. """ try: accessed = request.session.accessed modified = request.session.modified except AttributeError, ex: logging.error("Failed to get session attribute: %s" % str(ex)) else: if accessed: patch_vary_headers(response, ("Cookie",)) if request.session.modified or settings.SESSION_SAVE_EVERY_REQUEST: # Get or create the session key. session_key = request.session.get_or_create_session_key(request) # Update the session dictionary object in memcache. memcache.set(session_key, request.session._session, settings.SESSION_COOKIE_AGE) # Set the session key in the cookie. if settings.SESSION_EXPIRE_AT_BROWSER_CLOSE: max_age = None expires = None else: max_age = settings.SESSION_COOKIE_AGE expires_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age) expires = datetime.datetime.strftime(expires_time, "%a, %d-%b-%Y %H:%M:%S GMT") response.set_cookie( settings.SESSION_COOKIE_NAME, session_key, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None ) return response
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com> # - http://heavyz.blogspot.com/ # - http://buggarden.blogspot.com/ # # Created on 2008-11-12. # $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $ #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com> # - http://heavyz.blogspot.com/ # - http://buggarden.blogspot.com/ # # Django common middleware classes for the Bug Garden webapp. # # Created on 2008-10-20. # $Id: common.py 26 2009-08-04 22:06:00Z guolin.mobi $ # import logging from django.http import HttpRequest from django.http import HttpResponse from google.appengine.api import users #--------------------------------------------------------------------------------------------------- # DummyMiddleware #--------------------------------------------------------------------------------------------------- class DummyMiddleware(object): def __init__(self): """Most middleware classes won't need an initializer since middleware classes are essentially placeholders for the process_* methods. If you do need some global state you may use __init__ to set up. However, keep in mind a couple of caveats: * Django initializes your middleware without any arguments, so you can't define __init__ as requiring any arguments. * Unlike the process_* methods which get called once per request, __init__ gets called only once, when the web server starts up. """ pass def process_request(self, request): """This function is called on each request, before Django decides which view to execute. This function should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won't bother calling ANY other request, view or exception middleware, or the appropriate view; it'll return that HttpResponse. Response middleware is always called on every response. """ return None def process_view(self, request, view_func, view_args, view_kwargs): """This function is called just before Django calls the view. It should return either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won't bother calling ANY other request, view or exception middleware, or the appropriate view; it'll return that HttpResponse. Response middleware is always called on every response. """ return None def process_response(self, request, response): """This function should return an HttpResponse object. It could alter the given response, or it could create and return a brand-new HttpResponse. """ return response def process_exception(self, request, exception): """This function is called when a view raises an exception. This function should return either None or an HttpResponse object. If it returns an HttpResponse object, the response will be returned to the browser. Otherwise, default exception handling kicks in. """ return None #--------------------------------------------------------------------------------------------------- # LogErrorMiddleware #--------------------------------------------------------------------------------------------------- class LogErrorMiddleware(object): def process_exception(self, request, exception): logging.error( "Error occurred: (%s) %s" % (type(exception), str(exception)) ) return None
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com> # - http://heavyz.blogspot.com/ # - http://buggarden.blogspot.com/ # # Utility functions. # # Created on 2008-11-05. # $Id: utils.py 26 2009-08-04 22:06:00Z guolin.mobi $ # import logging import datetime import random from google.appengine.ext import db def munge_email(email): if email is not None: return email.replace("@", " (at) ") else: return None def demunge_email(munging_email): if munging_email is not None: return munging_email.replace(" (at) ", "@") else: return None def decode_utf8(string): return string.strip() def get_param(value_dict, name, default=None): value = decode_utf8(value_dict.get(name, "")) if len(value) == 0: return default else: return value def split_string(string): if string is not None: splitted = string.lower().replace(",", " ").replace(";", " ").split() else: splitted = [] return splitted def generate_random_id(prefix=""): timestamp = datetime.datetime.strftime(datetime.datetime.utcnow(), "%Y%m%d%H%M%S") suffix = "%x" % (random.random() * 65536) return (prefix + timestamp + suffix) #--------------------------------------------------------------------------------------------------- # EntityPage #--------------------------------------------------------------------------------------------------- class EntityPage(object): """ """ MIN_PER_PAGE = 1 MAX_PER_PAGE = 100 MIN_PAGE_RANGE = 0 MAX_PAGE_RANGE = 10 DEF_PAGE_RANGE = 5 def __init__(self, query, per_page, number=None, page_range=DEF_PAGE_RANGE): # Entity object count. self.object_count = query.count() # Entity objects per page. if per_page < EntityPage.MIN_PER_PAGE: self.per_page = EntityPage.MIN_PER_PAGE elif per_page > EntityPage.MAX_PER_PAGE: self.per_page = EntityPage.MAX_PER_PAGE else: self.per_page = per_page # First page number and last page number. self.first_page_number = 1 if self.object_count > 0: self.last_page_number = (self.object_count - 1) / self.per_page + 1 else: self.last_page_number = 1 # Current page number. try: if number is not None: self.number = int(number) else: self.number = 1 except ValueError: self.number = 1 if self.number < self.first_page_number: self.number = self.first_page_number elif self.number > self.last_page_number: self.number = self.last_page_number # Page range. if page_range < EntityPage.MIN_PAGE_RANGE: self.page_range = EntityPage.MIN_PAGE_RANGE elif page_range > EntityPage.MAX_PAGE_RANGE: self.page_range = EntityPage.MAX_PAGE_RANGE else: self.page_range = page_range # Entity object list. offset = (self.number - 1) * self.per_page self.object_list = query.fetch(self.per_page, offset) def has_previous(self): return (self.number > self.first_page_number) def previous_page_number(self): return (self.number - 1) def has_next(self): return (self.number < self.last_page_number) def next_page_number(self): return (self.number + 1) def previous_page_range(self): range_start_index = max( self.first_page_number, self.number - self.page_range ) range_end_index = self.number return range(range_start_index, range_end_index) def next_page_range(self): range_start_index = self.number + 1 range_end_index = min( self.last_page_number + 1, self.number + self.page_range + 1) return range(range_start_index, range_end_index) def is_first_page_in_range(self): return (self.first_page_number >= self.number - self.page_range) def is_last_page_in_range(self): return (self.last_page_number <= self.number + self.page_range)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Access for global app. # # Created on 2010-07-18. # $Id: models.py 29 2010-07-18 21:22:49Z guolin.mobi $ # from afcpweb.apps.common.config import Config def is_webmaster(user): if not user: return False else: return user.email() in Config.ADMINS class Access(object): def __init__(self, user): self._user = user def is_webmaster(self): return is_webmaster(sef._user)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Views for the global app. # # Created on 2008-10-28. # $Id: views.py 40 2010-03-08 23:05:09Z guolin.mobi $ # from django.http import HttpResponseRedirect from afcpweb.apps.members.models import get_current_user from afcpweb.apps.common import utils from afcpweb.apps.common.actions import Language def login_ok(request, url): try: profile = get_current_user().profile() if profile: profile.count_login() profile.put() except: pass return HttpResponseRedirect(url) def logout_ok(request, url): return HttpResponseRedirect(url) #--------------------------------------------------------------------------------------------------- # Change current language and logged-in/logged-out redirect #--------------------------------------------------------------------------------------------------- def change_language(request): "Change the current language." redirect_url = utils.get_param(request.REQUEST, "url" ) lang_code = utils.get_param(request.REQUEST, "lang") Language.set_lang(request, lang_code) return HttpResponseRedirect(redirect_url) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Access for global app. # # Created on 2010-07-18. # $Id: models.py 29 2010-07-18 21:22:49Z guolin.mobi $ # from afcpweb.apps.common.config import Config def is_webmaster(user): if not user: return False else: return user.email() in Config.ADMINS class Access(object): def __init__(self, user): self._user = user def is_webmaster(self): return is_webmaster(sef._user)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # afcpweb app commom actions. # # Created on 2008-10-28. # $Id: urls.py 26 2009-08-04 22:06:00Z guolin.mobi $ # import urllib from afcpweb.apps.common.config import Config from afcpweb.apps.members.models import get_current_user from afcpweb.apps.members.models import create_login_url from afcpweb.apps.members.models import create_logout_url import datetime from django.conf import settings #--------------------------------------------------------------------------------------------------- # Language class #--------------------------------------------------------------------------------------------------- class Language(object): LANG_SESSION_NAME = "django_language" ENGLISH_CODE = "en" FRENCH_CODE = "fr" CHINESE_CODE = "zh" DEFAULT_LANG_CODE = FRENCH_CODE SUPPORTED_LANG_CODES = ( FRENCH_CODE, CHINESE_CODE, ) def __init__(self, code, url, is_current): self.code = code self.url = url self.is_current = is_current @staticmethod def create_lang_url(redirect_url, lang_code): params = { "url" : redirect_url, "lang" : lang_code, } url = "/%s/lang/?%s" % ( Config.APP_NAME, urllib.urlencode(params)) return url @staticmethod def get_lang(request): try: lang_code = request.session.get(Language.LANG_SESSION_NAME, None) except AttributeError: lang_code = Language.DEFAULT_LANG_CODE return lang_code @staticmethod def set_lang(request, lang_code): try: request.session[Language.LANG_SESSION_NAME] = lang_code return True except AttributeError: return False #--------------------------------------------------------------------------------------------------- # Common functions #--------------------------------------------------------------------------------------------------- def get_common_data(request): # User info. user = get_current_user() if not user: log_url = create_login_url("%s/login_ok/%s" % ( Config.APP_NAME, request.path,)) log_text = "Login" is_admin = False else: log_url = create_logout_url("%s/login_ok/%s" % ( Config.APP_NAME, request.path,)) log_text = "Logout" is_admin = (user.email() in Config.ADMINS) # Language. current_lang_code = Language.get_lang(request) languages = [] for lang_code in Language.SUPPORTED_LANG_CODES: lang_url = Language.create_lang_url(request.path, lang_code) is_current = (lang_code == current_lang_code) languages.append(Language(lang_code, lang_url, is_current)) # Request meta info. http_referer = request.META.get("HTTP_REFERER", "unknown_http_referer") remote_addr = request.META.get("REMOTE_ADDR" , "unknown_remote_addr" ) remote_host = request.META.get("REMOTE_HOST" , "unknown_remote_host" ) # Return the common context dict. return { "user_" : user, "log_url_" : log_url, "log_text_" : log_text, "is_admin_" : is_admin, "languages_" : languages, "http_referer_" : http_referer, "remote_addr_" : remote_addr, "remote_host_" : remote_host, "static_" : Config.STATIC_PREFIX , "remaining_days" : (datetime.date(2013, 4, 18) - datetime.date.today()).days-1 , "LANGUAGES" : settings.LANGUAGES } #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Common URL mappings. # # Created on 2008-10-28. # $Id: urls.py 26 2009-08-04 22:06:00Z guolin.mobi $ # from django.conf.urls.defaults import patterns urlpatterns = patterns( "afcpweb.apps.common.views", ( r"^login_ok/(?P<url>.*)$" , "login_ok" ), ( r"^logout_ok/(?P<url>.*)$" , "logout_ok" ), ( r"^lang/$" , "change_language" ), # 404 not-found: must be the last URL pattern. ) urlpatterns += patterns( "afcpweb.apps.misc.views", ( r"^.*$" , "not_found" ), )
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # AFCP webapp global configurations. # # Created on 2008-10-28. # $Id: config.py 26 2009-08-04 22:06:00Z guolin.mobi $ # class Config(object): """This class contains constants for the AFCP webapp.""" APP_NAME = "common" STATIC_PREFIX = "/static" VERSION = "0.1" REVISION = "$Revision: 300 $" REVISED_DATE = "$Date: 2009-08-05 00:06:00 +0200 (10, 05 8 2009) $" ADMINS = ( "AFCParisTech[suffix]".replace("[suffix]", "@gmail.com"), "guolin.mobi[suffix]".replace("[suffix]", "@gmail.com"), "afcpweb[suffix]".replace("[suffix]", "@gmail.com") )
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com> # - http://heavyz.blogspot.com/ # - http://buggarden.blogspot.com/ # # Utility functions. # # Created on 2008-11-05. # $Id: utils.py 26 2009-08-04 22:06:00Z guolin.mobi $ # import logging import datetime import random from google.appengine.ext import db def munge_email(email): if email is not None: return email.replace("@", " (at) ") else: return None def demunge_email(munging_email): if munging_email is not None: return munging_email.replace(" (at) ", "@") else: return None def decode_utf8(string): return string.strip() def get_param(value_dict, name, default=None): value = decode_utf8(value_dict.get(name, "")) if len(value) == 0: return default else: return value def split_string(string): if string is not None: splitted = string.lower().replace(",", " ").replace(";", " ").split() else: splitted = [] return splitted def generate_random_id(prefix=""): timestamp = datetime.datetime.strftime(datetime.datetime.utcnow(), "%Y%m%d%H%M%S") suffix = "%x" % (random.random() * 65536) return (prefix + timestamp + suffix) #--------------------------------------------------------------------------------------------------- # EntityPage #--------------------------------------------------------------------------------------------------- class EntityPage(object): """ """ MIN_PER_PAGE = 1 MAX_PER_PAGE = 100 MIN_PAGE_RANGE = 0 MAX_PAGE_RANGE = 10 DEF_PAGE_RANGE = 5 def __init__(self, query, per_page, number=None, page_range=DEF_PAGE_RANGE): # Entity object count. self.object_count = query.count() # Entity objects per page. if per_page < EntityPage.MIN_PER_PAGE: self.per_page = EntityPage.MIN_PER_PAGE elif per_page > EntityPage.MAX_PER_PAGE: self.per_page = EntityPage.MAX_PER_PAGE else: self.per_page = per_page # First page number and last page number. self.first_page_number = 1 if self.object_count > 0: self.last_page_number = (self.object_count - 1) / self.per_page + 1 else: self.last_page_number = 1 # Current page number. try: if number is not None: self.number = int(number) else: self.number = 1 except ValueError: self.number = 1 if self.number < self.first_page_number: self.number = self.first_page_number elif self.number > self.last_page_number: self.number = self.last_page_number # Page range. if page_range < EntityPage.MIN_PAGE_RANGE: self.page_range = EntityPage.MIN_PAGE_RANGE elif page_range > EntityPage.MAX_PAGE_RANGE: self.page_range = EntityPage.MAX_PAGE_RANGE else: self.page_range = page_range # Entity object list. offset = (self.number - 1) * self.per_page self.object_list = query.fetch(self.per_page, offset) def has_previous(self): return (self.number > self.first_page_number) def previous_page_number(self): return (self.number - 1) def has_next(self): return (self.number < self.last_page_number) def next_page_number(self): return (self.number + 1) def previous_page_range(self): range_start_index = max( self.first_page_number, self.number - self.page_range ) range_end_index = self.number return range(range_start_index, range_end_index) def next_page_range(self): range_start_index = self.number + 1 range_end_index = min( self.last_page_number + 1, self.number + self.page_range + 1) return range(range_start_index, range_end_index) def is_first_page_in_range(self): return (self.first_page_number >= self.number - self.page_range) def is_last_page_in_range(self): return (self.last_page_number <= self.number + self.page_range)
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Common URL mappings. # # Created on 2008-10-28. # $Id: urls.py 26 2009-08-04 22:06:00Z guolin.mobi $ # from django.conf.urls.defaults import patterns urlpatterns = patterns( "afcpweb.apps.common.views", ( r"^login_ok/(?P<url>.*)$" , "login_ok" ), ( r"^logout_ok/(?P<url>.*)$" , "logout_ok" ), ( r"^lang/$" , "change_language" ), # 404 not-found: must be the last URL pattern. ) urlpatterns += patterns( "afcpweb.apps.misc.views", ( r"^.*$" , "not_found" ), )
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # afcpweb app commom actions. # # Created on 2008-10-28. # $Id: urls.py 26 2009-08-04 22:06:00Z guolin.mobi $ # import urllib from afcpweb.apps.common.config import Config from afcpweb.apps.members.models import get_current_user from afcpweb.apps.members.models import create_login_url from afcpweb.apps.members.models import create_logout_url import datetime from django.conf import settings #--------------------------------------------------------------------------------------------------- # Language class #--------------------------------------------------------------------------------------------------- class Language(object): LANG_SESSION_NAME = "django_language" ENGLISH_CODE = "en" FRENCH_CODE = "fr" CHINESE_CODE = "zh" DEFAULT_LANG_CODE = FRENCH_CODE SUPPORTED_LANG_CODES = ( FRENCH_CODE, CHINESE_CODE, ) def __init__(self, code, url, is_current): self.code = code self.url = url self.is_current = is_current @staticmethod def create_lang_url(redirect_url, lang_code): params = { "url" : redirect_url, "lang" : lang_code, } url = "/%s/lang/?%s" % ( Config.APP_NAME, urllib.urlencode(params)) return url @staticmethod def get_lang(request): try: lang_code = request.session.get(Language.LANG_SESSION_NAME, None) except AttributeError: lang_code = Language.DEFAULT_LANG_CODE return lang_code @staticmethod def set_lang(request, lang_code): try: request.session[Language.LANG_SESSION_NAME] = lang_code return True except AttributeError: return False #--------------------------------------------------------------------------------------------------- # Common functions #--------------------------------------------------------------------------------------------------- def get_common_data(request): # User info. user = get_current_user() if not user: log_url = create_login_url("%s/login_ok/%s" % ( Config.APP_NAME, request.path,)) log_text = "Login" is_admin = False else: log_url = create_logout_url("%s/login_ok/%s" % ( Config.APP_NAME, request.path,)) log_text = "Logout" is_admin = (user.email() in Config.ADMINS) # Language. current_lang_code = Language.get_lang(request) languages = [] for lang_code in Language.SUPPORTED_LANG_CODES: lang_url = Language.create_lang_url(request.path, lang_code) is_current = (lang_code == current_lang_code) languages.append(Language(lang_code, lang_url, is_current)) # Request meta info. http_referer = request.META.get("HTTP_REFERER", "unknown_http_referer") remote_addr = request.META.get("REMOTE_ADDR" , "unknown_remote_addr" ) remote_host = request.META.get("REMOTE_HOST" , "unknown_remote_host" ) # Return the common context dict. return { "user_" : user, "log_url_" : log_url, "log_text_" : log_text, "is_admin_" : is_admin, "languages_" : languages, "http_referer_" : http_referer, "remote_addr_" : remote_addr, "remote_host_" : remote_host, "static_" : Config.STATIC_PREFIX , "remaining_days" : (datetime.date(2013, 4, 18) - datetime.date.today()).days-1 , "LANGUAGES" : settings.LANGUAGES } #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com> # - http://heavyz.blogspot.com/ # - http://buggarden.blogspot.com/ # # Created on 2008-04-28 # $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $ #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Views for the global app. # # Created on 2008-10-28. # $Id: views.py 40 2010-03-08 23:05:09Z guolin.mobi $ # from django.http import HttpResponseRedirect from afcpweb.apps.members.models import get_current_user from afcpweb.apps.common import utils from afcpweb.apps.common.actions import Language def login_ok(request, url): try: profile = get_current_user().profile() if profile: profile.count_login() profile.put() except: pass return HttpResponseRedirect(url) def logout_ok(request, url): return HttpResponseRedirect(url) #--------------------------------------------------------------------------------------------------- # Change current language and logged-in/logged-out redirect #--------------------------------------------------------------------------------------------------- def change_language(request): "Change the current language." redirect_url = utils.get_param(request.REQUEST, "url" ) lang_code = utils.get_param(request.REQUEST, "lang") Language.set_lang(request, lang_code) return HttpResponseRedirect(redirect_url) #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # AFCP webapp global configurations. # # Created on 2008-10-28. # $Id: config.py 26 2009-08-04 22:06:00Z guolin.mobi $ # class Config(object): """This class contains constants for the AFCP webapp.""" APP_NAME = "common" STATIC_PREFIX = "/static" VERSION = "0.1" REVISION = "$Revision: 300 $" REVISED_DATE = "$Date: 2009-08-05 00:06:00 +0200 (10, 05 8 2009) $" ADMINS = ( "AFCParisTech[suffix]".replace("[suffix]", "@gmail.com"), "guolin.mobi[suffix]".replace("[suffix]", "@gmail.com"), "afcpweb[suffix]".replace("[suffix]", "@gmail.com") )
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Django settings for afcpweb project. # # Created on 2008-04-28 # $Id: settings.py 26 2009-08-04 22:06:00Z guolin.mobi $ # import os # importation du module de traduction de python en mode paresseux # pour pouvoir l'utiliser avec _ comme nom de fonction. from django.utils.translation import gettext_lazy as _ #ugettext = lambda s: s # If the webapp is deployed on localhost), set DEBUG to True; otherwise, set DEBUG to False. DEPLOYED_ON_LOCALHOST = os.environ.get("SERVER_NAME", "").startswith("localhost") # DEBUG = DEPLOYED_ON_LOCALHOST DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS # Google App Engine does not support Django models: # leave all DATABASE_* settings set to an empty string. DATABASE_ENGINE = "" DATABASE_NAME = "" DATABASE_USER = "" DATABASE_PASSWORD = "" DATABASE_HOST = "" DATABASE_PORT = "" # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = "Europe/Paris" # Language code for this installation. All choices can be found here: # http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes # http://blogs.law.harvard.edu/tech/stories/storyReader$15 #LANGUAGE_CODE = "en-us" LANGUAGE_CODE = "fr" SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True #USE_L10N = True LANGUAGES = ( ('fr', _('afficher en francais')), ('en', _('afficher en anglais')), ('zh', _('afficher en chinois')) # ('fr', ugettext('Français')), # ('en', ugettext('Anglais')), # ('zh', ugettext('Chinois')) ) DEFAULT_LANGUAGE = 1 # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = "" # URL that handles the media served from MEDIA_ROOT. # Example: "http://media.lawrence.com" MEDIA_URL = "" # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = "/media/" # Make this unique, and don't share it with anybody. SECRET_KEY = "*c(^-34)gdt8=g%3##=*apdl$!w8q-$4bc96+25!%2@%6-pj*q" # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( "django.template.loaders.filesystem.load_template_source", "django.template.loaders.app_directories.load_template_source", # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( # to use django with the NDB storage API (= base de données google) : #"google.appengine.ext.ndb.django_middleware.NdbDjangoMiddleware" "afcpweb.apps.middleware.sessions.SessionMiddleware", # "django.contrib.sessions.middleware.SessionMiddleware", # "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "afcpweb.apps.middleware.common.LogErrorMiddleware", # 'django.contrib.auth.middleware.AuthenticationMiddleware', "django.middleware.doc.XViewMiddleware", ) #TEMPLATE_CONTEXT_PROCESSORS = ( # "django.core.context_processors.i18n", #) ROOT_URLCONF = "afcpweb.urls" ROOT_PATH = os.path.dirname(__file__) TEMPLATE_DIRS = (os.path.normpath(os.path.join(os.path.dirname(__file__), "templates")),) # For serving static files. STATIC_DOC_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "static")) INSTALLED_APPS = ( "afcpweb", "afcpweb.apps", # "afcpweb.apps.activities", # "afcpweb.apps.afcp", "afcpweb.apps.admin", "afcpweb.apps.common", "afcpweb.apps.forum", "afcpweb.apps.members", "afcpweb.apps.misc", "afcpweb.apps.test", # "afcpweb.apps.temps", # 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', # 'django.contrib.sites', )
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Django settings for afcpweb project. # # Created on 2008-04-28 # $Id: settings.py 26 2009-08-04 22:06:00Z guolin.mobi $ # import os # importation du module de traduction de python en mode paresseux # pour pouvoir l'utiliser avec _ comme nom de fonction. from django.utils.translation import gettext_lazy as _ #ugettext = lambda s: s # If the webapp is deployed on localhost), set DEBUG to True; otherwise, set DEBUG to False. DEPLOYED_ON_LOCALHOST = os.environ.get("SERVER_NAME", "").startswith("localhost") # DEBUG = DEPLOYED_ON_LOCALHOST DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS # Google App Engine does not support Django models: # leave all DATABASE_* settings set to an empty string. DATABASE_ENGINE = "" DATABASE_NAME = "" DATABASE_USER = "" DATABASE_PASSWORD = "" DATABASE_HOST = "" DATABASE_PORT = "" # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = "Europe/Paris" # Language code for this installation. All choices can be found here: # http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes # http://blogs.law.harvard.edu/tech/stories/storyReader$15 #LANGUAGE_CODE = "en-us" LANGUAGE_CODE = "fr" SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True #USE_L10N = True LANGUAGES = ( ('fr', _('afficher en francais')), ('en', _('afficher en anglais')), ('zh', _('afficher en chinois')) # ('fr', ugettext('Français')), # ('en', ugettext('Anglais')), # ('zh', ugettext('Chinois')) ) DEFAULT_LANGUAGE = 1 # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = "" # URL that handles the media served from MEDIA_ROOT. # Example: "http://media.lawrence.com" MEDIA_URL = "" # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = "/media/" # Make this unique, and don't share it with anybody. SECRET_KEY = "*c(^-34)gdt8=g%3##=*apdl$!w8q-$4bc96+25!%2@%6-pj*q" # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( "django.template.loaders.filesystem.load_template_source", "django.template.loaders.app_directories.load_template_source", # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( # to use django with the NDB storage API (= base de données google) : #"google.appengine.ext.ndb.django_middleware.NdbDjangoMiddleware" "afcpweb.apps.middleware.sessions.SessionMiddleware", # "django.contrib.sessions.middleware.SessionMiddleware", # "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "afcpweb.apps.middleware.common.LogErrorMiddleware", # 'django.contrib.auth.middleware.AuthenticationMiddleware', "django.middleware.doc.XViewMiddleware", ) #TEMPLATE_CONTEXT_PROCESSORS = ( # "django.core.context_processors.i18n", #) ROOT_URLCONF = "afcpweb.urls" ROOT_PATH = os.path.dirname(__file__) TEMPLATE_DIRS = (os.path.normpath(os.path.join(os.path.dirname(__file__), "templates")),) # For serving static files. STATIC_DOC_ROOT = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "static")) INSTALLED_APPS = ( "afcpweb", "afcpweb.apps", # "afcpweb.apps.activities", # "afcpweb.apps.afcp", "afcpweb.apps.admin", "afcpweb.apps.common", "afcpweb.apps.forum", "afcpweb.apps.members", "afcpweb.apps.misc", "afcpweb.apps.test", # "afcpweb.apps.temps", # 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', # 'django.contrib.sites', )
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2008 ZHENG Zhong <heavyzheng nospam at gmail D0T com> # - http://heavyz.blogspot.com/ # - http://buggarden.blogspot.com/ # # Created on 2008-04-28 # $Id: __init__.py 26 2009-08-04 22:06:00Z guolin.mobi $ #
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # $Id: urls.py 26 2009-08-04 22:06:00Z guolin.mobi $ # # Django URL mappings. from django.conf.urls.defaults import patterns from django.conf.urls.defaults import include from django.contrib import admin admin.autodiscover() urlpatterns = patterns( "", # Sub-webapps in the bug garden. # ( r"^afcp/" , include("afcpweb.apps.afcp.urls") ), # ( r"^activities/" , include("afcpweb.apps.activities.urls") ), ( r"^test/" , include("afcpweb.apps.test.urls") ), # ( r"^admin/" , include("afcpweb.apps.admin.urls") ), # ( r"^admin/" , include(admin.site.urls) ), ( r"^common/" , include("afcpweb.apps.common.urls") ), # ( r"^forum/" , include("afcpweb.apps.forum.urls") ), # ( r"^members/" , include("afcpweb.apps.members.urls") ), # ( r"^temps/" , include("afcpweb.apps.temps.urls") ), # Forum pages ( r"^(?=.+/$)" , include("afcpweb.apps.forum.urls") ), # Top-level URL mappings. # ( r"^$" , "afcpweb.apps.forum.views.home" ), # ( r"^$" , "afcpweb.apps.misc.views.home" ), ( r"^$" , include("afcpweb.apps.forum.urls") ), # ( r"^$", "afcpweb.apps.misc.views.home" ), # ( r"^/*" , include("afcpweb.apps.forum.urls") ), # 404 not-found to catch all (this should always be the last URL pattern). ( r"^.*$/", "afcpweb.apps.misc.views.not_found"), )
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # $Id: urls.py 26 2009-08-04 22:06:00Z guolin.mobi $ # # Django URL mappings. from django.conf.urls.defaults import patterns from django.conf.urls.defaults import include from django.contrib import admin admin.autodiscover() urlpatterns = patterns( "", # Sub-webapps in the bug garden. # ( r"^afcp/" , include("afcpweb.apps.afcp.urls") ), # ( r"^activities/" , include("afcpweb.apps.activities.urls") ), ( r"^test/" , include("afcpweb.apps.test.urls") ), # ( r"^admin/" , include("afcpweb.apps.admin.urls") ), # ( r"^admin/" , include(admin.site.urls) ), ( r"^common/" , include("afcpweb.apps.common.urls") ), # ( r"^forum/" , include("afcpweb.apps.forum.urls") ), # ( r"^members/" , include("afcpweb.apps.members.urls") ), # ( r"^temps/" , include("afcpweb.apps.temps.urls") ), # Forum pages ( r"^(?=.+/$)" , include("afcpweb.apps.forum.urls") ), # Top-level URL mappings. # ( r"^$" , "afcpweb.apps.forum.views.home" ), # ( r"^$" , "afcpweb.apps.misc.views.home" ), ( r"^$" , include("afcpweb.apps.forum.urls") ), # ( r"^$", "afcpweb.apps.misc.views.home" ), # ( r"^/*" , include("afcpweb.apps.forum.urls") ), # 404 not-found to catch all (this should always be the last URL pattern). ( r"^.*$/", "afcpweb.apps.misc.views.not_found"), )
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2009-11-18. # $Id$ # from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter def mark_escape(value): return mark_safe(value) # EOF
Python