Example #1
0
    def __init__(self, config):
        super(GAN, self).__init__()
        self.config = config
        self.e_net = Encoder(config)
        self.g_net = Decoder(config)
        self.d_net = Disc(config)
        self.p_net = Projector(config)

        self._build_optimizers()
Example #2
0
    def __init__(self,
                 num_classes=1,
                 dim=32,
                 num_tokens=8,
                 token_c=32,
                 mlp_dim=128,
                 heads=8,
                 depth=2,
                 dropout=0.1):
        super(ViTNet, self).__init__()

        self.conv1 = Conv3d(1,
                            16,
                            kernel_size=3,
                            stride=1,
                            bias=False,
                            padding=1)
        self.conv2 = Conv3d(16,
                            dim,
                            kernel_size=3,
                            stride=1,
                            bias=False,
                            padding=1)
        self.bn1 = BatchNorm3d(16)
        self.bn2 = BatchNorm3d(dim)
        self.pool1 = MaxPool3d(2)
        self.pool2 = MaxPool3d(2)
        self.apply(_weights_init)  # 權重初始化

        # Tokenization
        self.token_wA = Linear(dim, num_tokens)  # Tokenization parameters
        torch.nn.init.xavier_uniform_(self.token_wA.weight)
        self.mat = einsum('bij,bjk->bik')
        self.token_wV = Linear(dim, token_c)  # Tokenization parameters
        torch.nn.init.xavier_uniform_(self.token_wV.weight)

        self.transformer = Transformer(token_c, depth, heads, mlp_dim, dropout)
        self.to_cls_token = nn.Identity()
        self.projector = Projector(in_channels=dim,
                                   out_channels=16,
                                   token_channels=token_c)

        # output
        self.nn1 = Linear(16 * 16 * 16 * 16, 2048)
        self.act1 = ReLU()
        torch.nn.init.xavier_uniform_(self.nn1.weight)
        torch.nn.init.normal_(self.nn1.bias, std=1e-6)
        self.do1 = Dropout(dropout)
        self.nn2 = Linear(2048, 128)
        self.act2 = ReLU()
        torch.nn.init.xavier_uniform_(self.nn2.weight)
        torch.nn.init.normal_(self.nn2.bias, std=1e-6)
        self.nn3 = Linear(128, num_classes)
        torch.nn.init.xavier_uniform_(self.nn3.weight)
        torch.nn.init.normal_(self.nn3.bias, std=1e-6)
def main():
    amp = Amplifier("Top-O-Line-Amplifier")
    tuner = Tuner("Top-O-Line AM/FM Tuner", amp)
    dvd_player = DvdPlayer("Top-O-Line DVD Player", amp)
    cd_player = CDPlayer("Top-O-Line CD Player", amp)
    projector = Projector("Top-O-Line Projector", dvd_player)
    lights = TheaterLights("Theater Ceiling Lights")
    screen = Screen("Theater Screen")
    popper = PopcornPopper("Popcorn Popper")

    home_theater = HomeTheaterFacade(amp, tuner, dvd_player, cd_player,
                                     projector, screen, lights, popper)
    home_theater.watch_movie("Lord of the Rings")
    print()
    home_theater.end_movie()
    print()
Example #4
0
def main():
    t0 = time.time()
    print('t0:', t0)

    # Initialize TensorFlow.
    tflib.init_tf()  # 0.82s

    print('t1:', time.time() - t0)

    # Load pre-trained network.
    with open('./models/stylegan2-ffhq-config-f.pkl', 'rb') as f:
        print('t2:', time.time() - t0)

        _G, _D, Gs = pickle.load(f)  # 13.09s

        print('t3:', time.time() - t0)

    with open('./models/vgg16_zhang_perceptual.pkl', 'rb') as f:
        lpips = pickle.load(f)

        print('t4:', time.time() - t0)

    proj = Projector()
    proj.set_network(Gs, lpips)

    image = PIL.Image.open('./images/example.png')
    #image = image.resize((Di.input_shape[2], Di.input_shape[3]), PIL.Image.ANTIALIAS)
    image_array = np.array(image).swapaxes(0, 2).swapaxes(1, 2)
    image_array = misc.adjust_dynamic_range(image_array, [0, 255], [-1, 1])

    print('t5:', time.time() - t0)

    proj.start([image_array])
    for step in proj.runSteps(1000):
        print('\rstep: %d' % step, end='', flush=True)
        if step % 10 == 0:
            results = proj.get_images()
            pilImage = misc.convert_to_pil_image(
                misc.create_image_grid(results), drange=[-1, 1])
            pilImage.save('./images/project-%d.png' % step)

    print('t6:', time.time() - t0)

    dlatents = proj.get_dlatents()
    noises = proj.get_noises()
    print('dlatents:', dlatents.shape)
    print('noises:', len(noises), noises[0].shape, noises[-1].shape)
