forked from patriciogonzalezvivo/glslTexture
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
227 lines (180 loc) · 7.46 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
bl_info = {
"name": "glslTexture",
"author": "Patricio Gonzalez Vivo",
"description": "Adds a texture generated from a GLSL frament shader",
"blender": (2, 80, 0),
"version": (0, 0, 1),
"location": "Operator Search",
"warning": "",
"doc_url": "",
"category": "Texture"
}
import bpy
import gpu
import bgl
from gpu_extras.batch import batch_for_shader
class TEXTURE_OT_glsl_texture(bpy.types.Operator):
"""Make a texture from a GLSL Shader"""
bl_idname = 'texture.glsl_texture'
bl_label = 'GlslTexture'
bl_options = { 'REGISTER', 'UNDO' }
width: bpy.props.IntProperty(
name = 'width',
description = 'Texture width',
default = 512,
min = 1
)
height: bpy.props.IntProperty(
name = 'height',
description = 'Texture height',
default = 512,
min = 1
)
source: bpy.props.StringProperty(
# subtype="FILE_PATH",
name = 'Source',
description = 'Text file name which contain the frament shader source code',
default = 'default.frag'
)
@classmethod
def poll(cls, context):
return True
def file_exist(self, filename):
try:
file = open( bpy.path.abspath(filename) ,'r')
file.close()
return True
except:
return False
def file_reload(self, filename):
text = bpy.data.texts[self.source]
# text.filepath = filename
# fp = bpy.path.abspath(text.filepath)
fp = bpy.path.abspath(filename)
text.clear()
with open(fp) as f:
text.write(f.read())
return True
_timer = None
def invoke(self, context, event):
self.vertex_shader = '''
in vec2 a_position;
in vec2 a_texcoord;
void main() {
gl_Position = vec4(a_position, 0.0, 1.0);
}
'''
self.default_shader = '''
uniform vec2 u_resolution;
void main() {
vec3 color = vec3(0.0);
vec2 st = gl_FragCoord.xy / u_resolution;
color.rg = st;
gl_FragColor = vec4(color, 1.0);
}
'''
self.current_shader = ''
self.fromFile = False
wm = context.window_manager
return wm.invoke_props_dialog(self)
def modal(self, context, event):
# if event.type in {'ESC'}:
# self.cancel(context)
# return {'CANCELLED'}
if event.type == 'TIMER':
if not self.source in bpy.data.texts:
print(f'File name {self.source} not found. Ready to create one')
if self.file_exist(self.source):
print("It's a file")
bpy.ops.text.open(filepath=self.source)
self.fromFile = True
else:
bpy.data.texts.new(self.source)
print("It's not a file, populate with the default shader")
bpy.data.texts[self.source].write(self.default_shader)
recompile = False
if not bpy.data.texts[self.source].is_in_memory and bpy.data.texts[self.source].is_modified:
print("Have been modify")
# bpy.ops.text.resolve_conflict(resolution='RELOAD')
# self.file_reload(self.source)
text = bpy.data.texts[self.source]
ctx = context.copy()
# ctx["edit_text"] = text
# bpy.ops.text.reload(ctx)
#Ensure context area is not None
ctx['area'] = ctx['screen'].areas[0]
oldAreaType = ctx['area'].type
ctx['area'].type = 'TEXT_EDITOR'
ctx['edit_text'] = text
bpy.ops.text.resolve_conflict(ctx, resolution='RELOAD')
#Restore context
ctx['area'].type = oldAreaType
if self.current_shader != bpy.data.texts[self.source].as_string():
recompile = True
if recompile:
print("Recompile... ")
fragment_shader = bpy.data.texts[self.source].as_string()
self.current_shader = fragment_shader
offscreen = gpu.types.GPUOffScreen(self.width, self.height)
with offscreen.bind():
bgl.glClear(bgl.GL_COLOR_BUFFER_BIT)
try:
shader = gpu.types.GPUShader(self.vertex_shader, fragment_shader)
except Exception as Err:
print(Err)
recompile = False
if recompile:
batch = batch_for_shader(
shader,
'TRI_FAN', {
'a_position': ((-1, -1), (1, -1), (1, 1), (-1, 1))
},
)
shader.bind()
# try:
# shader.uniform_float('u_time', bpy.context.scene.frame_float/bpy.context.scene.render.fps)
# except ValueError:
# print('Uniform: u_time not used')
try:
shader.uniform_float('u_resolution', (self.width, self.height))
except ValueError:
print('Uniform: u_resolution not used')
batch.draw(shader)
buffer = bgl.Buffer(bgl.GL_BYTE, self.width * self.height * 4)
bgl.glReadBuffer(bgl.GL_BACK)
bgl.glReadPixels(0, 0, self.width, self.height, bgl.GL_RGBA, bgl.GL_UNSIGNED_BYTE, buffer)
offscreen.free()
if recompile:
print("Success recompiling")
name = self.source.split(".")[0]
if not name in bpy.data.images:
bpy.data.images.new(name, self.width, self.height)
image = bpy.data.images[name]
image.scale(self.width, self.height)
image.pixels = [v / 255 for v in buffer]
return {'PASS_THROUGH'}
def execute(self, context):
wm = context.window_manager
self._timer = wm.event_timer_add(0.1, window=context.window)
wm.modal_handler_add(self)
return {'RUNNING_MODAL'}
def cancel(self, context):
print(f'GlslTexture {self.source} cancel refreshing')
wm = context.window_manager
wm.event_timer_remove(self._timer)
def register():
bpy.utils.register_class(TEXTURE_OT_glsl_texture)
def unregister():
bpy.utils.unregister_class(TEXTURE_OT_glsl_texture)