Beispiel #1
0
    def init_shaders(cls, noeuds):
        for noeud in noeuds:
            if noeud.GetObject() is not None:
                geo = noeud.GetObject().GetGeometry()
                i = geo.GetMaterialCount()
                n = 0
                while n < i:
                    materiau = geo.GetMaterial(n)
                    nom = materiau.GetName()
                    #Cherche le départ du chunk, grace au caractère '#'
                    of7 = 0
                    shader_ok = False
                    for htag in nom:
                        if htag == '#':
                            shader_ok = True
                            break
                        of7 += 1
                    if shader_ok:
                        chunk = nom[of7 + 1] + nom[of7 +
                                                   2] + nom[of7 +
                                                            3] + nom[of7 + 4]
                        if chunk == "bk00":
                            texture = materiau.GetTexture("diffuse_map")
                            materiau.SetSurfaceShader(Demo.shader_constant_map)
                            materiau.SetTexture("diffuse_map", texture)
                        elif chunk == "oc01":
                            texture = materiau.GetTexture("diffuse_map")
                            materiau.SetSurfaceShader(Demo.shader_ocean_01)
                            materiau.SetTexture("texture_couleur", texture)
                            materiau.SetTexture("texture_bruit",
                                                Demo.texture_bruit_01)
                        elif chunk == "oc02":
                            texture = materiau.GetTexture("diffuse_map")
                            materiau.SetSurfaceShader(Demo.shader_ocean_02)
                            materiau.SetTexture("texture_couleur", texture)
                            materiau.SetTexture("texture_bruit",
                                                Demo.texture_bruit_01)
                        elif chunk == "em01":
                            couleur = gs.Color()
                            couleur.r, couleur.g, couleur.b, couleur.a = materiau.GetFloat4(
                                "diffuse_color")
                            print(materiau.GetName() + " R:" + str(couleur.r) +
                                  " G:" + str(couleur.g) + " B:" +
                                  str(couleur.b))
                            materiau.SetSurfaceShader(Demo.shader_constant)
                            materiau.SetFloat4("diffuse_color", couleur.r,
                                               couleur.g, couleur.b, couleur.a)
                        elif chunk == "tr01":
                            couleur = gs.Color()
                            couleur.r, couleur.g, couleur.b, couleur.a = materiau.GetFloat4(
                                "diffuse_color")
                            materiau.SetSurfaceShader(Demo.shader_transparent)
                            materiau.SetFloat4("diffuse_color", couleur.r,
                                               couleur.g, couleur.b,
                                               couleur.a / 2)

                    n += 1
Beispiel #2
0
def draw_material_surface_variable_gui(imgui, mat, shd, i):
    var_name = shd.GetVariableName(i)
    var_type = shd.GetVariableType(i)
    var_hint = shd.GetVariableHint(i)

    if imgui.IsItemHovered():
        imgui.BeginTooltip()
        if var_hint is not None:
            imgui.Text(var_hint)
        else:
            imgui.Text(shader_type_to_string[var_type])

        imgui.EndTooltip()

    if var_hint == 'color':
        col = mat.GetFloat4(var_name)
        col = imgui.ColorEdit(var_name, gs.Color(col[0], col[1], col[2],
                                                 col[3]))
        mat.SetFloat4(var_name, col.r, col.g, col.b, col.a)
    else:
        if var_type == gs.ShaderInt:
            mat.SetInt(var_name, imgui.InputInt(var_name,
                                                mat.GetInt(var_name)))
        else:
            imgui.Text(var_name + ' (no edit)')
Beispiel #3
0
def change_groupe(scn, gui, openvr_frame_renderer):
    global current_stages, current_node_groupe, current_audio_group, counter_wait

    counter_wait -= plus.GetClockDt().to_sec()

    # switch highlighted group
    if (counter_wait < 0.0 and current_audio_group is None
            and current_node_groupe is None) or plus.KeyPress(
                gs.InputDevice.KeySpace):
        counter_wait = 1.0
        for node in scn_glow.GetNodes():
            node.SetEnabled(False)

        node = scn_glow.GetNode(app_stages[current_stages]["name_group"])
        if node is not None:
            node.SetEnabled(True)
            current_node_groupe = node
        else:
            current_node_groupe = None

        current_stages += 1
        if current_stages >= len(app_stages):
            current_stages = 0

    # launch audio after 1 sec, and if the user find it
    if counter_wait < 0.0 and current_audio_group is None and not gui.WantCaptureMouse(
    ):
        controller0 = gs.GetInputSystem().GetDevice("openvr_controller_0")
        # if slighlty press gachette
        if openvr_frame_renderer is not None and controller0 is not None and controller0.GetValue(
                gs.InputDevice.InputButton2) > 0.2:
            mat_controller = controller0.GetMatrix(gs.InputDevice.MatrixHead)

            pos_cam = scn.GetCurrentCamera().GetTransform().GetPosition()
            pos_laser = mat_controller.GetTranslation() + pos_cam
            dir_laser = mat_controller.GetZ()

            hit, trace = scn.GetPhysicSystem().Raycast(pos_laser, dir_laser, 4)
            if hit:
                scene_simple_graphic = scn.GetComponent("SceneOverlay")
                helper_2d.draw_line(scene_simple_graphic, pos_laser,
                                    trace.GetPosition(),
                                    gs.Color(238 / 255, 235 / 255, 92 / 255))

                name = trace.GetNode().GetName()
                if name == app_stages[current_stages][
                        "name_group"] and controller0.GetValue(
                            gs.InputDevice.InputButton2) == 1.0:
                    current_audio_group = plus.GetMixer().Stream(
                        app_stages[current_stages]["sound"])
        elif openvr_frame_renderer is None:
            current_audio_group = plus.GetMixer().Stream(
                app_stages[current_stages]["sound"])

    # if the audio finish, enable the switch group
    if current_audio_group is not None and plus.GetMixer().GetPlayState(
            current_audio_group) != gs.MixerPlaying:
        current_audio_group = None
        current_node_groupe = None
        counter_wait = 1.0
Beispiel #4
0
    def __init__(self,
                 nFrames,
                 premiereFrame,
                 nomSequence,
                 nomFichier,
                 centresTab=[],
                 pasTab=[]):
        """
        Charge une séquence de sprites
        :param nFrames:
        :param premiereFrame:
        :param nomSequence:
        :param nomFichier:
        :param centresTab:
        :param pasTab:
        :return:
        """
        """
        :param nFrames:
        :param premiereFrame: le numero du premier fichier de la série
        :param nomSequence:
        :param nomFichier:
        :param centresTab:
        :param pasTab:
        :return:
        """
        self.xPos, self.yPos = 400., 300.
        self.numFrames = nFrames
        self.frame_actuelle = 0
        self.frames = []
        self.nom = nomSequence
        self.couleur = gs.Color(1., 1., 1., 1.)
        self.c3, self.c2, self.c1, self.c0 = 0, 0, 0, 0

        i = 0
        while i < premiereFrame:
            self.incCompteur()
            i += 1
        i = 0

        if len(centresTab) > 0 and len(pasTab) > 0:
            while i < nFrames:
                self.frames.append(
                    SpriteFrame(nomFichier + str(self.c3) + str(self.c2) +
                                str(self.c1) + str(self.c0) + ".png"),
                    centresTab[i * 2], centresTab[i * 2 + 1], pasTab[i * 2],
                    pasTab[i * 2 + 1])
                self.incCompteur()
                i += 1
        else:
            while i < nFrames:
                self.frames.append(
                    SpriteFrame(nomFichier + str(self.c3) + str(self.c2) +
                                str(self.c1) + str(self.c0) + ".png"))
                self.incCompteur()
                i += 1
