コード例 #1
0
    def create_3dcube(self, pos, size):
        x, y, z = pos
        w, h, p = size
        fmt = [('vPosition', 3, 'float'), ('vColor', 4, 'float')]
        vertices = [
            x, y, z, 1, 0, 0, 1, x + w, y, z, .5, .5, 0, 1, x + w, y + h, z, 0,
            1, 0, 1, x, y + h, z, 0, .5, .5, 1, x, y, z + p, 0, 0, 1, 1, x + w,
            y, z + p, .5, 0, .5, 1, x + w, y + h, z + p, 0, 0, 0, 1, x, y + h,
            z + p, 1, 1, 1, 1
        ]
        indices = [
            0, 2, 1, 0, 3, 2, 5, 0, 1, 5, 4, 0, 5, 2, 6, 5, 1, 2, 4, 3, 0, 4,
            7, 3, 2, 7, 6, 2, 3, 7, 5, 6, 4, 4, 6, 7
        ]

        Color(1, 1, 1)
        Mesh(vertices=vertices, indices=indices, fmt=fmt, mode='triangles')

        vertices = [
            x, y, z, 1, 1, 1, 1, x + w, y, z, 1, 1, 1, 1, x + w, y + h, z, 1,
            1, 1, 1, x, y + h, z, 1, 1, 1, 1, x, y, z + p, 1, 1, 1, 1, x + w,
            y, z + p, 1, 1, 1, 1, x + w, y + h, z + p, 1, 1, 1, 1, x, y + h,
            z + p, 1, 1, 1, 1
        ]
        indices = [
            0, 2, 2, 1, 1, 0, 0, 3, 3, 2, 1, 5, 2, 5, 2, 6, 6, 5, 0, 4, 4, 3,
            3, 7, 7, 4, 7, 2, 0, 5, 4, 5, 7, 6, 4, 6
        ]

        Color(1, 1, 1)
        Mesh(vertices=vertices, indices=indices, fmt=fmt, mode='lines')
コード例 #2
0
ファイル: app.py プロジェクト: cr8ivecodesmith/kivy-demox
    def render(self):
        ff_vertices, ff_indices = self.render_font_file(color=(1, 0.5, 1))
        msg_vertices, msg_indices = self.render_text(
            'Awesome font rendering from a sprite sheet! ;)',
            pos=(5, 200),
            color=(0.5, 1.0, 1.0))
        msg2_vertices, msg2_indices = self.render_text(
            'Demonstration of background clipping for transparency.',
            pos=(5, 150),
            color=(0.5, 1.0, 1.0))

        with self.canvas:
            Mesh(fmt=self.vfmt,
                 mode=str('triangles'),
                 indices=ff_indices,
                 vertices=ff_vertices,
                 texture=self.texture)
            Mesh(fmt=self.vfmt,
                 mode=str('triangles'),
                 indices=msg_indices,
                 vertices=msg_vertices,
                 texture=self.texture)
            Mesh(fmt=self.vfmt,
                 mode=str('triangles'),
                 indices=msg2_indices,
                 vertices=msg2_vertices,
                 texture=self.texture)
コード例 #3
0
    def _regenerate_mesh(self):
        '''(re)generates mesh(map visualisation) according to the surface points'''
        vertices = []
        indices = []

        scene = self.scene

        for i in range(MapWidget.map_segments_count):
            x, y = self.surface[i]
            # surface point
            vertices.extend([int(x), int(y), 0, 0])
            # map bottom point
            vertices.extend([int(x), int(0), 0, 0])

        min_x = scene.float_x_to_pixels(0)
        min_y = scene.float_y_to_pixels(0)
        max_x = scene.float_x_to_pixels(1)
        max_y = scene.float_y_to_pixels(1)
        # corners to make it polygonal fill of widget under surface
        vertices.extend([max_x, scene.float_y_to_pixels(random()), 0, 0])
        vertices.extend([max_x, min_y, 0, 0])
        vertices.extend([max_x, min_y, 0, 0])
        vertices.extend([min_x, min_y, 0, 0])

        indices = list(range(MapWidget.map_segments_count*2 + 4))

        self.canvas.clear()
        with self.canvas.before:
            # blue sky
            Color(0.4, 0.9, 1)
            self.mesh = Mesh(vertices=[min_x,min_y,0,0 ,min_x,max_y,0,0 ,max_x,max_y,0,0 , max_x,min_y,0,0], indices=[0,1,2,3], mode='triangle_fan')
        with self.canvas:
            # green terrain
            Color(0.2, 0.85, 0.3)
            self.mesh = Mesh(vertices=vertices, indices=indices, mode='triangle_strip') 
コード例 #4
0
ファイル: main.py プロジェクト: luskynavy/pythoncode
        def _draw_element(m, texture='', texture1=''):
            #bind the texture BEFORE the draw (Mesh)
            if texture1:
                # here, we are binding a custom texture at index 1
                # this will be used as texture1 in shader.
                tex1 = Image(texture1).texture
                tex1.wrap = 'repeat'  #enable of uv support >1 or <0
                BindTexture(texture=tex1, index=1)
            #clear the texture if none
            else:
                BindTexture(source="", index=1)

            mesh = Mesh(
                vertices=m.vertices,
                indices=m.indices,
                fmt=m.vertex_format,
                mode='triangles',
                group='truc',
            )

            if texture:
                try:
                    texture = Image(texture).texture
                    texture.wrap = 'repeat'  #enable of uv support >1 or <0
                    mesh.texture = texture
                except:  #no texture if not found or not supported
                    pass
