Esempio n. 1
0
    def inter_ui(self):
        ui = lwsdk.LWPanels()
        panel = ui.create('Random Number')
        panel.setw(300)

        interval_control = panel.float_ctl('Change interval (seconds)')
        interval_control.set_float(self._change_interval)

        # 'width' for dir_ctl() is in characters, not pixels!
        path_control = panel.dir_ctl('Object path', 50)
        if len(self._object_path):
            path_control.set_str(self._object_path)
        path_control.set_event(self, self.path_callback)

        self._controls = [interval_control, path_control]

        panel.align_controls_vertical(self._controls)
        panel.size_to_layout(5, 5)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL):
            self._change_interval = interval_control.get_float()
            path = path_control.get_str()
            if not os.path.exists(path):
                lwsdk.LWMessageFuncs().error('The provided path',
                                             'is invalid!')
            else:
                self._object_path = path

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 2
0
    def process(self, generic_access):
        self.tree_root = TreeNode("root")
        self.tree_root.children.append(TreeNode("Item 1"))
        self.tree_root.children[-1].children.append(TreeNode("Child 1-1"))
        self.tree_root.children[-1].children[-1].children.append(
            TreeNode("Child 1-1-1"))
        self.tree_root.children[-1].children[-1].children.append(
            TreeNode("Child 1-1-2"))
        self.tree_root.children[-1].children[-1].children[-1].children.append(
            TreeNode("Child 1-1-2-1"))
        self.tree_root.children.append(TreeNode("Item 2"))
        self.tree_root.children.append(TreeNode("Item 3"))
        self.tree_root.children[-1].children.append(TreeNode("Child 3-1"))

        ui = lwsdk.LWPanels()
        panel = ui.create('Test Tree')

        c1 = panel.tree_ctl('Tree', 200, 200, self.tree_info_func,
                            self.tree_count_func, self.tree_node_func)
        c1.set_event(self.tree_event_func)  # note: no event data

        panel.align_controls_vertical([c1])
        panel.size_to_layout(5, 5)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 3
0
    def process(self, mod_command):
        ui = lwsdk.LWPanels()
        panel = ui.create('Subtract Weight')
        c = panel.listbox_ctl('Base Map', 300, 16, self.name_items,
                              self.count_items)

        panel.align_controls_vertical([c])
        panel.size_to_layout(1, 1)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK
        self._base = lwsdk.LWObjectFuncs().vmapName(lwsdk.LWVMAP_WGHT,
                                                    c.get_int())
        print('listed base weight: %s' % self._base)

        ui.destroy(panel)
        selname, selid = lwsdk.LWStateQueryFuncs().vmap(lwsdk.LWM_VMAP_WEIGHT)
        self._target = selname
        print('selected weight map id: %d' % selid)
        print('selected weight map name: %s' % selname)

        op = mod_command.editBegin(0, 0, lwsdk.OPSEL_USER)
        if not op:
            print >> sys.stderr, 'failed to editBegin'
            return lwsdk.AFUNC_OK

        result = lwsdk.EDERR_NONE
        try:
            selpoints = []
            result = op.fastPointScan(op.state, self.fast_point_scan,
                                      (selpoints, ), lwsdk.OPLYR_FG, 1)
            if result != lwsdk.EDERR_NONE:
                op.done(op.state, result, 0)
                return lwsdk.AFUNC_OK
            print('selected points: %d' % len(selpoints))
            #selpoints = op.genPoints(op.state, lwsdk.OPLYR_FG, 1)
            for p in selpoints:
                # get base value
                op.vMapSelect(op.state, self._base, lwsdk.LWVMAP_WGHT, 1)
                b = op.pointVGet(op.state, p)[1]
                print('pt:%d' % p)
                if (b != None):
                    print('w(B):%f' % b)
                # get target value
                op.vMapSelect(op.state, self._target, lwsdk.LWVMAP_WGHT, 1)
                v = op.pointVGet(op.state, p)[1]
                if (v != None):
                    print('w(A):%f' % v)
                if (b != None):
                    v = 1.0 - b
                else:
                    v = 1.0
                op.pntVMap(op.state, p, lwsdk.LWVMAP_WGHT, self._target, [v])
        except:
            result = lwsdk.EDERR_USERABORT
            raise
        finally:
            op.done(op.state, result, 0)
        return lwsdk.AFUNC_OK
Esempio n. 4
0
    def inter_ui(self):
        global object_path

        ui = lwsdk.LWPanels()
        panel = ui.create('Frame Timer')
        panel.setw(300)

        # 'width' for dir_ctl() is in characters, not pixels!
        self._path_control = panel.dir_ctl('Object path', 50)
        if len(object_path):
            self._path_control.set_str(object_path)
        self._path_control.set_event(self, self.path_callback)

        panel.size_to_layout(5, 5)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL):
            path = self._path_control.get_str()
            if not os.path.exists(path):
                lwsdk.LWMessageFuncs().error('The provided path',
                                             'is invalid!')
            else:
                object_path = path

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 5
0
    def inter_ui(self):
        ui = lwsdk.LWPanels()
        panel = ui.create('Lazy Points')
        panel.setw(200)

        lag_control = panel.float_ctl('Lag rate')
        lag_control.set_float(self._lag_rate)

        spin_control = panel.hdragbut_ctl('')

        # The second 'data' argument is optional, and will be set to None if omitted.
        spin_control.set_event(self.drag_callback)

        # instead of calling a class method, you can use a stand-alone function
        #  spin_control.set_event(drag_standalone, self)

        self._controls = [lag_control, spin_control]
        panel.align_controls_horizontal(self._controls)

        self._drag_accumulate = 0

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL):
            self._lag_rate = lag_control.get_float()

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 6
0
    def inter_ui(self):
        ui = lwsdk.LWPanels()
        panel = ui.create('Noisy Channel')
        panel.setw(150)

        offset_control = panel.float_ctl('Offset')
        offset_control.set_float(self._offset)

        speed_control = panel.float_ctl('Speed')
        speed_control.set_float(self._speed)

        scale_control = panel.float_ctl('Scale')
        scale_control.set_float(self._scale)

        phase_control = panel.float_ctl('Phase')
        phase_control.set_float(self._phase)

        self._controls = [
            offset_control, speed_control, scale_control, phase_control
        ]
        panel.align_controls_vertical(self._controls)
        #panel.size_to_layout(5, 5)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL):
            self._offset = offset_control.get_float()
            self._speed = speed_control.get_float()
            self._scale = scale_control.get_float()
            self._phase = phase_control.get_float()

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 7
0
    def process(self, mod_command):
        self.read_history()

        ui = lwsdk.LWPanels()
        panel = ui.create('Select layers by string ' + __version__ + ' - ' +
                          __copyright__)

        self.text_string = panel.str_ctl("String", 50)
        self.hchoice_contains = panel.hchoice_ctl(
            "Select FG Layer", ('Contains string', 'Not contains string'))
        self.bool_others = panel.bool_ctl("Select others as BG Layer")
        self.bool_sort_history = panel.bool_ctl(
            "Move the last condition up if they match")
        self.list_history = panel.multilist_ctl('History', 450, 10,
                                                self.nameCallback,
                                                self.countCallback,
                                                self.columnCallback)
        self.button_remove = panel.button_ctl("Remove")
        self.button_remove.ghost()

        self.list_history.set_select(self.selectCallback)
        self.button_remove.set_event(self.remove_history)

        self.set_default_values()

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)

            return lwsdk.AFUNC_OK

        history = HistoryData()
        history.string = self.text_string.get_str()
        history.select_contains = not self.hchoice_contains.get_int()
        history.select_others = self.bool_others.get_int()

        self.last_string = history.string
        self.last_select_contains = history.select_contains
        self.last_others = history.select_others
        self.sort_history = self.bool_sort_history.get_int()

        self.add_history(history)
        self.write_history()

        try:
            self.select_layers(mod_command, history)

        except NoForegroundLayer:
            message_funcs = lwsdk.LWMessageFuncs()
            message_funcs.error('No foreground layer', '')

        finally:
            return lwsdk.AFUNC_OK

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 8
0
    def process(self, generic_access):
        ui = lwsdk.LWPanels()
        panel = ui.create('Test Multilist')

        c1 = panel.multilist_ctl('Multilist', 200, 10, self.name_2d, self.count_2d, self.column_width)
        c1.set_select(self.multi_select_event_func)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_RESIZE) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 9
0
    def process(self, generic_access):
        ui = lwsdk.LWPanels()
        panel = ui.create('Test Custom Popup')

        self._c1 = panel.custpopup_ctl('Custom Popup', 200, self.name_1d, self.count_1d)
        self._c1.set_event(self.popup_event)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 10
0
    def process(self, generic_access):
        ui = lwsdk.LWPanels()
        panel = ui.create('Test Listbox')

        c1 = panel.listbox_ctl('Listbox', 200, 10, self.name_1d, self.count_1d)
        c1.set_select(self.single_select_event_func)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_RESIZE) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 11
0
    def process(self, mod_command):
        ui = lwsdk.LWPanels()
        panel = ui.create(RESOURCE % 'Test Multilist Control')

        c1 = panel.multilist_ctl(RESOURCE % 'Multilist', 200, 10,
                                 self.nameCallback, self.countCallback,
                                 self.columnCallback)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 12
0
    def process(self, generic_access):
        ui = lwsdk.LWPanels()
        panel = ui.create('Test Text')

        c1 = panel.text_ctl(
            'Text', ['Static text 1', 'Static text 1', 'Static text 1'])

        panel.align_controls_vertical([c1])
        panel.size_to_layout(5, 5)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_RESIZE) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 13
