示例#1
0
def set_visible(is_visible: bool):
    """Show or hide the window."""
    if is_visible:
        window.deiconify()
    else:
        window.withdraw()
    GEN_OPTS['Debug']['show_log_win'] = utils.bool_as_int(is_visible)
示例#2
0
 def save_conf(self):
     if self.can_save:
         self.config_file['win_state'][
             self.win_name + '_visible'] = utils.bool_as_int(self.visible)
         self.config_file['win_state'][self.win_name + '_x'] = str(self.relX)
         self.config_file['win_state'][self.win_name + '_y'] = str(self.relY)
         if self.can_resize_x:
             self.config_file['win_state'][
                 self.win_name + '_width'] = str(self.winfo_width())
         if self.can_resize_y:
             self.config_file['win_state'][
                 self.win_name + '_height'] = str(self.winfo_height())
示例#3
0
 def save_conf(self):
     if self.can_save:
         self.config_file['win_state'][self.win_name +
                                       '_visible'] = utils.bool_as_int(
                                           self.visible)
         self.config_file['win_state'][self.win_name + '_x'] = str(
             self.relX)
         self.config_file['win_state'][self.win_name + '_y'] = str(
             self.relY)
         if self.can_resize_x:
             self.config_file['win_state'][self.win_name + '_width'] = str(
                 self.winfo_width())
         if self.can_resize_y:
             self.config_file['win_state'][self.win_name + '_height'] = str(
                 self.winfo_height())
示例#4
0
def save_pist(key, val):
    if widgets['toplevel'].get() == widgets['bottomlevel'].get():
        # user moved them to match, switch the other one around
        sfx('swap')
        widgets['toplevel' if key == 'bottomlevel' else 'bottomlevel'].set(
            values[key])
    else:
        sfx('move')

    start_pos = widgets['toplevel'].get()
    end_pos = widgets['bottomlevel'].get()

    values['toplevel'] = start_pos
    values['bottomlevel'] = end_pos

    values['startup'] = utils.bool_as_int(start_pos > end_pos)
    out_values['toplevel'] = str(max(start_pos, end_pos))
    out_values['bottomlevel'] = str(min(start_pos, end_pos))
示例#5
0
def save_pist(key, val):
    if widgets['toplevel'].get() == widgets['bottomlevel'].get():
        # user moved them to match, switch the other one around
        sfx('swap')
        widgets[
            'toplevel' if key == 'bottomlevel' else 'bottomlevel'
            ].set(values[key])
    else:
        sfx('move')

    start_pos = widgets['toplevel'].get()
    end_pos = widgets['bottomlevel'].get()

    values['toplevel'] = start_pos
    values['bottomlevel'] = end_pos

    values['startup'] = utils.bool_as_int(start_pos > end_pos)
    out_values['toplevel'] = str(max(start_pos, end_pos))
    out_values['bottomlevel'] = str(min(start_pos, end_pos))
示例#6
0
 def save_opt():
     """Save the checkbox's values."""
     GEN_OPTS[section][item] = utils.bool_as_int(
         var.get()
     )
