コード例 #1
0
ファイル: main.py プロジェクト: Grifone75/PyProceduralPlanet
def DrawGLScene():
    global scene
    global camera
    global hud
    global frametimer
    global SceneMstr
    global Signals
 
    
    #update the scene
    frametimer.update()
    RequestManager.update()
    t0 = time.time()
    SceneMstr.update()
    Signals['update'].setvalue((time.time()-t0)*1000)
    # Clear The Screen And The Depth Buffer
    glFinish()
    
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    t0 = time.time()
    #draw all objects in the scene
    
    SceneMstr.draw()
    Signals['draw'].setvalue((time.time()-t0)*1000)
    #  since this is double buffered, swap the buffers to display what just got drawn. 
    glFinish()
    glutSwapBuffers()
コード例 #2
0
def main():
    if '-r' in sys.argv:
        RequestManager.read_tiindicators()
        sys.exit()
    config.verbose_log = ('-v' in sys.argv)
    print('fetching & parsing data from misp...')
    events = _get_events()
    parsed_events = list()
    for event in events:
        parsed_event = defaultdict(list)

        for key, mapping in EVENT_MAPPING.items():
            parsed_event[mapping] = event.get(key, "")
        parsed_event['tags'] = [
            tag['name'].strip() for tag in event.get("Tag", [])
        ]
        _handle_diamond_model(parsed_event)
        _handle_tlp_level(parsed_event)
        _handle_timestamp(parsed_event)

        for attr in event['Attribute']:
            if attr['type'] == 'threat-actor':
                parsed_event['activityGroupNames'].append(attr['value'])
            if attr['type'] == 'comment':
                parsed_event['description'] += attr['value']
            if attr['type'] in MISP_ACTIONABLE_TYPES:
                parsed_event['request_objects'].append(RequestObject(attr))

        parsed_events.append(parsed_event)
    del events

    total_indicators = sum([len(v['request_objects']) for v in parsed_events])
    with RequestManager(total_indicators) as request_manager:
        for request_body in _graph_post_request_body_generator(parsed_events):
            request_manager.handle_indicator(request_body)
コード例 #3
0
def get_fiat_value(self, start_date=datetime.date(datetime.now() - timedelta(days=1)), stop_date=datetime.date(datetime.now()),
                       base_currency="EUR", target_currency="USD"):
        """
        FIAT currency converter from European Central Bank, through https://exchangeratesapi.io API
        Parameters
        ----------
        start_date : datetime
            starting date for currency retrieval (default value: yesterday)
        stop_date : datetime
            stop date for currency retrieval (default value = today)
        base_currency : string
            base currency to convert from (EUR, USD, ...)
        target_currency : string
            target currency to convert to (USD, JPY, GBP, ...)

        Returns
        -------
        current_rate : float
            Exchange rate for stop date
        currecy_rates : dictionary(date: string<YYYY-MM-DD>, float)
            Exchange rates for whole configured date span (bank holidays not included, no rate for those dates)

        Raises
        ------
        ValueError
            If base currency and target currency are the same
            If stop date is previous to start date
            If any of the dates is in the future (beyond today)
        ConnectionError
            If response from server is not 200
        """
        currency_rates = dict()
        if base_currency == target_currency:
            raise ValueError("Base currency and target currency can not be equal")
        elif start_date >= datetime.now():
            raise ValueError("Start date must not be in the future or current date")
        elif stop_date > datetime.now():
            raise ValueError("Start date must not be in the future or current date")
        elif start_date > stop_date:
            raise ValueError("Start date can not be greater than stop date")
        else:
            # EUR / fiat_currency exchange rate from BCE
            date_start = start_date.strftime('%Y-%m-%d')
            date_stop = stop_date.strftime('%Y-%m-%d')
            headers = {
                'Accepts': 'application/json',
                'Accept-Encoding': 'deflate, gzip',
            }
            request_address = f'https://api.exchangeratesapi.io/history?base={base_currency.value}&start_at={date_start}&end_at={date_stop}&symbols={target_currency.value}'
            manager_fiat = RequestManager(headers)
            data = manager_fiat.send_request(parameters={}, url=request_address)

            # Check that everything was OK
            if manager_fiat.status_code == 200:
                rates = data["rates"]
                for rate in rates:
                    currency_rates[rate] = round(rates[rate][target_currency.value],4)
                return currency_rates[stop_date.strftime('%Y-%m-%d')], currency_rates
            else:
                raise ConnectionError("Connection did not finish as expected. HTTP error code {}\nRequest was: {}".format(manager_fiat.status_code, request_address))
コード例 #4
0
    def __init__(self):
        self.authorizer = Authorizer("auth_info.json")

        self.request_manager = RequestManager()

        self.sockets: Dict[int, socket.socket] = {}  # fileno : sock

        self.clients: Dict[int, Client] = {}  # fileno : client
        self.authorized_clients: Dict[str, Client] = {}  # username : client

        self.buffered_data: Dict[int, str] = {}  # fileno : data

        self.poller = select.poll()

        self.remove_idle_clients_forever()
コード例 #5
0
 def CheckLevelZeroTexComplete(self):
     if self.state <> 0:
         incomplete = False
         print 'checking completeness'
         for i in range(0, 6):
             if not (self.face[i].texture_baked):
                 incomplete = True
         if incomplete:
             print 'not complete, rescheduling'
             RequestManager.add_request(self.CheckLevelZeroTexComplete, [],
                                        'default', None, True)
         else:
             self.state = 0
             #  TODO 2017 - do not work - self.TexAtlas.save_texture_atlas_bmp("test2017")
             print 'complete now'
コード例 #6
0
def send_message(comments, footer, footer_icon):
    star = ":star:"
    data = {
        'score': comments['score'],
        'title': comments['title'],
        'date': comments['date'],
        'comment': comments['comment'],
        'pretext': '`TEST` UtaPass Android has a new review!',
        'text': ''.join(star * int(comments['score']) + ' Score : %s' % str(comments['score'])),
        'content': u'{}\n\n [Translation]\n*{}*\n\n{}\n\n_{}  ver.{}_'.format(comments['comment'],
                                                                              comments['translated_title'],
                                                                              comments['translated_comment'],
                                                                              (comments['date']).strftime('%Y-%m-%d'),
                                                                              comments['version']),
        'thumb_url': 'https://img.au-market.com/mapi/pc_icon/39767/3976700000002/100211_116788.png',
        'footer': footer,
        'footer_icon': footer_icon
    }
    # if review has no version info or from au Market, wouldn't show comments['version']
    if comments['version'] is None or footer == FOOTER[0]:
        data['content'] = u'{}\n\n [Translation]\n*{}*\n\n{}\n\n_{}_'.format(comments['comment'],
                                                                             comments['translated_title'],
                                                                             comments['translated_comment'],
                                                                             (comments['date']).strftime('%Y-%m-%d'))
    RequestManager().slackAttachmentsWithFieldsMessager('#test-b0t', data['pretext'], "", data['text'], "", "",
                                                        "Android Reviews Bot", data['footer'], data['title'],
                                                        data['content'], data['thumb_url'], data['footer_icon'])
コード例 #7
0
ファイル: Tracker.py プロジェクト: Boidkan/Crypto-Tracker
 def writeNewValues(self):
     file = open(self.file_path)
     config = json.load(file)
     data = RequestManager.getPrices(config)
     CSVManager.write(data[0], data[1])
     print("---------------- Added Line ----------------- ")
     print(data[0])
     print(data[1])
     self.scheduler.enter(self.timer, 1, self.writeNewValues)
コード例 #8
0
    def do_triangles_finalize(self, force_completion=False):
        #before doing anything let's check if a texture is baking
        if (self.texture_baking == True) and (force_completion == False):
            #reschedule and exit
            RequestManager.add_request(self.do_triangles_finalize, [],
                                       'get_triangles' + str(self.face),
                                       self.MinimumPriority)
        else:
            #update triangle count info
            self.NodesStats['Triangles'] -= self.currenttrianglecount
            self.currenttrianglecount = self.datadict['index'].__len__()
            self.NodesStats['Triangles'] += self.currenttrianglecount
            t01 = time.time() * 1000
            self.vertici = np.concatenate(self.datadict['vertex'])
            self.indici = np.array(self.datadict['index'], dtype='uint32')

            print(" ****  time conversion to nparrays: " +
                  str(time.time() * 1000 - t01))
            self.VBO_update = [True, True]
