コード例 #1
0
ファイル: bingImagesPythonista.py プロジェクト: km1230/pykm
def SavePic(src):
	try:
		pic = Image.open(bio(requests.get(src).content))
		photos.save_image(pic)
		print('Image saved.')
	except:
		print('Failed to save image.')
コード例 #2
0
ファイル: publicize.py プロジェクト: mr-nfamous/scripts
def test_m_load():
    import re
    from io import BytesIO as bio

    file = re.__file__
    with open(clean_fp(ptr(file)), 'rb') as fpx:
        src = fpx.read()
        as_fp = bio(src)
    name_as_str = ptr()
    name_as_file = ptr()

    name_as_fp = ptr('re' if PYTHON3 else b're')
    re_from_name = m_load(re.__name__, name_as_str)
    re_from_file = m_load(re.__file__, name_as_file)
    try:
        del sys.modules['re']
        re_from_fp = m_load(as_fp, name_as_fp)
    except Exception as er:
        exc = er
        LAST_ERROR.append(sys._getframe())
    else:
        assert as_fp.closed
        return re, re_from_name, re_from_file, re_from_fp
    finally:
        sys.modules['re'] = re
    raise exc
コード例 #3
0
ファイル: app.py プロジェクト: NimaAIMLDL/segmentation-app
def display_image(value, pic):
    if int(value) == 1:
        return html.Img(
            src='data:image/png;base64,{}'.format(
                base64.b64encode(open('data/test/' + pic,
                                      'rb').read()).decode()),
            style={
                'width': '400px',
                'text-align': 'center',
                'margin-top': '1rem',
                'margin-left': '0rem',
                'margin-right': '0rem',
                'margin-bottom': '1rem'
            },
        )
    elif int(value) == 2:
        testGene = testGenerator(img_path='data/test/', file=pic)
        results = model.predict_generator(testGene, verbose=1)
        buf = bio()  # in-memory files
        plt.imshow(results[0])
        plt.axis('off')
        # save to the above file object
        plt.savefig(buf, format="png", bbox_inches='tight')
        plt.close()
        # encode to html elements
        data = base64.b64encode(buf.getbuffer()).decode()
        # return "data:image/png;base64,{}".format(data)
        return html.Img(
            src='data:image/png;base64,{}'.format(data),
            style={
                'width': '400px',
                'text-align': 'center',
                'margin-top': '0rem',
                'margin-left': '0rem',
                'margin-right': '0rem',
                'margin-bottom': '0rem'
            },
        )
    else:
        return html.Img(
            src='data:image/png;base64,{}'.format(
                base64.b64encode(open('data/test/' + pic,
                                      'rb').read()).decode()),
            style={
                'width': '400px',
                'text-align': 'center',
                'margin-top': '1rem',
                'margin-left': '0rem',
                'margin-right': '0rem',
                'margin-bottom': '1rem'
            },
        )
コード例 #4
0
def load_image(url=''):
    # FIX NEEDED: wrong behaviour with the except, maybe just raise an error?
    # FEATURE NEEDED: maybe in another function, but create a function that detects if the image is inexistent,
    # so it'll make easier for Lucie to clean up the data base.
    try:
        reponse = requests.get(url)
        img = Image.open(bio(reponse.content))
        return img
    except:
        return load_image(
            url=
            'https://rhyshonemusic.files.wordpress.com/2013/03/munch-scream-by-pastiche.jpg'
        )
コード例 #5
0
def http_request(url, post_data=None):
    '''Make an HTTP request to a given URL with optional parameters.
    '''
    logger.debug('Requesting URL: %s', url)
    buf = bio()
    curl = pycurl.Curl()
    curl.setopt(curl.URL, url.encode('ascii', 'ignore'))

    # More verbose curl calls in debug mode
    if logger.getEffectiveLevel() == logging.DEBUG:
        curl.setopt(pycurl.VERBOSE, True)

    # Disable HTTPS verification methods if insecure is set
    if config('server', 'insecure'):
        curl.setopt(curl.SSL_VERIFYPEER, 0)
        curl.setopt(curl.SSL_VERIFYHOST, 0)

    if config('server', 'certificate'):
        # Make sure verification methods are turned on
        curl.setopt(curl.SSL_VERIFYPEER, 1)
        curl.setopt(curl.SSL_VERIFYHOST, 2)
        # Import your certificates
        curl.setopt(pycurl.CAINFO, config('server', 'certificate'))

    if config('ingest', 'upload_rate') > 0:
        curl.setopt(curl.MAX_SEND_SPEED_LARGE, config('ingest', 'upload_rate'))

    if post_data:
        curl.setopt(curl.HTTPPOST, post_data)
    curl.setopt(curl.WRITEFUNCTION, buf.write)
    logger.debug('Using authentication method %s',
                 config('server')['auth_method'])
    if config('server')['auth_method'] == 'digest':
        curl.setopt(curl.HTTPHEADER, ['X-Requested-Auth: Digest'])
        curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_DIGEST)
    curl.setopt(
        pycurl.USERPWD,
        ':'.join([config('server', 'username'),
                  config('server', 'password')]))
    curl.setopt(curl.FAILONERROR, True)
    curl.setopt(curl.FOLLOWLOCATION, True)
    curl.perform()
    curl.close()
    result = buf.getvalue()
    buf.close()
    return result
コード例 #6
0
 def sceaDwld(self):
     # the following ensures we get the latest game data files.
     gh = Github(tok)
     # get_repo does NOT like getting a variable as an argument.
     repo = gh.get_repo("aleph-one-marathon/alephone")
     tag_list = repo.get_tags()
     rel = tag_list[0].name
     for scen in ['Marathon', 'Marathon2', 'MarathonInfinity']:
         try:
             gam_check = Path("{}/scenarios/{}".format(basedir, scen))
         except FileNotFoundError:
             print("Games not detected...downloading")
             url = "https://github.com/{}/releases/download/{}/{}-{}-Data.zip".format(
                 git_rep, rel, scen,
                 rel.split('-')[1])
             http = Request.urlopen(url)
             zip = ZipFile(bio(http.read()))
             zip.extractall(path="{}/scenarios/.".format(basedir, scen))
         else:
             print("Trilogy detected....")
         finally:
             print("Moving Onward...")