コード例 #5
0
    def loadShaders(self):
        ## generate the glsl code
        #self.shader_substitutions.update(args)
        # print('scalar tracker subs')
        # print(self.shader_substitutions)

        self.shaders = glsl_utils.loadShaders('graph_renderer.glsl',
                                              self.shader_substitutions)

        # # ## set the meshes shaders to the generated glsl code
        self.render_context.shader.vs = self.shaders['vs']
        self.render_context.shader.fs = self.shaders['fs']

        ## replace any previous mesh with the new mesh
        if hasattr(self, 'curve_mesh'):
            self.render_context.remove(self.curve_mesh)
        fmt = [(b'v_pos', 2, 'float')]
        self.curve_mesh = Mesh(mode='line_strip', fmt=fmt)
        self.render_context['color'] = [1.0, 0.1, 0.0, 1.0]
        self.render_context.add(self.curve_mesh)

        if hasattr(self, 'fill_mesh'):
            self.render_context.remove(self.fill_mesh)
        fmt = [(b'v_pos', 2, 'float')]

        self.fill_mesh = Mesh(mode='triangles', fmt=fmt)
        self.render_context.add(self.fill_mesh)
コード例 #6
0
ファイル: __init__.py プロジェクト: zarar7576/plyer
    def __init__(self, **kwargs):
        super(Graph, self).__init__(**kwargs)

        self._mesh = Mesh(mode='lines')
        self._mesh_rect = Mesh(mode='line_strip')
        val = 0.25
        self.canvas.add(Color(1 * val, 1 * val, 1 * val))
        self.canvas.add(self._mesh)
        self.canvas.add(Color(1, 1, 1))
        self.canvas.add(self._mesh_rect)
        mesh = self._mesh_rect
        mesh.vertices = [0] * (5 * 4)
        mesh.indices = [k for k in xrange(5)]

        self._plot_area = StencilView()
        self.add_widget(self._plot_area)

        self._trigger = Clock.create_trigger(self._redraw_all)
        self._trigger_size = Clock.create_trigger(self._redraw_size)

        self.bind(center=self._trigger_size, padding=self._trigger_size,
                  font_size=self._trigger_size, plots=self._trigger_size,
                  x_grid=self._trigger_size, y_grid=self._trigger_size,
                  draw_border=self._trigger_size)
        self.bind(xmin=self._trigger, xmax=self._trigger,
                  xlog=self._trigger, x_ticks_major=self._trigger,
                  x_ticks_minor=self._trigger,
                  xlabel=self._trigger, x_grid_label=self._trigger,
                  ymin=self._trigger, ymax=self._trigger,
                  ylog=self._trigger, y_ticks_major=self._trigger,
                  y_ticks_minor=self._trigger,
                  ylabel=self._trigger, y_grid_label=self._trigger)
        self._trigger()
コード例 #7
0
    def build_mesh(self):
        #switch between original and alteration code
        #        switch = False   #original
        switch = True  #alteration
        """ returns a Mesh of a rough circle. """
        vertices = []
        indices = []
        step = 10
        istep = (pi * 2) / float(step)

        # my alteration
        # mask for mapping list of vertices
        # where is problem with format?
        vertex_format = [(b'v_pos', 2, "float")]

        for i in range(step):
            x = 300 + cos(istep * i) * 100
            y = 300 + sin(istep * i) * 100

            if switch == False:
                # originall code
                vertices.extend([x, y, 0, 0])
            else:
                # my alteration
                vertices.extend([x, y])

            indices.append(i)

        if switch == False:
            # originall code
            return Mesh(vertices=vertices, indices=indices)
        else:
            # my alteration
            return Mesh(vertices=vertices, indices=indices, fmt=vertex_format)
コード例 #8
0
ファイル: foobar.py プロジェクト: victor-rene/kivy-gamelib
 def __init__(self, **kwargs):
     super(FooBar, self).__init__(**kwargs)
     with self.canvas:
         self.mesh = Mesh(mode='triangles', source='img/bar.png')
         self.face = Mesh(mode='triangles', source='img/foo.png')
     self.build_mesh()
     self.build_face(self.vertices)
コード例 #9
0
ファイル: song.py プロジェクト: jwbowler/21m359-final
    def _make_ribbon_mesh(self, x, y, w, h):
        signal_power = np.square(self.data)
        frames_per_pixel = int(self.frames_per_beat / HORIZ_SCALE)
        scale_factor = frames_per_pixel * 2

        pad_size = math.ceil(float(signal_power.size)/scale_factor)*scale_factor - signal_power.size
        signal_power = np.append(signal_power, np.zeros(pad_size)*np.NaN)

        print signal_power.shape
        signal_power = signal_power.reshape(-1, scale_factor)
        print signal_power.shape

        signal_power = scipy.nanmean(signal_power, axis=1)
        print signal_power.shape

        signal_power /= np.max(signal_power)

        print 'signal power', len(signal_power)
        print signal_power[100:200]
        print np.max(signal_power)

        segments = self.blah_width

        mesh = Mesh()

        # create indices
        mesh.indices = range(segments * 2 + 2)

        # create vertices with evenly spaced texture coordinates
        span = np.linspace(0.0, 1.0, segments + 1)
        verts = []

        mid_y = y + h/2
        y_scale = h/2

        idx = 0
        for s in span:
            height = y_scale * signal_power[idx]
            verts += [x + s * w, mid_y - height, s, 0, x + s * w, mid_y + height, s, 1]
            idx += 1
        mesh.vertices = verts

        # # animate a sine wave by setting the vert positions every frame:
        # theta = 3.0 * self.time
        # y = 300 + 50 * np.sin(np.linspace(theta, theta + 2 * np.pi, self.segments + 1))
        # self.mesh.vertices[5::8] = y

        # seems that you have to reassign the entire verts list in order for the change
        # to take effect.
        mesh.vertices = mesh.vertices

        # # assign texture
        # if tex_file:
        #     mesh.texture = Image(tex_file).texture

        # standard triangle strip mode
        mesh.mode = 'triangle_strip'

        return mesh