コード例 #9
0
 def VBOupdate(self, vboindex):
     nact = 1 - self.activeVBO[vboindex]
     if self.VBO_need_update[vboindex] == 2 and self.face[
             vboindex].VBO_update[nact]:
         #update the nact vbo and reschedule an update
         self.vertexVBO[nact][vboindex].set_array(
             self.face[vboindex].vertici)
         self.indexVBO[nact][vboindex].set_array(self.face[vboindex].indici)
         self.VBO_need_update[vboindex] = self.activeVBO[vboindex]
     if self.VBO_need_update[vboindex] == nact and self.face[
             vboindex].VBO_update[nact]:
         #update the vbo and it's over
         self.vertexVBO[nact][vboindex].set_array(
             self.face[vboindex].vertici)
         self.indexVBO[nact][vboindex].set_array(self.face[vboindex].indici)
         self.VBO_need_update[vboindex] = 3
     if (self.VBO_need_update[vboindex] == self.activeVBO[vboindex]) or (
             self.face[vboindex].VBO_update[nact] == False):
         #cannot update now, reschedule the update
         RequestManager.add_request(self.VBOupdate, [vboindex])
コード例 #10
0
    def do_triangles(self, force_completion=False):
        #per il momento presuppone che datadict sia un dizionario con campi 'vertex' e 'index'
        #se l'oggetto e una foglia
        self.VBO_update = [False, False]
        self.datadict = {'vertex': [], 'index': []}
        if self.datadict['vertex'] == []:
            len = 0
        else:
            len = self.datadict['vertex'].__len__()

        if force_completion:
            if self.children == 0:
                self.get_triangles(self.datadict, True)
            else:
                for ch in self.children:
                    ch.get_triangles(self.datadict, True)
            self.do_triangles_finalize(True)
        else:
            if self.children == 0:
                RequestManager.add_request(self.get_triangles, [self.datadict],
                                           'get_triangles' + str(self.face),
                                           self.NodePriority)
            else:
                for ch in self.children:
                    RequestManager.add_request(ch.get_triangles,
                                               [self.datadict],
                                               'get_triangles' + str(ch.face),
                                               ch.NodePriority)
            #now the job that have to be executed last
            RequestManager.add_request(self.do_triangles_finalize, [],
                                       'get_triangles' + str(self.face),
                                       self.MinimumPriority)
コード例 #11
0
 def get_metadata(self, galleries):
     assert len(galleries) <= self.API_MAX_ENTRIES
     payload = copy.deepcopy(self.BASE_REQUEST)
     payload["gidlist"] = [g.id for g in galleries]
     response = RequestManager.post(self.API_URL, payload=payload)
     self.signals.progress.emit(self.inc_val)
     for gallery in galleries:
         for metadata in response["gmetadata"]:
             id = [metadata["gid"], metadata["token"]]
             if id == gallery.id:
                 gallery.update_metadata({"gmetadata": metadata})
                 gallery.update_qgallery()
                 break
コード例 #12
0
    def get_cypto_value(self,
                        start_date=datetime.date(datetime.now() -
                                                 timedelta(days=1)),
                        stop_date=datetime.date(datetime.now()),
                        currency="XBT"):
        """
        Crypto assets information gathered from CoinMarketCap
        Assets denomination can be found in ISO-4217 from IETF
        (https://tools.ietf.org/html/draft-stanish-x-iso4217-a3-01)
        Parameters
        ----------
        start_date : datetime
            starting date for currency retrieval (default value: yesterday)
        stop_date : datetime
            stop date for currency retrieval (default value = today)
        currency : string
            crypto currency to get information from (XBTC, XETH, ...)
        Returns
        -------
        data : JSON object
            data retreived from CoinMarketCap
        """
        url = 'https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
        parameters = {
            'start': '1',
            'limit': '1',
            'convert': f'{base_currency}'
        }
        headers = {
            'Accepts': 'application/json',
            'Accept-Encoding': 'deflate, gzip'
        }

        if self.api_key_coinmarketcap:
            headers['X-CMC_PRO_API_KEY'] = self.api_key_coinmarketcap

        crypto_manager = RequestManager(headers)
        data = crypto_manager.send_request(parameters, url)
        return data
コード例 #13
0
    def CheckTessellation(self):
        t1 = time.time() * 1000
        #retrieve the camera position in objectspace
        campostr = self.campostr

        self.GetHeightFieldValue(campostr)

        #check if there are cube faces to update from previous loop, otherwise, re-evaluate the needs
        if self.updatelist == []:  # the list of required updates is empty, reevaluate priorities
            #compute for each face the dot product with oncubecam
            #then sort the refresh order by this value
            for oneface in self.face:
                dotp = np.dot(campostr, oneface.facenormal)
                #if dotp >=0.0:
                self.updatelist.append([dotp, oneface])

            #sort the list by dot product decreasing
            if self.updatelist <> []:
                self.updatelist.sort(key=lambda el: el[0], reverse=True)

        else:  # the are updates to complete from previous cycles
            curr_face = self.updatelist[0][
                1]  #get the second element (face pointer) of the first element of the update list
            normalized_surface_height = GlobalSignals.read(
                'height:'
            ) * self.PlanetDescriptor.height / self.PlanetDescriptor.radius
            if curr_face.tessellate_by_distance(
                    campostr, normalized_surface_height, self.kdiv,
                    self.kred) > 0:  #check the tessellation by distance
                RequestManager.add_request(curr_face.do_triangles, [])
                self.VBO_need_update[self.face.index(curr_face)] = 2
            del self.updatelist[0]
        GlobalSignals.set('Nodes', self.face[0].NodesStats['Nodes'])
        GlobalSignals.set('Triangles', self.face[0].NodesStats['Triangles'])

        #debug code
        t2 = time.time() * 1000 - t1
        GlobalSignals.set('tessel ms', t2)
コード例 #14
0
    def update(self):
        #funny test: rotate o fa fraction around the rand_axis
        ca = np.cos(self.rand_angle / 2)
        sa = np.sin(self.rand_angle / 2)
        v = np.append(self.axis * sa, ca)
        qr = qts.Quat(v)
        self.orientation = qr.__mul__(self.orientation)

        #adapt near plane to current distance
        obj_space_distance = np.linalg.norm(self.ActiveCamera.position -
                                            self.position) / self.scale
        near_plane = smoothstephilo(0.1, 10, 1.005, 1.1, obj_space_distance)
        self.ActiveCamera.set_near_far(near_plane, 200000.0)
        GlobalSignals.set('near distance: ', near_plane)
        #check if we tessellate
        RequestManager.add_request(self.CheckTessellation, [])

        #check if a reduction of lod is required
        if self.TexAtlas.free_below_level(0.05):
            self.kdiv *= 0.995
            self.kred *= 0.995
        elif self.kdiv < 3.0 and self.TexAtlas.free_over_level(0.25):
            self.kdiv *= 1.001
            self.kred *= 1.001

        GlobalSignals.set('kdiv: ', self.kdiv)
        GlobalSignals.set('kred: ', self.kred)

        #debug
        GlobalSignals.set('req nr', RequestManager.get_queue_length())
        GlobalSignals.set('req max time',
                          RequestManager.get_queue_max_wait_time_ms())
        GlobalSignals.set(
            'size of patch:', 2 * 3.14 * self.PlanetDescriptor.radius / 4 /
            (2**GlobalSignals.read('level:')))
        GlobalSignals.set('size of unit:',
                          GlobalSignals.read('size of patch:') / 16)