コード例 #7
0
ファイル: import_lr2.py プロジェクト: Irup/ATDBlenderTool
def open_mdl2(filepath, open_bitmaps = True):
	f = open(filepath,'rb')
	
	if open_bitmaps:
		try: rootpath = filepath[:filepath.lower().index('game data')]
		except ValueError:
			open_bitmaps = False
			print('Could not trace back to root directory "GAME DATA".')
		
	bpy.ops.object.empty_add()
	obj_root = bpy.context.scene.objects[0]
	obj_root.name = splitext(split(filepath)[1])[0]
	
	bitmaps  = []
	matprops = []
	objects  = []
	
	chunk_name = f.read(4)
	chunk_size = unpack('I', f.read(4))
	if chunk_name == b'MDL2':
		# variable
		# variable
		# variable, 0 for map landmarks, 1 for small objects
		# always 1
		mdl2_inertiamulti   = unpack('3f', f.read(12))
		mdl2_boundingradius,\
		mdl2_distancefades ,\
		mdl2_hasboundingbox = unpack('f2I', f.read(12))
		
		if mdl2_hasboundingbox:
			mdl2_boundingboxmin    = unpack('3f', f.read(12))
			mdl2_boundingboxmax    = unpack('3f', f.read(12))
			mdl2_boundingboxcenter = unpack('3f', f.read(12))
			mdl2_boundingboxroty   = unpack('f', f.read(4))
			
		# always 0
		# always 0
		# always 0
		# always 0
		mdl2_useuniquematerials,\
		mdl2_useuniquetextures ,\
		mdl2_usegenericgeometry,\
		mdl2_vertexbufferflags  = unpack('4I', f.read(16)) # all these fields appear unused
		f.seek(f.tell() + 48)
		
		# variable
		mdl2_bitmap_count = unpack('I', f.read(4))[0]
		print('	Textures:', mdl2_bitmap_count)
		for bitmap_id in range(mdl2_bitmap_count):
			bitmap_path  = readnulltermstring(f.read(256)).decode('utf8')
			bitmap_type  ,\
			bitmap_index = unpack('2I', f.read(8))
			print('		' + bitmap_path)
			bitmaps += [(bitmap_path, bitmap_type, bitmap_index)]
		materials = [bpy.data.materials.new(x[0]) for x in bitmaps]
		
		# variable
		mdl2_matprop_count = unpack('I', f.read(4))[0]
		for matprop_id in range(mdl2_matprop_count):
			mdl2_matprop_ambient   = unpack('4f', f.read(16))
			mdl2_matprop_diffuse   = unpack('4f', f.read(16))
			mdl2_matprop_specular  = unpack('4f', f.read(16))
			mdl2_matprop_emissive  = unpack('4f', f.read(16))
			mdl2_matprop_shine     ,\
			mdl2_matprop_alpha     ,\
			mdl2_matprop_alphatype ,\
			mdl2_matprop_bitfield  = unpack('2f2I', f.read(16))
			mdl2_matprop_animname  = readnulltermstring(f.read(8))
			matprops += [(
				mdl2_matprop_ambient  ,
				mdl2_matprop_diffuse  ,
				mdl2_matprop_specular ,
				mdl2_matprop_emissive ,
				mdl2_matprop_shine    ,
				mdl2_matprop_alpha    ,
				mdl2_matprop_alphatype,
				mdl2_matprop_bitfield ,
				mdl2_matprop_animname ,
			)]
	elif chunk_name == b'MDL1':
		# variable
		# variable
		# variable, 0 for map landmarks, 1 for small objects
		# always 1
		mdl2_inertiamulti   = unpack('3f', f.read(12))
		mdl2_boundingradius,\
		mdl2_distancefades ,\
		mdl2_hasboundingbox = unpack('f2I', f.read(12))
		
		if mdl2_hasboundingbox:
			mdl2_boundingboxmin    = unpack('3f', f.read(12))
			mdl2_boundingboxmax    = unpack('3f', f.read(12))
			mdl2_boundingboxcenter = unpack('3f', f.read(12))
			mdl2_boundingboxroty   = unpack('f', f.read(4))
			
		# always 0
		# always 0
		# always 0
		# always 0
		mdl2_useuniquematerials,\
		mdl2_useuniquetextures ,\
		mdl2_usegenericgeometry,\
		mdl2_vertexbufferflags  = unpack('4I', f.read(16)) # all these fields appear unused
		f.seek(f.tell() + 48)
		
		# variable
		mdl2_bitmap_count = unpack('I', f.read(4))[0]
		print('	Textures:', mdl2_bitmap_count)
		for bitmap_id in range(mdl2_bitmap_count):
			bitmap_path  = readnulltermstring(f.read(256)).decode('utf8')
			bitmap_type  ,\
			bitmap_index = unpack('2I', f.read(8))
			print('		' + bitmap_path)
			bitmaps += [(bitmap_path, bitmap_type, bitmap_index)]
		materials = [bpy.data.materials.new(x[0]) for x in bitmaps]
		
		# variable
		mdl2_matprop_count = unpack('I', f.read(4))[0]
		for matprop_id in range(mdl2_matprop_count):
			mdl2_int0  ,\
			mdl2_float0,\
			mdl2_float1,\
			mdl2_float2,\
			mdl2_float3,\
			mdl2_float4,\
			mdl2_float5 = unpack('I6f', f.read(28))
			matprops += [(
				mdl2_int0  ,
				mdl2_float0,
				mdl2_float1,
				mdl2_float2,
				mdl2_float3,
				mdl2_float4,
				mdl2_float5,
			)]
	else: return
			
	
	offset = f.tell()
	while 1:
		chunk_name = f.read(4)
		if chunk_name == b'\0\0\0\0' or not chunk_name: break
		chunk_size = unpack('I', f.read(4))[0]
		
		print('%s: %s' % (chunk_name.decode('ascii'), hex(chunk_size)))
		
		if chunk_name == b'GEO1':
			#variable
			geo1_detaillevels = unpack('I', f.read(4))[0]
			
			detaillevel_string = 'Detail level %%0%ii' % len(str(geo1_detaillevels))
			for detaillevel_id in range(geo1_detaillevels):
				bpy.ops.object.empty_add()
				dl_root = bpy.context.scene.objects[0]
				dl_root.name = detaillevel_string % detaillevel_id
				dl_root.parent = obj_root
				
				# variable; 0 for base mesh, 1 for distant mesh (model type distant)
				# variable, unknown purpose, is the distance between the two most distant connected vertices
				# variable, detail level is split into submeshes as textures are applied per submesh
				geo1_detaillevel_type         ,\
				geo1_detaillevel_maxedgelength,\
				geo1_rendergroups       = unpack('IfI', f.read(12))
				f.seek(f.tell() + 8)
				
				rendergroup_string = 'Rendergroup %%0%ii (Material %%0%ii)' % (len(str(geo1_rendergroups)), len(str(len(bitmaps))))
				for rendergroup_id in range(geo1_rendergroups):
					# variable
					# variable
					# variable
					# 512 in rgeffects models, else 0
					work_bmesh = bmesh.new()
					geo1_rendergroup_polygons,\
					geo1_rendergroup_vertices,\
					geo1_rendergroup_material,\
					geo1_rendergroup_effects  = unpack('4H', f.read(8))
					f.seek(f.tell() + 12)
					
					# variable as 3, 9, 17, or 513 in effects models, else 0
					# always 0
					# 2 in effects models, else always 1
					# always 0
					# 2 in flow models, else always 1
					geo1_texblend_effectmask     ,\
					geo1_texblend_renderreference,\
					geo1_texblend_effects        ,\
					geo1_texblend_custom         ,\
					geo1_texblend_coordinates     = unpack('3H2B', f.read(8))
					geo1_texblend_blends          = tuple(unpack('IH2B', f.read(8)) for x in range(4))
					# I effect         
					# H textureindex    # the bitmap used on the rendergroup
					# B coordinateindex
					# B tilinginfo      # 0x3 = tiling enabled, 0 = disabled
					
					# always 0
					# always 12
					# variable (trash memory if not geo1_vertex_flags & VERTEX_HAS_COLOR)
					# variable on account of previous int
                    # variable on account of previous ints
					# either 1, or 2 (rare)
					# see VERTEX_HAS_VECTOR and related
					# identical to geo1_rendergroup_vertices
					# always 1
					# either 15998, 16256, or 0
					geo1_vertex_offset_vector  ,\
					geo1_vertex_offset_normal  ,\
					geo1_vertex_offset_colour  ,\
					geo1_vertex_offset_texcoord,\
					geo1_vertex_size_vertstruct,\
					geo1_vertex_num_texcoords  ,\
					geo1_vertex_flags          ,\
					geo1_vertex_vertices       ,\
					geo1_vertex_managedbuffer  ,\
					geo1_vertex_currentvertex   = unpack('4I2I4H', f.read(32))
					f.seek(f.tell() + 8)
					
					for vertex in range(geo1_vertex_vertices): work_bmesh.verts.new()
					work_bmesh.verts.ensure_lookup_table()
					
					uvs = []
					normals = []
					for vertex in range(geo1_vertex_vertices):
						vstruct = bio(f.read(geo1_vertex_size_vertstruct))
						vertex_xyz    = unpack('3f', vstruct.read(12))[::-1]
						vertex_normal = unpack('3f', vstruct.read(12))[::-1]
						if geo1_vertex_flags & VERTEX_HAS_COLOR:
							vertex_color = unpack('4f', vstruct.read(16))
						for texcoord_id in range(geo1_vertex_num_texcoords):
							vertex_uv     = unpack('2f', vstruct.read(8))
						work_bmesh.verts[vertex].co = vertex_xyz
						normals += [vertex_normal]
						uvs += [vertex_uv]
					
					# always 1
					# always 0
					# always equal to (geo1_rendergroup_polygons*3)
					geo1_fill_selectableprimblocks,\
					geo1_fill_type                ,\
					geo1_fill_indices              = unpack('3I', f.read(12))
					
					buildfaces(work_bmesh, geo1_fill_type, geo1_rendergroup_polygons, f)
					
					### uv
					work_bmesh.faces.ensure_lookup_table()
					work_bmesh.verts.index_update()
					uv_layer = work_bmesh.loops.layers.uv.new()
					for face in work_bmesh.faces:
						for loop in face.loops: loop[uv_layer].uv = uvs[loop.vert.index]
					### uv
					
					work_mesh = bpy.data.meshes.new(rendergroup_string % (rendergroup_id, geo1_texblend_blends[0][1]))
					work_bmesh.to_mesh(work_mesh)
					
					#### normal test
					work_mesh.normals_split_custom_set_from_vertices(normals)
					work_mesh.use_auto_smooth = True
					#### normal test
					
					work_obj = bpy.data.objects.new(rendergroup_string % (rendergroup_id, geo1_texblend_blends[0][1]), work_mesh)
					work_obj.data.materials.append(materials[geo1_texblend_blends[0][1]])
					work_obj.parent = dl_root
					bpy.context.scene.objects.link(work_obj)
		
		offset += 8 + chunk_size
		f.seek(offset)
	f.close()
	
	obj_root.rotation_euler = (__import__('math').pi / 2, 0, 0)
	
	if open_bitmaps:
		for bitmap in bitmaps:
			try:
				bpy.ops.image.open(filepath = join(rootpath, splitext(bitmap[0])[0] + '.mip'))
			except RuntimeError:
				print('Failed to open image %s' % (splitext(bitmap[0])[0] + '.mip'))