Beispiel #5
0
    def blur(tgt_1, pict_1, tgt_2, pict_2):
        plus.GetRendererAsync().SetRenderTarget(tgt_2)
        plus.GetRendererAsync().SetViewport(
            gs.fRect(0, 0, screen_size.x, screen_size.y))
        plus.GetRendererAsync().Set2DMatrices()
        plus.GetRendererAsync().EnableBlending(True)
        plus.GetRendererAsync().SetShader(single_texture_shader)
        plus.GetRenderSystemAsync().SetShaderEngineValues()
        horizontal = 0
        for i in range(5):
            plus.GetRendererAsync().SetRenderTarget(tgt_2)
            plus.GetRendererAsync().Clear(gs.Color(0, 0, 0, 0))
            plus.GetRendererAsync().SetShaderTexture("u_tex", pict_1)
            plus.GetRendererAsync().SetShaderValue("horizontal", horizontal)
            plus.GetRenderSystemAsync().DrawTriangleUV(2, vtxs, uvs)

            plus.GetRendererAsync().DrawFrame()
            plus.GetRendererAsync().Sync()
            tgt_1, tgt_2 = tgt_2, tgt_1
            pict_1, pict_2 = pict_2, pict_1
            horizontal = (horizontal + 1) % 2

        return pict_1
Beispiel #6
0
for spr_file in os.listdir("data/"):

    if not spr_file.startswith("scaled_"):
        render.init(512, 512, "../pkg.core")

        spr_pic = gs.LoadPicture("@data/" + spr_file)
        w, h = spr_pic.GetWidth(), spr_pic.GetHeight()

        render.uninit()

        render.init(w * scaled_copies, h, "../pkg.core")

        capture_buffer = gs.Picture(w * scaled_copies, h, gs.Picture.RGBA8)

        for i in range(2):
            render.clear(gs.Color(1, 0, 1))
            for i in range(scaled_copies):
                sprite_scale_factor = RangeAdjust(float(i), 0.0,
                                                  float(scaled_copies), 1.0,
                                                  min_factor)
                render.image2d(i * w + (w * (1.0 - sprite_scale_factor) * 0.5),
                               h * (1.0 - sprite_scale_factor) * 0.5,
                               sprite_scale_factor, "@data/" + spr_file)
            # render.sprite2d(512 - 64, 512 - 64, 128, "@data/blink.jpg")
            # render.blit2d(0, 0, 512, 512, 80, 80, 512 - 160, 512 - 160, "@data/owl.jpg")
            render.flip()

        render.get_renderer().CaptureFramebuffer(capture_buffer)
        gs.SavePicture(capture_buffer, "@data/" + "scaled_" + spr_file, 'STB',
                       'format:png')
gs.LoadPlugins(gs.get_default_plugins_path())

render.init(1280, 720, "../pkg.core")

scn = scene.new_scene()
cam = scene.add_camera(scn,
                       gs.Matrix4.TranslationMatrix(gs.Vector3(0, 3.5, -12.5)))
cam.GetTransform().SetRotation(
    gs.Vector3(pi * 5.0 / 180.0, pi * -5.0 / 180.0, 0))

scene.add_light(scn, gs.Matrix4.RotationMatrix(gs.Vector3(0.65, -0.45, 0)),
                gs.Light.Model_Linear, 150)
scene.add_light(scn,
                gs.Matrix4.RotationMatrix(gs.Vector3(0.55, pi, 0.2)),
                gs.Light.Model_Linear,
                diffuse=gs.Color(0.3, 0.3, 0.4))
scene.add_physic_plane(scn)

# nodes = add_kapla_tower(scn, 0.5, 2, 2, 6, 16)

width, height, length = 1, 1, 1

node_list = []
stream_list = []


def make_solid_pos(x, y):
    return gs.Vector3(x * 1.15, y + height * 0.5, cos(x * y + x) * 0.15)


cube_masks = [[0, 0, 1, 0], [0, 1, 1, 0], [1, 1, 1, 1]]
Beispiel #8
0
WIDTH1 = 720 // 2
HEIGHT1 = 160
DISPL_WIDTH1 = DEFAULT_DISP_WIDTH
DISPL_HEIGHT1 = 79

# ViewPort 2
# Checkerboard & bobs area
ANIM_STRIPE = 10
WIDTH2 = 320
DISPL_WIDTH2 = DEFAULT_DISP_WIDTH
DISPL_HEIGHT2 = 150
HEIGHT2 = (DISPL_HEIGHT2 * ANIM_STRIPE)

CHECKERBOARD_HEIGHT = 100

# ViewPort 2b
ANIM_STRIPEb = 8
WIDTH2b = 720 // 2
DISPL_WIDTH2b = DEFAULT_DISP_WIDTH
DISPL_HEIGHT2b = 150
HEIGHT2b = (DISPL_HEIGHT2b * ANIM_STRIPEb)

# ViewPort 3
# Scrolltext area
WIDTH3 = 720 // 2
DISPL_HEIGHT3 = 13
HEIGHT3 = (DISPL_HEIGHT3 << 1)

COLOUR_PURPLE_DARK = gs.Color(0x2a / 255.0, 0x12 / 255.0, 0x21 / 255.0, 1.0)
COLOUR_PURPLE = gs.Color(0x4a / 255.0, 0x22 / 255.0, 0x51 / 255.0, 1.0)
COLOUR_PURPLE_LIGHT = gs.Color(0x5F / 255.0, 0x00 / 255.0, 0x4B / 255.0, 1.0)
def calibration(scn, openvr_frame_renderer, gui):
    global calibration_matrix, do_calibration, timer, calibration_fov, show_live_cam, draw_calibration_picture

    show_live_cam = gui.Checkbox("Show live cam", show_live_cam)

    temp_calibration = gui.Checkbox("Calibration", do_calibration)
    if temp_calibration:
        if not show_live_cam and temp_calibration != do_calibration:
            load_record(scn, openvr_frame_renderer)

        # draw alpha picture
        draw_calibration_picture = gui.Checkbox("Draw calibration picture",
                                                draw_calibration_picture)
        if draw_calibration_picture:
            gs.GetPlus().Image2D(0, 0, 1.0, "calibration.png",
                                 gs.Color(1, 1, 1, 0.5))

        if gui.Button("Calibrate live from ground"):
            controller1 = gs.GetInputSystem().GetDevice("openvr_controller_1")
            if controller1 is not None:
                calibration_matrix = controller1.GetMatrix(
                    gs.InputDevice.MatrixHead).InversedFast()

        delta = 0.01
        pos_calibration = calibration_matrix.GetTranslation()
        if gui.Button("PosX -"):
            pos_calibration.x -= delta
        gui.SameLine()
        if gui.Button("PosX +"):
            pos_calibration.x += delta
        gui.SameLine()
        pos_calibration.x = gui.InputFloat("px", pos_calibration.x)[1]
        if gui.Button("PosY -"):
            pos_calibration.y -= delta
        gui.SameLine()
        if gui.Button("PosY +"):
            pos_calibration.y += delta
        gui.SameLine()
        pos_calibration.y = gui.InputFloat("py", pos_calibration.y)[1]
        if gui.Button("PosZ -"):
            pos_calibration.z -= delta
        gui.SameLine()
        if gui.Button("PosZ +"):
            pos_calibration.z += delta
        gui.SameLine()
        pos_calibration.z = gui.InputFloat("pz", pos_calibration.z)[1]
        # pos_calibration = gui.InputVector3("Pos", pos_calibration)[1]

        rot_calibration = calibration_matrix.GetRotation()

        if gui.Button("RotX -"):
            rot_calibration.x -= delta
        gui.SameLine()
        if gui.Button("RotX +"):
            rot_calibration.x += delta
        gui.SameLine()
        rot_calibration.x = gui.InputFloat(
            "rx", rot_calibration.x * 180.0 / 3.1415)[1] * 3.1415 / 180.0
        if gui.Button("RotY -"):
            rot_calibration.y -= delta
        gui.SameLine()
        if gui.Button("RotY +"):
            rot_calibration.y += delta
        gui.SameLine()
        rot_calibration.y = gui.InputFloat(
            "ry", rot_calibration.y * 180.0 / 3.1415)[1] * 3.1415 / 180.0
        if gui.Button("RotZ -"):
            rot_calibration.z -= delta
        gui.SameLine()
        if gui.Button("RotZ +"):
            rot_calibration.z += delta
        gui.SameLine()
        rot_calibration.z = gui.InputFloat(
            "rz", rot_calibration.z * 180.0 / 3.1415)[1] * 3.1415 / 180.0

        calibration_matrix = gs.Matrix4.TransformationMatrix(
            pos_calibration, rot_calibration)

        changed, calibration_fov = gui.SliderFloat("FOV (deg)",
                                                   calibration_fov, 1, 180)
        if changed:
            scn.GetCurrentCamera().GetCamera().SetZoomFactor(
                gs.FovToZoomFactor(calibration_fov * 3.1415 / 180.0))

        if records is not None:
            timer = gui.SliderFloat("Timeline", timer, 0,
                                    max([float(i) for i in records.keys()]))[1]
    else:
        if temp_calibration != do_calibration:
            save_calibration()
            stop_play(scn, openvr_frame_renderer)

    do_calibration = temp_calibration