コード例 #15
0
def send_message(comments):
    star = ":star:"
    data = {
        'score': comments['score'],
        'title': comments['title'],
        'date': comments['date'],
        'comment': comments['comment'],
        'pretext': '`TEST` UtaPass iOS has a new review!',
        'text': ''.join(star * int(comments['score']) + ' Score : %s' % str(comments['score'])),
        'content': u'{}\n\n [Translation]\n*{}*\n\n{}\n\n_{}  ver.{}_'.format(comments['comment'],
                                                                              comments['translated_title'],
                                                                              comments['translated_comment'],
                                                                              (comments['date']).strftime('%Y-%m-%d'),
                                                                              comments['version']),
        'thumb_url': 'https://img.au-market.com/mapi/pc_icon/39767/3976700000002/100211_116788.png',
        'footer': 'App Store reviews crawler',
        'footer_icon': 'https://banner2.kisspng.com/20180729/cup/kisspng-app-store-iphone-apple-app-store-icon-transparent-5b5e1adc964cf5.4117097315328939166156.jpg',
    }
    RequestManager().slackAttachmentsWithFieldsMessager('#test-b0t', data['pretext'], "", data['text'], "", "",
                                                        "iOS Reviews Bot", data['footer'], data['title'],
                                                        data['content'], data['thumb_url'], data['footer_icon'])
コード例 #16
0
    def Prepare_Own_Lod_Texture(self, step):
        if step == 0:  #just reserve a tex slot and schedule execution of 1step
            if self.level < self.MAX_DEPTH and self.tex_atlas.count_free_slots(
            ) > 0:
                self.temp_slot = self.tex_atlas.reserve_slot(self)
                self.texture_baking = True
                RequestManager.add_request(self.Prepare_Own_Lod_Texture, [1],
                                           'NodeTexBaking',
                                           self.Distance_From_Camera)

        if step == 1:  #prepare height texture
            self.su['fbo'].set_fbo_scene()
            self.temp_htex = self.su['fbo'].draw_fbo_cube(
                self.pd, self.face, 'pass_1', self.cf[0], self.cf[1],
                self.level, 0)
            #print(self.temp_htex)
            self.su['fbo'].set_base_scene()
            RequestManager.add_request(self.Prepare_Own_Lod_Texture, [2],
                                       'NodeTexBaking',
                                       self.Distance_From_Camera)

        if step == 2:  #prepare hnorm texture
            self.su['fbo'].set_fbo_scene()
            self.temp_hnorm = self.su['fbo'].draw_fbo_cube(
                self.pd, self.face, 'pass_2', self.cf[0], self.cf[1],
                self.level, self.temp_htex)
            #print(self.temp_hnorm)
            self.su['fbo'].set_base_scene()
            RequestManager.add_request(self.Prepare_Own_Lod_Texture, [3],
                                       'NodeTexBaking',
                                       self.Distance_From_Camera)

        if step == 3:  #set textures and cascade text coordinates
            self.tex_atlas.fill_reserved_slot(self.temp_hnorm, self.temp_slot)
            self.Assign_TexAtlas_Layer(self.temp_slot)
            self.Rescale_Tex_Coord(0.0, 0.0, 1.0, 1.0)
            #delete temp textures to free memory
            glDeleteTextures([self.temp_htex, self.temp_hnorm])
            self.texture_baking = False
            self.texture_baked = True
コード例 #17
0
 def __init__(self):
     self._torManager = TorManager()
     self._steamScraper = SteamScraper(730)
     self._requestManager = RequestManager(None)
     self._logger = logging.getLogger('BatchMain')
     self._logger.setLevel(logging.DEBUG)
コード例 #18
0
class BatchMain:

    _torManager = None
    _steamScraper = None
    _logger = None
    _torIPRatingFilename = "tor-ip-rating.json"

    def __init__(self):
        self._torManager = TorManager()
        self._steamScraper = SteamScraper(730)
        self._requestManager = RequestManager(None)
        self._logger = logging.getLogger('BatchMain')
        self._logger.setLevel(logging.DEBUG)

    def main(self):
        ProgrammStateVars.lastRequest = datetime.now()

        logging.debug(ProgrammStateVars.programmDir)
        self._prepareDir()

        steamMarketUrl = self._steamScraper.getUrl()
        realIP = self.testRealIP()

        torIPDict = {}
        if (path.isfile(
                path.join(ProgrammStateVars.programmDir,
                          ProgrammStateVars.jsonDir,
                          self._torIPRatingFilename))):
            torIPDict = self.loadTorIPRatingFromFile()

        torIP = ""
        while (steamMarketUrl != ""):
            if (torIP != "" and realIP != torIP):
                logging.info(steamMarketUrl)
                responseNormal = self._torManager.doRequest(steamMarketUrl)
                requestState = {
                    "Cookies": self._torManager.getCookies().get_dict(),
                    "RequestHeader": dict(self._torManager.getHeader()),
                    "ResponseHeader": dict(responseNormal.headers)
                }
                logging.info(requestState)
                if isinstance(responseNormal, Response):
                    if (responseNormal.status_code == 200):
                        self.writeTextToFile(
                            "csgo_" +
                            str(self._steamScraper.getStartPointer()) +
                            ".json", responseNormal.text)

                        self._steamScraper.nextPointer()
                        steamMarketUrl = self._steamScraper.getUrl()
                        torIPDict[torIP]["goodReq"].append(requestState)
                    else:  # among others HTTP Status 429
                        logging.error(
                            "Steam Rest Api Request wasn't successfull status_code != 200: "
                            .format(responseNormal.status_code))
                        logging.error("Response Text: {}".format(
                            responseNormal.headers))
                        torIPDict[torIP]["badReq"].append(requestState)
                        self._torManager.newOnionPath()
                        torIP = ""
                else:
                    logging.error(
                        "Returned Object of SteamAPI Request isn't a Response")
                    break
            else:
                torIP = self.testTORIP()
                if (torIP not in torIPDict):
                    torIPDict[torIP] = {"goodReq": [], "badReq": []}
            logging.debug(torIPDict)
            self.writeTorIPRatingFromFile(torIPDict)

        self.writeTorIPRatingFromFile(torIPDict)

    def _prepareDir(self):
        logging.debug("Create Dir \"{}\" for Dumps if not exists.".format(
            ProgrammStateVars.jsonDir))
        # Create Base Dir for JSONs
        Path(
            path.join(ProgrammStateVars.programmDir,
                      ProgrammStateVars.jsonDir)).mkdir(parents=True,
                                                        exist_ok=True)
        # Create Sub Dir for current Exec
        self._steamScraper.createNewDir()
        jsonDumpsDir = self._steamScraper.getDir()
        logging.debug(
            "Create Dir \"{}\" for current run JSON-Dumps if not exists.".
            format(jsonDumpsDir))
        Path(
            path.join(ProgrammStateVars.programmDir, ProgrammStateVars.jsonDir,
                      jsonDumpsDir)).mkdir(parents=True, exist_ok=True)

    def testTORIP(self):
        urlForIP = 'http://blob.bplaced.net'
        ipResponse = self._torManager.doRequest(urlForIP)
        if isinstance(ipResponse, Response):
            if (ipResponse.status_code == 200):
                logging.info("Tor IP: " + ipResponse.text)
                return ipResponse.text
            else:
                logging.error(
                    "Request for IP not successfull status_code != 200: {}".
                    format(ipResponse.status_code))
                logging.error("Response Text: {}".format(ipResponse.text))
        else:
            logging.error(
                "Returned Object of Request for IP isn't a Response: {}".
                format(ipResponse))
            self._torManager.getCookies().clear()
        return ""

    def testRealIP(self):
        urlForIP = 'http://blob.bplaced.net'
        ipResponse = self._requestManager.doRequest(urlForIP)
        if isinstance(ipResponse, Response):
            if (ipResponse.status_code == 200):
                logging.info("Real IP: " + ipResponse.text)
                return ipResponse.text
            else:
                logging.error(
                    "Request for IP not successfull status_code != 200: {}".
                    format(ipResponse.status_code))
                logging.error("Response Text: {}".format(ipResponse.text))
        else:
            logging.error(
                "Returned Object of Request for IP isn't a Response: {}".
                format(ipResponse))
            self._torManager.getCookies().clear()
        return ""

    def loadTorIPRatingFromFile(self):
        data = None
        with open(
                path.join(ProgrammStateVars.programmDir,
                          ProgrammStateVars.jsonDir,
                          self._torIPRatingFilename)) as file:
            data = json.load(file)
        return data

    def writeTextToFile(self, filename, text):
        with open(
                path.join(ProgrammStateVars.programmDir,
                          ProgrammStateVars.jsonDir,
                          self._steamScraper.getDir(), filename), 'w') as file:
            file.write(text)

    def writeTorIPRatingFromFile(self, dictJson):
        with open(
                path.join(ProgrammStateVars.programmDir,
                          ProgrammStateVars.jsonDir,
                          self._torIPRatingFilename), 'w') as file:
            json.dump(dictJson, file)