コード例 #10
0
    def __init__(self, **kwargs):
        super(Graph, self).__init__(**kwargs)

        with self.canvas:
            self._fbo = Fbo(size=self.size,
                            with_stencilbuffer=self._with_stencilbuffer)

        with self._fbo:
            self._background_color = Color(*self.background_color)
            self._background_rect = Rectangle(size=self.size)
            self._mesh_ticks_color = Color(*self.tick_color)
            self._mesh_ticks = Mesh(mode='lines')
            self._mesh_rect_color = Color(*self.border_color)
            self._mesh_rect = Mesh(mode='line_strip')

        with self.canvas:
            Color(1, 1, 1)
            self._fbo_rect = Rectangle(size=self.size,
                                       texture=self._fbo.texture)

        mesh = self._mesh_rect
        mesh.vertices = [0] * (5 * 4)
        mesh.indices = range(5)

        self._plot_area = StencilView()
        self.add_widget(self._plot_area)

        t = self._trigger = Clock.create_trigger(self._redraw_all)
        ts = self._trigger_size = Clock.create_trigger(self._redraw_size)
        tc = self._trigger_color = Clock.create_trigger(self._update_colors)

        self.bind(center=ts,
                  padding=ts,
                  precision=ts,
                  plots=ts,
                  x_grid=ts,
                  y_grid=ts,
                  draw_border=ts)
        self.bind(xmin=t,
                  xmax=t,
                  xlog=t,
                  x_ticks_major=t,
                  x_ticks_minor=t,
                  xlabel=t,
                  x_grid_label=t,
                  ymin=t,
                  ymax=t,
                  ylog=t,
                  y_ticks_major=t,
                  y_ticks_minor=t,
                  ylabel=t,
                  y_grid_label=t,
                  font_size=t,
                  label_options=t,
                  x_ticks_angle=t)
        self.bind(tick_color=tc, background_color=tc, border_color=tc)
        self._trigger()
コード例 #11
0
ファイル: main.py プロジェクト: letaiefbechir/kivy.tips
 def _draw_element(m, texture=''):
     mesh = Mesh(
         vertices=m.vertices,
         indices=m.indices,
         fmt=m.vertex_format,
         mode='triangles',
     )
     if texture:
         texture = Image(texture).texture
         mesh.texture = texture
コード例 #12
0
    def _create_arrow(self, start_point: np.array, dir_vec: np.array):
        """Renders an arrow starting from `start_point` and pointing towards `dir_vec`.

        Parameters
        ----------
        start_point : `numpy.array`, (3 x 1)
            The coordinates of the origin of the arrow.
        dir_vec : `numpy.array`, (3 x 1)
            The direction vector of the arrow.

        Returns
        -------
        arrow_shaft : `kivy.graphics.Mesh`
            The mesh data of the arrow's shaft.
        arrw_head : `kivy.graphics.Mesh`
            The mesh data of the arrow's head.
        """
        dir_vec /= 2
        end_point = start_point + dir_vec
        shaft_data = GLMeshData(
            np.concatenate((start_point, end_point), axis=0),
            normals=-np.ones((2, 3)),
            indices=[0, 1],
        )
        arrow_shaft = Mesh(
            vertices=shaft_data.verts_gl,
            indices=shaft_data.indices,
            fmt=shaft_data.vertex_format,
            mode="lines",
        )

        # Create the points of the arrow head's base circle
        bases = self._get_base_vecs(dir_vec)
        npoints = 20
        step = 2 * math.pi / npoints
        points = []
        for j in range(npoints):
            points.append(0.03 * (bases[0] * math.sin(step * j) +
                                  bases[1] * math.cos(step * j)))
        points = np.array(points)
        points += start_point + dir_vec * 0.8

        # Add to the points of the circle the tip of the arrow and set up the faces to create the mesh
        points = np.append(points, end_point, axis=0)
        faces = []
        for j in range(npoints):
            faces.append([j, npoints, (j + 1) % npoints])
        head_data = GLMeshData(points, faces=faces)
        arrow_head = Mesh(
            vertices=head_data.verts_gl,
            indices=head_data.indices,
            fmt=head_data.vertex_format,
            mode="triangles",
        )
        return (arrow_shaft, arrow_head)
コード例 #13
0
 def show_axis(self):
     Color(1, 1, 0, 1) #Yellow
     Mesh(
             vertices=[
                  -1,        0,      0, 1, 1, 0, 0, 0,
                   1,        0,      0, 1, 1, 0, 0, 0,
                 0.8,      0.1,      0, 1, 1, 0, 0, 0,
                 0.8,     -0.1,      0, 1, 1, 0, 0, 0,
                   1,        0,      0, 1, 1, 0, 0, 0,
                 0.8,        0,   -0.1, 1, 1, 0, 0, 0,
                 0.8,        0,    0.1, 1, 1, 0, 0, 0,
                   1,        0,      0, 1, 1, 0, 0, 0,
               ],
             indices=[0, 1, 2, 3, 4, 5, 6, 7],
             fmt=self.mesh_data.vertex_format,
             mode='line_strip',
         )
     Color(1, 0, 1, 1) # purple
     Mesh(
             vertices=[
                    0,      0,      -1, 0, 1, 1, 0, 0,
                    0,      0,       1, 0, 1, 1, 0, 0,
                  0.1,      0,     0.8, 0, 1, 1, 0, 0,
                 -0.1,      0,     0.8, 0, 1, 1, 0, 0,
                    0,      0,       1, 0, 1, 1, 0, 0,
                    0,   -0.1,     0.8, 0, 1, 1, 0, 0,
                    0,    0.1,     0.8, 0, 1, 1, 0, 0,
                    0,      0,       1, 0, 1, 1, 0, 0,
               ],
             indices=[0, 1, 2, 3, 4, 5, 6, 7],
             fmt=self.mesh_data.vertex_format,
             mode='line_strip',
         )
     Color(0, 1, 1, 1) # Baby Blue
     Mesh(
             vertices=[
                    0,      -1,      0, 1, 1, 0, 0, 0,
                    0,       1,      0, 1, 1, 0, 0, 0,
                  0.1,     0.8,      0, 1, 1, 0, 0, 0,
                 -0.1,     0.8,      0, 1, 1, 0, 0, 0,
                    0,       1,      0, 1, 1, 0, 0, 0,
                    0,     0.8,   -0.1, 1, 1, 0, 0, 0,
                    0,     0.8,    0.1, 1, 1, 0, 0, 0,
                    0,       1,      0, 1, 1, 0, 0, 0,
               ],
             indices=[0, 1, 2, 3, 4, 5, 6, 7],
             fmt=self.mesh_data.vertex_format,
             mode='line_strip',
         )