示例#7
0
文件: gameMan.py 项目: xDadiKx/BEE2.4
    def export(
            self,
            style,
            all_items,
            music,
            skybox,
            voice,
            style_vars,
            elevator,
            ):
        """Generate the editoritems.txt and vbsp_config.

        - If no backup is present, the original editoritems is backed up
        - We unlock the mandatory items if specified
        -
        """
        print('--------------------')
        print('Exporting Items and Style for "' + self.name + '"!')
        print('Style =', style)
        print('Music =', music)
        print('Voice =', voice)
        print('Skybox =', skybox)
        print('Elevator = ', elevator)
        print('Style Vars:\n  {')
        for key, val in style_vars.items():
            print('  {} = {!s}'.format(key, val))
        print('  }')

        vbsp_config = style.config.copy()

        # Editoritems.txt is composed of a "ItemData" block, holding "Item" and
        # "Renderables" sections.
        editoritems = Property("ItemData", *style.editor.find_all('Item'))

        for item in sorted(all_items):
            item_block, editor_parts, config_part = all_items[item].export()
            editoritems += item_block
            editoritems += editor_parts
            vbsp_config += config_part

        if voice is not None:
            vbsp_config += voice.config

        if skybox is not None:
            vbsp_config.set_key(
                ('Textures', 'Special', 'Sky'),
                skybox.material,
            )
            vbsp_config += skybox.config

        if music is not None:
            if music.sound is not None:
                vbsp_config.set_key(
                    ('Options', 'music_SoundScript'),
                    music.sound,
                )
            if music.inst is not None:
                vbsp_config.set_key(
                    ('Options', 'music_instance'),
                    music.inst,
                )

            vbsp_config.set_key(('Options', 'music_ID'), music.id)
            vbsp_config += music.config

        vbsp_config.set_key(('Options', 'BEE2_loc'),
            os.path.dirname(os.getcwd()) # Go up one dir to our actual location
        )

        # If there are multiple of these blocks, merge them together
        vbsp_config.merge_children('Conditions',
                                   'InstanceFiles',
                                   'Options',
                                   'StyleVars',
                                   'Textures')

        vbsp_config.ensure_exists('StyleVars')
        vbsp_config['StyleVars'] += [
            Property(key, utils.bool_as_int(val))
            for key, val in
            style_vars.items()
        ]

        for name, file, ext in FILES_TO_BACKUP:
            item_path = self.abs_path(file + ext)
            backup_path = self.abs_path(file + '_original' + ext)
            if os.path.isfile(item_path) and not os.path.isfile(backup_path):
                print('Backing up original ' + name + '!')
                shutil.copy(item_path, backup_path)

        # This is the connections "heart" icon and "error" icon
        editoritems += style.editor.find_key("Renderables", [])

        # Build a property tree listing all of the instances for each item
        all_instances = Property("AllInstances", [])
        for item in editoritems.find_all("Item"):
            item_prop = Property(item['Type'], [])
            all_instances.append(item_prop)
            for inst_block in item.find_all("Exporting", "instances"):
                for inst in inst_block:
                    item_prop.append(
                        Property('Instance', inst['Name'])
                    )

        if style_vars.get('UnlockDefault', False):
            print('Unlocking Items!')
            for item in editoritems.find_all('Item'):
                # If the Unlock Default Items stylevar is enabled, we
                # want to force the corridors and obs room to be
                # deletable and copyable
                if item['type', ''] in _UNLOCK_ITEMS:
                    for prop in item.find_key("Editor", []):
                        if prop.name == 'deletable' or prop.name == 'copyable':
                            prop.value = '1'

        print('Editing Gameinfo!')
        self.edit_gameinfo(True)

        print('Writing Editoritems!')
        os.makedirs(self.abs_path('portal2_dlc2/scripts/'), exist_ok=True)
        with open(self.abs_path(
                'portal2_dlc2/scripts/editoritems.txt'), 'w') as editor_file:
            for line in editoritems.export():
                editor_file.write(line)

        print('Writing VBSP Config!')
        os.makedirs(self.abs_path('bin/bee2/'), exist_ok=True)
        with open(self.abs_path('bin/bee2/vbsp_config.cfg'), 'w') as vbsp_file:
            for line in vbsp_config.export():
                vbsp_file.write(line)

        print('Writing instance list!')
        with open(self.abs_path('bin/bee2/instances.cfg'), 'w') as inst_file:
            for line in all_instances.export():
                inst_file.write(line)

        print('Copying Custom Compiler!')
        for file in os.listdir('../compiler'):
            print('\t* compiler/{0} -> bin/{0}'.format(file))
            shutil.copy(
                os.path.join('../compiler', file),
                self.abs_path('bin/')
            )

        for prefix, pretty in VOICE_PATHS:
            path = 'config/voice/{}_{}.cfg'.format(prefix, voice.id)
            if os.path.isfile(path):
                shutil.copy(
                    path,
                    self.abs_path('bin/bee2/{}.cfg'.format(prefix))
                )
                print('Written "{}.cfg"'.format(prefix))
            else:
                print('No ' + pretty + ' voice config!')
