def importProject(): """Import an existing project. Ask the user to select an existing project file, and then import all or selected data from it into the current project. """ proj = openProject(exist=True, access='r') if proj: # only if non-empty keys = proj.contents() res = draw.askItems( [ _I('mode', choices=['All', 'Defined', 'Undefined', 'Selected', 'None'], itemtype='radio'), _I('selected', choices=keys, itemtype='list'), ], caption='Select variables to import', ) if res: mode = res['mode'][0] if mode == 'A': pass elif mode == 'D': proj = utils.selectDict(proj, pf.PF) elif mode == 'U': proj = utils.removeDict(proj, pf.PF) elif mode == 'S': proj = utils.selectDict(proj, res['selected']) elif mode == 'N': return print("Importing symbols: %s" % proj.contents()) pf.PF.update(proj) listProject()
def accept(save=False): dia.acceptData() print("RESULTS", dia.results) if dia.results['render/mode'].startswith('smooth'): res = utils.subDict(dia.results, 'render/', strip=False) matname = dia.results['render/material'] matdata = utils.subDict(dia.results, 'material/') # Currently, set both in cfg and Material db pf.cfg['material/%s' % matname] = matdata pf.GUI.materials[matname] = canvas.Material(matname,**matdata) for i in range(4): key = 'light/light%s' % i res[key] = utils.subDict(dia.results, key+'/', strip=True) else: res = utils.selectDict(dia.results, ['render/mode', 'render/lighting']) res['_save_'] = save #print("RES", res) updateSettings(res) #print(pf.cfg) vp = pf.GUI.viewports.current vp.resetLighting() #if pf.cfg['render/mode'] != vp.rendermode: print("SETMODE %s %s" % (pf.cfg['render/mode'], pf.cfg['render/lighting'])) vp.setRenderMode(pf.cfg['render/mode'], pf.cfg['render/lighting']) #print(vp.rendermode,vp.settings.lighting) vp.update() toolbar.updateLightButton()
def __str__(self): keys = sorted(set(self.keys()) - set(('drawable', ))) s = utils.formatDict(utils.selectDict(self, keys)) for i, d in enumerate(self.drawable): s += "** Drawable %s **\n" % i s += d.__str__() return s
def registerSoftware(req): """Register the current values of required software""" from pyformex import utils soft = detectedSoftware() reg = {} for k in req: reg[k] = utils.selectDict(soft[k], req[k].keys()) return reg
def properties(o): """Return properties of an object properties are public attributes (not starting with an '_') that are not callable. """ keys = [ k for k in sorted(dir(o)) if not k.startswith('_') and not callable(getattr(o, k)) ] return utils.selectDict(o.__dict__, keys)
def filter_attrib(attrib): """Filter the storable attributes. Currently, only bool, int, float and str types are stored. """ okkeys = [ k for k in attrib if k is not 'color' and ( isinstance(attrib[k],(bool,int,float,str)) or isInt(attrib[k]) or isFloat(attrib[k]) ) ] return utils.selectDict(attrib,okkeys)
def draw(F, ## color='prop',colormap=None,alpha=None, ## bkcolor=None,bkcolormap=None,bkalpha=None, ## mode=None,linewidth=None,linestipple=None, ## marksize=None,nolight=False,ontop=False, ## view=None,bbox=None,shrink=None,clear=None, ## wait=True,allviews=False,highlight=False,silent=True, # A trick to allow 'clear' argument, but not inside kargs clear=None, single=False, **kargs): """Draw geometrical object(s) with specified drawing options and settings. This is the generic drawing function in pyFormex. The user can specifies the Geometry and optional drawing parameters. The function returns the Actor(s) resulting from the drawing operation. The Actors can further be used to change the rendering. Parameters: - `F`: specifies all geometry that will be drawn in a single argument. It can be one of the following: - a drawable object (a Geometry object like Formex, Mesh or TriSurface, or another object having a proper `actor` method), - the name of a global pyFormex variable refering to such an object, - a list or nested list of any of the above items. The possibility of a nested list means that any complex collections of geometry can be drawn in a single operations. The (nested) list is recursively flattened, replacing string values by the corresponding value from the pyFormex global variables dictionary, until a single list of drawable objects results. Next the undrawable items are removed from the list. The resulting list of drawable objects are drawn in a single pass, with the same options and default drawing attributes. - `clear`: clear the scene before drawing. - `single`: specifies the type of result if `F` is a list. If False, a flat list with all Actors for all Geometries in F is returned. It True, a single Actor corresponding with F[0] is returned, with the Actors for F[1:] set as its children. The remaining parameters are the default drawing parameters to be used. They will apply unless overridden by attributes set in the Geometry itself (see :meth:`geometry.Geometry.attrib`). There is a long list of possible settings, but in most case only a few will be needed. .. warning:: The remainder of this docstring is from the old version (<= 0.9) of pyFormex. While most of the arguments are still valid and the documentation below is useful, there might be some slight changes in the behavior. .. note:: DEVS: TODO: THIS DOCSTRING NEEDS TO BE UPDATED ! Settings: specify how the geometry will be drawn. These arguments will be passed to the corresponding Actor for the object. The Actor is the graphical representation of the geometry. Not all Actors use all of the settings that can be specified here. But they all accept specifying any setting even if unused. The settings hereafter are thus a superset of the settings used by the different Actors. Settings have a default value per viewport, and if unspecified, most Actors will use the viewport default for that value. - `color`, `colormap`: specifies the color of the object (see below) - `alpha`: float (0.0..1.0): alpha value to use in transparent mode - `bkcolor`, `bkcolormap`: color for the backside of surfaces, if different from the front side. Specification as for front color. - `bkalpha`: float (0.0..1.0): alpha value for back side. - `linewidth`: float, thickness of line drawing - `linestipple`: stipple pattern for line drawing - `marksize`: float: point size for dot drawing - `nolight`: bool: render object as unlighted in modes with lights on - `ontop`: bool: render object as if it is on top. This will make the object fully visible, even when it is hidden by other objects. If more than one objects is drawn with `ontop=True` the visibility of the object will depend on the order of drawing. Options: these arguments modify the working of the draw functions. If None, they are filled in from the current viewport drawing options. These can be changed with the :func:`setDrawOptions` function. The initial defaults are: view='last', bbox='auto', shrink=False, clear=False, shrinkfactor=0.8. - `view`: is either the name of a defined view or 'last' or None. Predefined views are 'front', 'back', 'top', 'bottom', 'left', 'right', 'iso'. With view=None the camera settings remain unchanged (but might be changed interactively through the user interface). This may make the drawn object out of view! With view='last', the camera angles will be set to the same camera angles as in the last draw operation, undoing any interactive changes. On creation of a viewport, the initial default view is 'front' (looking in the -z direction). - `bbox`: specifies the 3D volume at which the camera will be aimed (using the angles set by `view`). The camera position will be set so that the volume comes in view using the current lens (default 45 degrees). bbox is a list of two points or compatible (array with shape (2,3)). Setting the bbox to a volume not enclosing the object may make the object invisible on the canvas. The special value bbox='auto' will use the bounding box of the objects getting drawn (object.bbox()), thus ensuring that the camera will focus on these objects. The special value bbox=None will use the bounding box of the previous drawing operation, thus ensuring that the camera's target volume remains unchanged. - `shrink`: bool: if specified, each object will be transformed by the :meth:`Coords.shrink` transformation (with the current set shrinkfactor as a parameter), thus showing all the elements of the object separately. (Some other softwares call this an 'exploded' view). - `clear`: bool. By default each new draw operation adds the newly drawn objects to the shown scene. Using `clear=True` will clear the scene before drawing and thus only show the objects of the current draw action. - `wait`: bool. If True (default) the draw action activates a locking mechanism for the next draw action, which will only be allowed after `drawdelay` seconds have elapsed. This makes it easier to see subsequent renderings and is far more efficient than adding an explicit sleep() operation, because the script processing can continue up to the next drawing instruction. The value of drawdelay can be changed in the user settings or using the :func:`delay` function. Setting this value to 0 will disable the waiting mechanism for all subsequent draw statements (until set > 0 again). But often the user wants to specifically disable the waiting lock for some draw operation(s). This can be done without changing the `drawdelay` setting by specifyin `wait=False`. This means that the *next* draw operation does not have to wait. - `allviews`: currently not used - `highlight`: bool. If True, the object(s) will not be drawn as normal geometry, but as highlights (usually on top of other geometry), making them removeable by the remove highlight functions - `silent`: bool. If True (default), non-drawable objects will be silently ignored. If set False, an error is raised if an object is not drawable. - `**kargs`: any not-recognized keyword parameters are passed to the object's Actor constructor. This allows the user to create customized Actors with new parameters. Specifying color: Color specification can take many different forms. Some Actors recognize up to six different color modes and the draw function adds even another mode (property color) - no color: `color=None`. The object will be drawn in the current viewport foreground color. - single color: the whole object is drawn with the specified color. - element color: each element of the object has its own color. The specified color will normally contain precisely `nelems` colors, but will be resized to the required size if not. - vertex color: each vertex of each element of the object has its color. In smooth shading modes intermediate points will get an interpolated color. - element index color: like element color, but the color values are not specified directly, but as indices in a color table (the `colormap` argument). - vertex index color: like vertex color, but the colors are indices in a color table (the `colormap` argument). - property color: as an extra mode in the draw function, if `color='prop'` is specified, and the object has an attribute 'prop', that attribute will be used as a color index and the object will be drawn in element index color mode. If the object has no such attribute, the object is drawn in no color mode. Element and vertex color modes are usually only used with a single object in the `F` parameter, because they require a matching set of colors. Though the color set will be automatically resized if not matching, the result will seldomly be what the user expects. If single colors are specified as a tuple of three float values (see below), the correct size of a color array for an object with `nelems` elements of plexitude `nplex` would be: (nelems,3) in element color mode, and (nelems,nplex,3) in vertex color mode. In the index modes, color would then be an integer array with shape respectively (nelems,) and (nelems,nplex). Their values are indices in the colormap array, which could then have shape (ncolors,3), where ncolors would be larger than the highest used value in the index. If the colormap is insufficiently large, it will again be wrapped around. If no colormap is specified, the current viewport colormap is used. The default contains eight colors: black=0, red=1, green=2, blue=3, cyan=4, magenta=5, yellow=6, white=7. A color value can be specified in multiple ways, but should be convertible to a normalized OpenGL color using the :func:`colors.GLcolor` function. The normalized color value is a tuple of three values in the range 0.0..1.0. The values are the contributions of the red, green and blue components. """ def showActor(actor,highlight): """Add an actor or a highlight to the scene""" if highlight: pf.canvas.addHighlight(actor) else: pf.canvas.addActor(actor) if clear is not None: kargs['clear_'] = clear draw_options = [ 'silent','shrink','clear_','view','highlight','bbox', 'allviews' ] # For simplicity of the code, put objects to draw always in a list if isinstance(F, list): FL = F else: FL = [ F ] # Flatten the list, replacing named objects with their value FL = flatten(FL) ntot = len(FL) # Transform to list of drawable objects FL = drawable(FL) nres = len(FL) # Get default drawing options and overwrite with specified values opts = Attributes(pf.canvas.drawoptions) opts.update(utils.selectDict(kargs,draw_options,remove=True)) if nres < ntot and not opts.silent: raise ValueError("Data contains undrawable objects (%s/%s)" % (ntot-nres, ntot)) # Shrink the objects if requested if opts.shrink: FL = [ _shrink(Fi, opts.shrink_factor) for Fi in FL ] ## # Execute the drawlock wait before doing first canvas change pf.GUI.drawlock.wait() if opts.clear_: clear_canvas() if opts.view not in [ None, 'last', 'cur']: pf.debug("SETTING VIEW to %s" % opts.view, pf.DEBUG.DRAW) setView(opts.view) pf.GUI.setBusy() pf.app.processEvents() try: actors = [] # loop over the objects for F in FL: # Create the actor actor = F.actor(**kargs) if single and len(actors) > 0: # append the new actor to the children of the first actors[0].children.append(actor) else: # append the actor to the list of actors actors.append(actor) if actor is not None and not single: # Immediately show the new actor showActor(actor,opts.highlight) if single or not isinstance(F, list): # Return a single actor actor = actors[0] if len(actors) > 0 else None else: # Return the whole actor list actor = actors if single and actor is not None: # Draw all actors in a single shot showActor(actor,opts.highlight) view = opts.view bbox = opts.bbox pf.debug(pf.canvas.drawoptions, pf.DEBUG.OPENGL) pf.debug(opts, pf.DEBUG.OPENGL) pf.debug(view, pf.DEBUG.OPENGL) pf.debug(bbox, pf.DEBUG.OPENGL) # Adjust the camera if view not in [None, 'cur'] or bbox not in [None, 'last']: if view == 'last': view = pf.canvas.drawoptions['view'] # bbox can be an ndarray, for which '==' would fail if isinstance(bbox,str): if bbox == 'auto': bbox = pf.canvas.scene.bbox elif bbox == 'last': bbox = None pf.canvas.setCamera(bbox, view) # Update the rendering pf.canvas.update() pf.app.processEvents() # Save the rendering if autosave on pf.debug("AUTOSAVE %s" % image.autoSaveOn()) if image.autoSaveOn(): image.saveNext() # Make sure next drawing operation is retarded if opts.wait: pf.GUI.drawlock.lock() finally: pf.GUI.setBusy(False) # Return the created Actor(s) return actor
def __str__(self): keys = sorted(set(self.keys()) - set(('_default_dict_', ))) print("Keys %s" % keys) out = utils.formatDict(utils.selectDict(self, keys)) print(out) return out