コード例 #19
0
ファイル: server.py プロジェクト: luucasv/InfraCom
import threading
import socket
import pickle
import struct
from RequestManager import RequestManager

requestManager = RequestManager()
requestManagerLock = threading.Lock()
bufferSize = 4096
host = ''
port = 20041


def sendMsg(sock, msg):
    msg = struct.pack('>I', len(msg)) + msg
    sock.sendall(msg)


def recvMsg(sock):
    raw_msglen = recvall(sock, 4)
    if not raw_msglen:
        return None
    msglen = struct.unpack('>I', raw_msglen)[0]
    return recvall(sock, msglen)


def recvall(sock, n):
    data = ''.encode()
    while len(data) < n:
        packet = sock.recv(min(n - len(data), bufferSize))
        if not packet:
コード例 #20
0
    def __init__(self, host, user, pw):
        RequestManager.__init__(self, host, user, pw)

        self.stakeholderProtocol = StakeholderProtocol(host, user, pw)
コード例 #21
0
    def __init__(self, type, x, y, z, SceneUtils, PlanetDesc):

        # create the texture atlas for the cube
        self.TexAtlas = TextureAtlasArray(96 * 4, 128, 128)
        self.PlanetDescriptor = PlanetDesc

        #in the future, the active camera should be linked to the object using a more global methods
        # or making sceneutils a global access object
        self.ActiveCamera = SceneUtils['cam']
        self.SceneMgr = SceneUtils['fbo']

        #code to be put only if the planet has water bodies
        #set up a helper fbo for difraction maps
        self.helpfbo = FBO_RTT(1024, 1024)
        # and one for reflection maps
        self.helpfbo2 = FBO_RTT(1024, 1024)

        # state of the main texture data: 0 = full, <>0, not fully completed
        self.state = 1

        #create the cube face object
        # - define corners
        c000 = np.array([-1.0, -1.0, 1.0], dtype='float32')
        c010 = np.array([-1.0, 1.0, 1.0], dtype='float32')
        c110 = np.array([1.0, 1.0, 1.0], dtype='float32')
        c100 = np.array([1.0, -1.0, 1.0], dtype='float32')
        c001 = np.array([-1.0, -1.0, -1.0], dtype='float32')
        c011 = np.array([-1.0, 1.0, -1.0], dtype='float32')
        c111 = np.array([1.0, 1.0, -1.0], dtype='float32')
        c101 = np.array([1.0, -1.0, -1.0], dtype='float32')
        t00 = np.array([0.0, 0.0, 0.0, 1.0, 0.0, 0.0], dtype='float32')
        t10 = np.array([1.0, 0.0, 0.0, 1.0, 1.0, 0.0], dtype='float32')
        t11 = np.array([1.0, 1.0, 0.0, 1.0, 1.0, 1.0], dtype='float32')
        t01 = np.array([0.0, 1.0, 0.0, 1.0, 0.0, 1.0], dtype='float32')
        # - create the 6 cube faces, specifying vertices and texture coordinates with np.lib.append([x,y,z],[s,t]) calls
        self.face = []
        self.face.append(
            SurfaceNode(0, 0, 0, 0, np.lib.append(c000, t00),
                        np.lib.append(c010, t01), np.lib.append(c110, t11),
                        np.lib.append(c100, t10), SceneUtils, PlanetDesc,
                        self.TexAtlas))
        self.face.append(
            SurfaceNode(1, 0, 0, 0, np.lib.append(c001, t00),
                        np.lib.append(c011, t01), np.lib.append(c010, t11),
                        np.lib.append(c000, t10), SceneUtils, PlanetDesc,
                        self.TexAtlas))
        self.face.append(
            SurfaceNode(2, 0, 0, 0, np.lib.append(c101, t00),
                        np.lib.append(c111, t01), np.lib.append(c011, t11),
                        np.lib.append(c001, t10), SceneUtils, PlanetDesc,
                        self.TexAtlas))
        self.face.append(
            SurfaceNode(3, 0, 0, 0, np.lib.append(c100, t00),
                        np.lib.append(c110, t01), np.lib.append(c111, t11),
                        np.lib.append(c101, t10), SceneUtils, PlanetDesc,
                        self.TexAtlas))
        self.face.append(
            SurfaceNode(4, 0, 0, 0, np.lib.append(c001, t00),
                        np.lib.append(c000, t01), np.lib.append(c100, t11),
                        np.lib.append(c101, t10), SceneUtils, PlanetDesc,
                        self.TexAtlas))
        self.face.append(
            SurfaceNode(5, 0, 0, 0, np.lib.append(c010, t00),
                        np.lib.append(c011, t01), np.lib.append(c111, t11),
                        np.lib.append(c110, t10), SceneUtils, PlanetDesc,
                        self.TexAtlas))

        # generate heigthmap
        #self.GenHeightMapTex(SceneUtils['fbo'])
        RequestManager.add_request(self.CheckLevelZeroTexComplete, [])

        for aface in self.face:
            #aface.tessellate_all_to_level(2)
            aface.do_triangles(True)
            aface.VBO_All_Updated()

        #parameters for dynamic level of detail
        self.kdiv = 3.0
        self.kred = 3.2

        leng = 0

        self.activeVBO = [0, 0, 0, 0, 0, 0]  #implementing doublevbo
        self.VBO_need_update = [3, 3, 3, 3, 3, 3]  # to check
        self.sidetocheck = 6  #temporarily we check one side at a time to see if we tessellate
        self.updatelist = []
        self.vbotocomplete = [7, 7]  #face number and active number

        self.vertexVBO = [[]]
        self.indexVBO = [[]]
        self.vertexVBO.append([])
        self.indexVBO.append([])
        index = 0
        for i in self.face:
            i.faceindex = index
            index += 1
            self.vertici = np.array(
                np.array(i.datadict['vertex'], dtype='float32'))
            self.vertexVBO[0].append(
                vbo.VBO(data=self.vertici,
                        usage=GL_DYNAMIC_DRAW,
                        target=GL_ARRAY_BUFFER))
            self.vertexVBO[1].append(
                vbo.VBO(data=self.vertici,
                        usage=GL_DYNAMIC_DRAW,
                        target=GL_ARRAY_BUFFER))
            self.indici = np.array(
                np.array(i.datadict['index'], dtype='uint32'))
            self.indexVBO[0].append(
                vbo.VBO(data=self.indici,
                        usage=GL_DYNAMIC_DRAW,
                        target=GL_ELEMENT_ARRAY_BUFFER))
            self.indexVBO[1].append(
                vbo.VBO(data=self.indici,
                        usage=GL_DYNAMIC_DRAW,
                        target=GL_ELEMENT_ARRAY_BUFFER))
            leng += self.vertici.shape[0]

        # assign other object properties
        self.scale = PlanetDesc.radius
        self.position = [x, y, z]
        self.orientation = qts.Quat([0.0, 0.3, 0.5])

        #add a light as a test ..light should not be there
        self.light = RendLight((2000000.0, 0.0, 0.0), (1.0, 1.0, 0.8))

        #add a test skydome object
        self.sky = RenderableSkydome(16)
        self.sky.attach_light(self.light)

        # assign the shader and get attribute and uniform indexes (pointers)
        self.program = MaterialManager.Materials[PlanetDesc.main_material]
        self.program_sea = MaterialManager.Materials['planetsea']
        self.attrib_position = glGetAttribLocation(self.program, 'position')
        self.attrib_texcoord = glGetAttribLocation(self.program, 'texcoord')
        self.attrib_texcoord2 = glGetAttribLocation(self.program, 'texcoord2')
        self.attrib_scale = glGetAttribLocation(self.program, 'nodescale')

        self.main_attribs = {
            'position': glGetAttribLocation(self.program, 'position'),
            'texcoord': glGetAttribLocation(self.program, 'texcoord'),
            'nodescale': glGetAttribLocation(self.program, 'nodescale'),
            'texcoord2': glGetAttribLocation(self.program, 'texcoord2'),
        }

        self.sea_attribs = {
            'position': glGetAttribLocation(self.program_sea, 'position'),
            'texcoord': glGetAttribLocation(self.program_sea, 'texcoord'),
            'nodescale': glGetAttribLocation(self.program_sea, 'nodescale'),
            'texcoord2': glGetAttribLocation(self.program_sea, 'texcoord2'),
        }

        self.main_unifs = {
            'u_model': glGetUniformLocation(self.program, 'u_model'),
            'u_view': glGetUniformLocation(self.program, 'u_view'),
            'u_normal': glGetUniformLocation(self.program, 'u_normal'),
            'u_proj': glGetUniformLocation(self.program, 'u_proj'),
            'u_lposition3': glGetUniformLocation(self.program, 'u_lposition3'),
            'u_lintensity3': glGetUniformLocation(self.program,
                                                  'u_lintensity3'),
            'planet_radius': glGetUniformLocation(self.program,
                                                  'planet_radius'),
            'planet_height': glGetUniformLocation(self.program,
                                                  'planet_height'),
            'sea_level': glGetUniformLocation(self.program, 'sea_level'),
            'camdist': glGetUniformLocation(self.program, 'camdist'),
            'skirt_off': glGetUniformLocation(self.program, 'skirt_off'),
            'state': glGetUniformLocation(self.program, 'state'),
            'verse': glGetUniformLocation(self.program, 'verse'),
        }
        self.sea_unifs = {
            'model_m':
            glGetUniformLocation(self.program_sea, 'model_m'),
            'view_m':
            glGetUniformLocation(self.program_sea, 'view_m'),
            'normal_m':
            glGetUniformLocation(self.program_sea, 'normal_m'),
            'proj_m':
            glGetUniformLocation(self.program_sea, 'proj_m'),
            'u_lposition3':
            glGetUniformLocation(self.program_sea, 'u_lposition3'),
            'u_lintensity3':
            glGetUniformLocation(self.program_sea, 'u_lintensity3'),
            'planetradius':
            glGetUniformLocation(self.program_sea, 'planetradius'),
            'planetheight':
            glGetUniformLocation(self.program_sea, 'planetheight'),
            'sealevel':
            glGetUniformLocation(self.program_sea, 'sealevel'),
            'time':
            glGetUniformLocation(self.program_sea, 'time'),
            'camdist':
            glGetUniformLocation(self.program_sea, 'camdist'),
            'skirt_off':
            glGetUniformLocation(self.program_sea, 'skirt_off'),
        }

        # inscribe the object in the static list of the parent object
        RenderablePlanet.ListRends.append(self)
        # funny test code
        rand_axis = np.array(
            [random.random(),
             random.random(),
             random.random()])
        norma = np.linalg.norm(rand_axis)
        rand_axis /= norma
        #self.axis = np.array([0.0,1.0,0.0])
        self.axis = rand_axis
        self.rand_angle = 0.000 * (random.uniform(0.0, 20.0) - 10)
        self.cam_distance = 10
        ##test signals for the hud

        GlobalSignals.set('Triangles', leng)
        GlobalSignals.set('req nr', 0)
        GlobalSignals.set('req max time', 0)
        GlobalSignals.set('draw ms', 0)
        GlobalSignals.set('tessel ms', 0)
        GlobalSignals.set('tex slot free', 0)
        GlobalSignals.set('Nodes', leng)