示例#8
0
def init(cback):
    global callback, labels, win, is_open
    callback = cback
    is_open = False
    win = Toplevel(TK_ROOT)
    win.title("BEE2")
    win.resizable(False, False)
    win.iconbitmap('../BEE2.ico')
    win.protocol("WM_DELETE_WINDOW", exit_win)
    win.withdraw()
    labels['noOptions'] = ttk.Label(win, text='No Properties avalible!')
    widgets['saveButton'] = ttk.Button(win, text='Close', command=exit_win)
    widgets['titleLabel'] = ttk.Label(win, text='')
    widgets['titleLabel'].grid(columnspan=9)

    widgets['div_1'] = ttk.Separator(win, orient="vertical")
    widgets['div_2'] = ttk.Separator(win, orient="vertical")
    widgets['div_h'] = ttk.Separator(win, orient="horizontal")

    for key, (prop_type, prop_name) in PROP_TYPES.items():
        labels[key] = ttk.Label(win, text=prop_name+':')
        if prop_type == 'checkbox':
            values[key] = IntVar(value=DEFAULTS[key])
            out_values[key] = utils.bool_as_int(DEFAULTS[key])
            widgets[key] = ttk.Checkbutton(
                win,
                variable=values[key],
                command=func_partial(set_check, key),
                )
            widgets[key].bind(
                '<Return>',
                func_partial(
                    toggleCheck,
                    key,
                    values[key],
                    )
                )

        elif prop_type == 'railLift':
            values[key] = IntVar(value=DEFAULTS[key])
            out_values[key] = utils.bool_as_int(DEFAULTS[key])
            widgets[key] = ttk.Checkbutton(
                win,
                variable=values[key],
                command=func_partial(save_rail, key),
                )

        elif prop_type == 'panAngle':
            frm = ttk.Frame(win)
            widgets[key] = frm
            values[key] = StringVar(value=DEFAULTS[key])
            for pos, angle in enumerate(['30', '45', '60', '90']):
                ttk.Radiobutton(
                    frm,
                    variable=values[key],
                    value=angle,
                    text=angle,
                    command=func_partial(save_angle, key, angle),
                    ).grid(row=0, column=pos)
                frm.columnconfigure(pos, weight=1)

        elif prop_type == 'gelType':
            frm = ttk.Frame(win)
            widgets[key] = frm
            values[key] = IntVar(value=DEFAULTS[key])
            for pos, text in enumerate(PAINT_OPTS):
                ttk.Radiobutton(
                    frm,
                    variable=values[key],
                    value=pos,
                    text=text,
                    command=func_partial(save_paint, key, pos),
                    ).grid(row=0, column=pos)
                frm.columnconfigure(pos, weight=1)
            out_values[key] = str(DEFAULTS[key])

        elif prop_type == 'pistPlat':
            widgets[key] = Scale(
                win,
                from_=0,
                to=4,
                orient="horizontal",
                showvalue=False,
                command=func_partial(save_pist, key),
                )
            values[key] = DEFAULTS[key]
            out_values[key] = str(DEFAULTS[key])
            if ((key == 'toplevel' and DEFAULTS['startup']) or
                    (key == 'bottomlevel' and not DEFAULTS['startup'])):
                widgets[key].set(max(
                    DEFAULTS['toplevel'],
                    DEFAULTS['bottomlevel']
                    ))
            if ((key == 'toplevel' and not DEFAULTS['startup']) or
                    (key == 'bottomlevel' and DEFAULTS['startup'])):
                widgets[key].set(min(
                    DEFAULTS['toplevel'],
                    DEFAULTS['bottomlevel']))

        elif prop_type == 'timerDel':
            widgets[key] = ttk.Scale(
                win,
                from_=0,
                to=30,
                orient="horizontal",
                command=func_partial(save_tim, key),
                )
            values[key] = DEFAULTS[key]

        elif prop_type == 'railPlat':
            widgets[key] = ttk.Checkbutton(win)
    values['startup'] = DEFAULTS['startup']
示例#9
0
def check_toggled(var, config_section, quote_id):
    """Update the config file to match the checkbox."""
    config_section[quote_id] = utils.bool_as_int(var.get())
示例#10
0
 def test_bool_as_int(self):
     for val in true_vals:
         self.assertEqual(utils.bool_as_int(val), '1', repr(val))
     for val in false_vals:
         self.assertEqual(utils.bool_as_int(val), '0', repr(val))
示例#11
0
 def check_callback():
     GEN_OPTS['General']['enable_auto_backup'] = utils.bool_as_int(
         check_var.get()
     )
示例#12
0
def check_toggled(var, config_section, quote_id):
    """Update the config file to match the checkbox."""
    config_section[quote_id] = utils.bool_as_int(var.get())
示例#13
0
 def save_opt():
     """Save the checkbox's values."""
     GEN_OPTS[section][item] = utils.bool_as_int(var.get())