Beispiel #10
0
class Scene_base:

    #==== Les signaux globals de scène, qui servent à l'enchaînement des tableaux:
    SIG_RIEN = 0

    scene3d = None
    contexte = None
    components = None
    environnement = None
    couleur_horizon = gs.Color(170 / 255, 237 / 255, 255 / 255)
    couleur_zenith = gs.Color(130 / 255, 197 / 255, 255 / 255)
    couleur_ambiante = gs.Color(19 / 255, 42 / 255, 63 / 255)
    camera = None
    signal = SIG_RIEN

    #-------- La liste d'affichage des sprites, contient des objets SpriteTransform
    #liste_sprites_scene=[]          #Les sprites intégrés à la scène
    #liste_sprites_hors_scene=[]     #Les sprites hors scène (habillage visuel)

    #-------- Données pour le mini-éditeur embarqué, à supprimer après le dev:
    EDIT_OFF = 0
    EDIT_SCENE = 1
    EDIT_FILTRES = 2
    NUM_PAGES_EDIT = 2

    edit_id = EDIT_SCENE

    #---------

    fps = None  #Controle manuel de la caméra
    lumieres_intens_mem = []

    @classmethod
    def init(cls):
        raise NotImplementedError

    @classmethod
    def init_billboards(cls, noeuds, liste):
        for noeud in noeuds:
            nom = noeud.GetName()
            bb_chunk = nom[0] + nom[1] + nom[2]
            if bb_chunk == "bb.":
                materiau = noeud.GetObject().GetGeometry().GetMaterial(0)
                texture = materiau.GetTexture("diffuse_map")
                #shader=Demo.systeme.LoadSurfaceShader("shaders/sprite_alpha.isl",False)
                materiau.SetSurfaceShader(Demo.shader_billboards)
                materiau.SetTexture("diffuse_map", texture)
                cls.scene3d.RemoveNode(noeud)
                bill = BillBoard()
                bill.convertion_node(noeud)
                liste.append(bill)

    @classmethod
    def init_shaders(cls, noeuds):
        for noeud in noeuds:
            if noeud.GetObject() is not None:
                geo = noeud.GetObject().GetGeometry()
                i = geo.GetMaterialCount()
                n = 0
                while n < i:
                    materiau = geo.GetMaterial(n)
                    nom = materiau.GetName()
                    #Cherche le départ du chunk, grace au caractère '#'
                    of7 = 0
                    shader_ok = False
                    for htag in nom:
                        if htag == '#':
                            shader_ok = True
                            break
                        of7 += 1
                    if shader_ok:
                        chunk = nom[of7 + 1] + nom[of7 +
                                                   2] + nom[of7 +
                                                            3] + nom[of7 + 4]
                        if chunk == "bk00":
                            texture = materiau.GetTexture("diffuse_map")
                            materiau.SetSurfaceShader(Demo.shader_constant_map)
                            materiau.SetTexture("diffuse_map", texture)
                        elif chunk == "oc01":
                            texture = materiau.GetTexture("diffuse_map")
                            materiau.SetSurfaceShader(Demo.shader_ocean_01)
                            materiau.SetTexture("texture_couleur", texture)
                            materiau.SetTexture("texture_bruit",
                                                Demo.texture_bruit_01)
                        elif chunk == "oc02":
                            texture = materiau.GetTexture("diffuse_map")
                            materiau.SetSurfaceShader(Demo.shader_ocean_02)
                            materiau.SetTexture("texture_couleur", texture)
                            materiau.SetTexture("texture_bruit",
                                                Demo.texture_bruit_01)
                        elif chunk == "em01":
                            couleur = gs.Color()
                            couleur.r, couleur.g, couleur.b, couleur.a = materiau.GetFloat4(
                                "diffuse_color")
                            print(materiau.GetName() + " R:" + str(couleur.r) +
                                  " G:" + str(couleur.g) + " B:" +
                                  str(couleur.b))
                            materiau.SetSurfaceShader(Demo.shader_constant)
                            materiau.SetFloat4("diffuse_color", couleur.r,
                                               couleur.g, couleur.b, couleur.a)
                        elif chunk == "tr01":
                            couleur = gs.Color()
                            couleur.r, couleur.g, couleur.b, couleur.a = materiau.GetFloat4(
                                "diffuse_color")
                            materiau.SetSurfaceShader(Demo.shader_transparent)
                            materiau.SetFloat4("diffuse_color", couleur.r,
                                               couleur.g, couleur.b,
                                               couleur.a / 2)

                    n += 1

    @classmethod
    def raz_camera(cls):
        raise NotImplementedError

    @classmethod
    def raz_jeu(cls):
        raise NotImplementedError

    @classmethod
    def raz_temps(cls):
        raise NotImplementedError

    @classmethod
    def restart(cls, id_point_depart=1):
        raise NotImplementedError

    @classmethod
    def tri_sprites(cls, liste, camera):
        if len(liste) > 0:
            camPos = camera.GetTransform().GetWorld().GetTranslation()
            for sprite in liste:
                sprPos = camPos - gs.Vector3(sprite.x, sprite.y, sprite.z)
                sprite.distance_camera = sprPos.Len()
            return sorted(liste,
                          key=attrgetter("distance_camera"),
                          reverse=True)
        else:
            return liste

    @classmethod
    def affiche_sprites_hors_scene(cls, liste):
        for sprite in liste:
            sprite.affiche()

    @classmethod
    def affiche_sprites_scene(cls, liste):
        #print ("----------------------")
        for sprite in liste:
            sprite.affiche_geometrie()
            #print (str(sprite.distance_camera))

    #Méthode où sont rendu les objets en raymarching, pour une fusion avec la scène 3d classique:
    @classmethod
    def affiche_rendu_shaders(cls):
        raise NotImplementedError

    @classmethod
    def pre_scene(cls):
        raise NotImplementedError

    @classmethod
    def post_scene(cls):
        raise NotImplementedError

    @classmethod
    def maj_cinetique(cls):
        raise NotImplementedError

    #Avant la mise à jour de Danel
    @classmethod
    def maj_physique(cls):
        raise NotImplementedError

    @classmethod
    def maj_cinetique_personnages(cls):
        raise NotImplementedError

    @classmethod
    def maj_physique_personnages(cls):
        raise NotImplementedError

    @classmethod
    def interaction_Danel(cls):
        raise NotImplementedError

    @classmethod
    def maj_camera(cls):
        raise NotImplementedError

    @classmethod
    def renvoie_position_ecran(cls, point):
        """
        Renvoie les limites du champ de vision à la profondeur en entrée.
        La caméra doit être orienté vers l'axe des Z
        :param point: gs.Vector3(x,y,z)
        :return: gs.Vector3(x_ecran,y_ecran,z=0)
        """
        #drapeau,position=gs.Project(cls.camera.GetCamera(),cls.camera.GetTransform(),gs.Vector2(16/9,1),point)
        drapeau, position = gs.Project(cls.camera.GetTransform().GetWorld(),
                                       cls.camera.GetCamera().GetZoomFactor(),
                                       Demo.rendu.GetAspectRatio(), point)
        return position

    @classmethod
    def edition(cls):
        raise NotImplementedError

    @classmethod
    def edition_filtres(cls):
        raise NotImplementedError