コード例 #8
0
ファイル: import_lr2.py プロジェクト: Irup/ATDBlenderTool
def open_mdl0(filepath, open_bitmaps = True):
	f = open(filepath,'rb')
	
	if open_bitmaps:
		try: rootpath = filepath[:filepath.lower().index('game data')]
		except ValueError:
			open_bitmaps = False
			print('Could not trace back to root directory "GAME DATA".')
		
	work_bmesh = bmesh.new()
	
	offset   = 0
	bitmaps  = []
	matprops = []
	objects  = []
	
	mdl0_signature,\
	mdl0_int      ,\
	mdl0_int      ,\
	mdl0_int      ,\
	mdl0_float    ,\
	mdl0_bitmaps   = unpack('4s3IfI', f.read(24))
	
	for bitmap_id in range(mdl0_bitmaps):
		bitmaps += [readnulltermstring(f.read(256)).decode('utf8')]
	materials = [bpy.data.materials.new(x) for x in bitmaps]
	
	mdl0_int     ,\
	mdl0_int     ,\
	mdl0_int     ,\
	mdl0_int     ,\
	mdl0_int     ,\
	mdl0_int     ,\
	mdl0_int     ,\
	mdl0_int     ,\
	mdl0_float   ,\
	mdl0_int     ,\
	mdl0_int     ,\
	mdl0_int     ,\
	mdl0_polygons,\
	mdl0_vertices,\
	mdl0_int     ,\
	mdl0_int     ,\
	mdl0_int     ,\
	mdl0_int      = unpack('8If3I2H4I', f.read(68))
	
	mdl0_texblend_effectmask     ,\
	mdl0_texblend_renderreference,\
	mdl0_texblend_effects        ,\
	mdl0_texblend_custom         ,\
	mdl0_texblend_coordinates     = unpack('3H2B', f.read(8))
	mdl0_texblend_blends          = tuple(unpack('IH2B', f.read(8)) for x in range(4))
	# I effect         
	# H textureindex    # the bitmap used on the rendergroup
	# B coordinateindex
	# B tilinginfo      # 0x3 = tiling enabled, 0 = disabled

	# always 0
	# always 12
	# variable (trash memory if not geo1_vertex_flags & VERTEX_HAS_COLOR)
	# variable on account of previous int
    # variable on account of previous ints
	# either 1, or 2 (rare)
	# see VERTEX_HAS_VECTOR and related
	# identical to geo1_rendergroup_vertices
	# always 1
	# either 15998, 16256, or 0
	mdl0_vertex_offset_vector  ,\
	mdl0_vertex_offset_normal  ,\
	mdl0_vertex_offset_colour  ,\
	mdl0_vertex_offset_texcoord,\
	mdl0_vertex_size_vertstruct,\
	mdl0_vertex_num_texcoords  ,\
	mdl0_vertex_flags          ,\
	mdl0_vertex_vertices       ,\
	mdl0_vertex_managedbuffer  ,\
	mdl0_vertex_currentvertex   = unpack('4I2I4H', f.read(32))
	f.seek(f.tell() + 8)
	
	uvs = []
	normals = []
	for vertex in range(mdl0_vertices):
		vstruct = bio(f.read(mdl0_vertex_size_vertstruct))
		vertex_xyz    = unpack('3f', vstruct.read(12))[::-1]
		vertex_normal = unpack('3f', vstruct.read(12))[::-1]
		if mdl0_vertex_flags & VERTEX_HAS_COLOR:
			vertex_color = unpack('4f', vstruct.read(16))
		for texcoord_id in range(mdl0_vertex_num_texcoords):
			vertex_uv     = unpack('2f', vstruct.read(8))
		work_bmesh.verts.new(vertex_xyz)
		normals += [vertex_normal]
		uvs += [vertex_uv]
	work_bmesh.verts.ensure_lookup_table()
	work_bmesh.verts.index_update()
	
	mdl0_fill_type = unpack('I', f.read(4))[0]
	
	buildfaces(work_bmesh, mdl0_fill_type, mdl0_polygons, f)
	
	### uv
	work_bmesh.faces.ensure_lookup_table()
	uv_layer = work_bmesh.loops.layers.uv.new()
	for face in work_bmesh.faces:
		for loop in face.loops: loop[uv_layer].uv = uvs[loop.vert.index]
	### uv
	
	work_mesh = bpy.data.meshes.new('MDL0 mesh')
	work_bmesh.to_mesh(work_mesh)
	
	#### normal test
	work_mesh.normals_split_custom_set_from_vertices(normals)
	work_mesh.use_auto_smooth = True
	#### normal test
	
	work_obj = bpy.data.objects.new(splitext(split(filepath)[1])[0], work_mesh)
	work_obj.data.materials.append(materials[0])
	bpy.context.scene.objects.link(work_obj)
	
	f.close()
	
	work_obj.rotation_euler = (__import__('math').pi / 2, 0, 0)
	
	if open_bitmaps:
		for bitmap in bitmaps:
			try:
				bpy.ops.image.open(filepath = join(rootpath, splitext(bitmap[0])[0] + '.mip'))
			except RuntimeError:
				print('Failed to open image "%s"' % (splitext(bitmap[0])[0] + '.mip'))