Example #5
0
def loadProjector():
	global g_Projector
	if g_Projector:
		return g_Projector

	gs, _ = loadGs()
	lpips = loadLpips()

	g_Projector = Projector()
	g_Projector.regularize_noise_weight = float(os.environ.get('REGULARIZE_NOISE_WEIGHT', 1e5))
	g_Projector.initial_noise_factor = float(os.environ.get('INITIAL_NOISE_FACTOR', 0.05))
	g_Projector.uniform_latents = int(os.environ.get('UNIFORM_LATENTS', 0)) > 0
	g_Projector.euclidean_dist_weight = float(os.environ.get('EUCLIDEAN_DIST_WEIGHT', 1))
	g_Projector.regularize_magnitude_weight = float(os.environ.get('REGULARIZE_MAGNITUDE_WEIGHT', 0))
	g_Projector.set_network(gs, lpips)

	return g_Projector
Example #6
0
 def _createServices(self, eventloop):
     """Hardcoding a list of services - later we might add auto-detection of services present"""
     Airconditioner(self, self.config, eventloop)
     AutoShade(self, self.config, eventloop)
     AutoLight(self, self.config, eventloop)
     HiFi(self, self.config, eventloop)
     IrTrans(self, self.config, eventloop)
     Kodi(self, self.config, eventloop)
     Paradox(self, self.config, eventloop)
     Projector(self, self.config, eventloop)
     Scene(self, self.config, eventloop)
     Schedule(self, self.config, eventloop)
     SleepSense(self, self.config, eventloop)
     SunRiseSet(self, self.config, eventloop)
     ZWaveMios(self, self.config, eventloop)
     # let's make this last:
     TcpServer(self, self.config, eventloop)
    path = sys.argv[1]
    if os.path.isdir(path):
        image_files = glob.glob(path + '*.png')
        image_files += glob.glob(path + '*.jpg')
    else:
        image_files = [path]

    target_dir = sys.argv[2]
    os.makedirs(target_dir, exist_ok=True)

    # Load model
    g = Generator(1024, 512, 8, pretrained=True).to(device).train()
    for param in g.parameters():
        param.requires_grad = False

    proj = Projector(g)

    for i, file in tqdm(enumerate(sorted(image_files))):
        print('Projecting {}'.format(file))

        # Load image
        target_image = Image.open(file)
        transform = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
        ])
        target_image = transform(target_image).to(device)

        # Run projector
        proj.run(target_image)
