Skip to content

Instantly share code, notes, and snippets.

@Poikilos
Forked from tito/cpuradialgradient.py
Last active May 16, 2023 19:02
Show Gist options
  • Save Poikilos/aacf738d6bf44c187e9b8c52787942d7 to your computer and use it in GitHub Desktop.
Save Poikilos/aacf738d6bf44c187e9b8c52787942d7 to your computer and use it in GitHub Desktop.
radial gradient texture for kivy - Poikilos' Python 3 version of tito's fork
from kivy.graphics.texture import Texture
from kivy.graphics import Rectangle, Color
from kivy.uix.widget import Widget
from kivy.graphics.opengl import glFinish
from kivy.app import App
from time import time
class RadialGradient(App):
def build(self):
root = Widget()
glFinish()
start = time()
tex = self.create_tex()
glFinish()
end = time()
print('CPU RADIAL BUILD TIME: %.4fms' % ((end - start) * 100))
with root.canvas:
Color(1, 1, 1)
Rectangle(texture=tex, size=(500, 500))
return root
def create_tex(self, *args):
center_color = 255, 255, 0
border_color = 100, 0, 0
size = (64, 64)
tex = Texture.create(size=size)
sx_2 = size[0] / 2
sy_2 = size[1] / 2
buf = bytearray()
for x in range(-int(sx_2), int(sx_2)):
for y in range(-int(sy_2), int(sy_2)):
a = x / (1.0 * sx_2)
b = y / (1.0 * sy_2)
d = (a ** 2 + b ** 2) ** .5
for c in (0, 1, 2):
buf.append(max(0,
min(255,
int(center_color[c] * (1 - d)) +
int(border_color[c] * d))))
tex.blit_buffer(buf, colorfmt='rgb', bufferfmt='ubyte')
return tex
RadialGradient().run()
from kivy.graphics import Fbo, Rectangle, Color
from kivy.graphics.opengl import glFinish
from kivy.uix.widget import Widget
from kivy.app import App
from time import time
def radial_gradient(border_color=(1, 1, 0), center_color=(1, 0, 0),
size=(64, 64)):
fbo = Fbo(size=size)
fbo.shader.fs = '''
$HEADER$
uniform vec3 border_color;
uniform vec3 center_color;
void main (void) {
float d = clamp(distance(tex_coord0, vec2(0.5, 0.5)), 0., 1.);
gl_FragColor = vec4(mix(center_color, border_color, d), 1);
}
'''
# use the shader on the entire surface
fbo['border_color'] = list(map(float, border_color))
fbo['center_color'] = list(map(float, center_color))
with fbo:
Color(1, 1, 1)
Rectangle(size=size)
fbo.draw()
return fbo.texture
class GpuRadialGradient(App):
def build(self):
root = Widget()
glFinish()
start = time()
tex = radial_gradient()
glFinish()
end = time()
print('GPU RADIAL BUILD TIME: %.4fms' % ((end - start) * 100))
with root.canvas:
Color(1, 1, 1)
Rectangle(texture=tex, size=(500, 500))
return root
GpuRadialGradient().run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment