Get the node hierarchy

This is equivalent to the ls () function.

Sometimes you need to build a tree of objects in WX, But to create a tree, you need to know the nesting level of objects. Parsing the output of ls () is not the best option.

from direct.showbase.ShowBase import ShowBase

class MyApp(ShowBase):

    def __init__(self):
        ShowBase.__init__(self)

        # Model from the music-box example
        music_box = self.loader.loadModel("models/MusicBox")

        #music_box.ls()

        self.recursive(music_box)

    def recursive(self, path):
        global indent_level
        indent_level = 0 
        def childs(path):
            global indent_level
            print(' '*indent_level, str(path.node()).rstrip('\n'), sep='')
            for child in path.children:
                indent_level += 2
                childs(child)
            indent_level -= 2
        childs(path)

app = MyApp()
app.run()
2 Likes

Thanks, very useful!

This:

            if path.getNumChildren() != 0:
                for i in range(path.getNumChildren()):
                    indent_level += 2
                    childs(path.getChild(i))

can be simplified down to this equivalent code:

            for child in path.children:
                indent_level += 2
                childs(child)
2 Likes