コード例 #14
0
ファイル: graphics.py プロジェクト: TimSC/kivmap
def DrawTris(vertices, triangles, DrawCallback):
	
	#Arrange data in kivy internal mesh format
	vertMod = []
	for i in range(len(vertices)/2):
		vertMod.extend((vertices[i*2], vertices[(i*2)+1], 0., 0.))
	ind = []
	for tri in triangles:
		ind.extend(tri)
	
	mesh = Mesh()
	mesh.vertices = vertMod
	mesh.indices = ind
	mesh.mode = "triangles"
	DrawCallback(mesh)
コード例 #15
0
    def draw_object(self, obj_id):
        m = self._scene.objects[obj_id]
        self.obj_rot_z = Rotate(self.obj_rotation[2], 0, 0, 1)
        self.obj_rot_y = Rotate(self.obj_rotation[1], 0, 1, 0)
        self.obj_rot_x = Rotate(self.obj_rotation[0], 1, 0, 0)
        self.obj_translate = Translate(xyz=self.obj_translation)

        if len(m.indices) > 2**16:
            print '%s too big! %s indices' % (obj_id, len(m.indices))

        if m.texture:
            print "loading texture %s " % m.texture
            img = Image(
                source=resource_find(join(dirname(self.scene), m.texture)))
            texture = img.texture
            if texture:
                texture.wrap = 'repeat'
        else:
            texture = None

        vertex_lenght = sum(x[1] for x in m.vertex_format)
        if len(m.vertices) % vertex_lenght:
            print(('warning: vertices lenght (%s)'
                   'is not a multiple of vertex_format lenght(%s)') %
                  (len(m.vertices), vertex_lenght))
        Mesh(vertices=m.vertices,
             indices=m.indices,
             fmt=m.vertex_format,
             texture=texture,
             mode=self.mode)
コード例 #16
0
    def drawTriangles(self, lastPos, newPos, lastHeight, newHeight):
        trianglePts = []
        baseWhite = lastHeight >= 0.5 * self.height and newHeight >= 0.5 * self.height \
            and (lastHeight > 0.5 * self.height or newHeight > 0.5 * self.height)
        baseBlack = lastHeight <= 0.5 * self.height and newHeight <= 0.5 * self.height \
            and (lastHeight < 0.5 * self.height or newHeight < 0.5 * self.height)
        if baseWhite or baseBlack:
            refHeight = min(lastHeight, newHeight) if baseWhite else max(
                lastHeight, newHeight)
            biggestHeight = max(lastHeight, newHeight) if baseWhite else min(
                lastHeight, newHeight)

            refPos = lastPos if refHeight == lastHeight else newPos
            biggestPos = lastPos if biggestHeight == lastHeight else newPos

            trianglePts += [
                self.x + self.width * lastPos, self.y + 0.5 * self.height, 0,
                0, self.x + self.width * lastPos, self.y + refHeight, 0, 0,
                self.x + self.width * newPos, self.y + 0.5 * self.height, 0, 0,
                self.x + self.width * lastPos, self.y + refHeight, 0, 0,
                self.x + self.width * newPos, self.y + 0.5 * self.height, 0, 0,
                self.x + self.width * newPos, self.y + refHeight, 0, 0,
                self.x + self.width * refPos, self.y + refHeight, 0, 0,
                self.x + self.width * biggestPos, self.y + refHeight, 0, 0,
                self.x + self.width * biggestPos, self.y + biggestHeight, 0, 0
            ]
        baseColor = 0.65 if baseWhite else 0.35

        with self.canvas:
            Color(baseColor, baseColor, baseColor)
            if len(trianglePts) > 0:
                Mesh(vertices=trianglePts,
                     mode="triangles",
                     indices=range(int(len(trianglePts) / 4)))
コード例 #17
0
 def draw_mesh(self, star_list):
     star_tex = Image('star1.png').texture
     vertex_format = [
         (b'vPosition', 2, 'float'),
         (b'vSize', 1, 'float'),
         (b'vRotation', 1, 'float'),
     ]
     indices = []
     ia = indices.append
     for star_number in range(len(star_list)):
         ia(star_number)
     vertices = []
     e = vertices.extend
     for star in star_list:
         e([star[0], star[1], star[2], star[3]])
     if self.mesh == None:
         with self.canvas:
             PushMatrix()
             self.mesh = Mesh(indices=indices,
                              vertices=vertices,
                              fmt=vertex_format,
                              mode='points',
                              texture=star_tex)
             PopMatrix()
     else:
         self.mesh.indices = indices
         self.mesh.vertices = vertices
