Best Python code snippet using molecule_python
generate_pbr_textures.py
Source:generate_pbr_textures.py  
...747        else:748            slt = "EMIT"749        750        bpy.ops.node.link_bake_slots(bake_slots=self.bake_slot)751        bpy.ops.object.bake(type=slt)752        753        return {'FINISHED'}754755756class ConnectToBakeNode(bpy.types.Operator):757    """Connect the selected node to the bake node"""758    bl_idname = "node.pbr_bake_connect_to_bake_node"759    bl_label  = "Link selected node to bake node"760    bl_options = {"REGISTER", "UNDO"}761762763    bake_slots : bpy.props.EnumProperty(764        name = "Connect To Slot",765        items = bake_slots_input,
...TestBake.py
Source:TestBake.py  
1###############################################################################2# Copyright (c) 2013 INRIA3# 4# This program is free software; you can redistribute it and/or modify5# it under the terms of the GNU General Public License version 2 as6# published by the Free Software Foundation;7# 8# This program is distributed in the hope that it will be useful,9# but WITHOUT ANY WARRANTY; without even the implied warranty of10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the11# GNU General Public License for more details.12#13# You should have received a copy of the GNU General Public License14# along with this program; if not, write to the Free Software15# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA16#17# Authors: Daniel Camara  <daniel.camara@inria.fr>18#          Mathieu Lacage <mathieu.lacage@sophia.inria.fr>19###############################################################################20import unittest21# hack to save ourselves from having to use PYTHONPATH22import sys23import os24import commands25import re26from bake.Configuration import Configuration27from bake.ModuleSource import SystemDependency28from bake.ModuleEnvironment import ModuleEnvironment29from bake.ModuleLogger import StdoutModuleLogger30from bake.ModuleSource import ModuleSource31from bake.Exceptions import TaskError32from bake.Bake import Bake33sys.path.append(os.path.join (os.getcwd(), '..'))34def compensate_third_runner():35    """ Compensates the name of the file, if a third party program is36        inside eclipse."""37    fileName = sys.argv[0]38    if len(sys.argv) > 1:39        fileName = sys.argv[1]40    return fileName41class TestBake(unittest.TestCase):42    """Tests cases for the main Bake Class."""43           44    def setUp(self):45        """Common set Up environment, available for all tests."""46        pathname = os.path.dirname("/tmp/source/")  47        self._logger = StdoutModuleLogger();48        self._logger.set_verbose(1)49        self._env = ModuleEnvironment(self._logger, pathname, pathname, pathname)50#        testStatus = commands.getoutput('cp ' + pathname + '/bakefile.xml /tmp/.')51        testStatus = commands.getoutput('chmod 755 /tmp/source')52        testStatus = commands.getoutput('rm -rf /tmp/source')53        54    def tearDown(self):55        """Cleans the environment environment for the next tests."""56        self._env = None57        pathname = os.path.dirname("/tmp/source")  58#        pathname = os.path.dirname(compensate_third_runner())  59        testStatus = commands.getoutput('rm -f ' + pathname +'/bakefile.xml')60        testStatus = commands.getoutput('chmod 755 /tmp/source')61        testStatus = commands.getoutput('rm -rf /tmp/source')62        testStatus = commands.getoutput('mv bc.xml bakeconf.xml ')63        testStatus = commands.getoutput('mv bf.xml bakefile.xml ')64        testStatus = commands.getoutput('mv ~/.bakerc_saved ~/.bakerc')65    def test_simple_proceedings(self):66        """Tests a simple download and build of Bake. """67        mercurial = ModuleSource.create("mercurial")68        testResult = mercurial.check_version(self._env)69        self.assertTrue(testResult)70        mercurial.attribute("url").value = "http://code.nsnam.org/daniel/bake"71        self._env._module_name="bake"72        self._env._module_dir="bake"73        testStatus = commands.getoutput('rm -rf /tmp/source')74        self._logger.set_current_module(self._env._module_name)75        testResult = mercurial.download(self._env)76        self.assertFalse(testResult)77        testStatus = commands.getoutput('cd /tmp/source/bake;./bake.py configure -p ns3-min')78        self.assertEquals(testStatus, "", "Should have worked the download of the code")79        testStatus = commands.getoutput('cd /tmp/source/bake;./bake.py download')80        self.assertFalse("Problem" in testStatus, 81                        "Should have worked the download of the code")82        testStatus = commands.getoutput('cd /tmp/source/bake;./bake.py build')83        self.assertFalse("Problem" in testStatus, 84                        "Should have worked the build of the code")85  86 87    def test_read_resource_file(self):88        """Tests the _read_resource_file method of Class Bake."""89        90        configuration = Configuration("bakefile.xml")91        testStatus,testMessage = commands.getstatusoutput('mv ~/.bakerc ~/.bakerc_saved')92        self.assertTrue(testStatus==0 or testStatus==256,"Couldn't move the ressource file!")93        bake = Bake()94        95        testResult = bake._read_resource_file(configuration)96        self.assertFalse(testResult,"Shouldn't find a configuration!")97        98        testStatus = commands.getoutput('touch ~/.bakerc')99        testResult = bake._read_resource_file(configuration)100        self.assertFalse(testResult,"Configuration should be empty!")101        testStatus = commands.getoutput('cp ./bakeTest.rc ~/.bakerc')102        testResult = bake._read_resource_file(configuration)103        self.assertTrue(testResult[0].name=="my-ns3","Shouldn't find a configuration!")104        105        testStatus,testMessage = commands.getstatusoutput('mv ~/.bakerc_saved ~/.bakerc')106      107    def test_save_resource_configuration(self):108        """Tests the _save_resource_configuration method of Class Bake."""109        110        pathname = os.path.dirname(compensate_third_runner())  111        if not pathname:112            pathname="."113        testStatus = commands.getoutput('python ' + pathname + 114                                        '/../bake.py -f ./ttt.xml configure ' 115                                        '--enable=openflow-ns3 ' 116                                        '--sourcedir=/tmp/source ' 117                                        '--installdir=/tmp/source')118        configuration = Configuration("./ttt.xml")119        configuration.read()120        testStatus,testMessage = commands.getstatusoutput('mv ~/.bakerc ~/.bakerc_saved')121        self.assertTrue(testStatus==0 or testStatus==256,122                        "Couldn't move the resource file!")123        fileName = os.path.join(os.path.expanduser("~"), ".bakerc")124        testStatus,testMessage = commands.getstatusoutput('rm -rf ./ttt.xml')125        bake = Bake()126        127        testResult = bake._save_resource_configuration(configuration)128        self.assertFalse(testResult,"Should have write configuration!")129        self.assertTrue(os.path.isfile(fileName), "Didn't create the .bakerc file")130        fin = open(fileName, "r")131        string = fin.read()132        fin.close()133        self.assertTrue("last" in string, "Didn't save the last configuration")134        self.assertTrue("openflow-ns3" in string, 135                        "Didn't save the last configuration")136        137        testStatus = commands.getoutput('cp ./bakeTest.rc ~/.bakerc')138        fin = open(fileName, "r")139        string = fin.read()140        fin.close()141        self.assertFalse("last" in string, "Did find last in the configuration")142        143        testResult = bake._save_resource_configuration(configuration)144        self.assertFalse(testResult,"Should have write configuration!")145        self.assertTrue(os.path.isfile(fileName), "Didn't create the .bakerc file")146        fin = open(fileName, "r")147        string = fin.read()148        fin.close()149        self.assertTrue("<predefined name=\"last\">" in string, "Didn't save the last configuration")150        self.assertTrue("<enable name=\"openflow-ns3\"/>" in string, 151                        "Didn't save the last configuration")152        testStatus,testMessage = commands.getstatusoutput('mv ~/.bakerc_saved ~/.bakerc')153  154   155    def test_check_source_code(self):156        """Tests the _check_source_code method of Class Bake. """157        # Environment settings        158        mercurial = ModuleSource.create("mercurial")159        testResult = mercurial.check_version(self._env)160        self.assertTrue(testResult)161        162        pathname = os.path.dirname(compensate_third_runner())  163        if not pathname:164            pathname="."165        testStatus = commands.getoutput('python ' + pathname + 166                                        '/../bake.py configure ' 167                                        '--enable=openflow-ns3 ' 168                                        '--sourcedir=/tmp/source ' 169                                        '--installdir=/tmp/source')170        mercurial.attribute("url").value = "http://code.nsnam.org/bhurd/openflow"171        self._env._module_name="openflow-ns3"172        self._env._module_dir="openflow-ns3"173        testStatus = commands.getoutput('rm -rf /tmp/source')174        self._logger.set_current_module(self._env._module_name)175        testResult = mercurial.download(self._env)176        bake = Bake()177        config = "bakefile.xml" #bakefile.xml"178        args = []179        parser = bake._option_parser('build')180        parser.add_option('-j', '--jobs', 181                          help='Allow N jobs at once. Default is 1.',182                          type='int', action='store', dest='jobs', default=1)183        parser.add_option("--debug", action="store_true", 184                          dest="debug", default=True, 185                          help="Should we enable extra Bake debugging output ?")186        (options, args_left) = parser.parse_args(args)187#        bake.setMainOptions(options)188        Bake.main_options = options189        190        # Tests typical case, the module is there191        testResult = bake._check_source_code(config, options);192        self.assertEqual(testResult, None)193 194        # if the user has no permission to see the file195        testStatus = commands.getoutput('chmod 000 /tmp/source')196        testResult=None197        try:198            testResult = bake._check_source_code(config, options);199        except SystemExit as e:200            self.assertTrue(e.code==1,"Wrong error code received")201            202        self.assertFalse(testResult, None)    203        204        testStatus = commands.getoutput('chmod 755 /tmp/source')205           206        # if the folder is not where it should be207        testStatus = commands.getoutput('rm -rf /tmp/source')208        testResult=None209        try:210            testResult = bake._check_source_code(config, options);211        except SystemExit as e:212            self.assertTrue(e.code==1,"Wrong error code received")213            214        self.assertFalse(testResult, None)    215             216    def test_check_build_version(self):217        """Tests the _check_source_code method of Class Bake. """218        # Environment settings        219        # Environment settings        220        mercurial = ModuleSource.create("mercurial")221        testResult = mercurial.check_version(self._env)222        self.assertTrue(testResult)223        224        self._env._debug = True225        pathname = os.path.dirname(compensate_third_runner()) 226        if not pathname:227            pathname="."228 229        testStatus = commands.getoutput('python ' + pathname + 230                                        '/../bake.py configure' 231                                        ' --enable=openflow-ns3' 232                                        ' --sourcedir=/tmp/source' 233                                        ' --installdir=/tmp/source')234        mercurial.attribute("url").value = "http://code.nsnam.org/bhurd/openflow"235        self._env._module_name="openflow-ns3"236        self._env._module_dir="openflow-ns3"237        testStatus = commands.getoutput('rm -rf /tmp/source')238        self._logger.set_current_module(self._env._module_name)239        testResult = mercurial.download(self._env)240#        try:241#            testResult = mercurial.download(self._env)242#            self.fail("The directory does not exist, this shouldn't work")243#        except TaskError as e:244#            self.assertNotEqual(e._reason, None)    245#            self.assertEqual(testResult, None)246        247        bake = Bake()248        config = "bakefile.xml" #bakefile.xml"249        args = []250        parser = bake._option_parser('build')251        parser.add_option('-j', '--jobs', help='Allow N jobs at once. Default is 1.',252                          type='int', action='store', dest='jobs', default=1)253        parser.add_option("--debug", action="store_true", 254                          dest="debug", default=False, 255                          help="Should we enable extra Bake debugging output ?")256        (options, args_left) = parser.parse_args(args)257#        bake.setMainOptions(options)258        Bake.main_options = options259        260        # Tests typical case, the module is there and the object directory is not261        self._env._installdir = self._env.srcdir+"/install_bake"262        testResult = bake._check_build_version(config, options);263        self.assertEqual(testResult, None)264 265        # if the user has no permission to see the file266        testStatus = commands.getoutput('chmod 000 /tmp/source')267        testResult=None268        try:269            testResult = bake._check_source_code(config, options);270        except SystemExit as e:271            self.assertTrue(e.code==1,"Wrong error code received")272            273        self.assertFalse(testResult, None)    274        275        testStatus = commands.getoutput('chmod 755 /tmp/source')276           277        # if the folder is not where it should be278        testStatus = commands.getoutput('rm -rf /tmp/source')279        testResult=None280        testResult=None281        try:282            testResult = bake._check_source_code(config, options);283        except SystemExit as e:284            self.assertTrue(e.code==1,"Wrong error code received")285            286        self.assertFalse(testResult, None)    287    def test_check_configuration_file(self):288        """Tests the check_configuration_file method of Class Bake. """289        bakeInstance = Bake() 290        testResult = bakeInstance.check_configuration_file("strangeName")291        self.assertEqual(testResult, "strangeName", "New name is not respected")292        testResult = bakeInstance.check_configuration_file("bakeconf.xml")293        self.assertEqual(testResult, "bakeconf.xml", "Default file should"294                         " exist but it changed the name.")295        296        testStatus = commands.getoutput('mv bakeconf.xml bc.xml')297        testResult = bakeInstance.check_configuration_file("bakeconf.xml")298        self.assertTrue(testResult.endswith("bakeconf.xml"), "Should have"299                        " returned the bakeconf.xml but returned " + testResult)300#        testStatus = commands.getoutput('mv bakefile.xml bf.xml')301#        testStatus = commands.getoutput('mv bc.xml bakeconf.xml ')302#        testResult = bakeInstance.check_configuration_file("bakefile.xml", True)303#        self.assertTrue(testResult.endswith("bakeconf.xml"), "Should have"304#                        " returned the bakeconf but returned " + testResult)305        testStatus = commands.getoutput('mv bakeconf.xml bc.xml')306        testResult = bakeInstance.check_configuration_file("bakefile.xml")307        self.assertEqual(testResult, "bakefile.xml", "Default file should"308                         " be returned in the last case.")309        310        testStatus = commands.getoutput('mv bc.xml bakeconf.xml ')311        testStatus = commands.getoutput('mv bf.xml bakefile.xml ')312#     xmlVar = '<configuration> <modules> <module name="test1"> 313#    314#      <source type="mercurial">315#    <attribute name="url" value="http://code.nsnam.org/bake"/>316#      </source>317#      <build type="waf" objdir="yes">318#    <attribute name="configure_arguments" value="configure --prefix=$INSTALLDIR --enable-examples --enable-tests"/>319#      </build>320#  </module>321#322#    <module name="test2">323#      <source type="bazaar">324#    <attribute name="url" value="https://launchpad.net/pybindgen"/>325#    <attribute name="revision" value="revno:809"/>326#      </source>327#      <build type="waf" objdir="yes">328#    <attribute name="configure_arguments" value="configure --prefix=$INSTALLDIR"/>329#    <attribute name="build_arguments" value="--generate-version"/>330#      </build>331#      <depends_on name="test1" optional="False"/>332#    </module>333#334#    <module name="test3">335#      <source type="bazaar">336#    <attribute name="url" value="https://launchpad.net/pybindgen"/>337#    <attribute name="revision" value="revno:809"/>338#      </source>339#      <build type="waf" objdir="yes">340#    <attribute name="configure_arguments" value="configure --prefix=$INSTALLDIR"/>341#    <attribute name="build_arguments" value="--generate-version"/>342#      </build>343#      <depends_on name="test2" optional="True"/>344#      <depends_on name="pygccxml" optional="True"/>345#    </module>346#347#  </modules>348#349#</configuration>'350       351#    def test_dependencies(self):352#        """Tests the Dependencies mechanism of Bake. """353#        354#        configuration = Configuration("bakefile")355##        et = ET.parse(filename)356##        self._read_metadata(et)357#358#359#        testStatus = commands.getoutput('cp bakeconf.xml bc.xml ')360#        testStatus = commands.getoutput('cp bakefile.xml bf.xml ')361#362#        bake = Bake() 363#        config = "bakefile.xml" #bakefile.xml"364#        args = []365#        parser = bake._option_parser('install')366#        parser.add_option('-j', '--jobs', help='Allow N jobs at once. Default is 1.',367#                          type='int', action='store', dest='jobs', default=1)368#        parser.add_option("--debug", action="store_true", 369#                          dest="debug", default=False, 370#                          help="Should we enable extra Bake debugging output ?")371#        (options, args_left) = parser.parse_args(args)372#        Bake.main_options = options373#        374#        # Tests typical case, the module is there and the object directory is not375#        self._env._installdir = self._env.srcdir+"/install_bake"376#        testResult = bake._check_build_version(config, options);377#        self.assertEqual(testResult, None)378#379#380#        381#        testStatus = commands.getoutput('mv bc.xml bakeconf.xml ')382#        testStatus = commands.getoutput('mv bf.xml bakefile.xml ')383#       384    def test_systemReturnValues(self):385        """Tests the values get from the system point of view. """386        self._env._debug = True387        pathname = os.path.dirname(compensate_third_runner()) 388        if not pathname:389            pathname="."390 391        commandTmp = ('%s/../bake.py -f /tmp/myconf.xml configure -c %s/../bakeconf.xml --enable=openflow-ns3' 392        ' --sourcedir=/tmp/source' 393        ' --installdir=/tmp/source' %(pathname, pathname))394        (status, output) = commands.getstatusoutput(commandTmp)    395        (status, output) = commands.getstatusoutput('python ' + pathname + 396                                        '/../bake.py --debug download -vvv')397        self.assertFalse(status==0, 'Wrong system status return.')398        399#        (status, output) = commands.getstatusoutput('python ' + pathname + 400#                                        '/../bake.py --debug download -vvv --sudo')401#        self.assertTrue(status==0, 'Wrong system status return.')402    403        (status, output) = commands.getstatusoutput('python ' + pathname + 404                                        '/../bake.py build')405        self.assertTrue(status!=0, 'Wrong system status return.')    406        407    def test_printTree(self):408        """Tests tree visualization mechanism. """409        410        first = dict()411        second = dict()412        third = dict()413        bake = Bake()414        415        mainDep = {'first': first, 'second':second, 'third': third}416        417        keys = bake.deptree(mainDep, mainDep, 'main', dict(), ' ')418        self.assertTrue(keys!=None, 'Error during tree processing')    419        self.assertTrue(len(mainDep)>0, 'Error during tree processing')420        self.assertTrue(keys=='main/third.second.first.', 'Error during tree processing')421        first={'second':True}422        second={'third':True}423        mainDep = {'first': first, 'second':second, 'third': third}424        keys = bake.deptree(mainDep, mainDep, 'main', dict(), ' ')425        self.assertTrue(keys!=None, 'Error during tree processing')    426        self.assertTrue(len(mainDep)>0, 'Error during tree processing')427        self.assertTrue(keys=='main/third.first/second/third.second/third.')428        # One more level429        fourth = dict()430        second={'third':True, 'fourth':True}431        mainDep = {'first': first, 'second':second, 'third': third,'fourth':fourth};432        keys = bake.deptree(mainDep, mainDep, 'main', dict(), ' ')433        self.assertTrue(keys!=None, 'Error during tree processing')    434        self.assertTrue(len(mainDep)>0, 'Error during tree processing')435        self.assertTrue(keys=='main/third.fourth.first/second/third.fourth.second/third.fourth.')436        # the loops437        # simple to self438        first={'first':True}439        mainDep = {'first': first}440        keys = bake.deptree(mainDep, mainDep, 'main', dict(), ' ')441        self.assertTrue(keys!=None, 'Error during tree processing')    442        self.assertTrue(len(mainDep)>0, 'Error during tree processing')443        self.assertTrue(keys== 'main/first/> Cyclic Dependency.')444        # two levels loop445        first={'second':True}446        second={'first':True}447        mainDep = {'first': first, 'second':second};448        keys = bake.deptree(mainDep, mainDep, 'main', dict(), ' ')449        self.assertTrue(keys!=None, 'Error during tree processing')    450        self.assertTrue(len(mainDep)>0, 'Error during tree processing')451        self.assertTrue(keys== 'main/first/second/> Cyclic Dependency.'452                        'second/first/> Cyclic Dependency.')453        # the same as before, but now with loop454        second={'third':True, 'first':first}455        mainDep = {'first': first, 'second':second, 'third': third}456        keys = bake.deptree(mainDep, mainDep, 'main', dict(), ' ')457        self.assertTrue(keys!=None, 'Error during tree processing')    458        self.assertTrue(len(mainDep)>0, 'Error during tree processing')459        self.assertTrue(keys==460                        'main/third.first/second/third.> Cyclic Dependency.'461                        'second/third.first/> Cyclic Dependency.')462        # multyLayer loop463        fourth = {'first':True}464        third = {'second':True}465        second={'third':True, 'fourth':True}466        mainDep = {'first': first, 'second':second, 'third': third,'fourth':fourth}467        keys = bake.deptree(mainDep, mainDep, 'main', dict(), ' ')468        self.assertTrue(keys!=None, 'Error during tree processing')    469        self.assertTrue(len(mainDep)>0, 'Error during tree processing')470        self.assertTrue(keys=='main/first/second/fourth/> Cyclic'471                        ' Dependency.third/> Cyclic Dependency.fourth/first/second/>'472                        ' Cyclic Dependency.third/> Cyclic '473                        'Dependency.second/fourth/first/> Cyclic '474                        'Dependency.third/> Cyclic Dependency.third/second/fourth/first/>'475                        ' Cyclic Dependency.> Cyclic Dependency.')476        477    def test_printDependencies(self):478        """Tests the print of dependencies mechanism. """479        480        bake = Bake()481        first = SystemDependency()482        first.attribute('dependency_test').value ='passwd'483        first.attribute('more_information').value ='Missing the required dependency'484        first.attribute('name_apt-get').value = 'libpcap-dev'485        first.attribute('name_yum').value = 'libpcap-devel'486       487        mainDep = {'passwd': first};488        returnValue = bake.showSystemDependencies(mainDep, 'bakeconf.xml')489        self.assertTrue(returnValue!=None, 'Error during dependencies processing')    490        self.assertTrue(returnValue=='passwd')491        492        first.attribute('dependency_test').value ='nononononononononon'493        494        mainDep = {'nononononononononon': first}495        returnValue=None496        try:497            returnValue = bake.showSystemDependencies(mainDep, 'bakeconf.xml')498            self.fail("Should have stoped")499        except SystemExit as e: 500            self.assertTrue(returnValue==None, 'Error during dependencies processing')    501         502        second = SystemDependency()503        second.attribute('dependency_test').value ='passwd'504        second.attribute('more_information').value ='Has not the required dependency'505        mainDep = {'nononononononononon': first, 'passwd':second}506        returnValue=None507        try:508            returnValue = bake.showSystemDependencies(mainDep, 'bakeconf.xml')509            self.fail("Should have stoped")510        except SystemExit as e: 511            self.assertTrue(returnValue==None, 'Error during dependencies processing')    512 513# main call for the tests        514if __name__ == '__main__':...ml_worldBake.py
Source:ml_worldBake.py  
1# -= ml_worldBake.py =-2#                __   by Morgan Loomis3#     ____ ___  / /  http://morganloomis.com4#    / __ `__ \/ /  Revision 155#   / / / / / / /  2018-07-186#  /_/ /_/ /_/_/  _________7#               /_________/8# 9#     ______________10# - -/__ License __/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 11# 12# Copyright 2018 Morgan Loomis13# 14# Permission is hereby granted, free of charge, to any person obtaining a copy of 15# this software and associated documentation files (the "Software"), to deal in 16# the Software without restriction, including without limitation the rights to use, 17# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the 18# Software, and to permit persons to whom the Software is furnished to do so, 19# subject to the following conditions:20# 21# The above copyright notice and this permission notice shall be included in all 22# copies or substantial portions of the Software.23# 24# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 25# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 26# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 27# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 28# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 29# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.30# 31#     ___________________32# - -/__ Installation __/- - - - - - - - - - - - - - - - - - - - - - - - - - 33# 34# Copy this file into your maya scripts directory, for example:35#     C:/Documents and Settings/user/My Documents/maya/scripts/ml_worldBake.py36# 37# Run the tool in a python shell or shelf button by importing the module, 38# and then calling the primary function:39# 40#     import ml_worldBake41#     ml_worldBake.ui()42# 43# 44#     __________________45# - -/__ Description __/- - - - - - - - - - - - - - - - - - - - - - - - - - - 46# 47# Temporarily bake animation to locators in world (or custom) space. Use this48# tool to preserve the worldspace position of animation when you need to make49# positional changes to an object's parent.50# 51#     ____________52# - -/__ Usage __/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 53# 54# Run the tool, select the objects, then press the "To Locators" button. When55# you're ready to bake back, select the locators and press the "From Locators"56# button. Checking "Bake on Ones" will bake every frame, otherwise the keytimes57# will be derived from the original animation.58# 59#     _________60# - -/__ Ui __/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 61# 62# [Bake Selection To Locators] : Bake selected object to locators specified space.63# [Bake Selected Locators Back To Objects] : Bake from selected locators back to their source objects.64# [Re-Parent Animated] : Parent all selected nodes to the last selection.65# [Un-Parent Animated] : Parent all selected to world.66# [Bake Selected] : Bake from the first selected object directly to the second.67# [Bake Selected With Offset] : Bake from the first selected object directly to the second, maintaining offset.68# 69#     ___________________70# - -/__ Requirements __/- - - - - - - - - - - - - - - - - - - - - - - - - - 71# 72# This script requires the ml_utilities module, which can be downloaded here:73#     https://raw.githubusercontent.com/morganloomis/ml_tools/master/ml_utilities.py74# 75#                                                             __________76# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /_ Enjoy! _/- - -77__author__ = 'Morgan Loomis'78__license__ = 'MIT'79__revision__ = 1580__category__ = 'animation'81from functools import partial82import maya.cmds as mc83from maya import OpenMaya84try:85    import ml_utilities as utl86    utl.upToDateCheck(32)87except ImportError:88    result = mc.confirmDialog( title='Module Not Found', 89                message='This tool requires the ml_utilities module. Once downloaded you will need to restart Maya.', 90                button=['Download Module','Cancel'], 91                defaultButton='Cancel', cancelButton='Cancel', dismissString='Cancel' )92    93    if result == 'Download Module':94        mc.showHelp('http://morganloomis.com/tool/ml_utilities/',absolute=True)95def ui():96    '''97    User interface for world bake98    '''99    with utl.MlUi('ml_worldBake', 'World Bake', width=400, height=175, info='''Select objects, bake to locators in world, camera, or custom space.100When you're ready to bake back, select locators101and bake "from locators" to re-apply your animation.''') as win:102        mc.checkBoxGrp('ml_worldBake_bakeOnOnes_checkBox',label='Bake on Ones',103                       annotation='Bake every frame. If deselected, the tool will preserve keytimes.')104        tabs = mc.tabLayout()105        tab1 = mc.columnLayout(adj=True)106        mc.radioButtonGrp('ml_worldBake_space_radioButton', label='Bake To Space', numberOfRadioButtons=3,107                          labelArray3=('World','Camera','Last Selected'), select=1,108                          annotation='The locators will be parented to world, the current camera, or the last selection.')109        mc.checkBoxGrp('ml_worldBake_constrain_checkBox',label='Maintain Constraints',110                       annotation='Constrain source nodes to the created locators, after baking.')111        win.ButtonWithPopup(label='Bake Selection To Locators', command=toLocators, annotation='Bake selected object to locators specified space.',112            readUI_toArgs={'bakeOnOnes':'ml_worldBake_bakeOnOnes_checkBox',113                           'spaceInt':'ml_worldBake_space_radioButton',114                           'constrainSource':'ml_worldBake_constrain_checkBox'},115            name=win.name)#this last arg is temp..116        mc.setParent('..')117        tab2 = mc.columnLayout(adj=True)118        win.ButtonWithPopup(label='Bake Selected Locators Back To Objects', command=fromLocators, annotation='Bake from selected locators back to their source objects.',119            readUI_toArgs={'bakeOnOnes':'ml_worldBake_bakeOnOnes_checkBox'}, name=win.name)#this last arg is temp..120        mc.setParent('..')121        tab3 = mc.columnLayout(adj=True)122        win.ButtonWithPopup(label='Re-Parent Animated', command=reparent, annotation='Parent all selected nodes to the last selection.',123            readUI_toArgs={'bakeOnOnes':'ml_worldBake_bakeOnOnes_checkBox'}, name=win.name)124        win.ButtonWithPopup(label='Un-Parent Animated', command=unparent, annotation='Parent all selected to world.',125            readUI_toArgs={'bakeOnOnes':'ml_worldBake_bakeOnOnes_checkBox'}, name=win.name)126        mc.separator()127        mc.checkBoxGrp('ml_worldBake_maintainOffset_checkBox',label='Maintain Offset',128                       annotation='Maintain the offset between nodes, rather than snapping.')129        win.ButtonWithPopup(label='Bake Selected', command=utl.matchBake, annotation='Bake from the first selected object directly to the second.',130            readUI_toArgs={'bakeOnOnes':'ml_worldBake_bakeOnOnes_checkBox',131                           'maintainOffset':'ml_worldBake_maintainOffset_checkBox'}, name=win.name)132        mc.tabLayout( tabs, edit=True, tabLabel=((tab1, 'Bake To Locators'), (tab2, 'Bake From Locators'), (tab3, 'Bake Selection')) )133#        win.ButtonWithPopup(label='Bake Selected With Offset', command=matchBake, annotation='Bake from the first selected object directly to the second, maintaining offset.',134#            readUI_toArgs={'bakeOnOnes':'ml_worldBake_bakeOnOnes_checkBox'}, name=win.name)#this last arg is temp..135def toLocators(bakeOnOnes=False, space='world', spaceInt=None, constrainSource=False):136    '''137    Creates locators, and bakes their position to selection.138    Creates connections to the source objects, so they can139    be found later to bake back.140    '''141    if spaceInt and 0 <= spaceInt <= 2:142        space = ['world', 'camera', 'last'][spaceInt]143    sel = mc.ls(sl=True)144    parent = None145    if space == 'camera':146        parent = utl.getCurrentCamera()147    elif space == 'last':148        parent = sel[-1]149        sel = sel[:-1]150    mc.select(sel)151    matchBakeLocators(parent=parent, bakeOnOnes=bakeOnOnes, constrainSource=constrainSource)152def fromLocators(bakeOnOnes=False):153    '''154    Traces connections from selected locators to their source nodes, and155    bakes their position back.156    Arguments:157        bakeOnOnes :: Bool :: Preserve the original keytimes from the locator.158    '''159    #get neccesary nodes160    objs = mc.ls(sl=True)161    if not objs:162        OpenMaya.MGlobal.displayWarning('Select a previously baked locator.')163        return164    source = list()165    destination = list()166    for src in objs:167        try:168            dest = mc.listConnections(src+'.ml_bakeSource',destination=False)[0]169            if dest:170                source.append(src)171                destination.append(dest)172        except Exception:173            pass174    if not destination:175        OpenMaya.MGlobal.displayWarning('Select a previously baked locator.')176        return177    #delete constraints on destination nodes178    for each in destination:179        constraints = mc.listConnections(each, source=True, destination=False, type='constraint')180        if constraints:181            try:182                mc.delete(constraints)183            except Exception:184                pass185    utl.matchBake(source, destination, bakeOnOnes=bakeOnOnes)186    for each in source:187        mc.delete(each)188def matchBakeLocators(parent=None, bakeOnOnes=False, constrainSource=False):189    #get neccesary nodes190    objs = mc.ls(sl=True)191    if not objs:192        OpenMaya.MGlobal.displayWarning('Select an Object')193        return194    locs = list()195    cutIndex = dict()196    noKeys = list()197    noKeysLoc = list()198    for obj in objs:199        name = mc.ls(obj, shortNames=True)[0]200        if ':' in name:201            name = obj.rpartition(':')[-1]202        locator = mc.spaceLocator(name='worldBake_'+name+'_#')[0]203        mc.setAttr(locator+'.rotateOrder', 3)204        mc.addAttr(locator, longName='ml_bakeSource', attributeType='message')205        mc.connectAttr('.'.join((obj,'message')), '.'.join((locator,'ml_bakeSource')))206        mc.addAttr(locator, longName='ml_bakeSourceName', dataType='string')207        mc.setAttr('.'.join((locator,'ml_bakeSourceName')), name, type='string')208        if parent:209            locator = mc.parent(locator, parent)[0]210        locs.append(locator)211        #should look through all trans and rot212        if not mc.keyframe(obj, query=True, name=True):213            noKeys.append(obj)214            noKeysLoc.append(locator)215    utl.matchBake(objs, locs, bakeOnOnes=bakeOnOnes)216    if not bakeOnOnes and noKeys:217        utl.matchBake(noKeys, noKeysLoc, bakeOnOnes=True)218    if constrainSource:219        mc.cutKey(objs)220        for loc, obj in zip(locs, objs):221            mc.parentConstraint(loc, obj)222def reparent(bakeOnOnes=False):223    objs = mc.ls(sl=True)224    if not objs or len(objs) < 2:225        OpenMaya.MGlobal.displayWarning('Select one or more nodes, followed by the new parent.')226        return227    parentBake(objs[:-1], objs[-1], bakeOnOnes=bakeOnOnes)228def unparent(bakeOnOnes=False):229    objs = mc.ls(sl=True)230    if not objs:231        OpenMaya.MGlobal.displayWarning('Select one or more nodes to unparent.')232        return233    parentBake(objs, bakeOnOnes=bakeOnOnes)234def parentBake(objs, parent=None, bakeOnOnes=False):235    #check objects can be parented236    parentReferenced = mc.referenceQuery(parent, isNodeReferenced=True) if parent else False237    culledObjs = []238    for each in objs:239        eachParent = mc.listRelatives(each, parent=True)240        if mc.referenceQuery(each, isNodeReferenced=True):241            if parentReferenced:242                OpenMaya.MGlobal.displayWarning("Child and parent are both referenced, skipping: {} > {}".format(each, parent))243                continue244            if eachParent and mc.referenceQuery(eachParent[0], isNodeReferenced=True):245                OpenMaya.MGlobal.displayWarning("Node is referenced and can't be reparented, skipping: {}".format(each))246                continue247        if not parent and not eachParent:248            OpenMaya.MGlobal.displayWarning("Node is already child of the world, skipping: {}".format(each))249            continue250        culledObjs.append(each)251    if not culledObjs:252        OpenMaya.MGlobal.displayWarning("No nodes could be reparented.")253        return254    source = []255    destination = []256    for each in culledObjs:257        source.append(mc.duplicate(each, parentOnly=True)[0])258        mc.copyKey(each)259        mc.pasteKey(source[-1], option='replaceCompletely')260        try:261            if parent:262                destination.append(mc.parent(each, parent)[0])263            else:264                destination.append(mc.parent(each, world=True)[0])265        except RuntimeError as err:266            mc.delete(source)267            raise err268    utl.matchBake(source=source, destination=destination, bakeOnOnes=bakeOnOnes)269    mc.delete(source)270def mm_matchLocators(*args):271    matchBakeLocators()272def mm_matchLocatorsOnes(*args):273    matchBakeLocators(bakeOnOnes=True)274def mm_fromLocators(*args):275    fromLocators()276def mm_reparent(*args):277    reparent()278def mm_unparent(*args):279    unparent()280def markingMenu():281    menuKwargs = {'enable':True,282                  'subMenu':False,283                  'enableCommandRepeat':True,284                  'optionBox':False,285                  'boldFont':True}286    mc.menuItem(radialPosition='N', label='Bake To Locators', command=mm_matchLocators, **menuKwargs)287    mc.menuItem(radialPosition='NW', label='Bake To Locators (Ones)', command=mm_matchLocatorsOnes, **menuKwargs)288    mc.menuItem(radialPosition='W', label='Bake From Locators', command=mm_fromLocators, **menuKwargs)289    mc.menuItem(radialPosition='E', label='Re-Parent', command=mm_reparent, **menuKwargs)290    mc.menuItem(radialPosition='S', label='Un-Parent', command=mm_unparent, **menuKwargs)291    mc.menuItem(label='World Bake UI', command=ui, **menuKwargs)292if __name__ == '__main__':293    #matchBakeLocators(constrainSource=True)294    ui()295#      ______________________296# - -/__ Revision History __/- - - - - - - - - - - - - - - - - - - - - - - -297#298# Revision 1: : First publish299#300# Revision 6: : Updated to use ml_utilities. Changed from direct constraint to constrained duplicate node.301#302# Revision 7: 2011-05-13 : fixed a bug with transferring certain types of tangents.303#304# Revision 8: 2011-05-14 : fixed error baking things with transforms locked or hidden305#306# Revision 9: 2012-06-13 : fixing duplicate name bug, adding more error checking.307#308# Revision 10: 2012-11-15 : Converting UI to tabs, adding camera and explicit options.309#310# Revision 11: 2014-03-01 : adding category311#312# Revision 12: 2015-05-14 : Baking broken out and moved to ml_utilities313#314# Revision 13: 2018-02-17 : Updating license to MIT.315#316# Revision 14: 2018-06-27 : parenting options and marking menu317#...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