コード例 #22
0
    def draw(self):
        #pre draw stuff and preparation
        t1 = time.time() * 1000

        if GlobalSettings.read('linemode') == GL_LINE:
            skirt_off = 1.0
        else:
            skirt_off = 0.0

        #apply local transformations
        selfrot = np.ascontiguousarray(
            np.transpose(
                np.append(
                    np.append(self.orientation._get_transform(),
                              [[0], [0], [0]], 1), [[0, 0, 0, 1]], 0)))
        S = scale_matrix(self.scale)
        R = selfrot
        T = translation_matrix(self.position)
        self.model = np.dot(T, np.dot(R, S))
        #calculate mirror matrix
        #normalize camera position in object space
        selfrot = np.ascontiguousarray(
            np.transpose(
                np.append(
                    np.append(self.orientation._get_transform(),
                              [[0], [0], [0]], 1), [[0, 0, 0, 1]], 0)))
        Si = scale_matrix(float(1 / self.scale))
        Ri = np.transpose(selfrot)
        Ti = translation_matrix(
            [-self.position[0], -self.position[1], -self.position[2]])
        Minv = np.dot(Si, np.dot(Ri, Ti))
        self.campostr = np.ravel(
            np.dot(Minv, np.append(self.ActiveCamera.position, 1)))[0:3]
        self.cam_distance = np.linalg.norm(self.campostr)
        GlobalSignals.set('cam distance', self.cam_distance)

        #mcamera = np.dot(flip,np.dot(mirror,np.linalg.inv(self.ActiveCamera.view)))
        #mview = self.ActiveCamera.view

        if (self.cam_distance < 1.3) and (self.PlanetDescriptor.sea_level >
                                          0) and (self.state == 0):
            self.draw_fbo_refraction()
            self.draw_fbo_reflection(self.ActiveCamera.view)

        #test draw the sky if we are inside
        if (self.cam_distance <= 100):
            glBlendFunc(GL_SRC_ALPHA, GL_ZERO)
            #glDisable(GL_CULL_FACE)
            glCullFace(GL_FRONT)
            self.sky.draw_inner_sky(self.ActiveCamera.proj,
                                    self.ActiveCamera.view, self.model)
            #glEnable(GL_CULL_FACE)
            glCullFace(GL_BACK)

        #draw the planet

        glBlendFunc(GL_ONE, GL_ZERO)
        MaterialManager.use_material('planetmat1')
        #glUseProgram(self.program)

        glEnableVertexAttribArray(self.main_attribs['position'])
        glEnableVertexAttribArray(self.main_attribs['texcoord'])
        glEnableVertexAttribArray(self.main_attribs['nodescale'])
        glEnableVertexAttribArray(self.main_attribs['texcoord2'])

        glUniformMatrix4fv(self.main_unifs['u_model'], 1, GL_TRUE, self.model)
        glUniformMatrix4fv(self.main_unifs['u_view'], 1, GL_FALSE,
                           self.ActiveCamera.view)
        glUniformMatrix4fv(
            self.main_unifs['u_normal'], 1, GL_FALSE,
            np.transpose(
                np.linalg.inv(
                    np.dot(np.transpose(self.model), self.ActiveCamera.view))))
        glUniformMatrix4fv(self.main_unifs['u_proj'], 1, GL_FALSE,
                           self.ActiveCamera.proj)

        glUniform3fv(self.main_unifs['u_lposition3'], 1, self.light.get_pos())
        glUniform3fv(self.main_unifs['u_lintensity3'], 1,
                     self.light.get_intensity())

        glUniform1f(self.main_unifs['planet_radius'],
                    self.PlanetDescriptor.radius)
        glUniform1f(self.main_unifs['planet_height'],
                    self.PlanetDescriptor.height)
        glUniform1f(self.main_unifs['sea_level'],
                    self.PlanetDescriptor.sea_level)
        glUniform1f(self.main_unifs['camdist'], self.cam_distance)
        glUniform1f(self.main_unifs['skirt_off'], skirt_off)
        glUniform1i(self.main_unifs['state'], self.state)
        glUniform1f(self.main_unifs['verse'], 1.0)

        glEnable(GL_TEXTURE_2D)
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, self.PlanetDescriptor.mixmap)
        glUniform1i(glGetUniformLocation(self.program, 'surfacecolor'), 0)

        #bind the texture (from texture atlas array) for heightmap / normals
        glActiveTexture(GL_TEXTURE1)
        glBindTexture(GL_TEXTURE_2D_ARRAY, self.TexAtlas.get_tex_id())
        glUniform1i(glGetUniformLocation(self.program, 'heightmap'), 1)

        glActiveTexture(GL_TEXTURE2)
        glBindTexture(GL_TEXTURE_2D_ARRAY,
                      self.PlanetDescriptor.surface_textures.get_tex_id())
        glUniform1i(glGetUniformLocation(self.program, 'surface'), 2)
        #draw pass of the 6 VBOs
        for index in range(0, 6):

            #bind the VBO
            act = self.activeVBO[index]
            self.vertexVBO[act][index].bind()
            self.indexVBO[act][index].bind()
            #draw
            glVertexAttribPointer(self.attrib_position, 3, GL_FLOAT, GL_FALSE,
                                  36, self.vertexVBO[act][index])
            glVertexAttribPointer(self.attrib_texcoord, 3, GL_FLOAT, GL_FALSE,
                                  36, self.vertexVBO[act][index] + (3 * 4))
            glVertexAttribPointer(self.attrib_scale, 1, GL_FLOAT, GL_FALSE, 36,
                                  self.vertexVBO[act][index] + (6 * 4))
            glVertexAttribPointer(self.attrib_texcoord2, 2, GL_FLOAT, GL_FALSE,
                                  36, self.vertexVBO[act][index] + (7 * 4))
            nb_elements = self.indexVBO[act][index].shape[0]
            glDrawElements(GL_TRIANGLES, nb_elements, GL_UNSIGNED_INT,
                           self.indexVBO[act][index])
            # disable/unbind the arrays
            self.vertexVBO[act][index].unbind()
            self.indexVBO[act][index].unbind()

        glDisableVertexAttribArray(self.main_attribs['position'])
        glDisableVertexAttribArray(self.main_attribs['texcoord'])
        glDisableVertexAttribArray(self.main_attribs['nodescale'])
        glDisableVertexAttribArray(self.main_attribs['texcoord2'])

        # draw the sea
        #glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        if (self.cam_distance <
                1.05) and (self.PlanetDescriptor.sea_level > 0) and (
                    GlobalSettings.read('nosea')) and (self.state == 0):
            glUseProgram(self.program_sea)
            #enable attributes arrays
            glEnableVertexAttribArray(self.sea_attribs['position'])
            glEnableVertexAttribArray(self.sea_attribs['texcoord'])
            glEnableVertexAttribArray(self.sea_attribs['nodescale'])
            glEnableVertexAttribArray(self.sea_attribs['texcoord2'])

            glUniformMatrix4fv(self.sea_unifs['model_m'], 1, GL_TRUE,
                               self.model)
            glUniformMatrix4fv(self.sea_unifs['view_m'], 1, GL_FALSE,
                               self.ActiveCamera.view)
            glUniformMatrix4fv(
                self.sea_unifs['normal_m'], 1, GL_FALSE,
                np.transpose(
                    np.linalg.inv(
                        np.dot(np.transpose(self.model),
                               self.ActiveCamera.view))))
            glUniformMatrix4fv(self.sea_unifs['proj_m'], 1, GL_FALSE,
                               self.ActiveCamera.proj)

            glUniform3fv(self.sea_unifs['u_lposition3'], 1,
                         self.light.get_pos())
            glUniform3fv(self.sea_unifs['u_lintensity3'], 1,
                         self.light.get_intensity())

            glUniform1f(self.sea_unifs['planetradius'],
                        self.PlanetDescriptor.radius)
            glUniform1f(self.sea_unifs['planetheight'],
                        self.PlanetDescriptor.height)
            glUniform1f(self.sea_unifs['sealevel'],
                        self.PlanetDescriptor.sea_level)
            glUniform1f(self.sea_unifs['time'], time.clock())
            glUniform1f(self.sea_unifs['camdist'], self.cam_distance)
            glUniform1f(self.sea_unifs['skirt_off'], skirt_off)

            glEnable(GL_TEXTURE_2D)
            glActiveTexture(GL_TEXTURE0)
            glBindTexture(GL_TEXTURE_2D_ARRAY, self.PlanetDescriptor.wavetext)
            glUniform1i(glGetUniformLocation(self.program_sea, 'wavetext'), 0)

            #bind the texture (from texture atlas array) for heightmap / normals
            glActiveTexture(GL_TEXTURE1)
            glBindTexture(GL_TEXTURE_2D_ARRAY, self.TexAtlas.get_tex_id())
            glUniform1i(glGetUniformLocation(self.program_sea, 'heightmap'), 1)

            glActiveTexture(GL_TEXTURE2)
            glBindTexture(GL_TEXTURE_2D, self.helpfbo.rtt)
            glUniform1i(
                glGetUniformLocation(self.program_sea, 'refractiontexture'), 2)

            glActiveTexture(GL_TEXTURE3)
            glBindTexture(GL_TEXTURE_2D, self.helpfbo2.rtt)
            glUniform1i(
                glGetUniformLocation(self.program_sea, 'reflectiontexture'), 3)

            for index in range(0, 6):

                #bind the VBO
                act = self.activeVBO[index]
                self.vertexVBO[act][index].bind()
                self.indexVBO[act][index].bind()
                #draw
                glVertexAttribPointer(self.attrib_position, 3, GL_FLOAT,
                                      GL_FALSE, 36, self.vertexVBO[act][index])
                glVertexAttribPointer(self.attrib_texcoord, 3, GL_FLOAT,
                                      GL_FALSE, 36,
                                      self.vertexVBO[act][index] + (3 * 4))
                glVertexAttribPointer(self.attrib_scale, 1, GL_FLOAT, GL_FALSE,
                                      36, self.vertexVBO[act][index] + (6 * 4))
                glVertexAttribPointer(self.attrib_texcoord2, 2, GL_FLOAT,
                                      GL_FALSE, 36,
                                      self.vertexVBO[act][index] + (7 * 4))
                nb_elements = (self.indexVBO[act][index].shape[0])
                glDrawElements(GL_TRIANGLES, nb_elements, GL_UNSIGNED_INT,
                               self.indexVBO[act][index])
                # disable/unbind the arrays
                self.vertexVBO[act][index].unbind()
                self.indexVBO[act][index].unbind()

            glDisableVertexAttribArray(self.sea_attribs['position'])
            glDisableVertexAttribArray(self.sea_attribs['texcoord'])
            glDisableVertexAttribArray(self.sea_attribs['nodescale'])
            glDisableVertexAttribArray(self.sea_attribs['texcoord2'])

        #test draw the sky if we are outside
        if (self.cam_distance >= 1.1):
            glBlendFunc(GL_SRC_ALPHA, GL_ONE)
            glCullFace(GL_BACK)
            self.sky.draw_inner_sky(self.ActiveCamera.proj,
                                    self.ActiveCamera.view, self.model)

        glUseProgram(0)

        #VBO updating / maintenance
        for index in range(0, 6):
            #check if current face has a VBO to complete update
            if self.VBO_need_update[index] <> 3:
                RequestManager.add_request(self.VBOupdate, [index])
            #swap active VBO if no pending updates
            if self.VBO_need_update[index] <> (1 - act):
                self.activeVBO[index] = 1 - act

        #debug code
        t2 = time.time() * 1000 - t1
        GlobalSignals.set('draw ms', t2)
        GlobalSignals.set('tex slot free', self.TexAtlas.free_count)