コード例 #18
0
    def __init__(self, pos, texture, size_x=1.0, size_y=1.0, intensity=1.0, Tr=1.0):
        super(BillboardDisplay, self).__init__()
        
        self.intensity = intensity
        self.Tr = Tr

        self.translate = Translate()
        self.rotate_azi = Rotate(origin=(0,0,0), axis=(0,1,0))
        self.rotate_ele = Rotate(origin=(0,0,0), axis=(1,0,0))
        self.scale = Scale()
        self.color_instruction = InstructionGroup()
        self.mesh = Mesh(
            texture=texture,
            vertices=rectangle_nurb.vertices,
            indices=rectangle_nurb.indices,
            fmt=rectangle_nurb.vertex_format,
            mode='triangles'
        )

        self.add(PushMatrix())
        self.add(self.translate)
        self.add(self.rotate_azi)
        self.add(self.rotate_ele)
        self.add(self.scale)
        self.add(self.color_instruction)
        self.add(self.mesh)
        self.add(PopMatrix())

        self.set_color(intensity=intensity, Tr=Tr)
        self.set_size(size_x, size_y)
        self.set_pos(pos)
        self.set_texture(texture)
コード例 #19
0
 def draw_mesh(self, this_star_list):
     if self.this_op is None:
         self.this_op = PointRendererOp()
         star_tex = Image('star1.png').texture
         self.this_op.indices = []
         ia = self.this_op.indices.append
         for star_number in range(len(this_star_list)):
             ia(star_number)
         self.this_op.vertices = []
         e = self.this_op.vertices.extend
         for star in this_star_list:
             this_star = [ star[0], star[1], star[2], star[3], \
                           star[4], star[5], star[6], star[7] ]
             if len(this_star) != self.vertex_depth:
                 print("FATAL ERROR: array size does not match " + \
                       "vertex depth (offset)")
                 exit(1)
             e(this_star)
     if self.mesh == None:
         with self.canvas:
             PushMatrix()
             self.mesh = Mesh(indices=self.this_op.indices,
                              vertices=self.this_op.vertices,
                              fmt=self.vertex_format,
                              mode='points',
                              texture=star_tex)
             PopMatrix()
     else:
         # self.mesh.indices = self.this_op.indices
         self.mesh.vertices = self.this_op.vertices
         pass
コード例 #20
0
    def _geojson_part_geometry(self, geometry, properties):
        tp = geometry["type"]
        graphics = []
        if tp == "Polygon":
            tess = Tesselator()
            for c in geometry["coordinates"]:
                xy = list(self._lonlat_to_xy(c))
                xy = flatten(xy)
                tess.add_contour(xy)

            tess.tesselate(WINDING_ODD, TYPE_POLYGONS)

            color = self._get_color_from(properties.get("style").get("stroke", "FF000088"))
            graphics.append(Color(*color))
            for vertices, indices in tess.meshes:
                graphics.append(
                    Mesh(
                        vertices=vertices,
                        indices=indices,
                        mode="triangle_fan"))

        elif tp == "LineString":
            stroke = get_color_from_hex(properties.get("style").get("stroke", "#ffffff"))
            print "stroke: " + `stroke`
            #storke =  [0.0, 0.0, 0.0, 1]

            print 'properties.get("width") :' + `properties.get("style").get("width")`
            stroke_width = dp(properties.get("style").get("width"))
            print "stroke_width: " + `stroke_width`
            xy = list(self._lonlat_to_xy(geometry["coordinates"]))
            xy = flatten(xy)
            graphics.append(Color(*stroke))
            graphics.append(Line(points=xy, width=stroke_width))

        return graphics
コード例 #21
0
 def draw_mesh(self, star_list):
     address = 'assets/particles/'
     tex_choice = choice([
         'particle.png', 'smokeparticle.png', 'VFX-0-Circle.png',
         'VFX-0-Star.png', 'VFX-1-Star.png'
     ])
     tex = Image(address + tex_choice).texture
     vertex_format = [(b'vPosition', 2, 'float'), (b'vSize', 1, 'float'),
                      (b'vRotation', 1, 'float'), (b'vColor', 4, 'float')]
     indices = []
     ia = indices.append
     for star_number in range(len(star_list)):
         ia(star_number)
     vertices = []
     e = vertices.extend
     for star in star_list:
         color = star[4]
         e([
             star[0], star[1], star[2], star[3], color[0], color[1],
             color[2], color[3]
         ])
     if self.mesh == None:
         with self.canvas:
             PushMatrix()
             self.mesh = Mesh(indices=indices,
                              vertices=vertices,
                              fmt=vertex_format,
                              mode='points',
                              texture=tex)
             PopMatrix()
     else:
         self.mesh.indices = indices
         self.mesh.vertices = vertices
         self.mesh.texture = tex
コード例 #22
0
    def show_lines(self):
        indices = []
        grid = self.grid
        cols = grid.cols
        rows = grid.rows
        for col in range(grid.cols + 1):
            indices.extend((
                col * (rows + 1),
                col * (rows + 1) + rows,
            ))
        for row in range(grid.rows + 1):
            indices.extend((
                row,
                row + (cols * (rows + 1)),
            ))

        with self.canvas:
            self.g_canvas = Canvas()

        with self.g_canvas:
            Color(1, 0, 0, 0.5)
            PushMatrix()
            Scale(self.width, self.height, 1.)
            self.g_mesh = Mesh(vertices=self.grid.line_vertices,
                               indices=self.grid.line_indices,
                               mode="lines",
                               source="projectionmapping/data/white.png")
            PopMatrix()

        self.rebuild_informations()