0
    def inter_ui(self):
        global scale_choice

        ui = lwsdk.LWPanels()
        panel = ui.create('Sol')
        panel.setw(200)

        scale_control = panel.wpopup_ctl('Per-slice scaling',
                                         scaling_factors_str, 75)
        scale_control.set_int(scale_choice)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL):
            scale_choice = scale_control.get_int()
            self.adjust_scaling()

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 14
0
    def inter_ui(self):
        if self._panel:
            self.release_panel()
        else:
            if not self._ui:
                self._ui = lwsdk.LWPanels()
            self._panel = self._ui.create('Ring Test')

            target_obj_ctl = self._panel.item_ctl('Target', lwsdk.LWI_ANY)
            target_obj_ctl.set_event(self.effector_change)

            camera_obj_ctl = self._panel.item_ctl('Camera', lwsdk.LWI_CAMERA)
            camera_obj_ctl.set_event(self.camera_change)

            camera_active_ctl = self._panel.bool_ctl('Active')
            camera_active_ctl.set_event(self.active_change)
            camera_active_ctl.set_int(0)
            camera_active_ctl.ghost()

            target_active_ctl = self._panel.bool_ctl('Target object')
            target_active_ctl.set_event(self.target_change)
            target_active_ctl.set_int(0)
            target_active_ctl.ghost()

            radius_ctl = self._panel.percent_ctl('Radius')
            radius_ctl.set_event(self.radius_change)
            radius_ctl.set_float(100.0)
            radius_ctl.ghost()

            self._controls = [
                target_obj_ctl, camera_obj_ctl, camera_active_ctl,
                target_active_ctl, radius_ctl
            ]
            self._panel.align_controls_vertical(self._controls)
            self._panel.size_to_layout(5, 5)

            self._panel.set_close_callback(self.panel_close)

            self._panel.open(lwsdk.PANF_NOBUTT)

        return lwsdk.AFUNC_OK
Esempio n. 15
0
    def __init__(self,
                 context):  # context has no relevant value in a Master plug-in
        super(ring_test, self).__init__()

        self._item_info = lwsdk.LWItemInfo()

        self._ui = lwsdk.LWPanels()
        self._panel = None

        self._comring = lwsdk.LWComRing()

        self._selected_camera = None
        self._selected_camera_name = None
        self._camera_active = {}
        self._camera_radii = {}
        self._camera_target = {}

        self._target_object = None

        # connect to the channel
        self._comring.ringAttach("ringtest_channel", self, self.ring_event)
Esempio n. 16
0
    def process(self, mod_command):
        self.history = recall("history", [])
        print self.history

        ui = lwsdk.LWPanels()
        panel = ui.create(RESOURCE % 'historyList')

        self.c2 = panel.str_ctl(RESOURCE % "String", 50)
        self.c3 = panel.bool_ctl(RESOURCE % "contains string (FG)")
        self.c4 = panel.bool_ctl(RESOURCE % "others (BG)")
        self.listHistory = panel.multilist_ctl(RESOURCE % 'History', 450, 10,
                                               self.nameCallback,
                                               self.countCallback,
                                               self.columnCallback)

        self.listHistory.set_select(self.selectCallback)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        tmp_history = historyData()
        tmp_history.string = self.c2.get_str()
        tmp_history.isContain = False if self.c3.get_int() < 1 else True
        tmp_history.selectOthers = False if self.c4.get_int() < 1 else True

        index = self.searchHistory(tmp_history)

        if index < 0:
            if len(tmp_history.string) > 0:
                self.history.insert(0, tmp_history)
                store("history", self.history)
        else:
            self.moveHistoryRecordForward(index)
            store("history", self.history)

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 17
0
    def process(self, mod_command):
        ui = lwsdk.LWPanels()
        panel = ui.create(
            RESOURCE %
            'Select layers with string - Copyright(C)2012 naru design')

        self.c2 = panel.str_ctl(RESOURCE % "String", 50)
        self.c3 = panel.bool_ctl(RESOURCE % "contains string (FG)")
        self.c4 = panel.bool_ctl(RESOURCE % "others (BG)")
        self.c1 = panel.multilist_ctl(RESOURCE % 'History', 450, 10,
                                      self.nameCallback, self.countCallback,
                                      self.columnCallback)

        self.c1.set_select(self.selectCallback)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        ui.destroy(panel)

        return lwsdk.AFUNC_OK
Esempio n. 18
0
    def process(self, mod_command):
        ui = lwsdk.LWPanels()
        panel = ui.create('Random Point Distribution')

        c1 = panel.int_ctl('Number of points')
        c2 = panel.fvec_ctl('Radius')
        c3 = panel.hchoice_ctl('Shape', ['Round', 'Square'])
        c4 = panel.hchoice_ctl('Falloff towards', ['Center', 'Edges'])
        c5 = panel.int_ctl('Steepness')
        c6 = panel.hchoice_ctl('Density distribution', ['Linear', 'Exponential', 'Constant'])
        c7 = panel.str_ctl('Surface', 50)

        panel.align_controls_vertical([c1, c2, c3, c4, c5, c6, c7])
        panel.size_to_layout(5, 5)

        c1.set_int(self._num_points)
        c2.setv_fvec(self._radius)
        c3.set_int(self._shape)
        c4.set_int(self._falloff)
        c5.set_int(self._steepness)
        c6.set_int(self._density)
        c7.set_str(self._surface)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        self._num_points = c1.get_int()
        self._radius     = c2.getv_fvec()
        self._shape      = c3.get_int()
        self._falloff    = c4.get_int()
        self._steepness  = c5.get_int()
        self._density    = c6.get_int()
        self._surface    = c7.get_str()

        ui.destroy(panel)

        rmax = (self._radius[0] + self._radius[1] + self._radius[2]) / 3.0

        mesh_edit_op = mod_command.editBegin(0, 0, lwsdk.OPSEL_USER)
        if not mesh_edit_op:
            print >>sys.stderr, 'Failed to engage mesh edit operations!'
            return lwsdk.AFUNC_OK

        monitor_funcs = lwsdk.DynaMonitorFuncs()
        dyna_monitor = monitor_funcs.create("Random Point Distribution", "Generating points...")
        if dyna_monitor:
            dyna_monitor.init(dyna_monitor.data, self._num_points)

        edit_op_result = lwsdk.EDERR_NONE

        random.seed()

        # catch exceptions to make sure Modeler ends up on a sane state
        try:
            i = 0
            while i < self._num_points:
                if self._shape == ptspread.ROUND:
                    point = lwsdk.Vector( (2.0 * random.random() - 1.0) * self._radius[0],
                                          (2.0 * random.random() - 1.0) * self._radius[1],
                                          (2.0 * random.random() - 1.0) * self._radius[2] )

                    r = abs(lwsdk.Vector.magnitude(point))

                    p = self.point_prob(self._density + self._falloff, r, rmax, self._steepness)

                    if random.random() < p:
                        pid = mesh_edit_op.addPoint(mesh_edit_op.state, point)
                        mesh_edit_op.addPoly(mesh_edit_op.state, lwsdk.LWPOLTYPE_FACE, None, self._surface, [pid])

                        i += 1

                        if dyna_monitor:
                            if dyna_monitor.step(dyna_monitor.data, 1):
                                edit_op_result = lwsdk.EDERR_USERABORT
                                break

                else:   # SQUARE

                    point = lwsdk.Vector()
                    point.x = (2.0 * random.random() - 1.0) * self._radius[0]
                    p = self.point_prob(self._density + self._falloff, point.x, rmax, self._steepness)

                    point.y = (2.0 * random.random() - 1.0) * self._radius[1]
                    p += self.point_prob(self._density + self._falloff, point.y, rmax, self._steepness)

                    point.z = (2.0 * random.random() - 1.0) * self._radius[2]
                    p += self.point_prob(self._density + self._falloff, point.z, rmax, self._steepness)

                    p /= 3.0

                    if random.random() < p:
                        pid = mesh_edit_op.addPoint(mesh_edit_op.state, point)
                        mesh_edit_op.addPoly(mesh_edit_op.state, lwsdk.LWPOLTYPE_FACE, None, self._surface, [pid])

                        i += 1

                        if dyna_monitor:
                            if dyna_monitor.step(dyna_monitor.data, 1):
                                edit_op_result = lwsdk.EDERR_USERABORT
                                break
        except:
            edit_op_result = lwsdk.EDERR_USERABORT
            raise
        finally:
            mesh_edit_op.done(mesh_edit_op.state, edit_op_result, 0)

        if dyna_monitor:
            dyna_monitor.done(dyna_monitor.data)
            monitor_funcs.destroy(dyna_monitor)

        return lwsdk.AFUNC_OK