gs.plus.create_workers()
gs.LoadPlugins(gs.get_default_plugins_path())

render.init(1024, int(1024 * md_screen_h / md_screen_w), "../pkg.core")

scn = scene.new_scene()
scn.GetPhysicSystem().SetDefaultRigidBodyAxisLock(gs.LockZ + gs.LockRotX + gs.LockRotY)
scn.GetPhysicSystem().SetDebugVisuals(True)

cam = scene.add_camera(scn, gs.Matrix4.TranslationMatrix(gs.Vector3(0, 0.0, -md_screen_w * 1.15)))

screen = scene.add_plane(scn, mat=gs.Matrix4.TransformationMatrix(gs.Vector3(0,0,0), gs.Vector3(radians(-90),0,0)), width=md_screen_w, depth=md_screen_h)

scene.add_light(scn, gs.Matrix4.RotationMatrix(gs.Vector3(0.65, -0.45, 0)), gs.Light.Model_Linear, 150)
scene.add_light(scn, gs.Matrix4.RotationMatrix(gs.Vector3(0.55, pi, 0.2)), gs.Light.Model_Linear, diffuse=gs.Color(0.3, 0.3, 0.4))
ground = scene.add_physic_plane(scn, mat=gs.Matrix4.TransformationMatrix(gs.Vector3(0,-md_screen_h / 2,0), gs.Vector3(0,0,0)))


def enable_ground(flag):
	global ground, node_list
	ground[1].SetEnabled(flag)

	# if flag is False:
	# 	for _node in node_list:
	# 		if _node.GetComponent("RigidBody").GetIsSleeping():
	# 			print("Node is sleeping!")
	# 			_node.GetComponent("RigidBody").SetIsSleeping(False)
	# 			_node.GetComponent("RigidBody").ApplyLinearImpulse(gs.Vector3(0,-10,0))
	# 			_node.GetComponent("RigidBody").ApplyLinearForce(gs.Vector3(0,-10,0))
Beispiel #12
0
def update(scn, gui, openvr_frame_renderer):
    global render_tgt_a, render_tgt_b, render_tgt_scene, gpu_texture_a, gpu_texture_b, gpu_texture_scene, scn_glow, single_texture_shader, vtxs, uvs

    if not scn.IsReady():
        return

    screen_size = plus.GetRendererAsync().GetCurrentOutputWindow().GetSize()
    if render_tgt_a is None:
        render_tgt_a, gpu_texture_a = create_scene_render_target(
            screen_size.x, screen_size.y)
        render_tgt_b, gpu_texture_b = create_scene_render_target(
            screen_size.x, screen_size.y)

        render_tgt_scene, gpu_texture_scene = create_scene_render_target(
            screen_size.x, screen_size.y)

        scn_glow = plus.NewScene(False, False)
        plus.AddEnvironment(scn_glow,
                            gs.Color.Transparent)  # clear color to transparent

        scn_glow.SetCurrentCamera(
            plus.AddCamera(scn_glow,
                           scn.GetCurrentCamera().GetTransform().GetWorld()))

        # find all node with name group, insert in the scn_glow and remove from the other
        for node in scn.GetNodes():
            if "group" in node.GetName():
                new_node = plus.AddGeometry(
                    scn_glow,
                    node.GetObject().GetGeometry().GetName(),
                    node.GetTransform().GetWorld())
                new_node.SetName(node.GetName())
                # remove from the old
                scn.RemoveNode(node)

        plus.UpdateScene(scn_glow, gs.time(0))
        plus.UpdateScene(scn_glow, gs.time(0))

        single_texture_shader = plus.GetRendererAsync().LoadShader(
            "assets/blur_texture.isl")

        vtxs = [
            gs.Vector3(0, 0, 0.5),
            gs.Vector3(0, screen_size.y, 0.5),
            gs.Vector3(screen_size.x, screen_size.y, 0.5),
            gs.Vector3(0, 0, 0.5),
            gs.Vector3(screen_size.x, screen_size.y, 0.5),
            gs.Vector3(screen_size.x, 0, 0.5)
        ]
        uvs = [
            gs.Vector2(0, 1),
            gs.Vector2(0, 0),
            gs.Vector2(1, 0),
            gs.Vector2(0, 1),
            gs.Vector2(1, 0),
            gs.Vector2(1, 1)
        ]

    # check if change groupe
    change_groupe(scn, gui, openvr_frame_renderer)

    # render the geo in the first render target
    plus.GetRendererAsync().SetRenderTarget(render_tgt_a)
    plus.GetRendererAsync().Clear(gs.Color(0, 0, 0, 0))
    plus.GetRendererAsync().SetViewport(
        gs.fRect(0, 0, screen_size.x, screen_size.y))

    if scn_glow.GetCurrentCamera() is not None:
        scn_glow.GetCurrentCamera().GetTransform().SetWorld(
            scn.GetCurrentCamera().GetTransform().GetWorld())
    plus.UpdateScene(scn_glow, gs.time(0))

    # render the first picture into the main scene second picture
    def blur(tgt_1, pict_1, tgt_2, pict_2):
        plus.GetRendererAsync().SetRenderTarget(tgt_2)
        plus.GetRendererAsync().SetViewport(
            gs.fRect(0, 0, screen_size.x, screen_size.y))
        plus.GetRendererAsync().Set2DMatrices()
        plus.GetRendererAsync().EnableBlending(True)
        plus.GetRendererAsync().SetShader(single_texture_shader)
        plus.GetRenderSystemAsync().SetShaderEngineValues()
        horizontal = 0
        for i in range(5):
            plus.GetRendererAsync().SetRenderTarget(tgt_2)
            plus.GetRendererAsync().Clear(gs.Color(0, 0, 0, 0))
            plus.GetRendererAsync().SetShaderTexture("u_tex", pict_1)
            plus.GetRendererAsync().SetShaderValue("horizontal", horizontal)
            plus.GetRenderSystemAsync().DrawTriangleUV(2, vtxs, uvs)

            plus.GetRendererAsync().DrawFrame()
            plus.GetRendererAsync().Sync()
            tgt_1, tgt_2 = tgt_2, tgt_1
            pict_1, pict_2 = pict_2, pict_1
            horizontal = (horizontal + 1) % 2

        return pict_1

    if single_texture_shader is not None and single_texture_shader.IsReady():
        gpu_texture_blur = gpu_texture_a  #blur(render_tgt_a, gpu_texture_a, render_tgt_b, gpu_texture_b)

        # render the final picture
        plus.GetRendererAsync().SetRenderTarget(None)
        plus.GetRendererAsync().SetViewport(
            gs.fRect(0, 0, screen_size.x, screen_size.y))

        # render the slow scene output
        plus.Texture2D(0, 0, 1, gpu_texture_scene, gs.Color.White, False, True)
        plus.SetBlend2D(gs.BlendAlpha)
        plus.Texture2D(0, 0, 1, gpu_texture_blur, gs.Color.White, False, True)
        plus.SetBlend2D(gs.BlendOpaque)