コード例 #23
0
    def __init__(self, edges=3, color=None, **kwargs):
        super(RegularShape, self).__init__(**kwargs)
        if edges < 3:
            raise Exception('Not enough edges! (3+ only)')

        color = color or [random() for i in range(3)]
        rad_edge = (pi * 2) / float(edges)
        r_x = self.width / 2.0
        r_y = self.height / 2.0
        poly = []
        vertices = []
        for i in range(edges):
            # get points within a circle with radius of [r_x, r_y]
            x = cos(rad_edge * i) * r_x + self.center_x
            y = sin(rad_edge * i) * r_y + self.center_y
            poly.extend([x, y])

            # add UV layout zeros for Mesh, see Mesh docs
            vertices.extend([x, y, 0, 0])

        # draw Mesh shape from generated poly points
        with self.canvas:
            Color(rgba=(color[0], color[1], color[2], 0.6))
            self.shape = Mesh(pos=self.pos,
                              vertices=vertices,
                              indices=list(range(edges)),
                              mode='triangle_fan')
        self.poly = poly
コード例 #24
0
 def __init__(self, **kw):
     super(Background, self).__init__(**kw)
     # self.frames = -1
     with self.canvas:
         self.clr = Color(0, .2, .2, mode='hsv')
         self.mesh = Mesh(mode='triangles', source='img/background.png')
     self.build_mesh()
コード例 #25
0
ファイル: __init__.py プロジェクト: zarar7576/plyer
    def __init__(self, **kwargs):
        self._color = Color(1, 1, 1, group='LinePlot%d' % id(self))
        self._mesh = Mesh(mode='line_strip', group='LinePlot%d' % id(self))
        super(MeshLinePlot, self).__init__(**kwargs)

        self._trigger = Clock.create_trigger(self._redraw)
        self.bind(_params=self._trigger, points=self._trigger)
コード例 #26
0
 def generateMesh(self):
     hgt = self.generateHeightData(200, 200, 0.1)
     norm = self.calcNormals(hgt)
     idcs = self.generateTriangleCounterClockWiseIndices(hgt)
     print(hgt.shape)
     vtx = []
     idx = []
     i = 0
     for x in range(hgt.shape[0]):
         for y in range(hgt.shape[1]):
             vtx.extend([
                 float(x) / 10.0 - 5,
                 hgt[x, y],
                 float(y) / 10.0 - 5,
                 norm[x, y, 0] / 10.0,
                 norm[x, y, 1],
                 norm[x, y, 2] / 10.0,
                 0.0,
                 0.0,
             ])
             idx.append(i)
             i += 1
     m = Mesh(vertices=vtx,
              indices=idcs,
              mode='triangles',
              fmt=[('v_pos', 3, 'float'), ('v_normal', 3, 'float'),
                   ('v_tc0', 2, 'float')
                   ])  #[(b'v_pos', 2, b'float'), (b'tc', 2, b'float')])
     return m
コード例 #27
0
    def get_mesh(self):
        v = []
        # first calculate the distance between endpoints of the inner
        # arc, so we know how many steps to use when calculating
        # vertices
        end_point_inner = polar_to_rect(self.origin, self.r_min,
                                        self.theta_max)

        d_inner = d_outer = 3.
        theta_step_inner = (self.theta_max - self.theta_min) / d_inner

        end_point_outer = polar_to_rect(self.origin, self.r_max,
                                        self.theta_max)

        if self.r_min == 0:
            theta_step_outer = (self.theta_max - self.theta_min) / d_outer
            for x in range(int(d_outer)):
                v += (polar_to_rect(self.origin, 0, 0) * 2)
                v += (polar_to_rect(self.origin, self.r_max,
                                    self.theta_min + x * theta_step_outer) * 2)
        else:
            for x in range(int(d_inner + 2)):
                v += (polar_to_rect(self.origin, self.r_min - 1,
                                    self.theta_min + x * theta_step_inner) * 2)
                v += (polar_to_rect(self.origin, self.r_max + 1,
                                    self.theta_min + x * theta_step_inner) * 2)

        v += (end_point_inner * 2)
        v += (end_point_outer * 2)

        return Mesh(vertices=v,
                    indices=range(int(len(v) / 4)),
                    mode='triangle_strip')
コード例 #28
0
ファイル: spikegl.py プロジェクト: Createcafe3d/peachyscanner
    def make_pretty_dots(self):
        points_per_side = 50

        points = []
        for idx in range(points_per_side):
            v = -1.0 + ((2.0 / points_per_side) * float(idx))
            tex = idx / float(points_per_side)
            print("TEX: {}".format(str(tex)))
            points.append([[v, -1.0, -1.0, v, -1.0, -1.0, tex, 0.0],
                           [v, -1.0, 1.0, v, -1.0, 1.0, tex, 0.0],
                           [v, 1.0, -1.0, v, 1.0, -1.0, tex, 1.0],
                           [v, 1.0, 1.0, v, 1.0, 1.0, tex, 1.0],
                           [-1.0, v, -1.0, -1.0, v, -1.0, 0.0, tex],
                           [-1.0, v, 1.0, -1.0, v, 1.0, 0.0, tex],
                           [1.0, v, -1.0, 1.0, v, -1.0, 1.0, tex],
                           [1.0, v, 1.0, 1.0, v, 1.0, 1.0, tex],
                           [-1.0, -1.0, v, -1.0, -1.0, v, tex, tex],
                           [-1.0, 1.0, v, -1.0, 1.0, v, tex, tex],
                           [1.0, -1.0, v, 1.0, -1.0, v, tex, tex],
                           [1.0, 1.0, v, 1.0, 1.0, v, tex, tex]], )

        points = np.array(points).flatten()
        Color(1, 1, 1, 1)
        Mesh(
            vertices=points,
            indices=[i for i in range(len(points) / 8)],
            fmt=self.mesh_data.vertex_format,
            mode='points',
        )