Example #8
0
def main(args):
    if len(args) < 2:
        print "Usage: %s <project_directory> [sdk_verison]" % os.path.basename(
            args[0])
        sys.exit(1)

    # What needs to be done in order to perform a "true" export?
    # ---
    # Wipe the build dir
    # Migrate resources
    # Migrate tiapp.xml (required for scripts)
    # Generate project from template
    # Populate Info.plist
    # Compile/migrate i18n
    # Migrate scripts for compiling JSS files (and i18n)
    # Modify xcodeproj build steps to call the JSS compiler
    # Then... Share and Enjoy.

    project_dir = os.path.abspath(args[1])
    build_dir = os.path.join(project_dir, 'build', 'iphone')
    titanium_local = os.path.join(build_dir, 'titanium')

    if len(args) == 3:
        version = args[2]
        sdk_dir = find_sdk(version)
    else:
        sdk_dir = os.path.abspath(os.path.dirname(template_dir))
        version = os.path.basename(sdk_dir)

    tiappxml = os.path.join(project_dir, 'tiapp.xml')
    tiapp = TiAppXML(tiappxml)

    app_id = tiapp.properties['id']
    app_name = tiapp.properties['name']

    if app_id is None or app_name is None:
        info("Your tiapp.xml is malformed - please specify an app name and id")
        sys.exit(1)

    # Clean build dir (if it exists), error otherwise (no iphone support)
    info("Cleaning build...")
    if os.path.exists(build_dir):
        for f in os.listdir(build_dir):
            path = os.path.join(build_dir, f)
            if os.path.isfile(path):
                os.remove(path)
            else:
                shutil.rmtree(path)
    else:
        info("Your project is not configured to be built for iphone.")
        exit(1)

    # Migrate Resources
    info("Migrating resources...")
    project_resources = os.path.join(project_dir, 'Resources')
    resources_dir = os.path.join(build_dir, 'Resources')

    shutil.copytree(project_resources, resources_dir)

    # Migrate platform/iphone contents into Resources.
    info("Migrating platform/iphone to Resources...")
    project_platform = os.path.join(project_dir, 'platform', 'iphone')

    if os.path.isdir(project_platform):
        contents = os.listdir(project_platform)
        for file in contents:
            path = os.path.join(project_platform, file)
            if os.path.isdir(path):
                shutil.copytree(path, os.path.join(resources_dir, file))
            else:
                shutil.copy(path, os.path.join(resources_dir, file))

    # Migrate tiapp.xml
    info("Migrating tiapp.xml...")
    shutil.copy(tiappxml, build_dir)

    # Generate project stuff from the template
    info("Generating project from Titanium template...")
    project = Projector(app_name, version, template_dir, project_dir, app_id)
    project.create(template_dir, build_dir)

    # Because the debugger.plist is built as part of the required
    # resources, we need to autogen an empty one
    debug_plist = os.path.join(resources_dir, 'debugger.plist')
    force_xcode = write_debugger_plist(None, None, template_dir, debug_plist)

    # Populate Info.plist
    applogo = None
    info("Populating Info.plist...")
    plist_out = os.path.join(build_dir, 'Info.plist')
    create_info_plist(tiapp, template_dir, project_dir, plist_out)
    applogo = tiapp.generate_infoplist(plist_out, app_id, 'iphone',
                                       project_dir, None)

    # Run the compiler to autogenerate .m files
    info("Copying classes, creating generated .m files...")
    compiler = Compiler(project_dir, app_id, app_name, 'export')
    compiler.compileProject(silent=True)

    #... But we still have to nuke the stuff that gets built that we don't want
    # to bundle.
    ios_build = os.path.join(build_dir, 'build')
    if os.path.isdir(ios_build):
        shutil.rmtree(os.path.join(build_dir, 'build'))

    # Install applogo/splash/etc.
    info("Copying icons and splash...")
    install_logo(tiapp, applogo, project_dir, template_dir, resources_dir)
    install_defaults(project_dir, template_dir, resources_dir)

    # Get Modules
    detector = ModuleDetector(project_dir)
    missing_modules, modules = detector.find_app_modules(tiapp, 'iphone')

    if len(missing_modules) != 0:
        for module in missing_modules:
            info("MISSING MODULE: %s ... Project will not build correctly" %
                 module['id'])
        info("Terminating export: Please fix your modules.")
        sys.exit(1)

    module_search_path, module_asset_dirs = locate_modules(
        modules, project_dir, resources_dir, info)

    lib_dir = os.path.join(build_dir, 'lib')
    if not os.path.exists(lib_dir):
        os.makedirs(lib_dir)

    if len(module_search_path) > 0:
        info("Copying modules...")
        for module in module_search_path:
            module_name, module_path = module
            info("\t%s..." % module_name)
            shutil.copy(os.path.join(module_path, module_name), lib_dir)
            module[1] = os.path.join(lib_dir, module_name)

        info("Copying module metadata...")
        metadata_dir = os.path.join(build_dir, 'metadata')
        for module in modules:
            module_metadata = os.path.join(module.path, 'metadata.json')
            if os.path.exists(module_metadata):
                if not os.path.exists(metadata_dir):
                    os.makedirs(metadata_dir)
                target = os.path.join(metadata_dir,
                                      "%s.json" % module.manifest.moduleid)
                shutil.copyfile(module_metadata, target)

        # Note: The module link information has to be added to
        # the xcodeproj after it's created.
        # We also have to mod the module_search_path to reference
        # the local 'lib' directory instead of the original
        # module install location
        info("Linking modules...")
        local_modules = []
        for module in module_search_path:
            name = module[0]
            newpath = os.path.join('lib', name)
            local_modules.append([name, newpath])
        link_modules(local_modules, app_name, build_dir, relative=True)

    # Copy libraries
    info("Copying libraries...")
    iphone_dir = os.path.join(sdk_dir, 'iphone')
    for lib in glob.iglob(os.path.join(iphone_dir, 'lib*')):
        info("\t%s..." % lib)
        shutil.copy(lib, lib_dir)

    # Process i18n files
    info("Processing i18n...")
    locale_compiler = LocaleCompiler(app_name, project_dir, 'ios',
                                     'development', resources_dir)
    locale_compiler.compile()

    # Migrate compile scripts
    info("Copying custom Titanium compiler scripts...")
    shutil.copytree(os.path.join(sdk_dir, 'common'), titanium_local)
    shutil.copy(os.path.join(sdk_dir, 'tiapp.py'), titanium_local)

    iphone_script_dir = os.path.join(titanium_local, 'iphone')
    os.mkdir(iphone_script_dir)
    shutil.copy(os.path.join(sdk_dir, 'iphone', 'compiler.py'),
                iphone_script_dir)
    shutil.copy(os.path.join(sdk_dir, 'iphone', 'tools.py'), iphone_script_dir)
    shutil.copy(os.path.join(sdk_dir, 'iphone', 'run.py'), iphone_script_dir)
    shutil.copy(os.path.join(sdk_dir, 'iphone', 'csspacker.py'),
                iphone_script_dir)
    shutil.copy(os.path.join(sdk_dir, 'iphone', 'jspacker.py'),
                iphone_script_dir)
    shutil.copy(os.path.join(sdk_dir, 'iphone', 'titanium_prep'),
                iphone_script_dir)

    # Add compilation to the build script in project
    info("Modifying pre-compile stage...")
    xcodeproj = os.path.join(build_dir, '%s.xcodeproj' % app_name,
                             'project.pbxproj')
    contents = codecs.open(xcodeproj, 'r', encoding='utf-8').read()

    css_compiler = os.path.join('titanium', 'css', 'csscompiler.py')
    ti_compiler = os.path.join('titanium', 'iphone', 'compiler.py')
    script = """%s . ios Resources
%s . export-build $TARGETED_DEVICE_FAMILY $SDKROOT %s""" % (
        css_compiler, ti_compiler, version)
    contents = fix_xcode_script(contents, "Pre-Compile", script)

    # write our new project
    f = codecs.open(xcodeproj, 'w', encoding='utf-8')
    f.write(contents)
    f.close()

    info("Finished! Share and Enjoy.")