Beispiel #13
0
    def init(cls):

        #-------- Environnement:
        cls.couleur_horizon = gs.Color(1., .699, .586)
        cls.couleur_zenith = gs.Color(1., 0.978, 0.407)
        cls.couleur_ambiante = gs.Color(0.19, 0.42, 0.34)
        #cls.couleur_ambiante=gs.Color(0.5,0.5,0.5)

        #-------- Création de la scène:
        cls.scene3d = scene.new_scene()

        cls.contexte = gs.SceneLoadContext(render.get_render_system())
        cls.scene3d.Load("scene_01/Gare_test.scn", cls.contexte)
        #----------- Attend que la scène soit accessible:
        scene.update_scene(cls.scene3d, 1 / 60)

        #----------- Prise en main de la scène:
        cls.noeuds = cls.contexte.GetNodes()
        cls.components = cls.scene3d.GetComponents()

        for comp in cls.components:
            if comp.GetAspect() == "Environment":
                cls.environnement = comp
                break

        #----------- Init billboards et shaders:

        cls.init_billboards(cls.noeuds, cls.liste_sprites_scene)
        cls.init_shaders(cls.noeuds)

        #----------- Init environnement:

        cls.environnement.SetBackgroundColor(cls.couleur_horizon)
        cls.environnement.SetFogColor(cls.couleur_horizon)
        cls.environnement.SetFogNear(1)
        cls.environnement.SetFogFar(100)
        cls.environnement.SetAmbientIntensity(2)
        cls.environnement.SetAmbientColor(cls.couleur_ambiante)

        cls.camera = cls.scene3d.GetNode("Camera")
        cls.camera.GetCamera().SetZNear(.1)
        cls.camera.GetCamera().SetZFar(1000.)
        cls.camera_start_pos_mem = cls.camera.GetTransform().GetPosition()
        #cls.camera.AddComponent(gs.Target())   #Si la caméra suit une cible

        cls.lumiere_clair_obscur = cls.scene3d.GetNode("clair obscur")
        cls.lumiere_soleil = cls.scene3d.GetNode("soleil")

        cls.lumiere_soleil.GetLight().SetShadow(
            gs.Light.Shadow_Map)  #Active les ombres portées
        cls.lumiere_soleil.GetLight().SetShadowRange(100)

        cls.lumiere_soleil.GetLight().SetDiffuseIntensity(1.)
        cls.lumiere_soleil.GetLight().SetSpecularIntensity(1.)

        orientation = gs.Vector3(54 / 180 * pi, 135 / 180 * pi, 0)
        cls.lumiere_clair_obscur.GetTransform().SetRotation(orientation)

        orientation = gs.Vector3(54 / 180 * pi, -45 / 180 * pi, 0)
        cls.lumiere_soleil.GetTransform().SetRotation(orientation)

        #cls.lumiere_clair_obscur.GetLight().SetDiffuseIntensity(2.)
        #cls.lumiere_clair_obscur.GetLight().SetSpecularIntensity(2.)

        #-------- Mémorise les intensités lumineuses pour le switch des éclairages:
        noeuds = cls.scene3d.GetNodes()
        for noeud in noeuds:
            if not noeud.GetLight() == None:
                cls.lumieres_intens_mem.append(
                    noeud.GetLight().GetDiffuseIntensity())
                cls.lumieres_intens_mem.append(
                    noeud.GetLight().GetSpecularIntensity())

        #--------Init les variables de shaders:

        #Couleur d'ambiance:
        """
        for noeud in cls.noeuds:
            if not noeud.GetObject()==None:
                obj=noeud.GetObject()
                geo=obj.GetGeometry()
                n=geo.GetMaterialCount()
                i=0
                while i<n:
                    materiau=geo.GetMaterial(i)
                    materiau.SetFloat3("ambient_color",cls.couleur_ambiante.r*0.,cls.couleur_ambiante.g*0.,cls.couleur_ambiante.b*0.)
                    i+=1
        """
        #--------- Init listes des sprites:
        #cls.liste_sprites_scene.append(...)

        #--------- Inits de l'éditeur embarqué
        cls.cube_l_soleil = scene.add_cube(cls.scene3d, gs.Matrix4.Identity,
                                           0.5, 0.5, 2.)
        cls.cube_l_clair_obscur = scene.add_cube(cls.scene3d,
                                                 gs.Matrix4.Identity, 0.5, 0.5,
                                                 2.)

        cls.scene3d.SetCurrentCamera(cls.camera)

        scene.update_scene(cls.scene3d, 1 / 60)
    def init(cls):

        #-------- Environnement:
        cls.couleur_horizon = gs.Color(10. / 255., 1. / 255., 5. / 255., 1.)
        cls.couleur_zenith = gs.Color(70. / 255., 150. / 255., 255. / 255., 1.)
        cls.couleur_ambiante = gs.Color(70. / 255., 150. / 255., 255. / 255.,
                                        1.)
        #cls.couleur_ambiante=gs.Color(1,0,0,1)

        #-------- Création de la scène:
        cls.scene3d = scene.new_scene()

        cls.contexte = gs.SceneLoadContext(render.get_render_system())
        #cls.scene3d.Load("scene_terrain_marching/Terrain_Marching.scn",cls.contexte)
        cls.scene3d.Load("scene_01/Gare_test.scn", cls.contexte)
        #----------- Attend que la scène soit accessible:
        scene.update_scene(cls.scene3d, 1 / 60)

        #----------- Prise en main de la scène:
        cls.noeuds = cls.contexte.GetNodes()
        cls.components = cls.scene3d.GetComponents()

        for comp in cls.components:
            if comp.GetAspect() == "Environment":
                cls.environnement = comp
                break

        #----------- Init billboards et shaders:

        cls.init_billboards(cls.noeuds, cls.liste_sprites_scene)
        cls.init_shaders(cls.noeuds)

        #----------- Init environnement:

        cls.environnement.SetBackgroundColor(gs.Color(0., 0., 0., 0))
        cls.environnement.SetFogColor(cls.couleur_zenith)
        cls.environnement.SetFogNear(10)
        cls.environnement.SetFogFar(6000)
        cls.environnement.SetAmbientIntensity(.1)
        cls.environnement.SetAmbientColor(cls.couleur_ambiante)

        cls.camera = cls.scene3d.GetNode("Camera")
        cls.camera.GetCamera().SetZNear(.1)
        cls.camera.GetCamera().SetZFar(10000.)
        cls.camera_start_pos_mem = cls.camera.GetTransform().GetPosition()
        #cls.camera.AddComponent(gs.Target())   #Si la caméra suit une cible

        cls.lumiere_ciel = cls.scene3d.GetNode("clair obscur")
        cls.lumiere_soleil = cls.scene3d.GetNode("soleil")
        cls.lumiere_ciel.GetLight().SetDiffuseColor(
            gs.Color(77. / 255., 158. / 255., 255. / 255., 1.))
        cls.lumiere_ciel.GetLight().SetDiffuseIntensity(0.2)
        cls.lumiere_soleil.GetLight().SetDiffuseColor(
            gs.Color(255. / 255., 250. / 255., 223. / 255., 1.))

        cls.lumiere_soleil.GetLight().SetShadow(
            gs.Light.Shadow_Map)  #Active les ombres portées
        cls.lumiere_soleil.GetLight().SetShadowRange(100)

        cls.lumiere_soleil.GetLight().SetDiffuseIntensity(1.)
        cls.lumiere_soleil.GetLight().SetSpecularIntensity(1.)

        orientation = gs.Vector3(54 / 180 * pi, 135 / 180 * pi, 0)
        cls.lumiere_ciel.GetTransform().SetRotation(orientation)

        orientation = gs.Vector3(54 / 180 * pi, -45 / 180 * pi, 0)
        cls.lumiere_soleil.GetTransform().SetRotation(orientation)

        #cls.lumiere_ciel.GetLight().SetDiffuseIntensity(2.)
        #cls.lumiere_ciel.GetLight().SetSpecularIntensity(2.)

        #-------- Mémorise les intensités lumineuses pour le switch des éclairages:
        noeuds = cls.scene3d.GetNodes()
        for noeud in noeuds:
            if not noeud.GetLight() == None:
                cls.lumieres_intens_mem.append(
                    noeud.GetLight().GetDiffuseIntensity())
                cls.lumieres_intens_mem.append(
                    noeud.GetLight().GetSpecularIntensity())

        #--------Init les variables de shaders:

        #Couleur d'ambiance:
        """
        for noeud in cls.noeuds:
            if not noeud.GetObject()==None:
                obj=noeud.GetObject()
                geo=obj.GetGeometry()
                n=geo.GetMaterialCount()
                i=0
                while i<n:
                    materiau=geo.GetMaterial(i)
                    materiau.SetFloat3("ambient_color",cls.couleur_ambiante.r*0.,cls.couleur_ambiante.g*0.,cls.couleur_ambiante.b*0.)
                    i+=1
        """
        #--------- Init listes des sprites:
        #cls.liste_sprites_scene.append(...)

        #--------- Inits de l'éditeur embarqué
        cls.cube_l_soleil = scene.add_cube(cls.scene3d, gs.Matrix4.Identity,
                                           0.5, 0.5, 2.)
        cls.cube_l_ciel = scene.add_cube(cls.scene3d, gs.Matrix4.Identity, 0.5,
                                         0.5, 2.)

        cls.scene3d.SetCurrentCamera(cls.camera)

        scene.update_scene(cls.scene3d, 1 / 60)

        #------------- Filtres:
        Demo.pr_alpha_rendu = 1.
        Demo.pr_alpha_aura = 0.
        Demo.pr_taille_aura = 50
        Demo.pr_aura_contraste = 2
        Demo.pr_aura_seuil_contraste = 0.6

        #-------------- Init le shader de rendu de terrain:
        cls.shader_terrain = Demo.rendu.LoadShader(
            "shaders_marching/terrain_marching_montagnes.isl")
        cls.texture_terrain1 = Demo.rendu.LoadTexture(
            "textures/bruit_1024.png")
        cls.texture_terrain2 = Demo.rendu.LoadTexture("textures/bruit_512.png")
        cls.texture_terrain3 = Demo.rendu.LoadTexture("textures/bruit_512.png")

        cls.facteur_echelle_terrain_l1 = gs.Vector2(20000, 20000)
        cls.facteur_echelle_terrain_l2 = gs.Vector2(1000, 1000)
        cls.facteur_echelle_terrain_l3 = gs.Vector2(90, 90)

        cls.amplitude_l1 = 1000
        cls.amplitude_l2 = 37
        cls.amplitude_l3 = 4
        cls.terrain_intensite_ambiante = 0.2

        cls.facteur_precision_distance = 1.01
        cls.couleur_neige = gs.Color(0.91, 0.91, 1)
        cls.couleur_eau = gs.Color(117. / 255., 219. / 255., 211. / 255.)
        cls.altitude_eau = 15
    def edition_terrain(cls):

        if input.key_down(gs.InputDevice.KeyA):
            cls.facteur_echelle_terrain_l1.x += 100
        elif input.key_down(gs.InputDevice.KeyQ):
            cls.facteur_echelle_terrain_l1.x -= 100
            if cls.facteur_echelle_terrain_l1.x < 100:
                cls.facteur_echelle_terrain_l1.x = 100

        if input.key_down(gs.InputDevice.KeyZ):
            cls.facteur_echelle_terrain_l1.y += 100
        elif input.key_down(gs.InputDevice.KeyS):
            cls.facteur_echelle_terrain_l1.y -= 100
            if cls.facteur_echelle_terrain_l1.y < 100:
                cls.facteur_echelle_terrain_l1.y = 100

        if input.key_down(gs.InputDevice.KeyE):
            cls.facteur_echelle_terrain_l2.x += 100
        elif input.key_down(gs.InputDevice.KeyD):
            cls.facteur_echelle_terrain_l2.x -= 100
            if cls.facteur_echelle_terrain_l2.x < 100:
                cls.facteur_echelle_terrain_l2.x = 100

        if input.key_down(gs.InputDevice.KeyR):
            cls.facteur_echelle_terrain_l2.y += 100
        elif input.key_down(gs.InputDevice.KeyF):
            cls.facteur_echelle_terrain_l2.y -= 100
            if cls.facteur_echelle_terrain_l2.y < 100:
                cls.facteur_echelle_terrain_l2.y = 100

        if input.key_down(gs.InputDevice.KeyT):
            cls.facteur_echelle_terrain_l3.x += 100
        elif input.key_down(gs.InputDevice.KeyG):
            cls.facteur_echelle_terrain_l3.x -= 100
            if cls.facteur_echelle_terrain_l3.x < 100:
                cls.facteur_echelle_terrain_l3.x = 100

        if input.key_down(gs.InputDevice.KeyY):
            cls.facteur_echelle_terrain_l3.y += 100
        elif input.key_down(gs.InputDevice.KeyH):
            cls.facteur_echelle_terrain_l3.y -= 100
            if cls.facteur_echelle_terrain_l3.y < 100:
                cls.facteur_echelle_terrain_l3.y = 100

        elif input.key_down(gs.InputDevice.KeyU):
            cls.amplitude_l1 += 100
        elif input.key_down(gs.InputDevice.KeyJ):
            cls.amplitude_l1 -= 100
            if cls.amplitude_l1 < 100:
                cls.amplitude_l1 = 100

        elif input.key_down(gs.InputDevice.KeyI):
            cls.amplitude_l2 += 1
        elif input.key_down(gs.InputDevice.KeyK):
            cls.amplitude_l2 -= 1
            if cls.amplitude_l2 < 1:
                cls.amplitude_l2 = 1

        elif input.key_down(gs.InputDevice.KeyO):
            cls.amplitude_l3 += 0.05
        elif input.key_down(gs.InputDevice.KeyL):
            cls.amplitude_l3 -= 0.05
            if cls.amplitude_l3 < 0.05:
                cls.amplitude_l3 = 0.05

        elif input.key_down(gs.InputDevice.KeyP):
            cls.facteur_precision_distance += 0.001
        elif input.key_down(gs.InputDevice.KeyM):
            cls.facteur_precision_distance -= 0.001
            if cls.facteur_precision_distance < 1.001:
                cls.facteur_precision_distance = 1.001

        elif input.key_down(gs.InputDevice.KeyNumpad2):
            cls.altitude_eau += 1
        elif input.key_down(gs.InputDevice.KeyNumpad1):
            cls.altitude_eau -= 1

        window_size = Demo.rendu.GetDefaultOutputWindow().GetSize()
        xPos = 10
        yPos = window_size.y - 30

        c = gs.Color(1., 0, 0, 1.)
        render.text2d(
            xPos, yPos, "A/Q facteur_echelle_terrain_l1.x: " +
            str(cls.facteur_echelle_terrain_l1.x), 16, c)
        render.text2d(
            xPos, yPos - 15, "Z/S facteur_echelle_terrain_l1.y: " +
            str(cls.facteur_echelle_terrain_l1.y), 16, c)
        render.text2d(
            xPos, yPos - 15 * 2, "E/D facteur_echelle_terrain_l2.x: " +
            str(cls.facteur_echelle_terrain_l2.x), 16, c)
        render.text2d(
            xPos, yPos - 15 * 3, "R/F facteur_echelle_terrain_l2.y: " +
            str(cls.facteur_echelle_terrain_l2.y), 16, c)
        render.text2d(
            xPos, yPos - 15 * 4, "T/G facteur_echelle_terrain_l3.x: " +
            str(cls.facteur_echelle_terrain_l3.x), 16, c)
        render.text2d(
            xPos, yPos - 15 * 5, "Y/H facteur_echelle_terrain_l3.y: " +
            str(cls.facteur_echelle_terrain_l3.y), 16, c)
        render.text2d(xPos, yPos - 15 * 6,
                      "U/J amplitude_l1: " + str(cls.amplitude_l1), 16, c)
        render.text2d(xPos, yPos - 15 * 7,
                      "I/K amplitude_l2: " + str(cls.amplitude_l2), 16, c)
        render.text2d(xPos, yPos - 15 * 8,
                      "O/L amplitude_l3: " + str(cls.amplitude_l3), 16, c)
        render.text2d(
            xPos, yPos - 15 * 9, "P/M facteur_precision_distance: " +
            str(cls.facteur_precision_distance), 16, c)
        render.text2d(xPos, yPos - 15 * 10,
                      "1/2 altitude_eau: " + str(cls.altitude_eau), 16, c)
    def affiche_rendu_shaders(cls):
        window_size = Demo.rendu.GetDefaultOutputWindow().GetSize()
        Demo.rendu.SetViewport(
            gs.fRect(0, 0, window_size.x,
                     window_size.y))  # fit viewport to window dimensions
        Demo.rendu.Clear(gs.Color(0., 0., 0., 0.))
        Demo.rendu.EnableBlending(False)
        Demo.rendu.SetShader(cls.shader_terrain)
        Demo.rendu.SetShaderTexture("texture_terrain", cls.texture_terrain1)
        Demo.rendu.SetShaderTexture("texture_terrain2", cls.texture_terrain2)
        Demo.rendu.SetShaderTexture("texture_terrain3", cls.texture_terrain3)
        Demo.rendu.SetShaderFloat("ratio_ecran", window_size.y / window_size.x)
        Demo.rendu.SetShaderFloat(
            "distanceFocale", Demo.calcul_distance_focale(
                cls.camera))  #cls.camera.GetCamera().GetZoomFactor()/2.)
        cam = cls.camera.GetTransform()
        camPos = cam.GetPosition()
        Demo.rendu.SetShaderFloat3("obs_pos", camPos.x, camPos.y, camPos.z)
        Demo.rendu.SetShaderMatrix3("obs_mat_normale",
                                    cam.GetWorld().GetRotationMatrix())
        Demo.rendu.SetShaderFloat2("facteur_echelle_terrain",
                                   1. / cls.facteur_echelle_terrain_l1.x,
                                   1. / cls.facteur_echelle_terrain_l1.y)
        Demo.rendu.SetShaderFloat2("facteur_echelle_terrain2",
                                   1. / cls.facteur_echelle_terrain_l2.x,
                                   1. / cls.facteur_echelle_terrain_l2.y)
        Demo.rendu.SetShaderFloat2("facteur_echelle_terrain3",
                                   1. / cls.facteur_echelle_terrain_l3.x,
                                   1. / cls.facteur_echelle_terrain_l3.y)
        Demo.rendu.SetShaderFloat("amplitude_terrain", cls.amplitude_l1)
        Demo.rendu.SetShaderFloat("amplitude_terrain2", cls.amplitude_l2)
        Demo.rendu.SetShaderFloat("amplitude_terrain3", cls.amplitude_l3)
        Demo.rendu.SetShaderFloat("facteur_precision_distance",
                                  cls.facteur_precision_distance)
        Demo.rendu.SetShaderFloat("altitude_eau", cls.altitude_eau)
        Demo.rendu.SetShaderFloat("intensite_ambiante",
                                  cls.terrain_intensite_ambiante)
        Demo.rendu.SetShaderFloat3("couleur_zenith", cls.couleur_zenith.r,
                                   cls.couleur_zenith.g, cls.couleur_zenith.b)
        Demo.rendu.SetShaderFloat3("couleur_horizon", cls.couleur_horizon.r,
                                   cls.couleur_horizon.g,
                                   cls.couleur_horizon.b)
        Demo.rendu.SetShaderFloat3("couleur_neige", cls.couleur_neige.r,
                                   cls.couleur_neige.g, cls.couleur_neige.b)
        Demo.rendu.SetShaderFloat3("couleur_eau", cls.couleur_eau.r,
                                   cls.couleur_eau.g, cls.couleur_eau.b)

        l_dir = cls.lumiere_soleil.GetTransform().GetWorld().GetRotationMatrix(
        ).GetZ()
        Demo.drapeau_erreur = True
        Demo.message_erreur = {
            "x:" + str(l_dir.x), "y:" + str(l_dir.y), "z:" + str(l_dir.z)
        }
        Demo.rendu.SetShaderFloat3("l1_direction", l_dir.x, l_dir.y, l_dir.z)
        l_couleur = cls.lumiere_soleil.GetLight().GetDiffuseColor()
        Demo.rendu.SetShaderFloat3("l1_couleur", l_couleur.r, l_couleur.g,
                                   l_couleur.b)

        l_dir = cls.lumiere_ciel.GetTransform().GetWorld().GetRotationMatrix(
        ).GetZ()
        Demo.rendu.SetShaderFloat3("l2_direction", l_dir.x, l_dir.y, l_dir.z)
        l_couleur = cls.lumiere_ciel.GetLight().GetDiffuseColor(
        ) * cls.lumiere_ciel.GetLight().GetDiffuseIntensity()
        Demo.rendu.SetShaderFloat3("l2_couleur", l_couleur.r, l_couleur.g,
                                   l_couleur.b)

        Demo.rendu.SetShaderFloat2("zFrustum",
                                   cls.camera.GetCamera().GetZNear(),
                                   cls.camera.GetCamera().GetZFar())

        Demo.affiche_texture_rendu()
        pass