コード例 #23
0
def startup(args: argparse.Namespace, **kwargs: Dict[str, Any]) -> None:
    global announce, dispatcher, group, httpServer, notification, validator
    global registration, remote, request, security, statistics, storage, event
    global rootDirectory
    global aeStatistics
    global supportedReleaseVersions, cseType, defaultSerialization, cseCsi, cseRi, cseRn
    global cseOriginator
    global isHeadless

    rootDirectory = os.getcwd()  # get the root directory
    os.environ[
        "FLASK_ENV"] = "development"  # get rid if the warning message from flask.
    # Hopefully it is clear at this point that this is not a production CSE

    # Handle command line arguments and load the configuration
    if args is None:
        args = argparse.Namespace(
        )  # In case args is None create a new args object and populate it
        args.configfile = None
        args.resetdb = False
        args.loglevel = None
        args.headless = False
        for key, value in kwargs.items():
            args.__setattr__(key, value)
    isHeadless = args.headless

    if not Configuration.init(args):
        return

    # Initialize configurable constants
    supportedReleaseVersions = Configuration.get(
        'cse.supportedReleaseVersions')
    cseType = Configuration.get('cse.type')
    cseCsi = Configuration.get('cse.csi')
    cseRi = Configuration.get('cse.ri')
    cseRn = Configuration.get('cse.rn')
    cseOriginator = Configuration.get('cse.originator')

    defaultSerialization = Configuration.get('cse.defaultSerialization')

    # init Logging
    Logging.init()
    if not args.headless:
        Logging.console('Press ? for help')
    Logging.log('============')
    Logging.log('Starting CSE')
    Logging.log(f'CSE-Type: {cseType.name}')
    Logging.log('Configuration:')
    Logging.log(Configuration.print())

    # Initiatlize the resource storage
    storage = Storage()

    # Initialize the event manager
    event = EventManager()

    # Initialize the statistics system
    statistics = Statistics()

    # Initialize the registration manager
    registration = RegistrationManager()

    # Initialize the resource validator
    validator = Validator()

    # Initialize the resource dispatcher
    dispatcher = Dispatcher()

    # Initialize the request manager
    request = RequestManager()

    # Initialize the security manager
    security = SecurityManager()

    # Initialize the HTTP server
    httpServer = HttpServer()

    # Initialize the notification manager
    notification = NotificationManager()

    # Initialize the group manager
    group = GroupManager()

    # Import a default set of resources, e.g. the CSE, first ACP or resource structure
    # Import extra attribute policies for specializations first
    importer = Importer()
    if not importer.importAttributePolicies() or not importer.importResources(
    ):
        return

    # Initialize the remote CSE manager
    remote = RemoteCSEManager()

    # Initialize the announcement manager
    announce = AnnouncementManager()

    # Start AEs
    startAppsDelayed(
    )  # the Apps are actually started after the CSE finished the startup

    # Start the HTTP server
    event.cseStartup()  # type: ignore
    httpServer.run()  # This does return (!)

    Logging.log('CSE started')
    if isHeadless:
        # when in headless mode give the CSE a moment (2s) to experience fatal errors before printing the start message
        BackgroundWorkerPool.newActor(
            delay=2,
            workerCallback=lambda: Logging.console('CSE started')
            if not shuttingDown else None).start()

    #
    #	Enter an endless loop.
    #	Execute keyboard commands in the keyboardHandler's loop() function.
    #
    commands = {
        '?': _keyHelp,
        'h': _keyHelp,
        '\n': lambda c: print(),  # 1 empty line
        '\x03': _keyShutdownCSE,  # See handler below
        'c': _keyConfiguration,
        'C': _keyClearScreen,
        'D': _keyDeleteResource,
        'i': _keyInspectResource,
        'l': _keyToggleLogging,
        'Q': _keyShutdownCSE,  # See handler below
        'r': _keyCSERegistrations,
        's': _keyStatistics,
        't': _keyResourceTree,
        'T': _keyChildResourceTree,
        'w': _keyWorkers,
    }

    #	Endless runtime loop. This handles key input & commands
    #	The CSE's shutdown happens in one of the key handlers below
    loop(commands, catchKeyboardInterrupt=True, headless=args.headless)
    shutdown()