Example #9
0
def generate_images(network_pkl, target_fname):
    tflib.init_tf()
    print('Loading networks from "%s"...' % network_pkl)
    _G, _D, Gs = pretrained_networks.load_networks(network_pkl)

    # # Render images for a given dlatent vector.
    if target_fname is not None:
        target_pil = PIL.Image.open(target_fname)
        w, h = target_pil.size
        s = min(w, h)
        target_pil = target_pil.crop(
            ((w - s) // 2, (h - s) // 2, (w + s) // 2, (h + s) // 2))
        target_pil = target_pil.convert('RGB')
        target_pil = target_pil.resize(
            (Gs.output_shape[3], Gs.output_shape[2]), PIL.Image.ANTIALIAS)
        target_uint8 = np.array(target_pil, dtype=np.uint8)
        target_float = target_uint8.astype(np.float32).transpose(
            [2, 0, 1]) * (2 / 255) - 1

        proj = Projector()
        proj.set_network(Gs)
        proj.start([target_float])
        proj.dlatents

        dlatents = proj.dlatents  #np.load(dlatents_npz)['dlatents']
        assert dlatents.shape[1:] == (18, 512)  # [N, 18, 512]
        imgs = Gs.components.synthesis.run(
            dlatents,
            output_transform=dict(func=tflib.convert_images_to_uint8,
                                  nchw_to_nhwc=True))
        for i, img in enumerate(imgs):
            #fname = f'{outdir}/dlatent{i:02d}.png'
            #print (f'Saved {fname}')
            return PIL.Image.fromarray(img, 'RGB')  #.save(fname)

    # Render images for dlatents initialized from random seeds.
    Gs_kwargs = {
        'output_transform':
        dict(func=tflib.convert_images_to_uint8, nchw_to_nhwc=True),
        'randomize_noise':
        False
    }
    # if truncation_psi is not None:
    #     Gs_kwargs['truncation_psi'] = truncation_psi

    noise_vars = [
        var for name, var in Gs.components.synthesis.vars.items()
        if name.startswith('noise')
    ]
    label = np.zeros([1] + Gs.input_shapes[1][1:])
    # if class_idx is not None:
    #     label[:, class_idx] = 1

    # for seed_idx, seed in enumerate(seeds):
    # print('Generating image for seed %d (%d/%d) ...' % (seed, seed_idx, len(seeds)))
    seed = np.random.randint(0, 1000)
    rnd = np.random.RandomState(seed)
    z = rnd.randn(1, *Gs.input_shape[1:])  # [minibatch, component]
    tflib.set_vars(
        {var: rnd.randn(*var.shape.as_list())
         for var in noise_vars})  # [height, width]
    images = Gs.run(z, label,
                    **Gs_kwargs)  # [minibatch, height, width, channel]
    return PIL.Image.fromarray(images[0],
                               'RGB')  #.save(f'{outdir}/seed{seed:04d}.png')
Example #10
0
from projector import Projector, gray_block
from process_proxy import make_proxy
import time

#print(gray_block(3).astype(int))
#exit(0)

for i in range(1):
    print("Instantiating projector")
    projector = Projector()
    print("Making proxy")
    p = make_proxy(projector)
    print("Deleting original projector")
    del projector
    print("Displaying projector")
    p.show()
    print("Projector displayed")
    print("Getting monitor")
    print("Monitor: " + str(p.get_monitor()))
    print("Waiting...")
    time.sleep(1)
    print("Cycling column gray codes...")
    for b in range(p.get_gray_bits_width()):
        p.show_gray_cols(b)
        time.sleep(0.2)
    print("Cycling row gray codes...")
    for b in range(p.get_gray_bits_height()):
        p.show_gray_rows(b)
        time.sleep(0.2)
    print("Stopping projector")
    p.stop()
Example #11
0
##################################################################################
# Title: camera.py
# Author: Louie Liu
# Date: 15 April 2020
##################################################################################


from projector import Projector
import cv2

import numpy as np

p = Projector()
color = p.camera.getColorImage()
img = p.blankScreen()

cv2.namedWindow("window",cv2.WND_PROP_FULLSCREEN)
cv2.setWindowProperty("window", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
while(1):
    cv2.imshow("window", img)
    k = cv2.waitKey(33)
    if k == 27:
        break
    if k & 0b11111111 == ord('q'):
        sphero = p.findSphero()
        img = p.projectSpheroLine(sphero)
    elif k & 0b11111111 == ord('z'):
        img = p.blankScreen()
    elif k & 0b11111111 == ord('a'):
        angle = int(input("Input new angle between 0 and 360: "))
        img = p.projectSpheroLine(sphero,angle, True)
Example #12
0
    def drawCube(self, i, off=0):
        def deg(x):
            return x / 180.0 * math.pi

        proj = Projector()
        proj.set_yaw(deg(self.shemetype.zrot.get()))
        proj.set_pitch(-deg(self.shemetype.xrot.get()))
        proj.set_zmul(self.shemetype.zmul.get())
        proj.set_iso_projection(not self.shemetype.axonom.get())

        if i == 1:
            proj.set_mov(off, 0)

        P = self.shemetype.rebro.get()
        red = QPen()
        green = QPen()
        blue = QPen()

        red.setColor(QColor(255, 0, 0))
        green.setColor(QColor(0, 255, 0))
        blue.setColor(QColor(0, 0, 255))

        self.scene.addLine(QLineF(proj(+P, +P, +P), proj(-P, +P, +P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(+P, +P, +P), proj(+P, -P, +P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(+P, +P, +P), proj(+P, +P, -P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(+P, +P, -P), proj(-P, +P, -P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(+P, +P, -P), proj(+P, -P, -P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(-P, +P, -P), proj(-P, +P, +P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(+P, -P, -P), proj(+P, -P, +P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(-P, -P, +P), proj(-P, +P, +P)),
                           self.pen)
        self.scene.addLine(QLineF(proj(-P, -P, +P), proj(+P, -P, +P)),
                           self.pen)

        #axes:
        self.scene.addItem(
            ArrowItem(proj(+P, -P, -P),
                      proj(+2 * P, -P, -P),
                      arrow_size=(15, 3),
                      pen=self.halfpen,
                      brush=Qt.black))
        self.scene.addItem(
            ArrowItem(proj(-P, +P, -P),
                      proj(-P, +2 * P, -P),
                      arrow_size=(15, 3),
                      pen=self.halfpen,
                      brush=Qt.black))
        self.scene.addItem(
            ArrowItem(proj(-P, -P, +P),
                      proj(-P, -P, +2 * P),
                      arrow_size=(15, 3),
                      pen=self.halfpen,
                      brush=Qt.black))
        self.scene.addItem(
            TextItem("x",
                     font=self.font,
                     center=proj(+2 * P, -P, -P) + QPointF(0, -10),
                     pen=self.pen))
        self.scene.addItem(
            TextItem("z",
                     font=self.font,
                     center=proj(-P, +2 * P, -P) + QPointF(-8, 0),
                     pen=self.pen))
        self.scene.addItem(
            TextItem("y",
                     font=self.font,
                     center=proj(-P, -P, +2 * P) + QPointF(-8, 0),
                     pen=self.pen))

        #forces:
        qx = self.shemetype.task["sections"][i].qx
        qy = self.shemetype.task["sections"][i].qy
        qz = self.shemetype.task["sections"][i].qz
        mx = self.shemetype.task["sections"][i].mx
        my = self.shemetype.task["sections"][i].my
        mz = self.shemetype.task["sections"][i].mz

        qx_pnt = proj(2.5 * P, 0, 0)
        qy_pnt = proj(0, 0, 2.5 * P)
        qz_pnt = proj(0, 2.5 * P, 0)

        if qx != "нет":
            self.scene.addItem(
                ArrowItem(proj(P, 0, 0),
                          qx_pnt,
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=qx == "-"))
        if qy != "нет":
            self.scene.addItem(
                ArrowItem(proj(0, 0, P),
                          qy_pnt,
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=qy == "-"))
        if qz != "нет":
            self.scene.addItem(
                ArrowItem(proj(0, P, 0),
                          qz_pnt,
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=qz == "-"))

        M = 3 / 4
        if mz != "нет":
            reverse = mz == "-"
            self.scene.addItem(
                ArrowItem(proj(-P * M, 0, P),
                          proj(P * M, 0, P),
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=reverse))
            self.scene.addItem(
                ArrowItem(proj(P, 0, -P * M),
                          proj(P, 0, P * M),
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=reverse))

        if my != "нет":
            reverse = my == "-"
            self.scene.addItem(
                ArrowItem(proj(-P * M, P, 0),
                          proj(P * M, P, 0),
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=reverse))
            self.scene.addItem(
                ArrowItem(proj(P, -P * M, 0),
                          proj(P, P * M, 0),
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=reverse))

        if mx != "нет":
            reverse = mx == "-"
            self.scene.addItem(
                ArrowItem(proj(0, -P * M, P),
                          proj(0, P * M, P),
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=reverse))
            self.scene.addItem(
                ArrowItem(proj(0, P, -P * M),
                          proj(0, P, P * M),
                          arrow_size=(15, 5),
                          pen=self.pen,
                          brush=Qt.black,
                          reverse=reverse))

        #labels:
        if i == 0:

            def do_label(i, pnt=QPointF(0, 0), hint=None):
                text = self.shemetype.task["labels"][i].text
                x = self.shemetype.task["labels"][i].x
                y = self.shemetype.task["labels"][i].y
                item = TextItem(paintool.greek(text),
                                font=self.font,
                                center=pnt + QPointF(x, y),
                                pen=self.pen)
                self.scene.addItem(item)
                self.hovers[hint] = item
                item.hint = hint

            section = self.shemetype.task["sections"][0]
            if section.qx != "нет": do_label(0, qx_pnt, hint="qx")
            if section.qy != "нет": do_label(1, qy_pnt, hint="qy")
            if section.qz != "нет": do_label(2, qz_pnt, hint="qz")
            if section.mx != "нет": do_label(3, proj(0, 0, P), hint="mx")
            if section.my != "нет": do_label(4, proj(0, P, 0), hint="my")
            if section.mz != "нет": do_label(5, proj(P, 0, 0), hint="mz")

        if i == 1:

            def do_label(i, pnt=QPointF(0, 0), hint=None):
                text = self.shemetype.task["labels"][i].text2
                x = self.shemetype.task["labels"][i].x2
                y = self.shemetype.task["labels"][i].y2
                item = TextItem(text,
                                font=self.font,
                                center=pnt + QPointF(x, y),
                                pen=self.pen)
                self.scene.addItem(item)
                self.hovers[hint] = item
                item.hint = hint

            section = self.shemetype.task["sections"][1]
            if section.qx != "нет": do_label(0, qx_pnt, hint="qx2")
            if section.qy != "нет": do_label(1, qy_pnt, hint="qy2")
            if section.qz != "нет": do_label(2, qz_pnt, hint="qz2")
            if section.mx != "нет": do_label(3, proj(0, 0, P), hint="mx2")
            if section.my != "нет": do_label(4, proj(0, P, 0), hint="my2")
            if section.mz != "нет": do_label(5, proj(P, 0, 0), hint="mz2")
Example #13
0
def start():
    # setup scenegraph
    graph = avango.gua.nodes.SceneGraph(Name="scenegraph")
    loader = avango.gua.nodes.TriMeshLoader()

    projector = Projector()
    projector.Graph.value = graph
    projector.Texture.value = "data/textures/smiley.jpg"

    monkey = loader.create_geometry_from_file(
        "monkey", "data/objects/monkey.obj",
        avango.gua.LoaderFlags.NORMALIZE_SCALE)
    monkey.Material.connect_from(projector.Material)

    light = avango.gua.nodes.LightNode(
        Type=avango.gua.LightType.POINT,
        Name="light",
        Color=avango.gua.Color(1.0, 1.0, 1.0),
        Brightness=50.0,
        Transform=avango.gua.make_trans_mat(1, 1, 5) *
        avango.gua.make_scale_mat(15, 15, 15))

    size = avango.gua.Vec2ui(1024, 768)

    window = avango.gua.nodes.GlfwWindow(Size=size, LeftResolution=size)

    avango.gua.register_window("window", window)

    cam = avango.gua.nodes.CameraNode(LeftScreenPath="/screen",
                                      SceneGraph="scenegraph",
                                      Resolution=size,
                                      OutputWindowName="window",
                                      Transform=avango.gua.make_trans_mat(
                                          0.0, 0.0, 3.5))

    pipeline_description = avango.gua.nodes.PipelineDescription(Passes=[
        avango.gua.nodes.TriMeshPassDescription(),
        avango.gua.nodes.LightVisibilityPassDescription(),
        avango.gua.nodes.ResolvePassDescription()
    ])

    cam.PipelineDescription.value = pipeline_description

    screen = avango.gua.nodes.ScreenNode(Name="screen",
                                         Width=2,
                                         Height=1.5,
                                         Children=[cam])

    graph.Root.value.Children.value = [
        monkey, light, screen, projector.group_node
    ]

    #setup viewer
    viewer = avango.gua.nodes.Viewer()
    viewer.SceneGraphs.value = [graph]
    viewer.Windows.value = [window]

    #monkey rotation
    monkey_updater = TimedRotate()
    timer = avango.nodes.TimeSensor()
    monkey_updater.TimeIn.connect_from(timer.Time)
    monkey.Transform.connect_from(monkey_updater.MatrixOut)

    # projector movement
    navigator = Navigator()
    navigator.OutTransform.value = avango.gua.make_identity_mat()
    navigator.StartLocation.value = avango.gua.Vec3(0.0, 0.0, 1.0)

    navigator.RotationSpeed.value = 0.2
    navigator.MotionSpeed.value = 0.04

    projector.Transform.connect_from(navigator.OutTransform)

    guaVE = GuaVE()
    guaVE.start(locals(), globals())

    viewer.run()
Example #14
0
    (Projector) stores the pattens from the controller, feeds a pattern to the Grid, taking a generator object of
     frames in return. It then creates a clock and puts the frame to the physcial pixels at the appropriate fps. When
     a generator is out of instances the projector sends the next pattern to the grid and starts the process again.

Bit Cycle (specific steps between loading the current pattern and putting pixels):
    a. (Projector) frame = calls self._grid.pixelate(pattern, fps, duration)
    b. (Grid) runs a setup for pattern which creates 1 or more Bit objects and any limbs it/they have
    c. (Grid) uses the loop part of the pattern to call methods on all or some of the bits, causing them to change one or
        more attributes such as size, position, color, etc. and yields the result to (Projector) under the variable 'frame'
        ** the generator object will produce at least (fps * duration) frames**
    d. (Projector) uses the pyGame clock ticker to put_pixles (next(frame)) to the client a fps frames per second
'''

# internal imports
from grid import Grid
from bits import Bit
from paterns import *
from projector import Projector

#external imports

# create 'global' variables
fps = 60
dimensions = (16,16)
# CREATE GRID
grid = Grid(dimensions=dimensions)
# CREATE PROJECTOR
projector = Projector(fps=fps, grid=grid)
# send patterns to grid and initialize

Example #15
0
                    level=logging.DEBUG,
                    format='%(asctime)s %(name)s %(levelname)s: %(message)s')
logger = logging.getLogger('api')

# Use environment variable PROJECTOR_SERIAL to configure the port to use
if 'PROJECTOR_SERIAL' in os.environ:
    # this is automatically set to a suitable default in run.sh
    projector_port = os.environ['PROJECTOR_SERIAL']
else:
    # punt - fall back to a common serial port name on some Linux systems
    logger.error('PROJECTOR_SERIAL is not set in the environment')
    projector_port = '/dev/ttyS0'
logger.info('Serial port configured as: %s', projector_port)

# setup our objects
projector = Projector(projector_port)
spec = ProjectorSpec()
app = Flask(__name__)


# custom exceptions
class UnknownCommandError(ValueError):
    pass


class BadParameterError(ValueError):
    pass


class SerialError(ValueError):
    pass
Example #16
0
from projector import Projector

my_projector = Projector('wxga', 2000)
my_projector.get_projector_resolution()
Example #17
0
    def paintEventImplementation(self, ev):
        self.selected_item = None
        self.scene = QGraphicsScene()
        self.painter.setRenderHints(QPainter.Antialiasing)

        proj = Projector()
        proj.set_yaw(deg(self.shemetype.zrot.get()))
        proj.set_pitch(-deg(self.shemetype.xrot.get()))
        proj.set_zmul(self.shemetype.zmul.get())
        proj.set_iso_projection(not self.shemetype.axonom.get())
        self.proj = proj

        rebro = self.shemetype.rebro.get()

        br = QColor(0, 0, 0)
        br.setAlphaF(0)
        p = QPen()
        p.setColor(br)

        if self.selected_label_id:
            for label_id, item in self.label_items.items():
                if self.selected_label_id == label_id:
                    green70 = QColor(0, 255, 0)
                    green70.setAlphaF(0.7)
                    self.scene.addRect(item.boundingRect(), brush=green70)

        # Рисуем линии.
        for s in self.shemetype.task["sections"]:
            self.scene.addLine(QLineF(
                proj(s.ax, s.ay, s.az) * rebro,
                proj(s.bx, s.by, s.bz) * rebro,
            ),
                               pen=self.pen)
            self.draw_distrib_forces(s)

        # Кружки нодов.
        for n in self.shemetype.task["nodes"]:  #
            self.draw_sharn(n)
            self.draw_forces(n)
            self.draw_torques(n)

        self.label_items = {}
        # Тексты
        for s in self.shemetype.task["labels"]:
            self.draw_text(paintool.greek(s.text), s.pos, label=s)

        #Сечение

        #section_width = sections.draw_section_routine(
        #	self,
        #	hcenter=0,
        #	right=fini_width)
        rect = self.scene.itemsBoundingRect()
        sectitem = SectionItem(self)
        sectitem.setPos(rect.x() + rect.width(),
                        rect.y() + rect.height() * (4 / 8))
        self.scene.addItem(sectitem)

        # Отрисовка при наведении.
        if self.hovered_node:
            h = self.hovered_node
            pnt = self.proj(h.x, h.y, h.z) * rebro
            self.scene.addEllipse(QRectF(pnt + QPointF(-3, -3),
                                         pnt + QPointF(3, 3)),
                                  pen=self.green,
                                  brush=Qt.green)

            if self.mouse_pressed:
                self.pressed_nodes = []

                def do(a, b, pen, force=False):
                    if force or not self.has_section(self.point(a),
                                                     self.point(b)):
                        self.draw_point(b, pen)
                        self.draw_line(a, b, pen)
                        self.pressed_nodes.append(self.point(b[0], b[1], b[2]))

                do((h.x, h.y, h.z), (h.x + 1, h.y, h.z), self.green)
                do((h.x, h.y, h.z), (h.x - 1, h.y, h.z), self.green)
                do((h.x, h.y, h.z), (h.x, h.y + 1, h.z), self.green)
                do((h.x, h.y, h.z), (h.x, h.y - 1, h.z), self.green)
                do((h.x, h.y, h.z), (h.x, h.y, h.z + 1), self.green)
                do((h.x, h.y, h.z), (h.x, h.y, h.z - 1), self.green)

                if self.hovered_node_pressed is not None:
                    do((h.x, h.y, h.z),
                       self.hovered_node_pressed,
                       self.blue,
                       force=True)

        if self.hovered_sect:
            s = self.hovered_sect
            self.scene.addLine(QLineF(
                self.proj(s.ax, s.ay, s.az) * rebro,
                self.proj(s.bx, s.by, s.bz) * rebro,
            ),
                               pen=self.blue)

        WBORDER = self.shemetype.wborder.get()
        HBORDER = self.shemetype.hborder.get()

        if len(self.shemetype.task["sections"]) == 0:
            self.scene.addRect(QRectF(QPointF(-20, -20), QPointF(20, 20)),
                               brush=br,
                               pen=p)

        rect = self.scene.itemsBoundingRect()
        addtext = paintool.greek(self.shemetype.texteditor.toPlainText())
        n = len(addtext.splitlines())
        for i, l in enumerate(addtext.splitlines()):
            t = self.scene.addText(l, self.font)
            t.setPos(
                rect.x(),
                rect.height() + rect.y() +
                QFontMetrics(self.font).height() * i)

        rect = self.scene.itemsBoundingRect()

        self.scene.addRect(QRectF(rect.x() - WBORDER,
                                  rect.y() - HBORDER,
                                  rect.width() + WBORDER * 2,
                                  rect.height() + HBORDER * 2),
                           pen=p,
                           brush=br)
        self.offset = QPointF(rect.x() - WBORDER, rect.y() - HBORDER)
        self.scene.render(self.painter)

        self.resize_after_render(*self.scene_bound())
Example #18
0
from letter import Letter
from projector import Projector

l = Letter()
p = Projector(l)
p.animate()