示例#14
0
文件: gameMan.py 项目: goodDOS/BEE2.4
    def export(
            self,
            style,
            all_items,
            music,
            skybox,
            voice,
            style_vars,
            elevator,
            pack_list,
            editor_sounds,
            should_refresh=False,
            ):
        """Generate the editoritems.txt and vbsp_config.

        - If no backup is present, the original editoritems is backed up.
        - We unlock the mandatory items if specified.
        -
        """
        LOGGER.info('-' * 20)
        LOGGER.info('Exporting Items and Style for "{}"!', self.name)
        LOGGER.info('Style = {}', style)
        LOGGER.info('Music = {}', music)
        LOGGER.info('Voice = {}', voice)
        LOGGER.info('Skybox = {}', skybox)
        LOGGER.info('Elevator = {}', elevator)
        LOGGER.info('Style Vars:')
        LOGGER.info('  {')
        for key, val in style_vars.items():
            LOGGER.info('  {} = {!s}', key, val)
        LOGGER.info('  }')
        LOGGER.info('{} Pack Lists!', len(pack_list))
        LOGGER.info('{} Editor Sounds!', len(editor_sounds))
        LOGGER.info('-' * 20)

        # VBSP, VRAD, editoritems
        export_screen.set_length('BACK', len(FILES_TO_BACKUP))
        export_screen.set_length(
            'CONF',
            # VBSP_conf, Editoritems, instances, gameinfo, pack_lists,
            # editor_sounds, template VMF
            7 +
            # Don't add the voicelines to the progress bar if not selected
            (0 if voice is None else len(VOICE_PATHS)),
        )
        # files in compiler/
        export_screen.set_length('COMP', len(os.listdir('../compiler')))

        if should_refresh:
            export_screen.set_length('RES', extract_packages.res_count)
        else:
            export_screen.skip_stage('RES')

        export_screen.show()
        export_screen.grab_set_global()  # Stop interaction with other windows

        vbsp_config = style.config.copy()

        # Editoritems.txt is composed of a "ItemData" block, holding "Item" and
        # "Renderables" sections.
        editoritems = Property("ItemData", list(style.editor.find_all('Item')))

        for item in sorted(all_items):
            item_block, editor_parts, config_part = all_items[item].export()
            editoritems += item_block
            editoritems += editor_parts
            vbsp_config += config_part

        if voice is not None:
            vbsp_config += voice.config

        if skybox is not None:
            vbsp_config.set_key(
                ('Textures', 'Special', 'Sky'),
                skybox.material,
            )
            vbsp_config += skybox.config

        if style.has_video:
            if elevator is None:
                # Use a randomised video
                vbsp_config.set_key(
                    ('Elevator', 'type'),
                    'RAND',
                )
            elif elevator.id == 'VALVE_BLUESCREEN':
                # This video gets a special script and handling
                vbsp_config.set_key(
                    ('Elevator', 'type'),
                    'BSOD',
                )
            else:
                # Use the particular selected video
                vbsp_config.set_key(
                    ('Elevator', 'type'),
                    'FORCE',
                )
                vbsp_config.set_key(
                    ('Elevator', 'horiz'),
                    elevator.horiz_video,
                )
                vbsp_config.set_key(
                    ('Elevator', 'vert'),
                    elevator.vert_video,
                )
        else:  # No elevator video for this style
            vbsp_config.set_key(
                ('Elevator', 'type'),
                'NONE',
            )

        if music is not None:
            if music.sound is not None:
                vbsp_config.set_key(
                    ('Options', 'music_SoundScript'),
                    music.sound,
                )
            if music.inst is not None:
                vbsp_config.set_key(
                    ('Options', 'music_instance'),
                    music.inst,
                )
            if music.packfiles:
                vbsp_config.set_key(
                    ('PackTriggers', 'Forced'),
                    [
                        Property('File', file)
                        for file in
                        music.packfiles
                    ],
                )

            vbsp_config.set_key(('Options', 'music_ID'), music.id)
            vbsp_config += music.config

        if voice is not None:
            vbsp_config.set_key(
                ('Options', 'voice_pack'),
                voice.id,
            )
            vbsp_config.set_key(
                ('Options', 'voice_char'),
                ','.join(voice.chars)
            )
            if voice.cave_skin is not None:
                vbsp_config.set_key(
                    ('Options', 'cave_port_skin'),
                    voice.cave_skin,
                )

        vbsp_config.set_key(
            ('Options', 'BEE2_loc'),
            os.path.dirname(os.getcwd())  # Go up one dir to our actual location
        )
        vbsp_config.set_key(
            ('Options', 'Game_ID'),
            self.steamID,
        )

        vbsp_config.ensure_exists('StyleVars')
        vbsp_config['StyleVars'] += [
            Property(key, utils.bool_as_int(val))
            for key, val in
            style_vars.items()
        ]

        pack_block = Property('PackList', [])
        # A list of materials which will casue a specific packlist to be used.
        pack_triggers = Property('PackTriggers', [])

        for key, pack in pack_list.items():
            pack_block.append(Property(
                key,
                [
                    Property('File', file)
                    for file in
                    pack.files
                ]
            ))
            for trigger_mat in pack.trigger_mats:
                pack_triggers.append(
                    Property('Material', [
                        Property('Texture', trigger_mat),
                        Property('PackList', pack.id),
                    ])
                )
        if pack_triggers.value:
            vbsp_config.append(pack_triggers)

        # If there are multiple of these blocks, merge them together
        # They will end up in this order.
        vbsp_config.merge_children(
            'Textures',
            'Fizzler',
            'Options',
            'StyleVars',
            'Conditions',
            'Voice',
            'PackTriggers',
        )

        for name, file, ext in FILES_TO_BACKUP:
            item_path = self.abs_path(file + ext)
            backup_path = self.abs_path(file + '_original' + ext)
            if os.path.isfile(item_path) and not os.path.isfile(backup_path):
                LOGGER.info('Backing up original {}!', name)
                shutil.copy(item_path, backup_path)
            export_screen.step('BACK')

        # Backup puzzles, if desired
        backup.auto_backup(selected_game, export_screen)

        # This is the connections "heart" icon and "error" icon
        editoritems += style.editor.find_key("Renderables", [])


        if style_vars.get('UnlockDefault', False):
            LOGGER.info('Unlocking Items!')
            for item in editoritems.find_all('Item'):
                # If the Unlock Default Items stylevar is enabled, we
                # want to force the corridors and obs room to be
                # deletable and copyable
                # Also add DESIRES_UP, so they place in the correct orientation
                if item['type', ''] in _UNLOCK_ITEMS:
                    editor_section = item.find_key("Editor", [])
                    editor_section['deletable'] = '1'
                    editor_section['copyable'] = '1'
                    editor_section['DesiredFacing'] = 'DESIRES_UP'

        LOGGER.info('Editing Gameinfo!')
        self.edit_gameinfo(True)

        export_screen.step('CONF')

        LOGGER.info('Writing Editoritems!')
        os.makedirs(self.abs_path('portal2_dlc2/scripts/'), exist_ok=True)
        with open(self.abs_path(
                'portal2_dlc2/scripts/editoritems.txt'), 'w') as editor_file:
            for line in editoritems.export():
                editor_file.write(line)
        export_screen.step('CONF')

        LOGGER.info('Writing VBSP Config!')
        os.makedirs(self.abs_path('bin/bee2/'), exist_ok=True)
        with open(self.abs_path('bin/bee2/vbsp_config.cfg'), 'w') as vbsp_file:
            for line in vbsp_config.export():
                vbsp_file.write(line)
        export_screen.step('CONF')

        LOGGER.info('Writing instance list!')
        with open(self.abs_path('bin/bee2/instances.cfg'), 'w') as inst_file:
            for line in self.build_instance_data(editoritems):
                inst_file.write(line)
        export_screen.step('CONF')

        LOGGER.info('Writing packing list!')
        with open(self.abs_path('bin/bee2/pack_list.cfg'), 'w') as pack_file:
            for line in pack_block.export():
                pack_file.write(line)
        export_screen.step('CONF')

        LOGGER.info('Editing game_sounds!')
        self.add_editor_sounds(editor_sounds.values())
        export_screen.step('CONF')

        LOGGER.info('Exporting {} templates!',
            len(packageLoader.data['BrushTemplate'])
        )
        with open(self.abs_path('bin/bee2/templates.vmf'), 'w') as temp_file:
            packageLoader.TEMPLATE_FILE.export(temp_file)
        export_screen.step('CONF')

        if voice is not None:
            for prefix, dest, pretty in VOICE_PATHS:
                path = os.path.join(
                    os.getcwd(),
                    '..',
                    'config',
                    'voice',
                    prefix + voice.id + '.cfg',
                )
                LOGGER.info(path)
                if os.path.isfile(path):
                    shutil.copy(
                        path,
                        self.abs_path('bin/bee2/{}voice.cfg'.format(dest))
                    )
                    LOGGER.info('Written "{}voice.cfg"', dest)
                else:
                    LOGGER.info('No {} voice config!', pretty)
                export_screen.step('CONF')

        LOGGER.info('Copying Custom Compiler!')
        for file in os.listdir('../compiler'):
            LOGGER.info('\t* compiler/{0} -> bin/{0}', file)
            try:
                shutil.copy(
                    os.path.join('../compiler', file),
                    self.abs_path('bin/')
                )
            except PermissionError:
                # We might not have permissions, if the compiler is currently
                # running.
                export_screen.grab_release()
                export_screen.reset()
                messagebox.showerror(
                    title='BEE2 - Export Failed!',
                    message='Copying compiler file {file} failed.'
                            'Ensure the {game} is not running.'.format(
                                file=file,
                                game=self.name,
                            ),
                    master=TK_ROOT,
                )
                return False
            export_screen.step('COMP')

        if should_refresh:
            LOGGER.info('Copying Resources!')
            self.refresh_cache()

        export_screen.grab_release()
        export_screen.reset()  # Hide loading screen, we're done
        return True