コード例 #24
0
    def get_triangles(self, datadict, force_completion=False):
        #before doing anything let's check if a texture is baking
        if (self.texture_baking == True) and (force_completion
                                              == False) and False:
            #reschedule and exit
            RequestManager.add_request(self.get_triangles, [datadict],
                                       'get_triangles' + str(self.face),
                                       self.NodePriority)
        else:
            if datadict['vertex'] == []:
                len = 0
            else:
                len = datadict['vertex'].__len__()

            if self.children == 0:
                #add all vertexes of this node to the data dictionary
                self.ustep = (self.c01 - self.c00) / float(self.GRID)
                self.vstep = (self.c10 - self.c00) / float(self.GRID)
                self.ustep[6] = 0.0
                self.vstep[6] = 0.0
                diag = 0
                offset = 0
                #nodescale = 2**self.scalelevel
                for u in range(0, self.GRID):
                    u_ustep = u * self.ustep
                    for v in range(0, self.GRID):
                        self.cd00 = self.c00 + v * self.vstep + u_ustep
                        self.cd01 = self.cd00 + self.ustep
                        self.cd10 = self.cd00 + self.vstep
                        self.cd11 = self.cd01 + self.vstep

                        datadict['vertex'].append(self.cd00)
                        datadict['vertex'].append(self.cd10)
                        datadict['vertex'].append(self.cd11)
                        datadict['vertex'].append(self.cd01)
                        if diag == 0:
                            datadict['index'].extend([
                                0 + len + offset, 2 + len + offset,
                                3 + len + offset
                            ])
                            datadict['index'].extend([
                                0 + len + offset, 1 + len + offset,
                                2 + len + offset
                            ])
                        else:
                            datadict['index'].extend([
                                0 + len + offset, 1 + len + offset,
                                3 + len + offset
                            ])
                            datadict['index'].extend([
                                3 + len + offset, 1 + len + offset,
                                2 + len + offset
                            ])
                        offset += 4
                        diag = 1 - diag
                    diag = 1 - diag  # at column's end double inversion to make a diamond at the new column

                #emit the skirts
                for u in range(0, self.GRID):
                    u_ustep = u * self.ustep
                    self.cd00 = self.c00 + u_ustep
                    self.cd01 = self.cd00 + self.ustep
                    self.cd10 = self.cd00 - self.zstep
                    self.cd11 = self.cd01 - self.zstep
                    datadict['vertex'].append(self.cd00)
                    datadict['vertex'].append(self.cd10)
                    datadict['vertex'].append(self.cd11)
                    datadict['vertex'].append(self.cd01)
                    datadict['index'].extend(
                        [0 + len + offset, 3 + len + offset, 2 + len + offset])
                    datadict['index'].extend(
                        [0 + len + offset, 2 + len + offset, 1 + len + offset])
                    offset += 4
                    self.cd00 = self.c10 + u_ustep
                    self.cd01 = self.cd00 + self.ustep
                    self.cd10 = self.cd00 - self.zstep
                    self.cd11 = self.cd01 - self.zstep
                    datadict['vertex'].append(self.cd00)
                    datadict['vertex'].append(self.cd10)
                    datadict['vertex'].append(self.cd11)
                    datadict['vertex'].append(self.cd01)
                    datadict['index'].extend(
                        [0 + len + offset, 2 + len + offset, 3 + len + offset])
                    datadict['index'].extend(
                        [0 + len + offset, 1 + len + offset, 2 + len + offset])
                    offset += 4
                for v in range(0, self.GRID):
                    v_vstep = v * self.vstep
                    self.cd00 = self.c00 + v_vstep
                    self.cd01 = self.cd00 + self.vstep
                    self.cd10 = self.cd00 - self.zstep
                    self.cd11 = self.cd01 - self.zstep
                    datadict['vertex'].append(self.cd00)
                    datadict['vertex'].append(self.cd10)
                    datadict['vertex'].append(self.cd11)
                    datadict['vertex'].append(self.cd01)
                    datadict['index'].extend(
                        [0 + len + offset, 2 + len + offset, 3 + len + offset])
                    datadict['index'].extend(
                        [0 + len + offset, 1 + len + offset, 2 + len + offset])
                    offset += 4
                    self.cd00 = self.c01 + v_vstep
                    self.cd01 = self.cd00 + self.vstep
                    self.cd10 = self.cd00 - self.zstep
                    self.cd11 = self.cd01 - self.zstep
                    datadict['vertex'].append(self.cd00)
                    datadict['vertex'].append(self.cd10)
                    datadict['vertex'].append(self.cd11)
                    datadict['vertex'].append(self.cd01)
                    datadict['index'].extend(
                        [0 + len + offset, 3 + len + offset, 2 + len + offset])
                    datadict['index'].extend(
                        [0 + len + offset, 2 + len + offset, 1 + len + offset])
                    offset += 4

            else:
                if force_completion:
                    for ch in self.children:
                        ch.get_triangles(datadict, True)
                else:
                    for ch in self.children:
                        RequestManager.add_request(
                            ch.get_triangles, [datadict],
                            'get_triangles' + str(ch.face), ch.NodePriority)