コード例 #9
0
ファイル: solve.py プロジェクト: redpwn/picoCTF-2019
#!/usr/bin/env python3

from io import BytesIO as bio

mystery1 = bio(open('mystery.png', 'rb').read()[::-1])
mystery2 = bio(open('mystery2.png', 'rb').read()[::-1])
mystery3 = bio(open('mystery3.png', 'rb').read()[::-1])

read = lambda s, x: ord(s.read(x))
rrange = lambda a, b: reversed(range(a, b))

flag = [0] * 0x1a

for i in rrange(0xf, 0x1a):
    flag[i] = read(mystery1, 1)

for i in rrange(10, 0xf):
    flag[i] = read(mystery3, 1)

flag[3] = read(mystery2, 1) - (10 - 6) * 0x1

for i in rrange(6, 10):
    flag[i] = read(mystery1, 1)

flag[5] = read(mystery1, 1)
flag[4] = read(mystery3, 1)
flag[2] = read(mystery3, 1)
flag[0] = read(mystery2, 1) - 0x15
flag[1] = read(mystery3, 1)

print(bytes(flag).decode('utf-8', errors='replace'))
コード例 #10
0
ファイル: import_atd.py プロジェクト: Irup/ATDBlenderTool
def open_mdl0(filepath, usebitmaps=True):
    f = open(filepath, 'rb')
    fn = splitext(split(filepath)[1])[0]
    work_bmesh = bmesh.new()
    (
        mdl0_signature,
        mdl0_int,
        mdl0_int,
        mdl0_int,
        mdl0_float,
        mdl0_bitmaps,
    ) = unpack('4s3IfI', f.read(24))

    for bitmap_id in range(mdl0_bitmaps):
        bitmaps += [readnulltermstring(f.read(256)).decode('utf8')]
    materials = [bpy.data.materials.new(x) for x in bitmaps]

    (
        mdl0_int,
        mdl0_int,
        mdl0_int,
        mdl0_int,
        mdl0_int,
        mdl0_int,
        mdl0_int,
        mdl0_int,
        mdl0_float,
        mdl0_int,
        mdl0_int,
        mdl0_int,
        mdl0_polygons,
        mdl0_vertices,
        mdl0_int,
        mdl0_int,
        mdl0_int,
        mdl0_int,
    ) = unpack('8If3I2H4I', f.read(68))

    (
        mdl0_texblend_effectmask,
        mdl0_texblend_renderreference,
        mdl0_texblend_effects,
        mdl0_texblend_custom,
        mdl0_texblend_coordinates,
    ) = unpack('3H2B', f.read(8))
    mdl0_texblend_blends = tuple(unpack('IH2B', f.read(8)) for x in range(4))
    # I effect
    # H textureindex    # the bitmap used on the rendergroup
    # B coordinateindex
    # B tilinginfo      # 0x3 = tiling enabled, 0 = disabled

    (
        mdl0_vertex_offset_vector,  # always 0
        mdl0_vertex_offset_normal,  # always 12
        mdl0_vertex_offset_colour,  # variable (trash memory if not geo1_vertex_flags & VERTEX_HAS_COLOR)
        mdl0_vertex_offset_texcoord,  # variable on account of previous int
        mdl0_vertex_size_vertstruct,  # variable on account of previous ints
        mdl0_vertex_num_texcoords,  # either 1, or 2 (rare)
        mdl0_vertex_flags,  # see VERTEX_HAS_VECTOR and its following flags
        mdl0_vertex_vertices,  # identical to geo1_rendergroup_vertices
        mdl0_vertex_managedbuffer,  # always 1
        mdl0_vertex_currentvertex,  # either 15998, 16256, or 0
    ) = unpack('4I2I4H', f.read(32))
    f.seek(8, 1)

    uvs = []
    normals = []
    for vertex in range(mdl0_vertices):
        vstruct = bio(f.read(mdl0_vertex_size_vertstruct))
        vertex_xyz = unpack('3f', vstruct.read(12))[::-1]
        vertex_normal = unpack('3f', vstruct.read(12))[::-1]
        if mdl0_vertex_flags & VERTEX_HAS_COLOR:
            vertex_color = unpack('4f', vstruct.read(16))
        for texcoord_id in range(mdl0_vertex_num_texcoords):
            vertex_uv = unpack('2f', vstruct.read(8))
        work_bmesh.verts.new(vertex_xyz)
        normals += [vertex_normal]
        uvs += [vertex_uv]
    work_bmesh.verts.ensure_lookup_table()
    work_bmesh.verts.index_update()

    mdl0_fill_type = unpack('I', f.read(4))[0]

    buildfaces(work_bmesh, mdl0_fill_type, mdl0_polygons, f)

    ### uv
    work_bmesh.faces.ensure_lookup_table()
    uv_layer = work_bmesh.loops.layers.uv.new()
    for face in work_bmesh.faces:
        for loop in face.loops:
            loop[uv_layer].uv = uvs[loop.vert.index]
    ### uv

    work_mesh = bpy.data.meshes.new('MDL0 mesh')
    work_bmesh.to_mesh(work_mesh)

    #### normal test
    work_mesh.normals_split_custom_set_from_vertices(normals)
    work_mesh.use_auto_smooth = True
    #### normal test

    work_obj = bpy.data.objects.new(fn, work_mesh)
    work_obj.data.materials.append(materials[0])
    bpy.context.scene.objects.link(work_obj)

    f.close()
    work_obj.rotation_euler = (__import__('math').pi / 2, 0, 0)
    if usebitmaps: openbitmaps(filepath, bitmaps)