Beispiel #17
0
def check_switch_objects(scn, scene_simple_graphic, cam, use_vr):
    global button_pressed, selected_material
    if selected_material is None:  # load the selected material
        selected_material = plus.LoadMaterial("assets/selected.mat")

    controller0 = gs.GetInputSystem().GetDevice("openvr_controller_0")

    # restore material
    if selected["n"] is not None:
        geo = selected["n"].GetObject().GetGeometry()
        for m in range(geo.GetMaterialCount()):
            geo.SetMaterial(m, selected["m"][m])
        selected["n"] = None
        selected["m"] = None

    pos_laser = None
    dir_laser = None
    click_on_switch = False

    if use_vr is not None and controller0 is not None:
        if controller0.GetValue(gs.InputDevice.InputButton2) > 0.2:
            mat_controller = controller0.GetMatrix(gs.InputDevice.MatrixHead)

            pos_cam = cam.GetTransform().GetPosition()
            pos_laser = mat_controller.GetTranslation() + pos_cam
            dir_laser = mat_controller.GetZ()

            if controller0.GetValue(gs.InputDevice.InputButton2) == 1.0:
                click_on_switch = True
    else:
        if plus.KeyDown(gs.InputDevice.KeySpace) or plus.KeyDown(
                gs.InputDevice.KeyW):
            pos_laser = cam.GetTransform().GetPosition()
            dir_laser = cam.GetTransform().GetWorld().GetZ()

        if plus.KeyPress(gs.InputDevice.KeyW):
            click_on_switch = True

    if pos_laser is not None:
        hit, trace = scn.GetPhysicSystem().Raycast(pos_laser, dir_laser, 1)
        if hit:
            helper_2d.draw_line(scene_simple_graphic, pos_laser,
                                trace.GetPosition(),
                                gs.Color(238 / 255, 235 / 255, 92 / 255))
            if not use_vr:
                helper_2d.draw_cross(scene_simple_graphic, trace.GetPosition(),
                                     gs.Color(238 / 255, 235 / 255, 92 / 255))

            name = trace.GetNode().GetName()
            if "_switch_" in name:
                name = name[:-2]
                if name in switch_objects:
                    selected_node = switch_objects[name]["nodes"][
                        switch_objects[name]["current_display"]]

                    # if need to switch to selected material
                    current_material = selected_node.GetObject().GetGeometry(
                    ).GetMaterial(0)
                    if current_material != selected_material:
                        selected["n"] = selected_node
                        selected["m"] = []
                        geo = selected_node.GetObject().GetGeometry()
                        for m in range(geo.GetMaterialCount()):
                            selected["m"].append(geo.GetMaterial(m))
                            geo.SetMaterial(m, selected_material)
                            selected_material.SetTexture(
                                "diffuse_map",
                                current_material.GetTexture("diffuse_map"))

                    # switch if the trigger is triggered
                    if click_on_switch:
                        if not button_pressed:
                            button_pressed = True
                            switch_objects[name]["nodes"][switch_objects[name][
                                "current_display"]].SetEnabled(False)
                            switch_objects[name]["current_display"] += 1
                            if switch_objects[name]["current_display"] >= len(
                                    switch_objects[name]["nodes"]):
                                switch_objects[name]["current_display"] = 0
                            switch_objects[name]["nodes"][switch_objects[name][
                                "current_display"]].SetEnabled(True)
                    else:
                        button_pressed = False

        else:
            helper_2d.draw_line(scene_simple_graphic, pos_laser,
                                pos_laser + dir_laser * 10,
                                gs.Color(238 / 255, 235 / 255, 92 / 255))
            if not use_vr:
                helper_2d.draw_cross(scene_simple_graphic,
                                     pos_laser + dir_laser * 0.2,
                                     gs.Color(238 / 255, 235 / 255,
                                              92 / 255), 0.01)
        return True

    return False