コード例 #29
0
    def _geojson_part_geometry(self, geometry, properties):
        from kivy.graphics import Mesh, Line, Color
        from kivy.graphics.tesselator import Tesselator, WINDING_ODD, TYPE_POLYGONS
        from kivy.utils import get_color_from_hex
        from kivy.metrics import dp
        tp = geometry["type"]
        graphics = []
        if tp == "Polygon":
            tess = Tesselator()
            for c in geometry["coordinates"]:
                xy = list(self._lonlat_to_xy(c))
                xy = flatten(xy)
                tess.add_contour(xy)

            tess.tesselate(WINDING_ODD, TYPE_POLYGONS)

            color = self._get_color_from(properties.get("color", "FF000088"))
            graphics.append(Color(*color))
            for vertices, indices in tess.meshes:
                graphics.append(
                    Mesh(vertices=vertices,
                         indices=indices,
                         mode="triangle_fan"))

        elif tp == "LineString":
            stroke = get_color_from_hex(properties.get("stroke", "#ffffff"))
            stroke_width = dp(properties.get("stroke-width"))
            xy = list(self._lonlat_to_xy(geometry["coordinates"]))
            xy = flatten(xy)
            graphics.append(Color(*stroke))
            graphics.append(Line(points=xy, width=stroke_width))

        return graphics
コード例 #30
0
    def get_mesh(self):
        v = []
        # first calculate the distance between endpoints of the outer
        # arc, so we know how many steps to use when calculating
        # vertices
        theta_step_outer = 0.1
        theta = self.theta_max - self.theta_min
        d_outer = int(theta / theta_step_outer)
        theta_step_outer = theta / d_outer

        if self.r_min == 0:
            for x in range(0, d_outer, 2):
                v += (polar_to_rect(self.origin, self.r_max,
                                    self.theta_min + x * theta_step_outer) * 2)
                v += polar_to_rect(self.origin, 0, 0) * 2
                v += (
                    polar_to_rect(self.origin, self.r_max, self.theta_min +
                                  (x + 1) * theta_step_outer) * 2)
            if not d_outer & 1:  # add a last point if d_outer is even
                v += (
                    polar_to_rect(self.origin, self.r_max, self.theta_min +
                                  d_outer * theta_step_outer) * 2)
        else:
            for x in range(d_outer + 1):
                v += (polar_to_rect(self.origin, self.r_min,
                                    self.theta_min + x * theta_step_outer) * 2)
                v += (polar_to_rect(self.origin, self.r_max,
                                    self.theta_min + x * theta_step_outer) * 2)

        return Mesh(vertices=v,
                    indices=range(int(len(v) / 4)),
                    mode='triangle_strip')
コード例 #31
0
    def make_editable(self, editable = True, player_won_color = None, size_hint = None):
        self.editable = editable
        scores_holder = self.ids.scores_holder
        scores_holder.clear_widgets()

        if player_won_color != None:
            with self.canvas:
                # green terrain
                Color(player_won_color.r, player_won_color.g, player_won_color.b)
                self.mesh = Mesh(vertices=[0,0,0,0 ,0,size_hint.y,0,0 ,size_hint.x,size_hint.y,0,0 , size_hint.x,0,0,0], indices=[0,1,2,3], mode='triangle_fan')

        scores = []

        Path("./scores/").mkdir(parents=True, exist_ok=True)
        if not os.path.isfile('./scores/scores.txt'):
            with open('./scores/scores.txt', 'a'):
                pass
        if os.path.isfile('./scores/scores.txt') and os.stat('./scores/scores.txt').st_size > 0:
            with open('./scores/scores.txt', 'r') as f:
                content = f.readlines()
                scores = [line.strip('\n') for line in content]

        scores = scores + ["-Not filled yet-"] * (5-len(scores))

        if(editable):
            scores_holder.add_widget(TextInput(hint_text='Write your name..', id='score_input'))
            scores = scores[:-1]
        
        for score in scores:
            scores_holder.add_widget(Label(text=score, font_size = 15))
コード例 #32
0
 def __init__(self):
     super(Sprite, self).__init__()
     with self:
         self.color = Color()
         self.mesh = Mesh(vertices=[0.0] * 16,
                          indices=range(4),
                          mode=MODE_TRIANGLE_FAN)
コード例 #33
0
 def get_graphics(self, gc, polygons, points_line, rgbFace, closed=False):
     '''Return an instruction group which contains the necessary graphics
        instructions to draw the respective graphics.
     '''
     instruction_group = InstructionGroup()
     if isinstance(gc.line['dash_list'], tuple):
         gc.line['dash_list'] = list(gc.line['dash_list'])
     if rgbFace is not None:
         if len(polygons.meshes) != 0:
             instruction_group.add(Color(*rgbFace))
             for vertices, indices in polygons.meshes:
                 instruction_group.add(
                     Mesh(vertices=vertices,
                          indices=indices,
                          mode=str("triangle_fan")))
     instruction_group.add(Color(*gc.get_rgb()))
     if _mpl_1_5 and closed:
         points_poly_line = points_line[:-2]
     else:
         points_poly_line = points_line
     if gc.line['width'] > 0:
         instruction_group.add(
             Line(points=points_poly_line,
                  width=int(gc.line['width'] / 2),
                  dash_length=gc.line['dash_length'],
                  dash_offset=gc.line['dash_offset'],
                  dash_joint=gc.line['joint_style'],
                  dash_list=gc.line['dash_list']))
     return instruction_group
コード例 #34
0
 def _set_ticks(self, *args):
     mesh = self._mesh
     s_max = self.max
     s_min = self.min
     if self.ticks_major and s_max > s_min:
         if not mesh:
             mesh = Mesh(mode='lines', group=str('TickMarker%d' % id(self)))
             self._mesh = mesh
             self.canvas.add(mesh)
         indices = mesh.indices
         vertices = mesh.vertices
         compute_ticks(indices, vertices, self.ticks_minor,
                       self.ticks_major, self.padding, self.max,
                       self.min, self.log, self.orientation == 'horizontal',
                       tuple(self.size), tuple(self.pos))
         mesh.vertices = vertices
         mesh.indices = indices
     else:
         if mesh:
             self.canvas.remove_group(str('TickMarker%d' % id(self)))
             self._mesh = None