示例#15
0
    def export(
        self,
        style,
        all_items,
        music,
        skybox,
        voice,
        style_vars,
        elevator,
        pack_list,
        editor_sounds,
        should_refresh=False,
    ):
        """Generate the editoritems.txt and vbsp_config.

        - If no backup is present, the original editoritems is backed up
        - We unlock the mandatory items if specified
        -
        """
        print('-' * 20)
        print('Exporting Items and Style for "' + self.name + '"!')
        print('Style =', style)
        print('Music =', music)
        print('Voice =', voice)
        print('Skybox =', skybox)
        print('Elevator = ', elevator)
        print('Style Vars:\n  {')
        for key, val in style_vars.items():
            print('  {} = {!s}'.format(key, val))
        print('  }')
        print(len(pack_list), 'Pack Lists!')
        print(len(editor_sounds), 'Editor Sounds!')
        print('-' * 20)

        # VBSP, VRAD, editoritems
        export_screen.set_length('BACK', len(FILES_TO_BACKUP))
        export_screen.set_length(
            'CONF',
            # VBSP_conf, Editoritems, instances, gameinfo, pack_lists,
            # editor_sounds
            6 +
            # Don't add the voicelines to the progress bar if not selected
            (0 if voice is None else len(VOICE_PATHS)),
        )
        # files in compiler/
        export_screen.set_length('COMP', len(os.listdir('../compiler')))

        if should_refresh:
            export_screen.set_length('RES', extract_packages.res_count)
        else:
            export_screen.skip_stage('RES')

        export_screen.show()
        export_screen.grab_set_global()  # Stop interaction with other windows

        vbsp_config = style.config.copy()

        # Editoritems.txt is composed of a "ItemData" block, holding "Item" and
        # "Renderables" sections.
        editoritems = Property("ItemData", list(style.editor.find_all('Item')))

        for item in sorted(all_items):
            item_block, editor_parts, config_part = all_items[item].export()
            editoritems += item_block
            editoritems += editor_parts
            vbsp_config += config_part

        if voice is not None:
            vbsp_config += voice.config

        if skybox is not None:
            vbsp_config.set_key(
                ('Textures', 'Special', 'Sky'),
                skybox.material,
            )
            vbsp_config += skybox.config

        if style.has_video:
            if elevator is None:
                # Use a randomised video
                vbsp_config.set_key(
                    ('Elevator', 'type'),
                    'RAND',
                )
            elif elevator.id == 'VALVE_BLUESCREEN':
                # This video gets a special script and handling
                vbsp_config.set_key(
                    ('Elevator', 'type'),
                    'BSOD',
                )
            else:
                # Use the particular selected video
                vbsp_config.set_key(
                    ('Elevator', 'type'),
                    'FORCE',
                )
                vbsp_config.set_key(
                    ('Elevator', 'horiz'),
                    elevator.horiz_video,
                )
                vbsp_config.set_key(
                    ('Elevator', 'vert'),
                    elevator.vert_video,
                )
        else:  # No elevator video for this style
            vbsp_config.set_key(
                ('Elevator', 'type'),
                'NONE',
            )

        if music is not None:
            if music.sound is not None:
                vbsp_config.set_key(
                    ('Options', 'music_SoundScript'),
                    music.sound,
                )
            if music.inst is not None:
                vbsp_config.set_key(
                    ('Options', 'music_instance'),
                    music.inst,
                )

            vbsp_config.set_key(('Options', 'music_ID'), music.id)
            vbsp_config += music.config

        if voice is not None:
            vbsp_config.set_key(
                ('Options', 'voice_pack'),
                voice.id,
            )
            vbsp_config.set_key(('Options', 'voice_char'),
                                ','.join(voice.chars))

        vbsp_config.set_key(
            ('Options', 'BEE2_loc'),
            os.path.dirname(
                os.getcwd())  # Go up one dir to our actual location
        )

        vbsp_config.ensure_exists('StyleVars')
        vbsp_config['StyleVars'] += [
            Property(key, utils.bool_as_int(val))
            for key, val in style_vars.items()
        ]

        pack_block = Property('PackList', [])
        # A list of materials which will casue a specific packlist to be used.
        pack_triggers = Property('PackTriggers', [])

        for key, pack in pack_list.items():
            pack_block.append(
                Property(key, [Property('File', file) for file in pack.files]))
            for trigger_mat in pack.trigger_mats:
                pack_triggers.append(
                    Property('Material', [
                        Property('Texture', trigger_mat),
                        Property('PackList', pack.id),
                    ]))
        if pack_triggers.value:
            vbsp_config.append(pack_triggers)

        # If there are multiple of these blocks, merge them together
        # They will end up in this order.
        vbsp_config.merge_children(
            'Textures',
            'Fizzler',
            'Options',
            'StyleVars',
            'Conditions',
            'Voice',
            'PackTriggers',
        )

        for name, file, ext in FILES_TO_BACKUP:
            item_path = self.abs_path(file + ext)
            backup_path = self.abs_path(file + '_original' + ext)
            if os.path.isfile(item_path) and not os.path.isfile(backup_path):
                print('Backing up original ' + name + '!')
                shutil.copy(item_path, backup_path)
            export_screen.step('BACK')

        # This is the connections "heart" icon and "error" icon
        editoritems += style.editor.find_key("Renderables", [])

        # Build a property tree listing all of the instances for each item
        all_instances = Property("AllInstances", [])
        for item in editoritems.find_all("Item"):
            item_prop = Property(item['Type'], [])
            all_instances.append(item_prop)
            for inst_block in item.find_all("Exporting", "instances"):
                for inst in inst_block:
                    item_prop.append(Property('Instance', inst['Name']))

        if style_vars.get('UnlockDefault', False):
            print('Unlocking Items!')
            for item in editoritems.find_all('Item'):
                # If the Unlock Default Items stylevar is enabled, we
                # want to force the corridors and obs room to be
                # deletable and copyable
                # Also add DESIRES_UP, so they place in the correct orientation
                if item['type', ''] in _UNLOCK_ITEMS:
                    editor_section = item.find_key("Editor", [])
                    editor_section['deletable'] = '1'
                    editor_section['copyable'] = '1'
                    editor_section['DesiredFacing'] = 'DESIRES_UP'

        print('Editing Gameinfo!')
        self.edit_gameinfo(True)

        export_screen.step('CONF')

        print('Writing Editoritems!')
        os.makedirs(self.abs_path('portal2_dlc2/scripts/'), exist_ok=True)
        with open(self.abs_path('portal2_dlc2/scripts/editoritems.txt'),
                  'w') as editor_file:
            for line in editoritems.export():
                editor_file.write(line)
        export_screen.step('CONF')

        print('Writing VBSP Config!')
        os.makedirs(self.abs_path('bin/bee2/'), exist_ok=True)
        with open(self.abs_path('bin/bee2/vbsp_config.cfg'), 'w') as vbsp_file:
            for line in vbsp_config.export():
                vbsp_file.write(line)
        export_screen.step('CONF')

        print('Writing instance list!')
        with open(self.abs_path('bin/bee2/instances.cfg'), 'w') as inst_file:
            for line in all_instances.export():
                inst_file.write(line)
        export_screen.step('CONF')

        print('Writing packing list!')
        with open(self.abs_path('bin/bee2/pack_list.cfg'), 'w') as pack_file:
            for line in pack_block.export():
                pack_file.write(line)
        export_screen.step('CONF')

        print('Editing game_sounds!')
        self.add_editor_sounds(editor_sounds.values())
        export_screen.step('CONF')

        if voice is not None:
            for prefix, dest, pretty in VOICE_PATHS:
                path = os.path.join(
                    os.getcwd(),
                    '..',
                    'config',
                    'voice',
                    prefix + voice.id + '.cfg',
                )
                print(path)
                if os.path.isfile(path):
                    shutil.copy(
                        path,
                        self.abs_path('bin/bee2/{}voice.cfg'.format(dest)))
                    print('Written "{}voice.cfg"'.format(dest))
                else:
                    print('No ' + pretty + ' voice config!')
                export_screen.step('CONF')

        print('Copying Custom Compiler!')
        for file in os.listdir('../compiler'):
            print('\t* compiler/{0} -> bin/{0}'.format(file))
            shutil.copy(os.path.join('../compiler', file),
                        self.abs_path('bin/'))
            export_screen.step('COMP')

        if should_refresh:
            print('Copying Resources!')
            self.refresh_cache()

        export_screen.grab_release()
        export_screen.reset()  # Hide loading screen, we're done