Esempio n. 19
0
    def process(self, mod_command):
        ui = lwsdk.LWPanels()
        panel = ui.create('Bubbles')

        c1 = panel.hchoice_ctl('Sphere Type', ['Globe', 'Tesselated'])
        c2 = panel.int_ctl('Tesselation Level')
        c3 = panel.dist_ctl('Maximum Radius')
        c4 = panel.dist_ctl('Minimum Radius')
        c5 = panel.int_ctl('Globe Sides')
        c6 = panel.int_ctl('Globe Segments')
        c7 = panel.str_ctl('Surface', 50)

        panel.align_controls_vertical([c1, c2, c3, c4, c5, c6, c7])
        panel.size_to_layout(5, 5)

        c1.set_int(self._sphereType)
        c2.set_int(self._tessLevel)
        c3.set_float(self._maxRadius)
        c4.set_float(self._minRadius)
        c5.set_int(self._globeSides)
        c6.set_int(self._globeSegments)
        c7.set_str(self._surface)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        self._sphereType = c1.get_int()
        self._tessLevel = c2.get_int()
        self._maxRadius = c3.get_float()
        self._minRadius = c4.get_float()
        self._globeSides = c5.get_int()
        self._globeSegments = c6.get_int()
        self._surface = c7.get_str()

        ui.destroy(panel)

        cs_dict = self.get_commands(mod_command)

        random.seed()

        cs_options = lwsdk.marshall_dynavalues((self._surface, ))
        result, dyna_value = mod_command.execute(mod_command.data,
                                                 cs_dict["SURFACE"],
                                                 cs_options, lwsdk.OPSEL_USER)

        mesh_edit_op = mod_command.editBegin(0, 0, lwsdk.OPSEL_USER)
        if not mesh_edit_op:
            print >> sys.stderr, 'Failed to engage mesh edit operations!'
            return lwsdk.AFUNC_OK

        # gather up the point ids

        points = []

        # NOTE: we will be passing in a sequence (list or tuple) as the argument to the callback.
        # internally, Python expects a sequence as an argument to the function, so it MUST be encased
        # in another sequence, or it will be mistaken for a sequence containing the arguments
        # (instead of an argument itself).

        edit_op_result = mesh_edit_op.fastPointScan(mesh_edit_op.state,
                                                    self.fast_point_scan,
                                                    (points, ), lwsdk.OPLYR_FG,
                                                    1)
        if edit_op_result != lwsdk.EDERR_NONE:
            mesh_edit_op.done(mesh_edit_op.state, edit_op_result, 0)
            return lwsdk.AFUNC_OK

        point_count = len(points)

        # print some info to the PCore console
        print '%d points found for lwsdk.OPLYR_FG' % point_count

        edit_op_result = lwsdk.EDERR_NONE

        monitor_funcs = lwsdk.DynaMonitorFuncs()
        dyna_monitor = monitor_funcs.create("Bubbles", "Removing points...")
        if dyna_monitor:
            dyna_monitor.init(dyna_monitor.data, point_count)

        positions = []
        # catch exceptions to make sure Modeler ends up on a sane state
        try:
            for point in points:
                print type(point)
                positions.append(
                    lwsdk.Vector(
                        mesh_edit_op.pointPos(mesh_edit_op.state, point)))
                mesh_edit_op.remPoint(mesh_edit_op.state, point)

                if dyna_monitor:
                    if dyna_monitor.step(dyna_monitor.data, 1):
                        edit_op_result = lwsdk.EDERR_USERABORT
                        break
        except:
            edit_op_result = lwsdk.EDERR_USERABORT
            raise
        finally:
            mesh_edit_op.done(mesh_edit_op.state, edit_op_result, 0)

        if dyna_monitor:
            dyna_monitor.done(dyna_monitor.data)
            monitor_funcs.destroy(dyna_monitor)

        dyna_monitor = monitor_funcs.create("Bubbles", "Creating bubbles...")
        if dyna_monitor:
            dyna_monitor.init(dyna_monitor.data, point_count)

        for position in positions:
            percent = random.random()
            radius = lwsdk.Vector(self._minRadius + (
                (self._maxRadius - self._minRadius) * percent))

            if self._sphereType == bubbles.GLOBE:
                cs_options = lwsdk.marshall_dynavalues(
                    (radius, self._globeSides, self._globeSegments, position))
                result, dyna_value = mod_command.execute(
                    mod_command.data, cs_dict["MAKEBALL"], cs_options,
                    lwsdk.OPSEL_USER)
            else:
                cs_options = lwsdk.marshall_dynavalues(
                    (radius, self._tessLevel, position))
                result, dyna_value = mod_command.execute(
                    mod_command.data, cs_dict["MAKETESBALL"], cs_options,
                    lwsdk.OPSEL_USER)

            if dyna_monitor:
                if dyna_monitor.step(dyna_monitor.data, 1):
                    edit_op_result = lwsdk.EDERR_USERABORT
                    break

        if dyna_monitor:
            dyna_monitor.done(dyna_monitor.data)
            monitor_funcs.destroy(dyna_monitor)

        return lwsdk.AFUNC_OK
Esempio n. 20
0
    def process(self, ga):
        ui = lwsdk.LWPanels()
        panel = ui.create('Scatter Objects')

        c1 = panel.dist_ctl('Radius')
        c2 = panel.bool_ctl('X')
        c3 = panel.bool_ctl('Y')
        c4 = panel.bool_ctl('Z')

        c1.set_float(self._radius)
        c2.set_int(1 if self._include_x else 0)
        c3.set_int(1 if self._include_y else 0)
        c4.set_int(1 if self._include_z else 0)

        panel.align_controls_vertical([c1, c2, c3, c4])
        panel.size_to_layout(5, 5)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        self._radius = c1.get_float()
        self._include_x = (c2.get_int() == 1)
        self._include_y = (c3.get_int() == 1)
        self._include_z = (c4.get_int() == 1)

        ui.destroy(panel)

        item_info = lwsdk.LWItemInfo()

        interface_info = lwsdk.LWInterfaceInfo()
        current_time = interface_info.curTime
        autokey_is_on = ((interface_info.generalFlags & lwsdk.LWGENF_AUTOKEY) != 0)
        selected_items = interface_info.selected_items()

        for obj in selected_items:
            r = random()
            x_invert = -1 if r < 0.5 else 1
            x_value = 0.0
            if self._include_x:
                x_value = random() * self._radius * x_invert

            r = random()
            y_invert = -1 if r < 0.5 else 1
            y_value = 0.0
            if self._include_y:
                y_value = random() * self._radius * y_invert

            r = random()
            z_invert = -1 if r < 0.5 else 1
            z_value = 0.0
            if self._include_z:
                z_value = random() * self._radius * z_invert

            ga.evaluate(ga.data, "SelectItem %s" % lwsdk.itemid_to_str(obj))
            ga.evaluate(ga.data, "Position %f %f %f" % (x_value, y_value, z_value))

            if not autokey_is_on:
                ga.evaluate(ga.data, "CreateKey %f" % current_time)

        return lwsdk.AFUNC_OK
Esempio n. 21
0
    def process(self, generic_access):
        #launch interface

        ui = lwsdk.LWPanels()
        panel = ui.create('Package Scene')
        panel.setw(750)

        # The consolidate option doesn't move anything, but grabs all assets and puts them in the content structure
        # you're currently using

        self.consolidate_check = panel.bool_ctl("Consolidate files only")
        self.consolidate_check.move(150, self.consolidate_check.y() )
        self.consolidate_check.set_event(self.consolidate_active )

        # The panel.dir_ctl() call creates a requester in which you'll choose the destination folder

        self.target_folder = panel.dir_ctl("Destination folder:", 98)
        self.target_folder.set_event(self.refresh_items)
        self.preserve_check = panel.bool_ctl("Preserve Existing Structure")

        # Subfolders are folders that go below the Objects, Scenes, and Images folders, should they be needed.

        self.asset_string = panel.str_ctl("Subfolder:", 72)
        self.asset_string.set_event(self.refresh_items)

        # This gives the user the option of whether to copy complete image sequences or not.
        # If the user opts not to copy the sequences, only the first image of the sequence will be copied

        self.imseq_check = panel.bool_ctl("Copy Image Sequences")
        self.imseq_check.set_event(self.imseq_active)

        # This selection box gives the user the option to either consolidate all images (including sequences)
        # into the target Images directory, or to have subfolders created for image sequences to keep
        # them neat and tidy

        self.imsub_list = []
        self.imsub_list.append("Root Images folder")
        self.imsub_list.append("Sequence-named subfolder")
        self.imsub_choice = panel.hchoice_ctl("Image sequence destination:", self.imsub_list)
        self.imseq_active(self, self.imseq_active)

        # This displays the eventual path destinations for the individual asset types

        self.sc_string = panel.dir_ctl("Scenes path:", 98)
        self.ob_string = panel.dir_ctl("Objects path:", 98)
        self.im_string = panel.dir_ctl("Images path:", 98)
        self.dyn_string = panel.dir_ctl("Dynamics path:", 98)
        self.ies_string = panel.dir_ctl("Photometric lights path:",98)
        self.rad_string = panel.dir_ctl("Radiosity Cache path:",98)
        self.vert_string = panel.dir_ctl("Vertex Cache path:",98)

        self.radsave_check = panel.bool_ctl("Copy Radiosity cache file")
        self.radsave_check.set_event(self.radcache_active)
        self.radcache_active(self, self.radcache_active)
        self.radsave_check.set_int(1)
        self.rad_string.unghost()
        self.reload_check = panel.bool_ctl("Reload Original Scene")

        panel.align_controls_vertical([self.consolidate_check,
                                       self.target_folder,
                                       self.preserve_check,
                                       self.asset_string,
                                       self.imseq_check,
                                       self.imsub_choice,
                                       self.sc_string,
                                       self.ob_string,
                                       self.im_string,
                                       self.dyn_string,
                                       self.ies_string,
                                       self.rad_string,
                                       self.vert_string,
                                       self.radsave_check,
                                       self.reload_check])

        self.target_folder.set_str(self.content_dir)
        self.refresh_items(None,None)
        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        #end interface ------------------------------------------------------------------------

        #getting values ------------------------------------------------------------------------

        self.consolidate = self.consolidate_check.get_int()

        self.target_dir = self.target_folder.get_str()
        self.preserve = self.preserve_check.get_int()
        self.asset_str = self.asset_string.get_str()

        self.imseq = self.imseq_check.get_int()
        self.imsub = self.imsub_choice.get_int()

        self.ob_dir = self.ob_string.get_str()
        self.sc_dir = self.sc_string.get_str()
        self.im_dir = self.im_string.get_str()
        self.dyn_dir = self.dyn_string.get_str()
        self.ies_dir = self.ies_string.get_str()
        self.rad_dir = self.rad_string.get_str()
        self.vert_dir = self.vert_string.get_str()
        self.radsave = self.radsave_check.get_int()

        self.reload = self.reload_check.get_int()
        
        #end getting values ------------------------------------------------------------------------

        self.comring.ringAttach(self.RINGNAME,self,self.comring_event)
        data = self.comring.encodeData("s:512#2",(self.content_dir, self.target_dir));
        self.comring.ringMessage(self.RINGNAME,1,data); # event #1 would be "copy to new content"
        #self.comring.ringDetatch(self.RINGNAME)

        #begin image processing ------------------------------------------------------------------------
        if self.images.first() != None:  # there are images to be worked on
            if self.consolidate == True:
                asset_str = ""

                self.target_dir = self.content_dir
                self.ob_dir = self.consol_string("Objects")
                self.sc_dir = self.consol_string("Scenes")
                self.im_dir = self.consol_string("Images")
                self.dyn_dir = self.consol_string("Dynamics")
                self.ies_dir = self.consol_string("Lights")
                self.rad_dir = self.consol_string("Radiosity")
                self.vert_dir = self.consol_string("VertCache")

            for currentImage in self.imageMasterList:            
                #construct new path
                currentfile = self.images.filename(currentImage,0)  #current filename from the big list
                currentname = self.images.name(currentImage)
                if self.content_dir in currentfile:
                    validContent = True
                else:
                    validContent = False