コード例 #25
0
from EWSClientType import EWSClientType
from RequestManager import RequestManager
from FileManager import FileManager

try:
    import thread
except ImportError:
    import _thread as thread
import time

pi_id = str(3)

if len(sys.argv) > 1:
    pi_id = str(sys.argv[1])

rm = RequestManager()
fm = FileManager()

HOST = "wss://cs70esocmi.execute-api.us-east-1.amazonaws.com/dev"


def send_to_display_controller(message):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = '127.0.0.1'
    port = 1234

    s.connect((host, port))
    s.sendall(bytes(message, encoding="utf-8"))
    s.close()

コード例 #26
0
ファイル: main.py プロジェクト: Grifone75/PyProceduralPlanet
def main():
    global window
    global scene
    global hud
    global camera
    global mousex
    global mousey
    global action
    global frametimer
    global SceneMgr
    global SceneMstr
    global Signals
    global speed
    
    
    speed = 10.0
    
    RequestManager.set_time_budget(10)
    
    GlobalSettings.set('snapshot',False)
    
    #define the scenemaster object for the main scene
    SceneMstr = SceneMaster('Main Scene')
    #create the camera object & attach to scenemaster
    camera = CameraObj()
    SceneMstr.camera = camera #to be replaced by a setter function
    #define the scene manager for the switching between main scene and fbos
    SceneMgr = SceneManager(128,camera)


    #initialise the globals for mouse control
    mousex = 0
    mousey = 0
    action = 'NONE'
    #init the timer object
    frametimer = UtilTimer(20)
    
    #init the graphic system and create a window
    glutInit(sys.argv)

    # Select type of Display mode: double buffer,RGBA color,Alpha components supported , Depth buffer
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)

    
    # get a 640 x 480 window 
    glutInitWindowSize(1024, 800) 
    # the window starts at the upper left corner of the screen 
    glutInitWindowPosition(0, 0)
    window = glutCreateWindow("GL Planet")

   
    
    print(glGetIntegerv(GL_DEPTH_BITS))
    
    # Register the drawing function with glut, BUT in Python land, at least using PyOpenGL, we need to
    # set the function pointer and invoke a function to actually register the callback, otherwise it
    # would be very much like the C version of the code.    
    glutDisplayFunc(DrawGLScene)
    
    # Uncomment this line to get full screen.
    #glutFullScreen()
   
    # When we are doing nothing, redraw the scene.
    glutIdleFunc(DrawGLScene)
    # Register the function called when our window is resized.
    glutReshapeFunc(ReSizeGLScene)
    
    #registra la funzione per il mouse
    glutMouseFunc(MouseButton)
    glutMotionFunc(MouseMove)
    
    # Register the function called when the keyboard is pressed.  
    glutKeyboardFunc(keyPressed)

    # Initialize our window. 
    InitGL(SceneMgr, 800, 480) 
    
    #create the HUD object & attach to scenemaster
    hud = HUDObject()
    SceneMstr.hud = hud  #to be replaced by a setter function
    
    #DEBUG: register some measurements
    Signals = {}
    r1 = ReadableSignal('update time: ',0,10)
    r2 = ReadableSignal('draw time: ',0,10)
    hud.registersignal(r1)
    hud.registersignal(r2)
    Signals['update'] = r1
    Signals['draw'] = r2 
    
    #planet_texture = loadTexture('Media/Textures/Planet2.png')

    SceneUtils = {}
    SceneUtils['fbo'] = SceneMgr
    SceneUtils['hud'] = hud
    SceneUtils['cam'] = camera
    
    #initialise materials
    MaterialManager.load_material('Media/Materials/heightmat1.glsv', 'Media/Materials/heightmat1.glsf', 'fbomatheight')
    MaterialManager.load_material('Media/Materials/terra_v1.glsv','Media/Materials/terra_v1.glsf','planetmat1')
    MaterialManager.load_material('Media/Materials/normmat2.glsv','Media/Materials/normmat2.glsf','fbomatnorm')
    MaterialManager.load_material('Media/Materials/ocean_v1.glsv','Media/Materials/ocean_v1.glsf','planetsea')
    MaterialManager.load_material('Media/Materials/surfmeasure.glsv','Media/Materials/surfmeasure.glsf','surfacemeasure')
    MaterialManager.load_material('Media/Materials/sky_int_v1.glsv','Media/Materials/sky_int_v1.glsf','skybox_inside')
    MaterialManager.load_material('Media/Materials/underwater_v1.glsv','Media/Materials/underwater_v1.glsf','underwater')

    
    GlobalSettings.set('nosea',True)
    
    #create the planet descriptor
    P1 = PlanetDescriptor('Primum',10000.0,30.0, 0.2,'fbomatheight','fbomatnorm','planetmat1')
    #P1.GenerateTexture()
    
      
    # create the cube & attach to scenemaster
    # TO CHANGE: all various methods to attach things to the rendcubevbo object camera, scenemgr, materialmgr, to be
    #            replaced by a SceneMaster pointer
    scene = RenderablePlanet.RenderablePlanet('facevbo',0,0,-1500,SceneUtils,P1)
    SceneMstr.drawables.append(scene) # to be replaced by a setter in scenemaster


    scene.Timer = frametimer

    


    # Start Event Processing Engine    
    glutMainLoop()
コード例 #27
0
    def __init__(self, host, user, pw):
        RequestManager.__init__(self, host, user, pw)

        self.activityProtocol = ActivityProtocol(host, user, pw)
        self.activityLayer = None
コード例 #28
0
class ClientManager:
    TIMEOUT = 120  # seconds

    def __init__(self):
        self.authorizer = Authorizer("auth_info.json")

        self.request_manager = RequestManager()

        self.sockets: Dict[int, socket.socket] = {}  # fileno : sock

        self.clients: Dict[int, Client] = {}  # fileno : client
        self.authorized_clients: Dict[str, Client] = {}  # username : client

        self.buffered_data: Dict[int, str] = {}  # fileno : data

        self.poller = select.poll()

        self.remove_idle_clients_forever()

    def client_exists(self, sock: socket.socket):
        return sock.fileno() in self.clients

    def create_client(self, sock: socket.socket):
        if self.client_exists(sock):
            return

        client = Client(sock)

        self.clients[sock.fileno()] = client
        self.sockets[sock.fileno()] = sock
        self.poller.register(sock, select.POLLIN)

        print(str(client), "connected.")

    def login_client(self, client: Client, username: str):
        self.authorized_clients[username] = client
        client.set_authorized(username)

        print(str(client), "authorized.")

    def remove_client(self, client: Client):
        self.clients.pop(client.sock.fileno(), None)
        if client.username:
            self.authorized_clients.pop(client.username, None)
        self.sockets.pop(client.sock.fileno(), None)
        self.buffered_data.pop(client.sock.fileno(), None)
        if client.sock.fileno() > -1:
            self.poller.unregister(client.sock.fileno())

        client.sock.close()

        print(str(client), "disconnected.")

    def broadcast(self, response: Response):
        for client in self.authorized_clients.values():
            client.send_response(response)

    def remove_idle_clients_forever(self):
        now = time.time()
        for client in list(self.clients.values()):
            if now - client.last_interaction_time > ClientManager.TIMEOUT:
                self.remove_client(client)
                self.broadcast(SignOff(client.username))
                print("removing", str(client), "due to inactivity")

        Timer(10, self.remove_idle_clients_forever).start()

    def add_data(self, fileno, data):
        if fileno not in self.buffered_data:
            self.buffered_data[fileno] = ""
        self.buffered_data[fileno] += data

    def pop_buffered_requests(self, fileno: int):
        raw_messages = self.buffered_data.get(fileno)
        if not raw_messages:
            return []

        client = self.clients.get(fileno)

        split = raw_messages.split("\n")
        raw_messages = split[:-1]
        requests = []
        for raw_message in raw_messages:
            try:
                requests.append(
                    self.request_manager.get_request(client, raw_message))
            except InvalidRequestSyntax:
                self.remove_client(client)
                return []

        self.buffered_data[fileno] = split[-1]

        return requests