示例#16
0
def res_faith_mods(inst: VLib.Entity, res: Property):
    """Modify the trigger_catrapult that is created for ItemFaithPlate items.

    Values:
        - raise_trig: Raise or lower the trigger_catapults by this amount.
        - angled_targ, angled_in: Instance entity and input for angled plates
        - straight_targ, straight_in: Instance entity and input for
            straight plates
        - instvar: A $replace value to set to either 'angled' or '
            'straight'.
        - enabledVar: A $replace value which will be copied to the main
            trigger's Start Disabled value (and inverted).
        - trig_temp: An ID for a template brush to add. This will be offset by
            the trigger's position (in the case of the 'helper' trigger).
    """
    # Get data about the trigger this instance uses for flinging
    fixup_var = res['instvar', '']
    trig_enabled = res['enabledVar', None]
    trig_temp = res['trig_temp', '']
    offset = utils.conv_int(res['raise_trig', '0'])
    if offset:
        offset = Vec(0, 0, offset).rotate_by_str(inst['angles', '0 0 0'])
    else:
        offset = Vec()

    if trig_enabled is not None:
        trig_enabled = utils.conv_bool(inst.fixup[trig_enabled])
    else:
        trig_enabled = None

    for trig in vbsp.VMF.by_class['trigger_catapult']:
        if inst['targetname'] not in trig['targetname']:
            continue

        # Edit both the normal and the helper trigger..
        trig_origin = trig['origin'] = Vec.from_str(trig['origin']) + offset

        if offset and not trig_temp:
            # No template, shift the current brushes.
            for solid in trig.solids:
                solid.translate(offset)
        elif trig_temp:
            trig.solids = conditions.import_template(
                temp_name=trig_temp,
                origin=trig_origin,
                angles=Vec.from_str(inst['angles']),
                force_type=conditions.TEMP_TYPES.world,
            ).world
            # Remove the trigger solids from worldspawn..
            for solid in trig.solids:
                vbsp.VMF.remove_brush(solid)

        if trig_enabled is not None and 'helper' not in trig['targetname']:
            trig['startdisabled'] = utils.bool_as_int(not trig_enabled)

        # Inspect the outputs to determine the type.
        # We also change them if desired, since that's not possible
        # otherwise.

        for out in trig.outputs:
            if out.inst_in == 'animate_angled_relay':
                # Instead of an instance: output, use local names.
                # This allows us to strip the proxy, as well as use
                # overlay instances.
                out.inst_in = None
                out.target = conditions.local_name(
                    inst,
                    res['angled_targ', 'animate_angled_relay']
                )
                out.input = res['angled_in', 'Trigger']
                if fixup_var:
                    inst.fixup[fixup_var] = 'angled'
                break  # There's only one output we want to look for...

            elif out.inst_in == 'animate_straightup_relay':
                out.inst_in = None
                out.target = conditions.local_name(
                    inst,
                    res[
                        'straight_targ',
                        'animate_straightup_relay'
                    ],
                )
                out.input = res['straight_in', 'Trigger']

                if fixup_var:
                    inst.fixup[fixup_var] = 'straight'
                break