# sequence section ----
                if '(sequence)' in currentname and self.imseq == True:              #is a sequence and wants to copy it
                    if validContent == True and self.preserve == 1:                 #wants to preserve, and has a chance
                        #target is the destination content + original directory
                        image_target = os.path.join(self.target_dir,os.path.dirname(currentfile).replace(self.content_dir,'').strip('\\/') )   
                    else:                                                           #don't want to preserve or can't
                        image_target = self.im_dir                                  #not valid content directory, can't preserve
                    
                    first_image = self.copy_sequence(currentfile, currentname, image_target, self.imsub)    # process and copy sequence
                    self.images.replace(currentImage, first_image)

# image section ----------
                else:                                                               #not a sequence
                    if validContent == True and self.preserve == 1:                 #wants to preserve, and has a chance
                        #target is the destination content + original directory
                        image_target = os.path.join(self.target_dir,os.path.dirname(currentfile).replace(self.content_dir,'').strip('\\/') )
                    else:
                        image_target = self.make_content_target(currentfile,self.im_dir)    #get the destination target path
                        self.psCopy(currentfile, image_target)                          #copy, making directories if necessary
                        self.images.replace(currentImage, image_target)                 #replace old image with new
        else:  # no images loaded
            pass # "No Images to copy"

# end image processing -----------------------------

        lwsdk.command("ContentDirectory " + self.target_dir)

# begin object processing ---------------------------------------------

#get object list

        item_info = lwsdk.LWItemInfo()
        obj_info = lwsdk.LWObjectInfo()

        objlist = []
        myobj = item_info.first( lwsdk.LWI_OBJECT, lwsdk.LWITEM_NULL )
        if myobj != lwsdk.LWITEM_NULL:
            objlist.append( myobj )
            while myobj != lwsdk.LWITEM_NULL:
                myobj = item_info.next( myobj )
                if myobj != lwsdk.LWITEM_NULL:
                    objlist.append( myobj )
#get destination path

            for obj in objlist:
                #if item_info.name( obj ) != obj_info.filename( obj ):   # probably isn't a null object
                if obj_info.numPoints( obj ) != 1 and obj_info.numPolygons( obj ) != 0:
                    if self.preserve == True and os.path.dirname(obj_info.filename( obj )) != self.content_dir and self.content_dir in obj_info.filename( obj ):   # valid and can preserve
                        ob_path = obj_info.filename( obj ).replace(self.content_dir,'')
                        new_path = os.path.join(self.ob_dir, ob_path)
                    else:
                        new_path = os.path.join(self.ob_dir, os.path.basename(obj_info.filename( obj )))
                    try:
                        os.makedirs( os.path.dirname(new_path) )
                    except:
                        try:
                            os.makedirs( os.path.dirname(new_path) + os.sep )
                        except:
                            myerr = sys.exc_value
#save object to new path
                    if os.path.lexists( os.path.dirname(new_path) ) == True:
                        lwsdk.command("SelectByName " + item_info.name( obj ))
                        lwsdk.command("SaveObject " + new_path)
                else:
                    pass # "Must be null"

# end object processing ------------------