コード例 #11
0
ファイル: import_atd.py プロジェクト: Irup/ATDBlenderTool
def open_mdl1(filepath, usebitmaps=True):
    f = open(filepath, 'rb')
    fn = splitext(split(filepath)[1])[0]
    bpy.ops.object.empty_add()
    obj_root = bpy.context.scene.objects[0]
    obj_root.name = fn

    chunk_name = f.read(4)
    chunk_size = unpack('I', f.read(4))
    (
        head_inertiamulti,  # variable
        head_boundingradius,  # variable
        head_distancefades,  # boolean, 0 for map landmarks, 1 for small objects
        head_hasboundingbox,  # always 1
    ) = unpack('3ff2I', f.read(24))
    if head_hasboundingbox:
        (
            head_boundingboxmin,
            head_boundingboxmax,
            head_boundingboxcenter,
            head_boundingboxroty,
        ) = unpack('3f3f3ff', f.read(40))
    (  # all these fields appear unused
        head_useuniquematerials,  # always 0
        head_useuniquetextures,  # always 0
        head_usegenericgeometry,  # always 0
        head_vertexbufferflags,  # always 0
    ) = unpack('4I', f.read(16))
    f.seek(48, 1)

    head_bitmap_count = unpack('I', f.read(4))[0]
    bitmaps = buildbitmaplist(f, head_bitmap_count)
    materials = [bpy.data.materials.new(x[0]) for x in bitmaps]

    head_matprop_count = unpack('I', f.read(4))[0]
    matprops = []
    for matprop_id in range(head_matprop_count):
        (
            head_int0,
            head_float0,
            head_float1,
            head_float2,
            head_float3,
            head_float4,
            head_float5,
        ) = unpack('I6f', f.read(28))
        matprops += [(
            head_int0,
            head_float0,
            head_float1,
            head_float2,
            head_float3,
            head_float4,
            head_float5,
        )]

    offset = f.tell()
    while 1:
        chunk_name = f.read(4)
        if chunk_name == b'\0\0\0\0' or not len(chunk_name) == 4: break
        chunk_size = unpack('I', f.read(4))[0]

        print('%s: %s' % (chunk_name.decode('ascii'), hex(chunk_size)))

        if chunk_name == b'GEO1':
            #variable
            geo1_detaillevels = unpack('I', f.read(4))[0]

            detaillevel_string = 'Detail level %%0%ii' % len(
                str(geo1_detaillevels))
            for detaillevel_id in range(geo1_detaillevels):
                bpy.ops.object.empty_add()
                dl_root = bpy.context.scene.objects[0]
                dl_root.name = detaillevel_string % detaillevel_id
                dl_root.parent = obj_root
                (
                    geo1_detaillevel_type,  # variable; 0 for base mesh, 1 for distant mesh (model type distant)
                    geo1_detaillevel_maxedgelength,  # variable, unknown purpose, is the distance between the two most distant connected vertices
                    geo1_rendergroups,  # variable, detail level is split into submeshes as textures are applied per submesh
                ) = unpack('IfI', f.read(12))
                f.seek(8, 1)
                rendergroup_string = 'Rendergroup %%0%ii (Material %%0%ii)' % (
                    len(str(geo1_rendergroups)), len(str(len(bitmaps))))
                for rendergroup_id in range(geo1_rendergroups):
                    work_bmesh = bmesh.new()
                    (
                        geo1_rendergroup_polygons,  # variable
                        geo1_rendergroup_vertices,  # variable
                        geo1_rendergroup_material,  # variable
                        geo1_rendergroup_effects,  # 512 in rgeffects models, else 0
                    ) = unpack('4H', f.read(8))
                    f.seek(12, 1)
                    (
                        geo1_texblend_effectmask,  # variable as 3, 9, 17, or 513 in effects models, else 0
                        geo1_texblend_renderreference,  # always 0
                        geo1_texblend_effects,  # 2 in effects models, else always 1
                        geo1_texblend_custom,  # always 0
                        geo1_texblend_coordinates,  # 2 in flow models, else always 1
                    ) = unpack('3H2B', f.read(8))
                    geo1_texblend_blends = tuple(
                        unpack('IH2B', f.read(8)) for x in range(4))
                    # I effect
                    # H textureindex    # the bitmap used on the rendergroup
                    # B coordinateindex
                    # B tilinginfo      # 0x3 = tiling enabled, 0 = disabled

                    (
                        geo1_vertex_offset_vector,  # always 0
                        geo1_vertex_offset_normal,  # always 12
                        geo1_vertex_offset_colour,  # variable (trash memory if not geo1_vertex_flags & VERTEX_HAS_COLOR)
                        geo1_vertex_offset_texcoord,  # variable on account of previous int
                        geo1_vertex_size_vertstruct,  # variable on account of previous ints
                        geo1_vertex_num_texcoords,  # either 1, or 2 (rare)
                        geo1_vertex_flags,  # see VERTEX_HAS_VECTOR and its following flags
                        geo1_vertex_vertices,  # identical to geo1_rendergroup_vertices
                        geo1_vertex_managedbuffer,  # always 1
                        geo1_vertex_currentvertex,  # either 15998, 16256, or 0
                    ) = unpack('4I2I4H', f.read(32))
                    f.seek(8, 1)

                    for vertex in range(geo1_vertex_vertices):
                        work_bmesh.verts.new()
                    work_bmesh.verts.ensure_lookup_table()

                    uvs = []
                    normals = []
                    for vertex in range(geo1_vertex_vertices):
                        vstruct = bio(f.read(geo1_vertex_size_vertstruct))
                        vertex_xyz = unpack('3f', vstruct.read(12))[::-1]
                        vertex_normal = unpack('3f', vstruct.read(12))[::-1]
                        if geo1_vertex_flags & VERTEX_HAS_COLOR:
                            vertex_color = unpack('4f', vstruct.read(16))
                        for texcoord_id in range(geo1_vertex_num_texcoords):
                            vertex_uv = unpack('2f', vstruct.read(8))
                        work_bmesh.verts[vertex].co = vertex_xyz
                        normals += [vertex_normal]
                        uvs += [vertex_uv]
                    (
                        geo1_fill_selectableprimblocks,  # always 1
                        geo1_fill_type,  # always 0
                        geo1_fill_indices,  # always equal to (geo1_rendergroup_polygons*3)
                    ) = unpack('3I', f.read(12))

                    buildfaces(work_bmesh, geo1_fill_type,
                               geo1_rendergroup_polygons, f)

                    ### uv
                    work_bmesh.faces.ensure_lookup_table()
                    work_bmesh.verts.index_update()
                    uv_layer = work_bmesh.loops.layers.uv.new()
                    for face in work_bmesh.faces:
                        for loop in face.loops:
                            loop[uv_layer].uv = uvs[loop.vert.index]
                    ### uv

                    work_mesh = bpy.data.meshes.new(
                        rendergroup_string %
                        (rendergroup_id, geo1_texblend_blends[0][1]))
                    work_bmesh.to_mesh(work_mesh)

                    #### normal test
                    work_mesh.normals_split_custom_set_from_vertices(normals)
                    work_mesh.use_auto_smooth = True
                    #### normal test

                    work_obj = bpy.data.objects.new(
                        rendergroup_string %
                        (rendergroup_id, geo1_texblend_blends[0][1]),
                        work_mesh)
                    work_obj.data.materials.append(
                        materials[geo1_texblend_blends[0][1]])
                    work_obj.parent = dl_root
                    bpy.context.scene.objects.link(work_obj)
        offset += 8 + chunk_size
        f.seek(offset)
    f.close()
    obj_root.rotation_euler = (__import__('math').pi / 2, 0, 0)
    if usebitmaps: openbitmaps(filepath, bitmaps)
