def pre_process(self): G.debug(''.join(['Doing post upgrade when globalvars = ',str(self.globalvars)])) filename = getkey(self.arguments,'primary', False) if not filename: G.error('No filename specified, skipping Input') return G.info(''.join(['Inserting ', filename])) p = None if os.path.isfile(getkey(self.globalvars,'root')+filename): p = Processor.Processor(getkey(self.globalvars,'root'), filename, _is_main_file=False) if os.path.isfile(getkey(self.globalvars,'root')+'templates/'+filename): p = Processor.Processor(getkey(self.globalvars,'root')+'templates/', filename, _is_main_file=False) elif os.path.isfile(getkey(self.globalvars,'templatedir')+filename): p = Processor.Processor(getkey(self.globalvars,'templatedir'), filename, _is_main_file=False) elif os.path.isfile(G.template_dir+filename): p = Processor.Processor(G.template_dir, filename, _is_main_file=False) else: G.error('Could not find file requested by Input: '+filename) return # Use the uppermost globalvars dictionary p.globalvars = self.globalvars # Load the objects if p.init_file(): p.load_objects() p.close_file() # Copy objects from the processor to the object self.sub_objects = p.objects G.debug(''.join(['Input objects are: ', p.get_objects_as_string()])) self.removed = True
def upgrade(self): class_name = self.object_name if class_name == 'vim': return False #class_name += "."+class_name module_name = ''.join(['Plugin.',class_name]) G.debug(''.join(['Trying to upgrade to ',class_name])) try: new_module = __import__(module_name) except ImportError: G.error(''.join(['No plugin for ', class_name,'.'])) self.removed = True return False else: try: new_class_module = getattr(new_module, class_name) new_class = getattr(new_class_module, class_name) G.debug(''.join(['Successfully upgraded to ', module_name,'/',class_name,'.'])) except AttributeError: G.critical(''.join(['Plugin error: ', module_name,' should have class named ',class_name,'.'])) self.removed = True return False else: G.debug("New_class is "+str(type(new_class))) self.__class__ = new_class self.post_upgrade() return True
def game_main(): """ init game :return: """ import sys G.cmd_argv = sys.argv # --------------------------------------------------- # init app from commandline args # --------------------------------------------------- argc = len(G.cmd_argv) if argc < 2: print 'app not specified' return if argc > 2: use_glut = G.cmd_argv[2] print "use glut" from framework.zgraphics_glut import Graphics G.graphicsm = Graphics() else: print "use glfw" from framework.zgraphics_glfw import Graphics G.graphicsm = Graphics() app_dir = G.cmd_argv[1] sys.path += [app_dir] app_main = app_dir + '\\app_main.py' execfile(app_main) # --------------------------------------------------- # init engine & start mainloop # --------------------------------------------------- G.main_initialize() G.appm.main()
def close_file(self): try: self.file.close() except IOError: G.warning('File close failed.') return False else: return True
def test_grammar(): P = G.P({ "S": "aA | bC | a | ε", "A": "bB | aA | b | c", "B": "aB | bC | aC | cA | c", "C": "a | b | aA | bB" }) A = G(Set("S", "A", "C", "B"), Set("a", "b", "c"), P, "S") B = A.toNFA()
def post_upgrade(self): # I am not sure this is needed, they can be treated as normal objects, # as long as they possible to look up. # Register me as subprocessor G.info('Registering myself as inline subprocessor') sp = getkey(self.globalvars, '$Subprocessors', []) sp.append(self) self.globalvars['$Subprocessors'] = sp self.localvars['$Accepts'] = ['Paragraph'] # is this the right place? return
def pre_process(self): _from = getkey(self.arguments, 'primary', False) _to = getkey(self.arguments, 'to', False) _lang = getkey(self.arguments, 'language', 'en') if (not _from and _to): G.error('Translate must have both from and to arguments') return if (not _lang in getkey(self.globalvars, '$i18n', {})): self.globalvars['$i18n'][_lang] = {_from: _to} else: self.globalvars['$i18n'][_lang][_from] = _to
def pre_process(self): if not 'language' in self.arguments: self.arguments['language'] = getkey(self.arguments, 'primary', u'?') self.arguments['caption'] = getkey(self.arguments, 'caption', u'') self.arguments['linenumbers'] = getkey(self.arguments, 'linenumbers', u'no') self.arguments['highlight'] = getkey(self.arguments, 'highlight', '') self.arguments['wrap'] = getkey(self.arguments, 'wrap', 'yes') self.localvars['id'] = 'code%i' % G.getid() if not self.content: G.warn("Empty Code object at %s +%d! Perhaps it starts with xxxx: Then add a - separator line before content." % (self.filepath, self.lineno)) return # Clean empty lines self.content = self.content.replace('\n \n', '\n\n') if have_pygment: if getkey(self.arguments, 'language', u'') == u'': lexer = guess_lexer(self.content) else: try: lexer = get_lexer_by_name(getkey(self.arguments, 'language', 'text')) except ClassNotFound: G.error('Cound not find class %s at %s +%d' % (getkey(self.arguments, 'language', 'text'), self.filepath, self.lineno)) lexer = get_lexer_by_name('text') G.debug(u''.join(['Lexer is ',str(lexer)])) linenumbers = True if self.arguments['linenumbers'] == 'yes' else False wrap = True if self.arguments['wrap'] == 'yes' else False highlights = self.arguments['highlight'].split(',') highlight_lines = [] for hl in highlights: parts = hl.split('-') if len(parts) == 2: highlight_lines += range(int(parts[0]), int(parts[1])+ 1) elif hl: highlight_lines.append(int(hl)) formatter = HtmlFormatter( linenos = linenumbers, nowrap = not wrap, hl_lines = highlight_lines ) self.localvars['code'] = unicode(highlight(unicode(self.content), lexer, formatter)) else: G.debug('No highlighting done') self.localvars['code'] = u'\n'.join(['<pre>',unicode(self.content),'</pre>']) self.script = unicode(getkey(self.globalvars, '$Templates.Code.script', u'')) self.script = varsub(self.script, [self.localvars, self.arguments, self.globalvars], getkey(self.globalvars, '$Templates', False), recursive=getkey(self.arguments, 'substitute', 'yes') != 'no')
def on_key_down(key): print "get key down key", key send_msg = "" if key == "c": if not G.actor_dict.has_key(1): G.add_actor(1, 1, 1, 4) send_msg += "C#1#1#1#4$" elif not G.actor_dict.has_key(2): G.add_actor(2, 3, 1, 4) send_msg += "C#2#3#1#4$" else: pass elif key == "p": send_msg += "P#0#0#0#0$" actor_id = 1 pos = G.px_manager.GetPosition(actor_id) print "get actor_id %s pos: %s" % (actor_id, pos) actor_id = 2 pos = G.px_manager.GetPosition(actor_id) print "get actor_id %s pos: %s\n============" % (actor_id, pos) else: actor_id = 0 add_x = 0 add_y = 0 add_z = 0 if key == "a" or key == "h": add_x = -1 elif key == "s" or key == "j": add_z = -1 elif key == "d" or key == "k": add_x = 1 elif key == "w" or key == "u": add_z = 1 elif key == "x" or key == "m": add_y = 3 if key in ["a", "s", "d", "w", "x"]: actor_id = 1 else: actor_id = 2 if add_x + add_y + add_z == 0: return print "get cur info actor_id ", actor_id, add_x, add_y, add_z G.px_manager.MovePosition(actor_id, add_x * 1.0, add_y * 1.0, add_z * 1.0, 1) send_msg += "M#%s#%s#%s#%s$" % (actor_id, add_x, add_y, add_z) if not send_msg: return print "send_msg ========", send_msg if G.client_stub: G.client_stub.messages.append(send_msg) return
def pre_process(self): if not 'language' in self.arguments: self.arguments['language'] = getkey(self.arguments, 'primary', u'?') self.arguments['caption'] = getkey(self.arguments, 'caption', u'') self.arguments['linenumbers'] = getkey(self.arguments, 'linenumbers', u'no') self.arguments['highlight'] = getkey(self.arguments, 'highlight', '') self.arguments['wrap'] = getkey(self.arguments, 'wrap', 'yes') self.localvars['id'] = 'code%i' % G.getid() if not self.content: G.warn("Empty Code object at %s +%d! Perhaps it starts with xxxx: Then add a - separator line before content." % (self.filepath, self.lineno)) return # Clean empty lines code_result = run(self.content) self.content = code_result.replace('\n \n', '\n\n') if have_pygment: if getkey(self.arguments, 'language', u'') == u'': lexer = guess_lexer(self.content) else: try: lexer = get_lexer_by_name(getkey(self.arguments, 'language', 'text')) except ClassNotFound: G.error('Cound not find class %s at %s +%d' % (getkey(self.arguments, 'language', 'text'), self.filepath, self.lineno)) lexer = get_lexer_by_name('text') G.debug(u''.join(['Lexer is ',str(lexer)])) linenumbers = True if self.arguments['linenumbers'] == 'yes' else False wrap = True if self.arguments['wrap'] == 'yes' else False highlights = self.arguments['highlight'].split(',') highlight_lines = [] for hl in highlights: parts = hl.split('-') if len(parts) == 2: highlight_lines += range(int(parts[0]), int(parts[1])+ 1) elif hl: highlight_lines.append(int(hl)) formatter = HtmlFormatter( linenos = linenumbers, nowrap = not wrap, hl_lines = highlight_lines ) self.localvars['code'] = unicode(highlight(unicode(self.content), lexer, formatter)) else: G.debug('No highlighting done') self.localvars['code'] = u'\n'.join(['<pre>',unicode(self.content),'</pre>']) self.script = unicode(getkey(self.globalvars, '$Templates.Exec.script', u'')) self.script = varsub(self.script, [self.localvars, self.arguments, self.globalvars], getkey(self.globalvars, '$Templates', False), recursive=getkey(self.arguments, 'substitute', 'yes') != 'no')
def process_objects_for_syntax_sugar(self): G.info('Starting syntax sugar processing.') for obj in self.objects: # SyntaxSugar translation (for paragraphs, which is the fallback object type) if obj.object_name == "Paragraph" and len(obj.lines): if '$SyntaxSugar' in self.globalvars: for sugar in self.globalvars['$SyntaxSugar']: if not sugar.broken: G.debug(''.join(['Running SyntaxSugar: ',sugar.regexp_string])) if sugar.translate(obj.lines[0]): obj.content = '' # clear object content from old syntax sugar G.info(''.join(['Processing pattern: ',sugar.regexp_string])) obj.lines.pop(0) obj.lines[:0] = sugar.result obj.transform() # reload object from new source obj.process_inline() # Look for %Inlineobject% things and add those at the end of the document # This must also create a hash $InlineObjects with the keys as hashes of # the inline call. Those hashes are later used for inline varsub # The proccess will be recursicve since the Inline objects are added last # to the object queue. # # This code must both look for correct inline object definitions as well # as the costumizable short forms, which should be stored as SyntaxSugars in # a special hash $InlineSyntaxSugar. G.info('Finished syntax sugar processing.')
def process_objects_for_syntax_sugar(self): G.info('Starting syntax sugar processing.') for obj in self.objects: # SyntaxSugar translation (for paragraphs, which is the fallback object type) if obj.object_name == "Paragraph" and len(obj.lines): if '$SyntaxSugar' in self.globalvars: for sugar in self.globalvars['$SyntaxSugar']: if not sugar.broken: G.debug(''.join( ['Running SyntaxSugar: ', sugar.regexp_string])) if sugar.translate(obj.lines[0]): obj.content = '' # clear object content from old syntax sugar G.info(''.join([ 'Processing pattern: ', sugar.regexp_string ])) obj.lines.pop(0) obj.lines[:0] = sugar.result obj.transform( ) # reload object from new source obj.process_inline() # Look for %Inlineobject% things and add those at the end of the document # This must also create a hash $InlineObjects with the keys as hashes of # the inline call. Those hashes are later used for inline varsub # The proccess will be recursicve since the Inline objects are added last # to the object queue. # # This code must both look for correct inline object definitions as well # as the costumizable short forms, which should be stored as SyntaxSugars in # a special hash $InlineSyntaxSugar. G.info('Finished syntax sugar processing.')
def getkey(_dict, _key, _default=''): if not _dict: G.debug('Dict is not defined or empty for getkey') return _default parts = _key.split('.') if len(parts) == 1: if _key in _dict: return _dict[_key] else: if parts[0] in _dict: # FIXME maybe optimise this by not converting to and from arrays return getkey(_dict[parts[0]], '.'.join(parts[1:]), _default) G.debug(''.join(['Key "', _key, '" not found in hash.'])) return _default
def perform_wrapping(self): G.info('Starting wrapping.') self.globalvars['body'] = '' self.globalvars['style'] = '' self.globalvars['prescript'] = '' self.globalvars['script'] = '' for obj in self.objects: if not obj.removed: if len(obj.body): self.globalvars['body'] = u'\n'.join([self.globalvars['body'], obj.body]) if len(obj.style): self.globalvars['style'] = u'\n'.join([self.globalvars['style'], obj.style]) if len(obj.prescript): self.globalvars['prescript'] = u'\n'.join([self.globalvars['script'], obj.script]) if len(obj.script): self.globalvars['script'] = u'\n'.join([self.globalvars['script'], obj.script]) templates = getkey(self.globalvars, '$Templates', {}) for tname in templates: G.debug('Adding template to style/script for '+tname) template = getkey(templates, tname, {}) self.globalvars['style'] = '\n'.join([self.globalvars['style'], getkey(template, 'style')]) self.globalvars['prescript'] = '\n'.join([self.globalvars['prescript'], getkey(template, 'prescript')]) #self.globalvars['script'] = '\n'.join([self.globalvars['script'], getkey(template, 'script')]) wrapper = getkey(self.globalvars, '$Wrapper', False) if wrapper: wrapper.process() self.document = wrapper.body else: G.critical("No wrapper registered") self.document = u'no wrapper' G.info('Finished wrapping.')
def generate(self): # Store todays date self.globalvars['today'] = str(datetime.date.today()) if not self.init_file(): return False self.load_objects() self.close_file() G.debug('\n'.join( ['POST LOAD_OBJECT DUMP', self.get_objects_as_string()])) self.preprocess_objects() G.debug('\n'.join( ['POST PRE_PROCESS DUMP', self.get_objects_as_string()])) self.process_objects_for_syntax_sugar() G.debug('\n'.join([ 'POST PROCESS_OBJECT_FOR_SYNTAX_SUGAR DUMP', self.get_objects_as_string() ])) self.process_object_queue() G.debug('\n'.join( ['POST PROCESS_OBJECT_QUEUE DUMP', self.get_objects_as_string()])) self.perform_wrapping()
def setup(self): if '$Table' in self.globalvars: G.info("Table already setup.") return G.info("Setting up Table.") # Set defaults self.globalvars['$Table'] = { 'mode': 'inline', 'headers': 'yes', } # Init TOT (Table of Tables) list self.globalvars['$TOT'] = [] counter_create(self.globalvars['$Counters'], 'table', None) self.globalvars['numberingtable'] = '!!table!!.'
def getkey(_dict, _key, _default=''): if not _dict: G.debug('Dict is not defined or empty for getkey') return _default parts = _key.split('.') if len(parts) == 1: if _key in _dict: return _dict[_key] else: if parts[0] in _dict: # FIXME maybe optimise this by not converting to and from arrays return getkey(_dict[parts[0]], '.'.join(parts[1:]), _default) G.debug(''.join(['Key "',_key,'" not found in hash.'])) return _default
def process(self): template_name = getkey(self.arguments, 'template', self.object_name) template = getkey(self.globalvars['$Templates'], template_name) self.body = unicode(getkey(template, 'body')) self.pre_process() self.body = self.body.replace('%content%', unicode(self.content)) G.debug(self.globalvars['$Labels']) self.body = varsub(self.body, [self.localvars, self.arguments, self.globalvars], getkey(self.globalvars, '$Templates', False), recursive=getkey(self.arguments, 'substitute', 'yes') != 'no')
def __init__(self, _regexp, _params, _output): self.regexp_string = _regexp try: self.regexp = re.compile(_regexp, re.UNICODE) except re.error: G.critical(''.join(['Regexp ',_regexp,' failed to compile, ignoring it.'])) self.broken = True else: G.debug(''.join(['Registred SyntaxSugar:\nRegexp: ',_regexp, ', Params: ',str(_params), ', Output: ',_output])) self.broken = False self.output = _output self.params = _params self.result = 'none'
def post_upgrade(self): template = getkey(self.arguments, 'primary') G.info(''.join(['Reading template object ', template])) if not template in self.globalvars['$Templates']: self.globalvars['$Templates'][template] = {} output = getkey(self.arguments, 'output', getkey(self.globalvars, 'output', 'html')) place = getkey(self.arguments, 'place', 'body') if output == getkey(self.globalvars, 'output', 'html'): G.info(''.join(['Loading template object as ', template, '/', output, '/', place])) self.globalvars['$Templates'][template][place] = self.content self.removed = True
def setup(self): if '$Figure' in self.globalvars: G.info("Figure already setup.") return G.info("Setting up Figure.") # Set defaults self.globalvars['$Figure'] = { 'mode': 'base64', 'width': '100%', } self.globalvars['$Base64Data'] = {} # Init TOF list self.globalvars['$TOF'] = [] counter_create(self.globalvars['$Counters'], 'figure', None) self.globalvars['numberingfigure'] = '!!figure!!.'
def country_texts_parsed(factsys, data): factsys.grammar.embed("G") import G fields = factsys.fieldnames.split() facts = [] for tuple in data: countr = factsys.data2lin("CName", tuple.country) cap = factsys.data2lin('CName', tuple.capital) tcont = G.cdProperty( factsys.str2exp('Name', tuple.continent).unpack()[1][0]) cont = factsys.exp2str(tcont) curr = factsys.data2lin('Name', tuple.currency) pop = factsys.data2lin("Numeric", tuple.population) are = factsys.data2lin("Numeric", tuple.area) doc = factsys.str2exp( "Doc", ("{} is a {} country with {} inhabitants. " "its area is {} . " "the capital of {} is {} and its currency is {}.").format( countr, cont, pop, are, countr, cap, curr)) facts.append(doc) return facts
def render_progress(A): from .termui import get_terminal_size as G if A.is_hidden: return B = [] if A.autowidth: H = A.width A.width = 0 I = term_len(A.format_progress_line()) D = max(0, G()[0] - I) if D < H: B.append(BEFORE_BAR) B.append(_E * A.max_width) A.max_width = D A.width = D F = A.width if A.max_width is not _A: F = A.max_width B.append(BEFORE_BAR) C = A.format_progress_line() E = term_len(C) if A.max_width is _A or A.max_width < E: A.max_width = E B.append(C) B.append(_E * (F - E)) C = ''.join(B) if C != A._last_line and not A.is_fast(): A._last_line = C echo(C, file=A.file, color=A.color, nl=_C) A.file.flush()
def get_line(self): if len(self.first_lines): G.debug("Return first line") self.doing_first_lines = True return self.first_lines.pop(0) # shift if self.doing_first_lines: self.first_object = True self.doing_first_lines = False try: line = self.file.readline() self.lineno += 1 except IOError: G.warning('IO Error: Could not read line.') return '' else: return line
def game_main_from_app(app, use_glut=False): import sys G.cmd_argv = sys.argv G.use_glut = use_glut app() if use_glut: print "use glut" from framework.zgraphics_glut import Graphics G.graphicsm = Graphics() else: print "use glfw" from framework.zgraphics_glfw import Graphics G.graphicsm = Graphics() G.main_initialize() G.appm.main()
def CutClothWithCutterCurve(self, oMeshCutCloth, sMirrorX=None): #print("-CCurve.CutClothWithCutterCurve() on curve '{}'".format(self.sName)) G.Dump("CutClothWithCutterCurve: " + oMeshCutCloth.name) self.RebuildCurve() ###CHECK17:? #=== Mirror the cutter mesh about X=0.5 if requested (needed for side cuts to enforce symmetry === if sMirrorX == "MirrorX": oModMirrorX = Util_CreateMirrorModifierX(self.oCutterO) oModMirrorX.mirror_object = bpy.data.objects["EmptyAtZeroPointFiveForClothCutting"] # Specify empty set to X=0.5 so mirror is done about body center AssertFinished(bpy.ops.object.modifier_apply(modifier=oModMirrorX.name)) #=== Create a boolean modifier and apply it to remove the extra bit beyond the current cutter === SelectObject(oMeshCutCloth.name, True) oModBoolean = oMeshCutCloth.modifiers.new('BOOLEAN', 'BOOLEAN') #oModBoolean.solver = "CARVE" ###INFO: Older 'CARVE' Boolean Solver appears to destroy all the custom data layers. BMESH is default but it has problems... ###DESIGN17: what to do? ###BUG17: BMESH cuts sometime don't work oModBoolean.object = self.oCutterO oModBoolean.operation = 'DIFFERENCE' ###INFO: Difference is the one we always want when cutting as the others appear useless! Note that this is totally influenced by side of cutter normals!! AssertFinished(bpy.ops.object.modifier_apply(modifier=oModBoolean.name)) ###INFO: Have to specify 'modifier' or this won't work! #=== Boolean cut leaves quads and ngons on the border and triangles give us more control on what to delete -> Triangulate before border cleanup === bpy.ops.object.mode_set(mode='EDIT') bpy.ops.mesh.select_all(action='SELECT') bpy.ops.mesh.delete_loose() # For some reason back cloth leaves loose verts! Clean with this call bpy.ops.mesh.quads_convert_to_tris() ###CHECK17: Needed?? bpy.ops.mesh.select_all(action='DESELECT') bpy.ops.object.mode_set(mode='OBJECT') Util_HideMesh(self.oCutterO)
def pre_process(self): # Do heading and toc stuff here if self.arguments.has_key('level'): self.localvars['level'] = self.arguments['level'] else: self.localvars['level'] = '2' G.debug(''.join(['Level set to ', self.localvars['level']])) if self.arguments.has_key('primary'): self.localvars['title'] = self.arguments['primary'] G.debug(''.join(['Title set to ', self.localvars['title']])) # Store title to TOC if u'label' in self.arguments: self.localvars['safe_title'] = self.arguments[u'label'] self.globalvars['$Labels'][self.arguments[u'label']] = { 'id': self.localvars['safe_title'], 'caption': getkey(self.localvars, 'title', 'title missing'), } else: self.localvars['safe_title'] = safe_link( getkey(self.localvars, 'title', 'title missing')) counter_tick(self.globalvars['$Counters'], ''.join(['toc', str(self.localvars['level'])])) tocitem = { 'safe_title': self.localvars['safe_title'], 'link': '#%s' % self.localvars['safe_title'], 'title': self.localvars['title'], 'level': self.localvars['level'], 'numbering': varsub(''.join(['%numbering', self.localvars['level'], '%']), [self.globalvars], []) } self.localvars['numbering'] = tocitem['numbering'] if (int(self.localvars['level']) <= int( getkey(self.globalvars, 'toc_depth', 3))): self.globalvars['$TOC'].append(tocitem) if (int(self.localvars['level']) <= int( getkey(self.globalvars, 'alt_toc_depth', 3))): self.globalvars['$ALTTOC'].append(tocitem) return True
def __init__(self, _regexp, _params, _output): self.regexp_string = _regexp try: self.regexp = re.compile(_regexp, re.UNICODE) except re.error: G.critical(''.join( ['Regexp ', _regexp, ' failed to compile, ignoring it.'])) self.broken = True else: G.debug(''.join([ 'Registred SyntaxSugar:\nRegexp: ', _regexp, ', Params: ', str(_params), ', Output: ', _output ])) self.broken = False self.output = _output self.params = _params self.result = 'none'
def pre_process(self): # Do heading and toc stuff here if self.arguments.has_key('level'): self.localvars['level'] = self.arguments['level'] else: self.localvars['level'] = '2' G.debug(''.join(['Level set to ',self.localvars['level']])) if self.arguments.has_key('primary'): self.localvars['title'] = self.arguments['primary'] G.debug(''.join(['Title set to ',self.localvars['title']])) # Store title to TOC if u'label' in self.arguments: self.localvars['safe_title'] = self.arguments[u'label'] self.globalvars['$Labels'][self.arguments[u'label']] = { 'id': self.localvars['safe_title'], 'caption': getkey(self.localvars,'title','title missing'), } else: self.localvars['safe_title'] = safe_link( getkey(self.localvars,'title','title missing')) counter_tick(self.globalvars['$Counters'], ''.join(['toc',str(self.localvars['level'])])) tocitem = { 'safe_title': self.localvars['safe_title'], 'link': '#%s' % self.localvars['safe_title'], 'title': self.localvars['title'], 'level': self.localvars['level'], 'numbering': varsub( ''.join(['%numbering', self.localvars['level'], '%']), [self.globalvars], []) } self.localvars['numbering'] = tocitem['numbering'] if (int(self.localvars['level']) <= int(getkey(self.globalvars, 'toc_depth', 3))): self.globalvars['$TOC'].append(tocitem) if (int(self.localvars['level']) <= int(getkey(self.globalvars, 'alt_toc_depth', 3))): self.globalvars['$ALTTOC'].append(tocitem) return True
def pre_process(self): G.debug(''.join( ['Doing post upgrade when globalvars = ', str(self.globalvars)])) filename = getkey(self.arguments, 'primary', False) if not filename: G.error('No filename specified, skipping Input') return G.info(''.join(['Inserting ', filename])) p = None if os.path.isfile(getkey(self.globalvars, 'root') + filename): p = Processor.Processor(getkey(self.globalvars, 'root'), filename, _is_main_file=False) if os.path.isfile( getkey(self.globalvars, 'root') + 'templates/' + filename): p = Processor.Processor(getkey(self.globalvars, 'root') + 'templates/', filename, _is_main_file=False) elif os.path.isfile(getkey(self.globalvars, 'templatedir') + filename): p = Processor.Processor(getkey(self.globalvars, 'templatedir'), filename, _is_main_file=False) elif os.path.isfile(G.template_dir + filename): p = Processor.Processor(G.template_dir, filename, _is_main_file=False) else: G.error('Could not find file requested by Input: ' + filename) return # Use the uppermost globalvars dictionary p.globalvars = self.globalvars # Load the objects if p.init_file(): p.load_objects() p.close_file() # Copy objects from the processor to the object self.sub_objects = p.objects G.debug(''.join(['Input objects are: ', p.get_objects_as_string()])) self.removed = True
def run_dev(): # run as a dev environment. # this run setting will load the file source/main.py and expect class Main(Component) # as a default component G.window(True, 480, 640) clear_camera = G.camera("clear") clear_showcase = G.showcase("clear") for i in range(0, 8): G.SHOWCASES.append(G.showcase("3dcase")) G.SCENE = G.Scene("Main scene") # TODO: CHANGE MAIN HERE, WE NOT USING IT AT ALL from source.main import Main G.GameObject.Create("Main gameplay object").add_component(Main()) # init main component while True: G.DT = G.ELAPSED_TIME = G.getElapsedTime() # moveVector = G.vec3(0.0, 0.0, 0.0) # touch = G.singleTouch() # if touch is not None: # if touch["is_pressed"]: # print("ASDASDSD") # moveVector = G.vec3( # touch["cur_x"] - touch["org_x"], 0, -(touch["cur_y"] - touch["org_y"]) # ) # moveVector = G.vec3(cam.camera.viewInverseMatrix * moveVector) for go in G.SCENE.gameobjects: go.awake() # awake inactivated components for go in G.SCENE.gameobjects: go.start() # start inactivated components for go in G.SCENE.gameobjects: go.update() # update the components clear_camera.shoot(clear_showcase, clearColor=True) for go in G.SCENE.gameobjects: go.try_render_camera() # render the camera components G.swap() G.SCENE.update_collections()
def pre_process(self): # Export variables if not self.arguments.get('primary') in (u'', 'no-overwrite'): G.info('Exporting global var with contents') self.globalvars[self.arguments.get('primary')] = self.content else: G.info('Exporting global vars') for varname in self.arguments.keys(): G.debug(''.join(['Preparing "',varname,'" = "',self.arguments[varname],'".'])) if (varname != 'primary' and not (self.arguments['primary'] == 'no-overwrite' and varname in self.globalvars.keys())): G.debug(''.join(['Copying "',varname,'" = "',self.arguments[varname],'" to globals.'])) self.globalvars[varname] = self.arguments[varname]
def country_facts_embedded(factsys, tuple): countr = factsys.str2exp("CName", tuple[0]) cap = factsys.str2exp('Name', tuple.capital) cont = factsys.str2exp('CName', tuple.continent) curr = factsys.str2exp('Name', tuple.currency) pop = mkInt(tuple.population) are = mkInt(tuple.area) factsys.grammar.embed("G") import G object = G.NameObject(G.cName(countr)) return [ G.AttributeFact(G.capital_Attribute, object, G.NameValue(cap)), G.AttributeFact(G.area_Attribute, object, G.IntValue(are)), G.populationFact(countr, pop), G.continentFact(countr, cont), G.AttributeFact(G.currency_Attribute, object, G.NameValue(curr)) ]
def gBL_ClothCut_ApplyCut( sNameBody, sNameCurve, nCenterX, nCenterY, nCenterZ ): # Client-side wrapup of Cut_ApplyCut() that apples the given cutter to a virgin new cloth mesh copied from source oMeshClothCutO = DuplicateAsSingleton( sNameBody + G.C_NameSuffix_ClothBase, sNameBody + G.C_NameSuffix_ClothCut, G.C_NodeFolder_Game, True) # Copy the base mesh to reset the cut to start oCurveO = bpy.data.objects[sNameCurve] aBorderLocatorVertPos = {} vecCurveCenterClient = Vector((nCenterX, nCenterY, nCenterZ)) vecCurveCenter = G.VectorU2B(vecCurveCenterClient) Cut_ApplyCut(oMeshClothCutO, oCurveO, vecCurveCenter, aBorderLocatorVertPos) Client.Client_ConvertMeshForUnity( oMeshClothCutO, True ) # Mesh has changed topology, update its state for Client ###CHECK!!!! Expensive complex call??? Do all of that??? return G.DumpStr( "OK: gBL_Cut_ApplyCut(ClothCut = '[]' Curve='{}')".format( oMeshClothCutO.name, sNameCurve))
def translate(self, _input): if self.broken: G.debug('This SyntaxSugar is broken.') return False G.debug(''.join(['Testing expression: ', _input])) m = re.match(self.regexp, _input) if m: G.debug(''.join([u'Match! Parameters: ',unicode(self.params)])) result = self.output for i in range(1, len(self.params)+1): G.debug(''.join(['Replacing parameter: ', ''.join(['%',self.params[i-1],'%']), ' -> ', m.group(i)])) result = result.replace( ''.join(['%',self.params[i-1],'%']), m.group(i) ) G.debug(''.join(['Result: ', result])) self.result = result.split('\n') return True else: return False
def post_upgrade(self): G.info(''.join( ['Doing post upgrade when globalvars = ', str(self.globalvars)])) G.info(''.join(['Content -> output will be: ', self.content])) ss = SyntaxSugarDefinition(getkey(self.arguments, 'pattern'), getkey(self.arguments, 'params').split(','), self.content) if not ss.broken: self.globalvars['$SyntaxSugar'].append(ss) G.info('Added SyntaxSugar.') else: G.warn('SyntaxSugar was broken.')
def post_upgrade(self): G.info(''.join(['Doing post upgrade when globalvars = ',str(self.globalvars)])) G.info(''.join(['Content -> output will be: ',self.content])) ss = SyntaxSugarDefinition( getkey(self.arguments, 'pattern'), getkey(self.arguments, 'params').split(','), self.content ) if not ss.broken: self.globalvars['$SyntaxSugar'].append(ss) G.info('Added SyntaxSugar.') else: G.warn('SyntaxSugar was broken.')
def continent_text(factsys, data, cont): factsys.grammar.embed("G") import G facts = [] cont_data = [d for d in data if cont in [d.continent, the_world]] ncountries = len(cont_data) largestpop = max(cont_data, key=lambda c: int(c.population)).country largestarea = max(cont_data, key=lambda c: int(c.area)).country totalpop = sum([int(c.population) for c in cont_data]) // 1000000 doc = factsys.str2exp("Doc", ("there are {} countries in {}.").format( ncountries, cont)) doc = G.AddSentenceDoc( doc, factsys.str2exp("Sentence", ("the total population of {} is {} million").format( cont, totalpop))) doc = G.AddSentenceDoc( doc, factsys.str2exp( "Sentence", ("{} has the largest population and {} has the largest area" ).format(largestpop, largestarea))) billions = [c.country for c in cont_data if int(c.population) > 1000000000] if len(billions) == 1: subject = billions[0] property = ' is the only country ' elif len(billions) > 1: subject = ', '.join(billions[:-1]) + ' and ' + billions[-1] property = ' are the only countries ' if billions: doc = G.AddSentenceDoc( doc, factsys.str2exp( 'Sentence', subject + property + 'with over a billion inhabitants')) return doc
def from_array(self, _source): self.lines = _source first_line = True done_with_arguments = False re_def = '^([A-Za-z0-9]+?):' for line in _source: if first_line: parts = re.match(re_def, line) if (not parts): G.debug(''.join(['is_first=',str(self.is_first),', is_main_file=',str(self.is_main_file)])) if self.is_first and self.is_main_file: # Special fallback for first object as title self.object_name = 'Title' self.arguments[u'title'] = unicode(line) else: self.object_name = 'Paragraph' # fallback, but can also be SyntaxSugar self.content = unicode(line) done_with_arguments = True else: self.object_name = unicode(parts.group(1)) self.arguments['primary'] = unicode(line[len(self.object_name)+2:].strip()) first_line = False else: # not first line if not done_with_arguments: if (line == '-'): # use - as separetor if contents start with argoid line done_with_arguments = True else: parts = re.match(re_def, line) if (not parts): if self.is_first: # Special fallback for first object as subtitle self.arguments['subtitle'] = unicode(line) else: self.content = u''.join([self.content,'\n',line]) done_with_arguments = True else: self.arguments[parts.group(1)] = unicode(line[len(parts.group(1))+2:].strip()) else: self.content = u''.join([self.content,'\n',line]) self.upgrade() G.debug(''.join(['Read object: ', self.object_name,' args=',str(self.arguments),' content=',self.content])) return True
def generate(self): # Store todays date self.globalvars['today'] = str(datetime.date.today()) if not self.init_file(): return False self.load_objects() self.close_file() G.debug('\n'.join(['POST LOAD_OBJECT DUMP', self.get_objects_as_string()])) self.preprocess_objects() G.debug('\n'.join(['POST PRE_PROCESS DUMP', self.get_objects_as_string()])) self.process_objects_for_syntax_sugar() G.debug('\n'.join(['POST PROCESS_OBJECT_FOR_SYNTAX_SUGAR DUMP', self.get_objects_as_string()])) self.process_object_queue() G.debug('\n'.join(['POST PROCESS_OBJECT_QUEUE DUMP', self.get_objects_as_string()])) self.perform_wrapping()
def process_object_queue(self): G.info('Starting queue processing.') subprocessors = getkey(self.globalvars, '$Subprocessors', []) while(len(self.process_queue)): obj = self.process_queue.pop(0) if not obj.removed: G.info(''.join(['Processing object of type ', obj.object_name])) for sp in subprocessors: new_objects = sp.run(obj) if len(new_objects): for no in new_objects: self.objects.append(no) self.process_queue.append(no) obj.needs_rerun = True obj.process() if obj.needs_rerun: G.debug('Reputting object %s' % obj.__class__) self.process_queue.append(obj) G.info('Finished queue processing.')
def process(self): template_name = getkey(self.arguments, 'template', self.object_name) template = getkey(self.globalvars['$Templates'], template_name) self.body = getkey(template, 'wrapper') self.pre_process() # Insert localvars for k in self.localvars: G.debug(''.join(['Replacing localvar: ',str(k),'.'])) self.body = self.body.replace(''.join(['%',str(k),'%']),unicode(self.localvars[k])) # Insert arguments for k in self.arguments: G.debug(''.join(['Replacing argument: ',str(k),'.'])) self.body = self.body.replace(''.join(['%',str(k),'%']),unicode(self.arguments[k])) # Insert globalvars for k in self.globalvars: if not k[0] == '$': # non-string start with $ G.debug(''.join(['Replacing globalvar: ',str(k),'.'])) self.body = self.body.replace(''.join(['%',str(k),'%']),unicode(self.globalvars[k])) # Insert content G.debug(''.join(['Calculated body: ', self.body]))
def init_file(self): self.first_lines = list(getkey(G.first_lines, self.output, [])) if self.is_main_file else [] self.filepath = ''.join([self.root,self.filename]) self.lineno = 0 G.info(''.join(['Trying to open file "',self.filepath,'".'])) try: self.file = io.open(self.filepath, 'r') except IOError: G.critical(''.join(['The file "',self.filepath,'" could not be opened.'])) return False else: G.info(''.join(['The file "',self.filepath,'" was opened.'])) return True
def post_upgrade(self): primary = getkey(self.arguments, 'primary') if not primary == '': G.info(''.join(['Creating a dummy object of type ', primary])) obj = Generic( self.globalvars, [''.join([primary,':'])] + self.lines[1:] ) obj.setup() G.debug('\n'.join(['DUMPING DUMMY OBJECT', obj.dump()])) else: G.critical(''.join('Missing argument: primary')) self.removed = True # This object's purpose is done
def load_objects(self): self.doing_first_lines = True self.first_object = True # First object will be treated differently last_line = False # A flag for last line (eof) detection lines = [] # A object line buffer, cleared after each object stored object_start_line = 0 # line number of object start while (True): next_line = self.get_line() # Detect last line before stripping away te \n if len(next_line) == 0: last_line = True G.debug('Detected last line.') next_line = next_line.strip('\n\r') G.debug(''.join(['Reading line: ',next_line])) # Check if it is an empty line, if so, finish object if not next_line: if len(lines): G.debug('Creating object.') # Create a Generic Object that can later be upgraded obj = Plugin.Generic(self.globalvars, lines, self.first_object, self.is_main_file, _filepath=self.filepath, _lineno=object_start_line) # Prepare for next round and save the current object lines = [] if not self.doing_first_lines: self.first_object = False if not obj.removed: self.objects.append(obj) else: G.debug('Skipping empty object.') object_start_line = self.lineno + 1 else: lines.append(next_line) #lines.append(next_line.strip()) if last_line: return
def counter_tick(counter_hash, name, step=1): counter = getkey(counter_hash, name, False) child_name = getkey(counter, 'child', False) if child_name: child = getkey(counter_hash, child_name, False) else: child = False if not counter: G.debug("Counter "+name+" does not exist") return 'counter error' G.debug("Adding "+str(step)+" to counter "+name) counter['value'] += step if child: G.debug("Resetting counter "+child_name) child['value'] = 0 return 0
def __init__(self, _globalvars = {},_source=None, _is_first=False, _is_main_file=True, _filepath='', _lineno=0): self.id = G.getid() self.object_name = 'None' self.arguments = {} self.content = u'' self.is_first = _is_first self.is_main_file = _is_main_file self.needs_rerun = False self.localvars = {} self.globalvars = _globalvars self.sub_objects = [] self.lines = [] # store the source lines self.filepath = _filepath self.lineno = _lineno # Output stuff self.removed = False self.body = u'' self.style = u'' self.prescript = u'' self.script = u'' if (_source): self.from_array(_source)
def safe_link(title): safe_title = re.sub('[\W]','', title.replace(' ','_')).lower() G.debug(''.join(['Safing ',title,' to ',safe_title,'.'])) return '_'.join([safe_title, str(G.getSafeLinkId())])
import G from Utils import getkey, varsub from Generic import Generic from Utils import counter_create, counter_tick try: from pygments import highlight from pygments.lexers import (get_lexer_by_name, get_lexer_for_filename, get_lexer_for_mimetype) from pygments.lexers import guess_lexer, guess_lexer_for_filename from pygments.formatters import HtmlFormatter from pygments.util import ClassNotFound except ImportError: have_pygment = False G.critical("Could not load Pygment.") else: have_pygment = True G.info("Loaded Pygment.") class Code(Generic): def __init__(self): super(Code, self).__init__() self.init() def pre_process(self): if not 'language' in self.arguments: self.arguments['language'] = getkey(self.arguments, 'primary', u'?') self.arguments['caption'] = getkey(self.arguments, 'caption', u'') self.arguments['linenumbers'] = getkey(self.arguments, 'linenumbers', u'no') self.arguments['highlight'] = getkey(self.arguments, 'highlight', '')
def varsub(_text, _dicts, _templates, recursive=True, last_chance=False): # Regexps re_var = '(%(\w+?)%)' re_list = '(%(\$\w+?) using (\w+?)%)' re_counter = '(\!\!(\w+?)\!\!)' re_translate = '(__(\w+?)__)' re_inline = '(%([A-Za-z0-9]+?):(\w+?)%)' re_link = '(\[\[([^\]]+?)\]\])' # Foundness tracker found = False # Single variables %variable% m_var = re.findall(re_var, _text) for m in m_var: G.debug(u'Varsub variable: '+m[0]) value = None for d in _dicts: v = getkey(d, m[1], False) if v is not False: value = v found = found or v break if value is not None: G.debug(u'Varsub variable value: '+unicode(value)) _text = _text.replace(m[0], unicode(value)) if not recursive: return _text # Translations __token__ m_var = re.findall(re_translate, _text) for m in m_var: G.debug(u'Varsub variable: '+m[0]) value = '' for d in _dicts: t = getkey(d, '$i18n', False) if t: l = getkey(t, getkey(d, 'language', 'en'), False) if l: v = getkey(l, m[1], False) if v is not False: value = v found = found or v break G.debug(u'Varsub variable value: '+unicode(value)) _text = _text.replace(m[0], unicode(value)) # List using template for items %$List using template% m_var = re.findall(re_list, _text) for m in m_var: G.debug(u'Varsub list placeholder: '+m[0]) G.debug(u'Varsub list variable: '+m[1]) G.debug(u'Varsub list template: '+m[2]) itemlist = [] for d in _dicts: v = getkey(d, m[1], False) if v: itemlist = v found = found or v break template = getkey(_templates, m[2], False) if template: # remove this when nested getkey is implemented template = getkey(template, 'body', False) if not template: G.critical(''.join(['Template not found: ',m[2]])) next result = u'' for item in itemlist: G.debug('Varsub list processing item: '+ getkey(item, 'caption', '[item caption not found!!!]')) result = u'\n'.join([result, varsub(template, [item]+_dicts, _templates)]) _text = _text.replace(m[0], result) # Counter for items !!counter!! m_var = re.findall(re_counter, _text) counters = [] for m in m_var: G.debug(u'Varsub counter placeholder: '+m[0]) G.debug(u'Varsub counter variable: '+m[1]) for d in _dicts: v = getkey(d, '$Counters', False) if v: counters = v break if v: counter = getkey(counters, m[1], False) if counter: _text = _text.replace(m[0], counter_get(counter)) # Links [[link]] m_var = re.findall(re_link, _text) for m in m_var: G.debug(u'Link expression: '+m[0]) value = '' v = False parts = m[1].split(' ', 1) emergency_caption = '[[missing caption]]' if len(parts) == 1: target = parts[0] caption = False emergency_caption = target else: target = parts[0] caption = parts[1] G.debug(u'Link target/caption: %s/%s' % (target, caption)) source = False if target[0] == '#': source = '$Labels' elif target[0] == '!': source = '$References' else: v = '<a href="%s">%s</a>' % (target, caption) G.debug(u'Link is external %s' % v) value = v found = found or v if source: G.debug(u'Link %s has source: %s' % (target, source)) target = target[1:] for d in _dicts: if source in d: label = getkey(d[source], target, False) if label: v = '<a href="#%s">%s</a>' % (getkey(label, 'id', ''), caption or getkey(label, 'caption', emergency_caption)) G.debug(u'Link is internal %s' % v) if v: value = v found = found or v break if v: G.debug(u'Varsub link variable value: '+unicode(value)) _text = _text.replace(m[0], unicode(value)) elif last_chance: G.error(u'Link creation failed for %s, missing label?' % m[0]) # Tail recursive substitution if found: return varsub(_text, _dicts, _templates) else: return _text