Beispiel #18
0
def update_camera_teleporter(scn, scene_simple_graphic, cam, use_vr, authorise_ground_node):
	controller0 = gs.GetInputSystem().GetDevice("openvr_controller_0")
	pos_start = None
	dir_teleporter = None
	teleporter_activate = False

	if use_vr is not None and controller0 is not None:
		if controller0.GetValue(gs.InputDevice.InputButton0) != 0 or controller0.GetValue(gs.InputDevice.InputButton1) != 0:
			pos_cam = cam.GetTransform().GetPosition()
			mat_controller = controller0.GetMatrix(gs.InputDevice.MatrixHead)
			dir_teleporter = mat_controller.GetZ()
			pos_start = mat_controller.GetTranslation() + pos_cam

			teleporter_activate = controller0.WasButtonPressed(gs.InputDevice.Button0)
	else:
		if plus.KeyDown(gs.InputDevice.KeyX) or plus.KeyDown(gs.InputDevice.KeyC):
			pos_start = cam.GetTransform().GetPosition()
			dir_teleporter = cam.GetTransform().GetWorld().GetZ()

	if pos_start is not None:
		if pos_start.y < 0:
			return

		# teleporter
		# project point on the ground
		cos_angle = dir_teleporter.Dot(gs.Vector3(dir_teleporter.x, 0, dir_teleporter.z).Normalized())
		cos_angle = min(1.0, max(cos_angle, -1))
		angle = math.acos(cos_angle)
		if dir_teleporter.y < 0:
			angle = -angle

			velocity = 5
			d = ((velocity * cos_angle) / 9.81) * (velocity * math.sin(angle) + math.sqrt((velocity * math.sin(angle)) ** 2 + 2 * 9.81 * pos_start.y))

		else:
			velocity = 5
			min_d = ((velocity * 1) / 9.81) * (velocity * math.sin(0) + math.sqrt((velocity * math.sin(0)) ** 2 + 2 * 9.81 * pos_start.y))
			max_d = 10
			d = min_d + (1.0 - abs(cos_angle)) * max_d

		ground_pos = gs.Vector3(pos_start.x, 0, pos_start.z) + gs.Vector3(dir_teleporter.x, 0, dir_teleporter.z).Normalized() *d

		authorise_movement = True
		if authorise_ground_node is not None:
			authorise_ground_node.GetObject().GetGeometry().GetMaterial(0).SetFloat3("pos_touched", ground_pos.x, ground_pos.y, ground_pos.z)
			hit, trace = scn.GetPhysicSystem().Raycast(ground_pos + gs.Vector3(0, 0.5, 0), gs.Vector3(0, -1, 0), 4, 3)
			if not hit or trace.GetNode() != authorise_ground_node:
				authorise_movement = False

		strength_force = math.pow((math.sin(angle) + 1) / 2, 2) * 2

		color = gs.Color(0, 1, 198/255) if authorise_movement else gs.Color(1, 18/255, 0)
		helper_2d.draw_spline(scene_simple_graphic, pos_start, pos_start + dir_teleporter * strength_force, ground_pos + gs.Vector3(0, strength_force, 0), ground_pos, color)

		if authorise_ground_node is None:
			helper_2d.draw_circle(scene_simple_graphic, gs.Matrix4.TranslationMatrix(ground_pos), 1, color)

		if authorise_movement and teleporter_activate:
			if use_vr:
				head_controller = gs.GetInputSystem().GetDevice("openvr_hmd")
				head_pos = head_controller.GetMatrix(gs.InputDevice.MatrixHead).GetTranslation()
				head_pos.y = 0
				ground_pos = ground_pos - head_pos
			cam.GetTransform().SetWorld(gs.Matrix4.TranslationMatrix(ground_pos))
	else:
		if authorise_ground_node is not None:
			authorise_ground_node.GetObject().GetGeometry().GetMaterial(0).SetFloat3("pos_touched", 99999, 99999, 99999)