コード例 #12
0
ファイル: import_atd.py プロジェクト: Irup/ATDBlenderTool
def open_mdl2(filepath, usebitmaps=True, usetext=True):
    f = open(filepath, 'rb')
    fn = splitext(split(filepath)[1])[0]
    bpy.ops.object.empty_add()
    obj_root = bpy.context.scene.objects[0]
    obj_root.name = fn

    if usetext:
        text = bpy.data.texts.new(fn)
        text.write(
            '# Model configuration file for Lego Racers 2\n'
            '# Keep this file named the same as your root to export with its settings.\n\n'
        )

    chunk_name = f.read(4)
    chunk_size = unpack('I', f.read(4))
    head_inertiamulti = unpack('3f', f.read(12))
    head_boundingradius = unpack('f', f.read(4))
    (
        head_distancefades,  # boolean, 0 for map landmarks, 1 for small objects
        head_hasboundingbox,  # always 1
    ) = unpack('2I', f.read(8))

    if usetext:  ###########################
        text.write('InertiaTensor  = %.06f, %.06f, %.06f\n' %
                   head_inertiamulti +
                   'BoundingRadius = %.06f\n' % head_boundingradius +
                   'DistanceFades  = %s\n' % i2b(head_distancefades) +
                   'HasBoundingBox = %s\n\n' % i2b(head_hasboundingbox))

    if head_hasboundingbox:
        head_boundingboxmin = unpack('3f', f.read(12))
        head_boundingboxmax = unpack('3f', f.read(12))
        head_boundingboxcenter = unpack('3f', f.read(12))
        head_boundingboxroty = unpack('f', f.read(4))

        if usetext:  ##########################
            text.write('BoundingBoxMin    = %.06f, %.06f, %.06f\n' %
                       head_boundingboxmin +
                       'BoundingBoxMax    = %.06f, %.06f, %.06f\n' %
                       head_boundingboxmax +
                       'BoundingBoxCenter = %.06f, %.06f, %.06f\n' %
                       head_boundingboxcenter +
                       'BoundingBoxYaw    = %.06f\n\n' % head_boundingboxroty)

    (  # all these fields appear unused and always 0
        head_useuniquematerials,
        head_useuniquetextures,
        head_usegenericgeometry,
        head_vertexbufferflags,
    ) = unpack('4I', f.read(16))

    if usetext:  ##########################
        text.write('# Weird stuff, might not actually do anything.\n'
                   'UseUniqueMaterials = %s\n' % i2b(head_useuniquematerials) +
                   'UseUniqueTextures  = %s\n' % i2b(head_useuniquetextures) +
                   'UseGenericGeometry = %s\n' % i2b(head_usegenericgeometry) +
                   'VertexBufferFlags  = %s\n\n' % i2x(head_vertexbufferflags))

    f.seek(48, 1)
    head_bitmap_count = unpack('I', f.read(4))[0]
    bitmaps = buildbitmaplist(f, head_bitmap_count)
    materials = [bpy.data.materials.new(x[0]) for x in bitmaps]

    head_matprop_count = unpack('I', f.read(4))[0]
    matprops = []
    print('MatProps: %i' % head_matprop_count)
    for matprop_id in range(head_matprop_count):
        head_matprop_ambient = unpack('4f', f.read(16))
        head_matprop_diffuse = unpack('4f', f.read(16))
        head_matprop_specular = unpack('4f', f.read(16))
        head_matprop_emissive = unpack('4f', f.read(16))
        (
            head_matprop_shine,
            head_matprop_alpha,
            head_matprop_alphatype,
            head_matprop_bitfield,
        ) = unpack('2f2I', f.read(16))
        head_matprop_animname = readnulltermstring(f.read(8))

        if usetext:  ##########################
            text.write('# Shaders\n' +
                       'MatPropAmbient   = %.06f, %.06f, %.06f, %.06f\n' %
                       head_matprop_ambient +
                       'MatPropDiffuse   = %.06f, %.06f, %.06f, %.06f\n' %
                       head_matprop_diffuse +
                       'MatPropSpecular  = %.06f, %.06f, %.06f, %.06f\n' %
                       head_matprop_specular +
                       'MatPropEmissive  = %.06f, %.06f, %.06f, %.06f\n' %
                       head_matprop_emissive +
                       'MatPropShine     = %.06f\n' % head_matprop_shine +
                       'MatPropAlpha     = %.06f\n' % head_matprop_alpha +
                       'MatPropAlphaType = %i\n' % head_matprop_alphatype +
                       'MatPropFlags     = %s\n' % i2x(head_matprop_bitfield) +
                       'MatPropName      = %s\n\n' %
                       str(head_matprop_animname))

        matprops += [(
            head_matprop_ambient,
            head_matprop_diffuse,
            head_matprop_specular,
            head_matprop_emissive,
            head_matprop_shine,
            head_matprop_alpha,
            head_matprop_alphatype,
            head_matprop_bitfield,
            head_matprop_animname,
        )]

    offset = f.tell()
    while 1:
        chunk_name = f.read(4)
        if chunk_name == b'\0\0\0\0' or not len(chunk_name) == 4: break
        chunk_size = unpack('I', f.read(4))[0]

        print('%s: %s' % (chunk_name.decode('ascii'), hex(chunk_size)))

        if chunk_name == b'GEO1':
            geo1_detaillevels = unpack('I', f.read(4))[0]

            detaillevel_string = 'Detail level %%0%ii' % len(
                str(geo1_detaillevels))
            for detaillevel_id in range(geo1_detaillevels):
                bpy.ops.object.empty_add()
                dl_root = bpy.context.scene.objects[0]
                dl_root.name = detaillevel_string % detaillevel_id
                dl_root.parent = obj_root
                (
                    geo1_detaillevel_type,  # 0 for base mesh, 1 for distant mesh (model type distant)
                    geo1_detaillevel_maxedgelength,  # unknown purpose, is the distance between the two most distant connected vertices
                    geo1_rendergroups,  # detail level is split into submeshes as textures are applied per submesh
                ) = unpack('IfI', f.read(12))
                f.seek(8, 1)
                rendergroup_string = 'Rendergroup %%0%ii (Material %%0%ii)' % (
                    len(str(geo1_rendergroups)), len(str(len(bitmaps))))
                for rendergroup_id in range(geo1_rendergroups):
                    work_bmesh = bmesh.new()
                    (
                        geo1_rendergroup_polygons,  #
                        geo1_rendergroup_vertices,  #
                        geo1_rendergroup_material,  #
                        geo1_rendergroup_effects,  # 512 in rgeffects models, else 0
                    ) = unpack('4H', f.read(8))
                    f.seek(12, 1)
                    (
                        geo1_texblend_effectmask,  # variable as 3, 9, 17, or 513 in effects models, else 0
                        geo1_texblend_renderreference,  # always 0
                        geo1_texblend_effects,  # 2 in effects models, else always 1
                        geo1_texblend_custom,  # always 0
                        geo1_texblend_coordinates,  # 2 in flow models, else always 1
                    ) = unpack('3H2B', f.read(8))
                    geo1_texblend_blends = tuple(
                        unpack('IH2B', f.read(8)) for x in range(4))
                    # I effect
                    # H textureindex    # the bitmap used on the rendergroup
                    # B coordinateindex
                    # B tilinginfo      # 0x3 = tiling enabled, 0 = disabled

                    (
                        geo1_vertex_offset_vector,  # always 0
                        geo1_vertex_offset_normal,  # always 12
                        geo1_vertex_offset_colour,  # variable (trash memory if not geo1_vertex_flags & VERTEX_HAS_COLOR)
                        geo1_vertex_offset_texcoord,  # variable on account of previous int
                        geo1_vertex_size_vertstruct,  # variable on account of previous ints
                        geo1_vertex_num_texcoords,  # either 1, or 2 (rare)
                        geo1_vertex_flags,  # see VERTEX_HAS_VECTOR and its following flags
                        geo1_vertex_vertices,  # identical to geo1_rendergroup_vertices
                        geo1_vertex_managedbuffer,  # always 1
                        geo1_vertex_currentvertex,  # either 15998, 16256, or 0
                    ) = unpack('4I2I4H', f.read(32))
                    f.seek(8, 1)

                    for vertex in range(geo1_vertex_vertices):
                        work_bmesh.verts.new()
                    work_bmesh.verts.ensure_lookup_table()

                    uvs = []
                    normals = []
                    for vertex in range(geo1_vertex_vertices):
                        vstruct = bio(f.read(geo1_vertex_size_vertstruct))
                        vertex_xyz = unpack('3f', vstruct.read(12))[::-1]
                        vertex_normal = unpack('3f', vstruct.read(12))[::-1]
                        if geo1_vertex_flags & VERTEX_HAS_COLOR:
                            vertex_color = unpack('4f', vstruct.read(16))
                        for texcoord_id in range(geo1_vertex_num_texcoords):
                            vertex_uv = unpack('2f', vstruct.read(8))
                        work_bmesh.verts[vertex].co = vertex_xyz
                        normals += [vertex_normal]
                        uvs += [vertex_uv]
                    (
                        geo1_fill_selectableprimblocks,  # always 1
                        geo1_fill_type,  # always 0
                        geo1_fill_indices,  # always equal to (geo1_rendergroup_polygons*3)
                    ) = unpack('3I', f.read(12))

                    buildfaces(work_bmesh, geo1_fill_type,
                               geo1_rendergroup_polygons, f)

                    ### uv
                    work_bmesh.faces.ensure_lookup_table()
                    work_bmesh.verts.index_update()
                    uv_layer = work_bmesh.loops.layers.uv.new()
                    for face in work_bmesh.faces:
                        for loop in face.loops:
                            loop[uv_layer].uv = uvs[loop.vert.index]
                    ### uv

                    work_mesh = bpy.data.meshes.new(
                        rendergroup_string %
                        (rendergroup_id, geo1_texblend_blends[0][1]))
                    work_bmesh.to_mesh(work_mesh)

                    #### normal test
                    work_mesh.normals_split_custom_set_from_vertices(normals)
                    work_mesh.use_auto_smooth = True
                    #### normal test

                    work_obj = bpy.data.objects.new(
                        rendergroup_string %
                        (rendergroup_id, geo1_texblend_blends[0][1]),
                        work_mesh)
                    work_obj.data.materials.append(
                        materials[geo1_texblend_blends[0][1]])
                    work_obj.parent = dl_root
                    bpy.context.scene.objects.link(work_obj)
        offset += 8 + chunk_size
        f.seek(offset)
    f.close()
    obj_root.rotation_euler = (__import__('math').pi / 2, 0, 0)
    if usebitmaps: openbitmaps(filepath, bitmaps)
コード例 #13
0
import requests
import os
from bs4 import BeautifulSoup as bs
from io import BytesIO as bio
from PIL import Image

search = ('+').join(input('Looking for: ').split())
searchEngine = 'https://www.bing.com/images/search?q=' + search + '&FORM=HDRSC2'
r = requests.get(searchEngine)
print('Reaching server...')
if r.status_code == 200:
    print('Reached server. Listening...')
    code = bs(r.text, 'html.parser')
    link = code.find('a', class_='thumb').get('href')
    imgLink = requests.get(link)
    if imgLink.status_code == 200:
        desktop = os.path.expanduser('~/Desktop')
        os.chdir(desktop)
        print('Item found...')
        img = Image.open(bio(imgLink.content))
        print('Downloading...')
        img.save(link[-15:-5] + '.' + img.format)
        print('Image saved!')
コード例 #14
0
ファイル: collector_DQMGUI.py プロジェクト: rovere/utilities
 def __init__(self, type):
     self.type_ = type
     self.content_ = bio()