示例#17
0
def init(cback):
    global callback, labels, win, is_open
    callback = cback
    is_open = False
    win = Toplevel(TK_ROOT)
    win.title("BEE2")
    win.resizable(False, False)
    win.iconbitmap('../BEE2.ico')
    win.protocol("WM_DELETE_WINDOW", exit_win)
    win.withdraw()
    labels['noOptions'] = ttk.Label(win, text='No Properties avalible!')
    widgets['saveButton'] = ttk.Button(win, text='Close', command=exit_win)
    widgets['titleLabel'] = ttk.Label(win, text='')
    widgets['titleLabel'].grid(columnspan=9)

    widgets['div_1'] = ttk.Separator(win, orient="vertical")
    widgets['div_2'] = ttk.Separator(win, orient="vertical")
    widgets['div_h'] = ttk.Separator(win, orient="horizontal")

    for key, (prop_type, prop_name) in PROP_TYPES.items():
        labels[key] = ttk.Label(win, text=prop_name + ':')
        if prop_type == 'checkbox':
            values[key] = IntVar(value=DEFAULTS[key])
            out_values[key] = utils.bool_as_int(DEFAULTS[key])
            widgets[key] = ttk.Checkbutton(
                win,
                variable=values[key],
                command=func_partial(set_check, key),
            )
            widgets[key].bind('<Return>',
                              func_partial(
                                  toggleCheck,
                                  key,
                                  values[key],
                              ))

        elif prop_type == 'railLift':
            values[key] = IntVar(value=DEFAULTS[key])
            out_values[key] = utils.bool_as_int(DEFAULTS[key])
            widgets[key] = ttk.Checkbutton(
                win,
                variable=values[key],
                command=func_partial(save_rail, key),
            )

        elif prop_type == 'panAngle':
            frm = ttk.Frame(win)
            widgets[key] = frm
            values[key] = StringVar(value=DEFAULTS[key])
            for pos, angle in enumerate(['30', '45', '60', '90']):
                ttk.Radiobutton(
                    frm,
                    variable=values[key],
                    value=angle,
                    text=angle,
                    command=func_partial(save_angle, key, angle),
                ).grid(row=0, column=pos)
                frm.columnconfigure(pos, weight=1)

        elif prop_type == 'gelType':
            frm = ttk.Frame(win)
            widgets[key] = frm
            values[key] = IntVar(value=DEFAULTS[key])
            for pos, text in enumerate(PAINT_OPTS):
                ttk.Radiobutton(
                    frm,
                    variable=values[key],
                    value=pos,
                    text=text,
                    command=func_partial(save_paint, key, pos),
                ).grid(row=0, column=pos)
                frm.columnconfigure(pos, weight=1)
            out_values[key] = str(DEFAULTS[key])

        elif prop_type == 'pistPlat':
            widgets[key] = Scale(
                win,
                from_=0,
                to=4,
                orient="horizontal",
                showvalue=False,
                command=func_partial(save_pist, key),
            )
            values[key] = DEFAULTS[key]
            out_values[key] = str(DEFAULTS[key])
            if ((key == 'toplevel' and DEFAULTS['startup'])
                    or (key == 'bottomlevel' and not DEFAULTS['startup'])):
                widgets[key].set(
                    max(DEFAULTS['toplevel'], DEFAULTS['bottomlevel']))
            if ((key == 'toplevel' and not DEFAULTS['startup'])
                    or (key == 'bottomlevel' and DEFAULTS['startup'])):
                widgets[key].set(
                    min(DEFAULTS['toplevel'], DEFAULTS['bottomlevel']))

        elif prop_type == 'timerDel':
            widgets[key] = ttk.Scale(
                win,
                from_=0,
                to=30,
                orient="horizontal",
                command=func_partial(save_tim, key),
            )
            values[key] = DEFAULTS[key]

        elif prop_type == 'railPlat':
            widgets[key] = ttk.Checkbutton(win)
    values['startup'] = DEFAULTS['startup']
示例#18
0
    def set_enabled(self, value: bool):
        if self.id == CLEAN_PACKAGE:
            raise ValueError('The Clean Style package cannot be disabled!')

        PACK_CONFIG[self.id]['Enabled'] = utils.bool_as_int(value)