コード例 #35
0
    def _set_ticks(self, *args):
        mesh = self._mesh
        s_max = self.max
        s_min = self.min
        if self.ticks_major and s_max > s_min:
            if not mesh:
                mesh = Mesh(mode='lines', group=str('TickMarker%d' % id(self)))
                self._mesh = mesh
                self.canvas.add(mesh)
            indices = mesh.indices
            vertices = mesh.vertices
            ticks_minor = self.ticks_minor
            ticks_major = self.ticks_major
            padding = self.padding
            log = self.log

            if log:
                # count the decades in min - max. This is in actual decades,
                # not logs.
                n_decades = floor(s_max - s_min)
                # for the fractional part of the last decade, we need to
                # convert the log value, x, to 10**x but need to handle
                # differently if the last incomplete decade has a decade
                # boundary in it
                if floor(s_min + n_decades) != floor(s_max):
                    n_decades += 1 - (10 ** (s_min + n_decades + 1) - 10 **
                                      s_max) / 10 ** floor(s_max + 1)
                else:
                    n_decades += ((10 ** s_max - 10 ** (s_min + n_decades)) /
                                  10 ** floor(s_max + 1))
                # this might be larger than what is needed, but we delete
                # excess later
                n_ticks = n_decades / float(ticks_major)
                n_ticks = int(floor(n_ticks * (ticks_minor if ticks_minor >=
                                               1. else 1.0))) + 2
                # in decade multiples, e.g. 0.1 of the decade, the distance
                # between ticks
                decade_dist = ticks_major / float(ticks_minor if
                                                  ticks_minor else 1.0)

                points = [0] * n_ticks
                points[0] = (0., True)  # first element is always a major tick
                k = 1  # position in points
                # because each decade is missing 0.1 of the decade, if a tick
                # falls in < min_pos skip it
                min_pos = 0.1 - 0.00001 * decade_dist
                s_min_low = floor(s_min)
                # first real tick location. value is in fractions of decades
                # from the start we have to use decimals here, otherwise
                # floating point inaccuracies results in bad values
                start_dec = ceil((10 ** Decimal(s_min - s_min_low - 1)) /
                                 Decimal(decade_dist)) * decade_dist
                count_min = (0 if not ticks_minor else
                             floor(start_dec / decade_dist) % ticks_minor)
                start_dec += s_min_low
                count = 0  # number of ticks we currently have passed start
                while True:
                    # this is the current position in decade that we are.
                    # e.g. -0.9 means that we're at 0.1 of the 10**ceil(-0.9)
                    # decade
                    pos_dec = start_dec + decade_dist * count
                    pos_dec_low = floor(pos_dec)
                    diff = pos_dec - pos_dec_low
                    zero = abs(diff) < 0.001 * decade_dist
                    if zero:
                        # the same value as pos_dec but in log scale
                        pos_log = pos_dec_low
                    else:
                        pos_log = log10((pos_dec - pos_dec_low
                                         ) * 10 ** ceil(pos_dec))
                    if pos_log > s_max:
                        break
                    count += 1
                    if zero or diff >= min_pos:
                        points[k] = (pos_log - s_min, ticks_minor
                                     and not count_min % ticks_minor)
                        k += 1
                    count_min += 1
                del points[k:]
                n_ticks = len(points)
            else:
                # distance between each tick
                tick_dist = ticks_major / float(ticks_minor if
                                                ticks_minor else 1.0)
                n_ticks = int(floor((s_max - s_min) / tick_dist) + 1)

            count = len(indices) // 2
            # adjust mesh size
            if count > n_ticks:
                del vertices[n_ticks * 8:]
                del indices[n_ticks * 2:]
            elif count < n_ticks:
                    vertices.extend([0] * (8 * (n_ticks - count)))
                    indices.extend(range(2 * count, 2 * n_ticks))

            if self.orientation == 'horizontal':
                center = self.center_y
                axis_dist = self.width
                start = self.x + padding
                above, below, dist1, dist2 = 1, 5, 0, 4
            else:
                center = self.center_x
                axis_dist = self.height
                start = self.y + padding
                above, below, dist1, dist2 = 0, 4, 1, 5
            # now, the physical distance between ticks
            tick_dist = (axis_dist - 2 * padding
                         ) / float(s_max - s_min) * (tick_dist if not log
                                                     else 1.0)
            # amounts that ticks extend above/below axis
            maj_plus = center + metrics.dp(12)
            maj_minus = center - metrics.dp(12)
            min_plus = center + metrics.dp(6)
            min_minus = center - metrics.dp(6)

            if log:
                for k in range(0, n_ticks):
                    m = k * 8
                    vertices[m + dist1] = start + points[k][0] * tick_dist
                    vertices[m + dist2] = vertices[m + dist1]
                    if not points[k][1]:
                        vertices[m + above] = min_plus
                        vertices[m + below] = min_minus
                    else:
                        vertices[m + above] = maj_plus
                        vertices[m + below] = maj_minus
            else:
                for k in range(0, n_ticks):
                    m = k * 8
                    vertices[m + dist1] = start + k * tick_dist
                    vertices[m + dist2] = vertices[m + dist1]
                    if ticks_minor and k % ticks_minor:
                        vertices[m + above] = min_plus
                        vertices[m + below] = min_minus
                    else:
                        vertices[m + above] = maj_plus
                        vertices[m + below] = maj_minus
            mesh.vertices = vertices
            mesh.indices = indices
        else:
            if mesh:
                self.canvas.remove_group(str('TickMarker%d' % id(self)))
                self._mesh = None