Beispiel #19
0
def render_overlay():
    global plus

    strings = [["AMOS allows up to", 40, 1, 0, "bilko-opti-bold", 42],
               ["eight screens to be", 65, 1, 0, "bilko-opti-bold", 42],
               ["displayed at any", 90, 1, 0, "bilko-opti-bold", 42],
               ["one time.", 115, 1, 0, "bilko-opti-bold", 42]]

    render_text_screen(strings, plus=plus, exit_callback=demo_exit_test)

    strings = [["Each screen can", 40, 1, 0, "bilko-opti-bold", 42],
               ["be manipulated in a", 65, 1, 0, "bilko-opti-bold", 42],
               ["variety of unusual ways.", 90, 1, 0, "bilko-opti-bold", 42]]

    render_text_screen(strings, plus=plus, exit_callback=demo_exit_test)

    strings = [[
        "OVERLAPPING SCREENS WITH DIFFERENT SIZES, RESOLUTIONS AND COLOURS IS EASY",
        40, 1, 0, "topaz-a500", 20
    ]]

    fx_timer = 0.0
    fx_duration = 8.0
    screen_0 = [0, 200, -2]
    screen_1 = [0, 0, 3]
    screen_2 = [0, 0, 1.25]

    while fx_timer < fx_duration:
        demo_exit_test()
        dt_sec = clock.update()
        fx_timer += dt_sec
        plus.Clear()

        # back image
        plus.Image2D(
            (demo_screen_size[0] - amiga_screen_size[0] * zoom_size()) * 0.5 +
            screen_0[0] * zoom_size(),
            (amiga_screen_size[1] - screen_0[1]) * zoom_size(),
            zoom_size() * 0.5, "@assets/multiscreen_pixelart.png")
        plus.Image2D(
            (demo_screen_size[0] - amiga_screen_size[0] * zoom_size()) * 0.5 +
            (screen_0[0] + amiga_screen_size[0]) * zoom_size(),
            (amiga_screen_size[1] - screen_0[1]) * zoom_size(),
            zoom_size() * 0.5, "@assets/multiscreen_pixelart.png")

        screen_0[0] += dt_sec * 60.0 * screen_0[2]
        if screen_0[0] < -amiga_screen_size[0]:
            screen_0[0] = -amiga_screen_size[0]
            screen_0[2] *= -1
        elif screen_0[0] > 0:
            screen_0[0] = 0
            screen_0[2] *= -1

        # front image
        plus.Image2D(
            (demo_screen_size[0] - amiga_screen_size[0] * zoom_size()) * 0.5 +
            screen_1[0] * zoom_size(),
            (amiga_screen_size[1] - screen_1[1]) * zoom_size(),
            zoom_size() * 0.5, "@assets/multiscreen_ham.png")

        screen_1[1] += dt_sec * 60.0 * screen_1[2]
        if screen_1[1] > amiga_screen_size[1] * 2:
            screen_1[1] = -amiga_screen_size[1]

        text_bg_y = (amiga_screen_size[1] - screen_2[1]) * zoom_size() - 3
        text_bg_col = gs.Color(0.1, 0.1, 0.1, 1.0)
        plus.Quad2D(0, text_bg_y, 0, text_bg_y + 32, demo_screen_size[0],
                    text_bg_y + 32, demo_screen_size[0], text_bg_y,
                    text_bg_col, text_bg_col, text_bg_col, text_bg_col)
        plus.Commit2D()
        strings[0][1] = screen_2[1]
        render_strings_array(strings, plus=plus)

        screen_2[1] += dt_sec * 60.0 * screen_2[2]
        if screen_2[1] > amiga_screen_size[1] * 1.25:
            screen_2[1] = -amiga_screen_size[1] * 0.25

        plus.Flip()