# begin scene processing -----------------
        if self.preserve == 1 and self.content_dir in self.scene.filename and os.path.dirname(self.scene.filename) != self.content_dir:
            sc_sub = self.scene.filename.replace(self.content_dir,'')
            new_scene = os.path.join(self.sc_dir, sc_sub, self.scene.name)
        else:
            new_scene = os.path.join(self.sc_dir, self.scene.name)

        try:
            os.makedirs( os.path.dirname(new_scene) )
        except:
            try:
                os.makedirs( os.path.dirname(new_scene) + os.sep )
            except:
                myerr = sys.exc_value

        if os.path.lexists( os.path.dirname(new_scene) ) == True:
            tempdir = tempfile.mkdtemp()
            tempscene = os.path.join(tempdir, self.scene.name)
            lwsdk.command("SaveSceneCopy " + tempscene)

        infile = open(tempscene, "r")
        lines = infile.readlines()
        infile.close()

        outfile = open(new_scene, 'w')

        photo_on = False
        bdd_on = False
        mdd_on = False
        vert_on = False
        mddnode_on = False
        flock_on = False

        # scan scene for ancillary files
        for l in lines:
            l = l.replace('\n','')  # strip newline

            # 1. Get path
            # 2. Find old item
            # 3. Prepare new path
            # 4. Copy old item to new path
            # 5. Write new path to Scene file

            #process bdd files

            #if ".bdd" in l:  # l is the line out of the Scene file
            if "FX_Break" in l:     # l is the line out of the Scene file
                bdd_on = True   # Switch this on, since we've found a BDD line
                outfile.write(l + "\n")

            elif ".bdd" in l and bdd_on == True:
                bddunc = False  # Start out assuming it is NOT a UNC path
                if l.startswith("\\\\"):
                    bddunc = True       # If the line starts with at double-backslash, fair bet it's a UNC path
                ls = l.replace('\\','/')
                oldbddpath = os.path.join(self.content_dir, ls )
                if self.preserve == True:
                    if content_dir in oldbddpath:
                        preserve = True
                    else:
                        preserve = False
                if preserve == True and self.preserve == True:
                    newbddpath = os.path.join(self.target_dir, os.path.dirname(ls), os.path.basename(ls) )
                else:
                    newbddpath = os.path.join(self.dyn_dir, os.path.basename(ls) )
                self.psCopy(oldbddpath.replace('\\','/'), newbddpath.replace('\\','/') )
                if bddunc == True:
                    outfile.write( newbddpath + "\n")
                else:
                    outfile.write( l + "\n")

            elif "EndPlugin" in l and bdd_on == True:
                outfile.write(l + "\n")
                outfile.write("\n")
                bdd_on = False

            elif "FX_MotionDrive" in l:
                mdd_on = True
                outfile.write(l + "\n")
            elif ".mdd" in l and mdd_on == True:
                mdd_on = False
                l = l.replace('\\','/')
                oldmddpath = os.path.join(self.content_dir, l)
                if self.preserve == True:
                    newmddpath = os.path.join(self.target_dir, l)
                else:
                    newmddpath = os.path.join( self.dyn_dir, os.path.basename(l) )
                self.psCopy(oldmddpath, newmddpath)
                outfile.write( l + "\n" )

            elif "MD_Plug" in l:
                vert_on = True
                outfile.write( l + "\n" )

            elif ".mdd" in l and vert_on == True and mddnode_on == False:
                vertunc = False
                oldvertpath = os.path.join( self.content_dir, l.strip().replace('\"','') )
                if oldvertpath.startswith("\\\\"):
                    vertunc = True
                ls = l.strip().replace('\"','').split('\\/')
                newvertpath = os.path.join( self.vert_dir, os.path.basename(l.strip().replace('\"','') )  )
                if vertunc == True:
                    oldvertnorm = os.path.normpath(oldvertpath)
                    oldvertnorm = oldvertnorm.replace(r'\\\\',r'\\')
                    self.psCopy(oldvertnorm, newvertpath)
                else:
                    self.psCopy(oldvertpath, newvertpath)
                outline = '    \"' + self.strip_first_slash(newvertpath[len(self.target_dir):]) + '\"\n'
                outfile.write(outline)
                vert_on = False

            elif ".xml" in l and vert_on == True and mddnode_on == False:
                xmlunc = False
                oldvertpath = os.path.join( self.content_dir, l.strip().replace('\"','') )
                oldmc = os.path.splitext(oldvertpath)[0] + ".mc"
                if oldvertpath.startswith("\\\\"):
                    xmlunc = True
                ls = l.strip().replace('\"','').split('\\/')
                newvertpath = os.path.join( self.vert_dir, os.path.basename(l.strip().replace('\"','') )  )
                newmc = os.path.splitext(newvertpath)[0] + ".mc"
                if xmlunc == True:
                    oldvertnorm = os.path.normpath(oldvertpath)
                    oldvertnorm = oldvertnorm.replace(r'\\\\',r'\\')
                    oldmcnorm = os.path.normpath(oldmc)
                    oldmcnorm = oldmcnorm.replace(r'\\\\',r'\\')
                    self.psCopy(oldvertnorm, newvertpath)
                    self.psCopy(oldmcnorm, newmc)
                    self.copy_mc_sequence(oldmcnorm, newmc)
                else:
                    self.psCopy(oldvertpath, newvertpath)
                    self.psCopy(oldmc, newmc)
                    self.copy_mc_sequence(oldmc, newmc)
                outline = '    \"' + self.strip_first_slash(newvertpath[len(self.target_dir):]) + '\"\n'
                outfile.write(outline)
                vert_on = False

            elif "{ MDReader" in l:
                outfile.write( l + "\n" )

            elif "MDD_Node" in l:
                mddnode_on = True
                outfile.write( l + "\n")

            elif ".mdd" in l and mddnode_on == True and vert_on == False:
                mddnode_on = False
                l = l.replace('\\','/')
                oldvertpath = os.path.join( self.content_dir, l.strip().replace('\"','') )
                ls = l.strip().replace('\"','').split('\\/')
                newvertpath = os.path.join( self.vert_dir, os.path.basename(l.strip().replace('\"','') )  )
                self.psCopy(oldvertpath, newvertpath)
                outline = '\"' + self.strip_first_slash(newvertpath[len(self.target_dir):]) + '\"\n'
                outfile.write('        Filename ' + outline )

            # Process Particle FX files
            elif ".pfx" in l:
                pfxunc = False
                lsplit = l.split(None,5)
                ls = os.path.normpath(lsplit[5])
                if ls.startswith("\\\\"):    #UNC path
                    pfxunc = True
                if '\\' in ls or '/' in ls:  # this section is for the Mac, if it's having trouble
                    lsp = ls.split('\\')     # dealing with backslashes
                    ls = lsp[-1]
                oldpfxpath = os.path.join( self.content_dir,lsplit[5] )

                if self.content_dir in oldpfxpath:
                    preserve = True
                else:
                    preserve = False

                if preserve == 1 and self.preserve == 1:
                    newpfxpath = os.path.join(self.target_dir,lsplit[5])
                else:
                    newpfxpath = os.path.join(self.dyn_dir, os.path.basename(ls) )
                psCopySource = oldpfxpath.replace('\\','/')
                psCopyDest = newpfxpath.replace('\\','/')
                self.psCopy(psCopySource, psCopyDest)

                lsplit[5] = newpfxpath

                outline = ' '.join(lsplit)
                outfile.write(" " + outline + "\n")

            # Process IES Lights
            elif "Plugin LightHandler" in l and "PhotometricLight" in l:
                outfile.write("Plugin LightHandler 1 PhotometricLight\n")
                photo_on = True

            elif photo_on == True and "File \"" in l:
                oldiespath = l[8:-1]
                if oldiespath[:1] == ":":
                    oldiespath = os.sep + oldiespath[1:]
                newiespath = os.path.join(self.ies_dir, os.path.basename(oldiespath))
                if newiespath[:1] == ":":
                    newiespath = os.sep + newiespath[1:] 
                outfile.write('  File \"' + self.strip_first_slash(newiespath) + '\"\n')
                self.psCopy(oldiespath, newiespath)
                photo_on = False

            # Process Radiosity Cache files
            elif "RadiosityCacheFilePath" in l and self.radsave == True:
                l = l.split(None,1)[1]
                oldradpath_drive = os.path.splitdrive(l)[0]
                oldradpath_path = os.path.dirname(os.path.splitdrive(l)[1])
                oldradpath_file = os.path.basename(l)
                if oldradpath_drive != None:
                    oldradpath = os.path.join(oldradpath_drive, oldradpath_path, oldradpath_file).replace('\\','/')
                    if oldradpath[:1] == ":":
                        oldradpath = os.sep + oldradpath[1:]
                else:
                    oldradpath = os.path.join(self.content_dir, l)
                newradpath = os.path.join(self.rad_dir, oldradpath_file).replace('\\','/')
                if newradpath[:1] == ":":
                    newradpath = os.sep + newradpath[1:]
                self.psCopy(oldradpath, newradpath )
                outfile.write('RadiosityCacheFilePath ' + self.strip_first_slash(newradpath) + "\n")

            #Copy flocking cache data
            elif "FlockMaster" in l:
                outfile.write(l + "\n")
                flock_on = True
                flock_count = 1

            elif flock_on == True and flock_count == 1:
                outfile.write(l + "\n")
                flock_count = flock_count + 1

            elif flock_on == True and flock_count == 2:
                flock_count = flock_count + 1
                flockunc = False
                lsplit = l.replace("\"",'')
                ls = os.path.normpath(lsplit)
                if ls.startswith("\\\\"):
                    flockunc = True
                if '\\' in ls or '/' in ls:
                    lsp = ls.split('\\')
                    ls = lsp[-1]
                oldflockpath = os.path.join( self.content_dir, lsplit)
                if self.preserve == True:
                    if self.content_dir in oldflockpath:
                        preserve = True
                    else:
                        preserve = False
                if self.preserve == True and preserve == True:
                    newflockpath = os.path.join(self.dyn_dir, ls)
                else:
                    newflockpath = os.path.join(self.dyn_dir, os.path.basename(ls))
                psCopySource = os.path.normpath(oldflockpath)
                psCopyDest = os.path.normpath(newflockpath)
                self.psCopy(psCopySource, psCopyDest)
                newflockwrite = '\"' + newflockpath.replace('\\','\\\\') + '\"'

            elif flock_on == True and "EndPlugin" in l:
                flock_on = False
                outfile.write(l + "\n")

            else:   #if nothing matched, just pass the line right through to the new scene
                outfile.write( l + "\n")

        # copy over Bullet dynamics cache file
        if os.path.lexists(os.path.join( self.content_dir, "Dynamics") ):
            dynasource = os.path.join( self.content_dir, "Dynamics", self.scene.name[:-4]) + ".dynacache"
            dynadest = os.path.join( self.dyn_dir, os.path.basename( dynasource ) )
            self.psCopy(dynasource, dynadest)

        outfile.close()

        self.psCopy(tempscene, new_scene)
        if self.reload == True:
            lwsdk.command("LoadScene " + self.scene.filename)
        else:
            lwsdk.command("LoadScene " + new_scene)

        os.remove(tempscene)
        os.rmdir(tempdir)

        return lwsdk.AFUNC_OK
    def process(self, mod_command):
        ui = lwsdk.LWPanels()
        panel = ui.create('Final Fantasy 7:Remake Import')

        controlWidth = 64
        c1 = panel.load_ctl('Select File', controlWidth)
        c1.set_str(self._filepath)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        self.filepath = c1.get_str()
        edit_op_result = lwsdk.EDERR_NONE
        cs_dict = self.get_commands(mod_command)

        progress_count = 8

        cs_test0 = mod_command.lookup(mod_command.data, "cmdseq")

        t1 = time.time()

        files = path_wrangler(self.filepath)
        files.get_files()
        #Dump(files)

        md = open(files.data['uexp'], 'rb')
        ua = open(files.data['uasset'], 'rb')

        meshName = files.data['meshName']
        submesh_name = files.data['submesh_name']

        arm = False
        weightData = {}
        Weight_array = []
        vertexArray = []
        NA = []
        normal_array = []

        UVs0 = []
        UVs1 = []
        UVs2 = []
        UVs3 = []
        UVs4 = []

        faces = []

        names = readUasset(ua)
        ua.close()

        mod_command.undoGroupBegin()

        pattern0 = re.compile(
            b'\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00........')
        for x in xrange(20000):
            s1 = struct.unpack("18s", md.read(18))[0]
            if pattern0.match(s1):
                c0 = struct.unpack("<L", md.read(4))[0]
                c1 = struct.unpack("<L", md.read(4))[0]
                c2 = struct.unpack("<L", md.read(4))[0]
                c3 = struct.unpack("<L", md.read(4))[0]
                c4 = struct.unpack("<L", md.read(4))[0]
                if (c0 and c1 and c2 and c3 and c4 > 1000000000):
                    break
                else:
                    md.seek(-20, 1)
            md.seek(-17, 1)

        materialCount = struct.unpack("<L", md.read(4))[0]

        progress_count += materialCount

        materials = {}
        for m in xrange(materialCount):
            materials[m] = {}
            materials[m]['val0'] = struct.unpack("<l", md.read(4))[0]
            stringIndex = struct.unpack("<L", md.read(4))[0]
            unk0 = struct.unpack("<L", md.read(4))[0]
            unk1 = struct.unpack("<L", md.read(4))[0]
            unk2 = struct.unpack("<L", md.read(4))[0]
            unk3 = struct.unpack("<f", md.read(4))[0]
            unk4 = struct.unpack("<f", md.read(4))[0]
            unk5 = struct.unpack("<L", md.read(4))[0]
            unk6 = struct.unpack("<L", md.read(4))[0]

            materials[m]['name'] = names[stringIndex]

        boneCount = struct.unpack("<L", md.read(4))[0]
        joint_data = {}
        joint_names = []
        for i in xrange(boneCount):
            string_index = struct.unpack("<L", md.read(4))[0]
            jName = names[string_index]
            unk = struct.unpack("<L", md.read(4))[0]
            parent = struct.unpack("<l", md.read(4))[0]

            joint_data[i] = {"name": jName, "parent": parent}
            joint_names.append(jName)

        boneCount2 = struct.unpack("<L", md.read(4))[0]

        if not moninit(progress_count, "Importing", title='Progress'):
            raise Exception('Hell!')

        layerindex = 1
        for i in range(boneCount):
            m1 = struct.unpack("<10f", md.read(40))
        monstep()

        cs_options = lwsdk.marshall_dynavalues(str(layerindex))
        result = mod_command.execute(mod_command.data, cs_dict["SETLAYER"],
                                     cs_options, lwsdk.OPSEL_USER)
        cs_options = lwsdk.marshall_dynavalues(meshName)
        result = mod_command.execute(mod_command.data, cs_dict["SETLAYERNAME"],
                                     cs_options, lwsdk.OPSEL_USER)
        layerindex += 1

        boneCount3 = struct.unpack("<L", md.read(4))[0]
        md.seek(boneCount3 * 12, 1)

        vertexGroups = {}
        unk0 = struct.unpack("<L", md.read(4))[0]
        unk1 = struct.unpack("B", md.read(1))[0]
        unk2 = struct.unpack("B", md.read(1))[0]
        groupCount = struct.unpack("<L", md.read(4))[0]
        for m in xrange(groupCount):
            z1 = struct.unpack("<H", md.read(2))[0]
            ID = struct.unpack("<H", md.read(2))[0]

            md.seek(24, 1)
            vertexGroups[ID] = {'range': 0, 'bones': []}

            # pragma region bone palette
            start = struct.unpack("<L", md.read(4))[0]
            count = struct.unpack("<L", md.read(4))[0]
            vertexGroups[ID]['bones_np'] = np.zeros((boneCount2, ), dtype=int)
            bone_names = []
            for bn in xrange(count):
                bid = struct.unpack("<H", md.read(2))[0]
                vertexGroups[ID]['bones_np'][bn] = bid
                vertexGroups[ID]['bones'].append(bid)
                bone_names.append(joint_data[bid]["name"])
            # pragma endregion bone palette

            size = struct.unpack("<L", md.read(4))[0]
            stop = start + size
            vertexGroups[ID]['range'] = np.arange(start, stop)
            vertexGroups[ID]["start"] = start
            vertexGroups[ID]["stop"] = stop
            vertexGroups[ID]["size"] = size
            vertexGroups[ID]["names"] = bone_names

            md.seek(34, 1)
            FFx4 = readHexString(md, 4)
            flag = struct.unpack("<L", md.read(4))[0]
            if flag:  # extra data for this group
                count = struct.unpack("<L", md.read(4))[0]
                md.seek(count * 16, 1)
            else:
                null = struct.unpack("<L", md.read(4))[0]

        unk = struct.unpack("B", md.read(1))[0]
        checkHere = md.tell()
        stride = struct.unpack("<L", md.read(4))[0]
        fCount = struct.unpack("<L", md.read(4))[0]

        faceByteCount = fCount * stride
        fi = np.fromfile(md, dtype='B', count=faceByteCount)
        if stride == 4:
            fi_0 = fi.view(dtype='<L').reshape(fCount // 3, 3)
        elif stride == 2:
            fi_0 = fi.view(dtype='<H').reshape(fCount // 3, 3)
        fi_0[:, [0, 1]] = fi_0[:, [1, 0]]
        faces = fi_0.tolist()

        unkCount = struct.unpack("<L", md.read(4))[0]
        md.seek(unkCount * 2, 1)

        unk = struct.unpack("<L", md.read(4))[0]
        vertexCount = struct.unpack("<L", md.read(4))[0]
        boneCount = struct.unpack("<L", md.read(4))[0]
        md.seek(boneCount * 2, 1)

        null0 = struct.unpack("<L", md.read(4))[0]
        null1 = struct.unpack("<L", md.read(4))[0]

        uv_count = struct.unpack("<L", md.read(4))[0]
        unk0 = struct.unpack("<H", md.read(2))[0]
        uv_count2 = struct.unpack("<L", md.read(4))[0]

        null2 = struct.unpack("<L", md.read(4))[0]

        unk1 = struct.unpack("<f", md.read(4))[0]
        unk2 = struct.unpack("<f", md.read(4))[0]
        unk3 = struct.unpack("<f", md.read(4))[0]

        null3 = struct.unpack("<L", md.read(4))[0]
        null4 = struct.unpack("<L", md.read(4))[0]
        null5 = struct.unpack("<L", md.read(4))[0]

        vStride = struct.unpack("<L", md.read(4))[0]
        vCount = struct.unpack("<L", md.read(4))[0]

        byteCount = vCount * vStride
        vi = np.fromfile(md, dtype='B', count=byteCount).reshape(
            (vCount, vStride))
        pos = vi[:, 8:20].ravel().view(dtype='<f').reshape((vCount, 3))
        pos[:, [0, 2]] = pos[:, [2, 0]]
        pos[:, [0, 1]] = pos[:, [1, 0]]
        VA = pos.tolist()

        if uv_count > 0:
            uvData_0 = vi[:, 20:24].ravel().view(dtype='<f2').reshape(
                (vCount, 2))
            uvData_0[:, 1:2] *= -1
            uvData_0[:, 1:2] += 1
            UVs0 = uvData_0.tolist()

        if uv_count > 1:
            uvData_1 = vi[:, 24:28].ravel().view(dtype='<f2').reshape(
                (vCount, 2))
            uvData_1[:, 1:2] *= -1
            uvData_1[:, 1:2] += 1
            UVs1 = uvData_1.tolist()

        if uv_count > 2:
            uvData_2 = vi[:, 28:32].ravel().view(dtype='<f2').reshape(
                (vCount, 2))
            uvData_2[:, 1:2] *= -1
            uvData_2[:, 1:2] += 1
            UVs2 = uvData_2.tolist()

        if uv_count > 3:
            uvData_3 = vi[:, 32:36].ravel().view(dtype='<f2').reshape(
                (vCount, 2))
            uvData_3[:, 1:2] *= -1
            uvData_3[:, 1:2] += 1
            UVs3 = uvData_3.tolist()

        if uv_count > 4:
            uvData_4 = vi[:, 36:40].ravel().view(dtype='<f2').reshape(
                (vCount, 2))
            uvData_4[:, 1:2] *= -1
            uvData_4[:, 1:2] += 1
            UVs4 = uvData_4.tolist()
        monstep()

        mesh_edit_op = mod_command.editBegin(0, 0, lwsdk.OPSEL_USER)

        #points
        map(lambda x: v_f(x, vertexArray, mesh_edit_op), VA)
        monstep()

        #faces
        material_IDs = np.empty([1, fCount],
                                dtype='U32').reshape(fCount // 3, 3)
        for g in vertexGroups:
            h = np.in1d(fi_0, vertexGroups[g]['range']).reshape(fi_0.shape)
            m = np.all(h, axis=1)
            material_IDs[m] = materials[g]['name']
        monstep()
        map(lambda x, y: f_f(x, vertexArray, mesh_edit_op, y), faces,
            material_IDs)
        monstep()

        #UVs
        val = 0
        if uv_count > 0:
            map(lambda x, y: uv_f(x, y, val, mesh_edit_op, meshName),
                vertexArray, UVs0)
            val += 1

        if uv_count > 1:
            map(lambda x, y: uv_f(x, y, val, mesh_edit_op, meshName),
                vertexArray, UVs1)
            val += 1

        if uv_count > 2:
            map(lambda x, y: uv_f(x, y, val, mesh_edit_op, meshName),
                vertexArray, UVs2)
            val += 1

        if uv_count > 3:
            map(lambda x, y: uv_f(x, y, val, mesh_edit_op, meshName),
                vertexArray, UVs3)
            val += 1

        if uv_count > 4:
            map(lambda x, y: uv_f(x, y, val, mesh_edit_op, meshName),
                vertexArray, UVs4)
            val += 1
        monstep()

        unkS = struct.unpack("<H", md.read(2))[0]
        extraBoneWeights = struct.unpack("<L", md.read(4))[0]
        wCount = struct.unpack("<L", md.read(4))[0]
        stride = struct.unpack("<L", md.read(4))[0]
        wCount2 = struct.unpack("<L", md.read(4))[0]

        subStride = stride // 2

        for q in xrange(len(vertexGroups)):
            boneNames = vertexGroups[q]["names"]
            start = vertexGroups[q]["start"]
            stop = vertexGroups[q]["stop"]

            for j in xrange(start, stop):
                b0 = struct.unpack("B", md.read(1))[0]
                b1 = struct.unpack("B", md.read(1))[0]
                b2 = struct.unpack("B", md.read(1))[0]
                b3 = struct.unpack("B", md.read(1))[0]
                b4 = struct.unpack("B", md.read(1))[0]
                b5 = struct.unpack("B", md.read(1))[0]
                b6 = struct.unpack("B", md.read(1))[0]
                b7 = struct.unpack("B", md.read(1))[0]

                bn0 = boneNames[b0]
                bn1 = boneNames[b1]
                bn2 = boneNames[b2]
                bn3 = boneNames[b3]
                bn4 = boneNames[b4]
                bn5 = boneNames[b5]
                bn6 = boneNames[b6]
                bn7 = boneNames[b7]

                w0 = struct.unpack("B", md.read(1))[0] / 255.0
                w1 = struct.unpack("B", md.read(1))[0] / 255.0
                w2 = struct.unpack("B", md.read(1))[0] / 255.0
                w3 = struct.unpack("B", md.read(1))[0] / 255.0
                w4 = struct.unpack("B", md.read(1))[0] / 255.0
                w5 = struct.unpack("B", md.read(1))[0] / 255.0
                w6 = struct.unpack("B", md.read(1))[0] / 255.0
                w7 = struct.unpack("B", md.read(1))[0] / 255.0

                mesh_edit_op.pntVMap(mesh_edit_op.state, vertexArray[j],
                                     lwsdk.LWVMAP_WGHT, bn0, [w0])
                mesh_edit_op.pntVMap(mesh_edit_op.state, vertexArray[j],
                                     lwsdk.LWVMAP_WGHT, bn1, [w1])
                mesh_edit_op.pntVMap(mesh_edit_op.state, vertexArray[j],
                                     lwsdk.LWVMAP_WGHT, bn2, [w2])
                mesh_edit_op.pntVMap(mesh_edit_op.state, vertexArray[j],
                                     lwsdk.LWVMAP_WGHT, bn3, [w3])
                mesh_edit_op.pntVMap(mesh_edit_op.state, vertexArray[j],
                                     lwsdk.LWVMAP_WGHT, bn4, [w4])
                mesh_edit_op.pntVMap(mesh_edit_op.state, vertexArray[j],
                                     lwsdk.LWVMAP_WGHT, bn5, [w5])
                mesh_edit_op.pntVMap(mesh_edit_op.state, vertexArray[j],
                                     lwsdk.LWVMAP_WGHT, bn6, [w6])
                mesh_edit_op.pntVMap(mesh_edit_op.state, vertexArray[j],
                                     lwsdk.LWVMAP_WGHT, bn7, [w7])
            monstep()

        mesh_edit_op.done(mesh_edit_op.state, edit_op_result, 0)
        monend()
        mod_command.undoGroupEnd()

        elapsed = time.time() - t1
        print "Time: " + str(elapsed)

        md.close()

        return lwsdk.AFUNC_OK
Esempio n. 23
0
    def process(self, ga):
        ui = lwsdk.LWPanels()
        panel = ui.create('Final Fantasy 7:Remake  Import')

        controlWidth = 64
        c1 = panel.load_ctl('Select File', controlWidth)
        c1.set_str(self._filepath)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        self.filepath = c1.get_str()
        progress_count = 8

        t1 = time.time()

        interface_info = lwsdk.LWInterfaceInfo()
        if not (interface_info.generalFlags & lwsdk.LWGENF_PARENTINPLACE):
            ga.evaluate(ga.data, "ParentInPlace")

        #set bind pose at frame -10
        ga.evaluate(ga.data, "GoToFrame -10")

        interface_info = lwsdk.LWInterfaceInfo()
        selected_items = interface_info.selected_items()

        #if a mesh not selected create a parent null for the bones
        if not selected_items:
            result = ga.evaluate(ga.data, "AddNull Root")
            interface_info = lwsdk.LWInterfaceInfo()
            selected_items = interface_info.selected_items()
            buildItemID = selected_items[0]
        else:
            item_info = lwsdk.LWItemInfo()
            mytype = item_info.type(selected_items[0])
            if mytype == lwsdk.LWI_OBJECT:
                buildItemID = selected_items[0]
            else:
                result = ga.evaluate(ga.data, "AddNull Root")
                interface_info = lwsdk.LWInterfaceInfo()
                selected_items = interface_info.selected_items()
                buildItemID = selected_items[0]

        #get weightmap count
        object_functions = lwsdk.LWObjectFuncs()
        numWeights = object_functions.numVMaps(lwsdk.LWVMAP_WGHT)

        files = path_wrangler(self.filepath)
        files.get_files()

        md = open(files.data['uexp'], 'rb')
        ua = open(files.data['uasset'], 'rb')

        meshName = files.data['meshName']
        submesh_name = files.data['submesh_name']

        arm = False
        weightData = {}
        Weight_array = []
        vertexArray = []
        NA = []
        normal_array = []

        UVs0 = []
        UVs1 = []
        UVs2 = []
        UVs3 = []
        UVs4 = []

        faces = []

        names = readUasset(ua)
        ua.close()

        pattern0 = re.compile(
            b'\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00........')
        for x in xrange(20000):
            s1 = struct.unpack("18s", md.read(18))[0]
            if pattern0.match(s1):
                c0 = struct.unpack("<L", md.read(4))[0]
                c1 = struct.unpack("<L", md.read(4))[0]
                c2 = struct.unpack("<L", md.read(4))[0]
                c3 = struct.unpack("<L", md.read(4))[0]
                c4 = struct.unpack("<L", md.read(4))[0]
                if (c0 and c1 and c2 and c3 and c4 > 1000000000):
                    break
                else:
                    md.seek(-20, 1)
            md.seek(-17, 1)

        materialCount = struct.unpack("<L", md.read(4))[0]

        materials = {}
        for m in xrange(materialCount):
            materials[m] = {}
            materials[m]['val0'] = struct.unpack("<l", md.read(4))[0]
            stringIndex = struct.unpack("<L", md.read(4))[0]
            unk0 = struct.unpack("<L", md.read(4))[0]
            unk1 = struct.unpack("<L", md.read(4))[0]
            unk2 = struct.unpack("<L", md.read(4))[0]
            unk3 = struct.unpack("<f", md.read(4))[0]
            unk4 = struct.unpack("<f", md.read(4))[0]
            unk5 = struct.unpack("<L", md.read(4))[0]
            unk6 = struct.unpack("<L", md.read(4))[0]

            materials[m]['name'] = names[stringIndex]

        boneCount = struct.unpack("<L", md.read(4))[0]
        joint_data = {}
        joint_names = []
        for i in xrange(boneCount):
            string_index = struct.unpack("<L", md.read(4))[0]
            jName = names[string_index]
            unk = struct.unpack("<L", md.read(4))[0]
            parent = struct.unpack("<l", md.read(4))[0]

            joint_data[i] = {"name": jName, "parent": parent}

        boneCount2 = struct.unpack("<L", md.read(4))[0]

        progress_count += boneCount2
        if not moninit(progress_count, "Importing", title='Progress'):
            raise Exception('Hell!')

        boneArray = []
        psn = {}
        IDs = []
        for bn in range(boneCount2):
            boneName = joint_data[bn]["name"]
            BNparent = joint_data[bn]["parent"]

            m1 = struct.unpack("<10f", md.read(40))

            ps0 = (m1[4], m1[5], m1[6])
            #BNps = np.asarray(ps0)

            rt0_ = (m1[3], m1[0], m1[1], m1[2])
            rt0 = quat2mat(rt0_)

            if BNparent == -1:
                BNparent = 0

            #BNps = [mi[3,1], mi[3,2], mi[3,0]]
            BNps = ps0
            psn[bn] = BNps

            #BNrt = mat2euler(mi, axes='ryxz')

            ga.evaluate(ga.data,
                        "SelectItem %s" % lwsdk.itemid_to_str(buildItemID))
            layoutCommand = "AddBone " + boneName
            result = ga.evaluate(ga.data, layoutCommand)

            # no influence except for weight maps
            result = ga.evaluate(ga.data, 'BoneStrength 0')
            interface_info = lwsdk.LWInterfaceInfo()
            selected_items = interface_info.selected_items()
            itemID = selected_items[0]
            IDs.append(itemID)

            #UpdateMotion needed for parent in place
            if bn != 0:
                ga.evaluate(ga.data, 'UpdateMotion')
                ga.evaluate(
                    ga.data,
                    "ParentItem %s" % lwsdk.itemid_to_str(IDs[BNparent]))

            layoutCommand = "Position " + str(BNps[0]) + " " + str(
                BNps[1]) + " " + str(BNps[2])
            result = ga.evaluate(ga.data, layoutCommand)

            if bn == 0:
                result = ga.evaluate(ga.data, "BoneRestLength 0.5")
            else:
                lenX = psn[BNparent][0] - BNps[0]
                lenY = psn[BNparent][1] - BNps[1]
                lenZ = psn[BNparent][2] - BNps[2]

                #dont use full bone length....dummy
                boneLength = math.sqrt(lenX * lenX + lenY * lenY +
                                       lenZ * lenZ) * 0.6
                result = ga.evaluate(ga.data,
                                     "BoneRestLength " + str(boneLength))

            #BNrt = quat2euler(rt0_, axes='szyx')
            BNrt = quat2euler(rt0_, axes='ryxz')
            rotx = (180.0 / math.pi) * BNrt[0]
            roty = (180.0 / math.pi) * BNrt[1]
            rotz = (180.0 / math.pi) * BNrt[2]

            layoutCommand = "Rotation " + str(rotx) + " " + str(
                roty) + " " + str(rotz)
            result = ga.evaluate(ga.data, layoutCommand)

            if bn == 0:
                layoutCommand = "Rotation " + str(180.0) + " " + str(
                    180.0) + " " + str(0.0)
                result = ga.evaluate(ga.data, layoutCommand)

            # if 'autokey' is not turned on, we need to explicitly
            # create keys for the object at the current time offset
            if not (interface_info.generalFlags & lwsdk.LWGENF_AUTOKEY):
                ga.evaluate(ga.data, "CreateKey %f" % interface_info.curTime)

            #keys created at frame -10 so delete any at frame 0
            ga.evaluate(ga.data, 'DeleteKey 0')

            if (numWeights > 0):
                if bn != 0:
                    for b in range(numWeights):
                        weightName = object_functions.vmapName(
                            lwsdk.LWVMAP_WGHT, b)
                        if weightName == boneName:
                            layoutCommand = 'BoneWeightMapName ' + boneName
                            result = ga.evaluate(ga.data, layoutCommand)
                            result = ga.evaluate(ga.data, 'BoneWeightMapOnly')
            ga.evaluate(ga.data, 'RecordRestPosition')

            monstep()

        #-----------------------------------------------------------#
        boneCount3 = struct.unpack("<L", md.read(4))[0]
        md.seek(boneCount3 * 12, 1)
        vertexGroups = {}
        unk0 = struct.unpack("<L", md.read(4))[0]
        unk1 = struct.unpack("B", md.read(1))[0]
        unk2 = struct.unpack("B", md.read(1))[0]
        groupCount = struct.unpack("<L", md.read(4))[0]
        for m in xrange(groupCount):
            z1 = struct.unpack("<H", md.read(2))[0]
            ID = struct.unpack("<H", md.read(2))[0]

            md.seek(24, 1)
            vertexGroups[ID] = {'range': 0, 'bones': []}

            # pragma region bone palette
            start = struct.unpack("<L", md.read(4))[0]
            count = struct.unpack("<L", md.read(4))[0]
            vertexGroups[ID]['bones_np'] = np.zeros((boneCount2, ), dtype=int)
            bone_names = []
            for bn in xrange(count):
                bid = struct.unpack("<H", md.read(2))[0]
                vertexGroups[ID]['bones_np'][bn] = bid
                vertexGroups[ID]['bones'].append(bid)
                bone_names.append(joint_data[bid]["name"])
            # pragma endregion bone palette

            size = struct.unpack("<L", md.read(4))[0]
            stop = start + size
            vertexGroups[ID]['range'] = np.arange(start, stop)
            vertexGroups[ID]["start"] = start
            vertexGroups[ID]["stop"] = stop
            vertexGroups[ID]["size"] = size
            vertexGroups[ID]["names"] = bone_names

            md.seek(34, 1)
            FFx4 = readHexString(md, 4)
            flag = struct.unpack("<L", md.read(4))[0]
            if flag:  # extra data for this group
                count = struct.unpack("<L", md.read(4))[0]
                md.seek(count * 16, 1)
            else:
                null = struct.unpack("<L", md.read(4))[0]

        process_surfaces(files, vertexGroups, materials)
        #-----------------------------------------------------------#

        ga.evaluate(ga.data, 'SelectAllBones')
        #ga.evaluate(ga.data, 'RecordRestPosition')
        bonemayastyledraw()
        itemiconscale(0.2)

        monend()

        elapsed = time.time() - t1
        print "Time: " + str(elapsed)

        md.close()

        return lwsdk.AFUNC_OK
Esempio n. 24
0
    def process(self, mod_command):
        ui = lwsdk.LWPanels()
        panel = ui.create('Gears')

        c1 = panel.hchoice_ctl('Axis', ['X', 'Y', 'Z'])
        c2 = panel.int_ctl('Number of Teeth')
        c3 = panel.dist_ctl('Inner Radius')
        c4 = panel.dist_ctl('Outer Radius')
        c5 = panel.dist_ctl('Thickness')
        c6 = panel.hchoice_ctl('Gear Type', ['Angular', 'Smooth'])
        c7 = panel.fvec_ctl('Center')

        panel.align_controls_vertical([c1, c2, c3, c4, c5, c6, c7])
        panel.size_to_layout(5, 5)

        c1.set_int(self._axis)
        c2.set_int(self._teeth)
        c3.set_float(self._rad_inner)
        c4.set_float(self._rad_outer)
        c5.set_float(self._thickness)
        c6.set_int(self._geartype)
        c7.setv_fvec(self._center)

        if panel.open(lwsdk.PANF_BLOCKING | lwsdk.PANF_CANCEL) == 0:
            ui.destroy(panel)
            return lwsdk.AFUNC_OK

        self._axis = c1.get_int()
        self._teeth = c2.get_int()
        self._rad_inner = c3.get_float()
        self._rad_outer = c4.get_float()
        self._thickness = c5.get_float()
        self._geartype = c6.get_int()
        self._center = c7.getv_fvec()

        ui.destroy(panel)

        cs_dict = self.get_commands(mod_command)

        cx = self._center[0]
        cy = self._center[1]
        cz = self._center[2] - (self._thickness / 2)

        t_ang = 360 / self._teeth / 57.2957794

        # figure out the layers we need to use and those that are
        # available for our temporary work

        fg_layers = lwsdk.LWStateQueryFuncs().layerList(lwsdk.OPLYR_FG, None)
        fg_layers_list = fg_layers.split()
        empty_layers = lwsdk.LWStateQueryFuncs().layerList(
            lwsdk.OPLYR_EMPTY, None)
        empty_layers_list = empty_layers.split()

        cs_options = lwsdk.marshall_dynavalues(fg_layers_list[0])
        result = mod_command.execute(mod_command.data, cs_dict["SETLAYER"],
                                     cs_options, lwsdk.OPSEL_USER)

        x = 0
        empty_layer = empty_layers_list[x]
        while x < len(empty_layers_list) and (empty_layer in fg_layers_list):
            x += 1
            empty_layer = empty_layers_list[x]

        # only punch a hole if we can get an empty layer to work in

        if x == len(empty_layers_list):
            print >> sys.stderr, "Cannot locate an empty background layer!"
            return lwsdk.AFUNC_OK

        mesh_edit_op = mod_command.editBegin(0, 0, lwsdk.OPSEL_USER)
        if not mesh_edit_op:
            print >> sys.stderr, 'Failed to engage mesh edit operations!'
            return lwsdk.AFUNC_OK

        monitor_funcs = lwsdk.DynaMonitorFuncs()
        dyna_monitor = monitor_funcs.create("Gears", "Generating gear...")
        if dyna_monitor:
            dyna_monitor.init(dyna_monitor.data, self._teeth)

        edit_op_result = lwsdk.EDERR_NONE
        ptID = []

        cancelled = False

        # catch exceptions to make sure Modeler ends up on a sane state
        try:
            tooth = 0
            for tooth in range(self._teeth):
                a1 = t_ang * tooth
                a2 = a1 + (t_ang * 3 / 6)
                a3 = a1 + (t_ang * 4 / 6)
                a4 = a1 + (t_ang * 5 / 6)

                pt = [(self._rad_inner * math.sin(a1) + cx),
                      (self._rad_inner * math.cos(a1) + cy), cz]
                ptID.append(mesh_edit_op.addPoint(mesh_edit_op.state, pt))

                pt = [(self._rad_inner * math.sin(a2) + cx),
                      (self._rad_inner * math.cos(a2) + cy), cz]
                ptID.append(mesh_edit_op.addPoint(mesh_edit_op.state, pt))

                pt = [(self._rad_outer * math.sin(a3) + cx),
                      (self._rad_outer * math.cos(a3) + cy), cz]
                ptID.append(mesh_edit_op.addPoint(mesh_edit_op.state, pt))

                pt = [(self._rad_outer * math.sin(a4) + cx),
                      (self._rad_outer * math.cos(a4) + cy), cz]
                ptID.append(mesh_edit_op.addPoint(mesh_edit_op.state, pt))

                if dyna_monitor:
                    result = dyna_monitor.step(dyna_monitor.data, 1)
                    if result:
                        cancelled = True
                        break

            if cancelled:
                edit_op_result = lwsdk.EDERR_USERABORT
            else:
                if self._geartype == gears.ANGULAR:
                    mesh_edit_op.addPoly(mesh_edit_op.state,
                                         lwsdk.LWPOLTYPE_FACE, None, "Gear",
                                         ptID)
                else:  # Smooth
                    ptID.append(ptID[0])  # close the loop
                    mesh_edit_op.addCurve(mesh_edit_op.state, None, ptID, 0)
        except:
            edit_op_result = lwsdk.EDERR_USERABORT
            raise
        finally:
            mesh_edit_op.done(mesh_edit_op.state, edit_op_result, 0)

        if dyna_monitor:
            dyna_monitor.done(dyna_monitor.data)
            monitor_funcs.destroy(dyna_monitor)

        if cancelled:
            return lwsdk.AFUNC_OK

        if self._geartype == gears.SMOOTH:
            result = mod_command.execute(mod_command.data,
                                         cs_dict["FREEZECURVES"], None,
                                         lwsdk.OPSEL_USER)

        cs_options = lwsdk.marshall_dynavalues(('Z', self._thickness))
        result = mod_command.execute(mod_command.data, cs_dict["EXTRUDE"],
                                     cs_options, lwsdk.OPSEL_USER)

        # make hole with a diameter 25% of the gear's radius

        cs_options = lwsdk.marshall_dynavalues(empty_layer)
        result = mod_command.execute(mod_command.data, cs_dict["SETLAYER"],
                                     cs_options, lwsdk.OPSEL_USER)

        cs_options = lwsdk.marshall_dynavalues((
            [
                self._rad_outer * 0.25,  # radius
                self._rad_outer * 0.25,
                self._rad_outer * 0.25
            ],
            -0.5,  # top
            self._thickness + 1,  # bottom
            'Z',  # axis
            32,  # number of sides
            1,  # number of segments
            [cx, cy, cz]  # center
        ))
        result = mod_command.execute(mod_command.data, cs_dict["MAKEDISC"],
                                     cs_options, lwsdk.OPSEL_USER)

        cs_options = lwsdk.marshall_dynavalues(fg_layers_list[0])
        result = mod_command.execute(mod_command.data, cs_dict["SETLAYER"],
                                     cs_options, lwsdk.OPSEL_USER)

        cs_options = lwsdk.marshall_dynavalues(empty_layer)
        result = mod_command.execute(mod_command.data, cs_dict["SETBLAYER"],
                                     cs_options, lwsdk.OPSEL_USER)

        cs_options = lwsdk.marshall_dynavalues('SUBTRACT')
        result = mod_command.execute(mod_command.data, cs_dict["BOOLEAN"],
                                     cs_options, lwsdk.OPSEL_USER)

        cs_options = lwsdk.marshall_dynavalues(empty_layer)
        result = mod_command.execute(mod_command.data, cs_dict["SETLAYER"],
                                     cs_options, lwsdk.OPSEL_USER)

        result = mod_command.execute(mod_command.data, cs_dict["DELETE"], None,
                                     lwsdk.OPSEL_USER)

        cs_options = lwsdk.marshall_dynavalues(fg_layers_list[0])
        result = mod_command.execute(mod_command.data, cs_dict["SETLAYER"],
                                     cs_options, lwsdk.OPSEL_USER)

        result = mod_command.execute(mod_command.data, cs_dict["MERGEPOINTS"],
                                     None, lwsdk.OPSEL_USER)

        result = mod_command.execute(mod_command.data, cs_dict["ALIGNPOLS"],
                                     None, lwsdk.OPSEL_USER)

        if self._geartype == gears.SMOOTH:
            result = mod_command.execute(mod_command.data, cs_dict["FLIP"],
                                         None, lwsdk.OPSEL_USER)

        if self._axis != gears.Z:
            angle = 90.0
            if self._axis == gears.X:
                cs_options = lwsdk.marshall_dynavalues((angle, 'Y'))
            elif self._axis == gears.Y:
                cs_options = lwsdk.marshall_dynavalues((angle, 'X'))

            result = mod_command.execute(mod_command.data, cs_dict["ROTATE"],
                                         cs_options, lwsdk.OPSEL_USER)

        cs_options = lwsdk.marshall_dynavalues(fg_layers)
        result = mod_command.execute(mod_command.data, cs_dict["SETLAYER"],
                                     cs_options, lwsdk.OPSEL_USER)

        return lwsdk.AFUNC_OK