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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import bpy
import gradio as gr
import math
import os
import random
from diffusers.utils import load_image
from PIL import Image
import PIL.Image
##from io_scene_gltf2.blender.exp import gltf2_blender_export

os.putenv("XDG_RUNTIME_DIR", '.')
fin_rend = './rendered_scene.png'
fin_pth = './path_to_exp.blend'
fin_blend = './exp_scene.blend'
fin_obj = './exp_scene.obj'
fin_glb = './exp_scene.glb'
fin_gltf = './exp_scene.gltf'
fin_anim = './animation.mp4'
img = bpy.data.images.load('./STScI-01G8H1NK4W8CJYHF2DDFD1W0DQ.png')
earth_texture = bpy.data.images.load('./ear0xuu2.jpg')
mars_texture = bpy.data.images.load('mar0kuu2.jpg')
apol=[]

def add_planet(name, radius, mass, distance_from_sun):
    material = bpy.data.materials.new(name="Mymarsmat"+str(random.randint(1,36)))
    ##material = bpy.data.materials.new(name="MyMaterial")
    material.use_nodes = True

    ##for node in material.node_tree.nodes:
    ##    material.node_tree.nodes.remove(node)


    image_texture_node = material.node_tree.nodes.new('ShaderNodeTexImage')
    if name=="mars":
        image_texture_node.image = bpy.data.images.load("mar0kuu2.jpg")
    else:
        image_texture_node.image = bpy.data.images.load("ear0xuu2.jpg")

    # Link the image texture node to the principled shader
    bsdf_node = material.node_tree.nodes.get('Principled BSDF')
    material.node_tree.links.new(bsdf_node.inputs['Base Color'], image_texture_node.outputs['Color'])


    bpy.ops.mesh.primitive_uv_sphere_add(radius=radius, location=(distance_from_sun * random.uniform(-8, 8), random.uniform(-8, 8), random.uniform(-8, 3)))
    planet = bpy.context.active_object
    planet.name = name
    ##planet_material = bpy.data.materials.new(name=name + "_texture")
    planet.data.materials.append(material)
    planet["mass"] = mass
    return planet

def visualize_planets():
    bpy.ops.object.select_all(action='DESELECT')
    for obj in bpy.context.scene.objects:
        if obj.type == 'MESH' and "mass" in obj:
            obj.select_set(True)
    bpy.ops.view3d.snap_cursor_to_selected()
    bpy.ops.object.origin_set(type='ORIGIN_CURSOR')
    bpy.context.scene.cursor.location = (0, 0, 0)

##visualize_planets()

def create_planet_flyby_animation(planet, radius, duration):
    bpy.context.view_layer.objects.active = planet
    planet.select_set(True)
    planet.animation_data_create()
    planet.animation_data.action = bpy.data.actions.new(name="OrbitAction")
    start_frame = 1
    end_frame = int(duration * 10)
    for frame in range(start_frame, end_frame + 1):
        angle = (frame / end_frame) * 2 * math.pi
        x = radius * math.cos(angle)
        y = radius * math.sin(angle)
        z = planet.location.z  # Maintain the planet's z-coordinate
        planet.location = (x, y, z)
        planet.keyframe_insert(data_path="location", index=-1, frame=frame)

##create_planet_flyby_animation(planet, radius, 2)

def add_animated_space_rocks():
    bpy.context.scene.render.fps = 10
    duration = 2
    for i in range(30):
        bpy.ops.mesh.primitive_uv_sphere_add(radius=random.uniform(0.01, 0.1), location=(random.uniform(-10, 10), random.uniform(-10, 10), random.uniform(-4, 9)))
        space_rock = bpy.context.active_object
        space_rock.keyframe_insert(data_path="location", frame=1)
        space_rock.location = (random.uniform(-10, 10), random.uniform(-10, 10), random.uniform(-10, 10))
        space_rock.keyframe_insert(data_path="location", frame=duration * bpy.context.scene.render.fps)

def create_particle_effects_animation():
    bpy.context.scene.render.fps = 10
    duration = 2

    bpy.ops.mesh.primitive_uv_sphere_add(radius=random.uniform(0.05, 0.10), location=(random.uniform(-1, 1), random.uniform(-1, 1), 1))
    emitter = bpy.context.active_object
    emitter.name = "ParticleEmitter"
    
    particle_system = emitter.modifiers.new(name="ParticleSettings", type='PARTICLE_SYSTEM')
    particle_system.particle_system.settings.count = 30
    particle_system.particle_system.settings.frame_start = 1
    particle_system.particle_system.settings.frame_end = duration * bpy.context.scene.render.fps

    # Set the particle system to be rendered as an object
    particle_system.particle_system.settings.render_type = 'OBJECT'
    particle_system.particle_system.settings.instance_object = bpy.data.objects["ParticleOne"]

    # Animate the emitter's location, rotation, and scale
    emitter.keyframe_insert(data_path="location", index=-1, frame=1)
    emitter.location = (random.uniform(-10, 10), random.uniform(-10, 10), random.uniform(-10, 10))  # Set the new location for the end of the animation
    emitter.keyframe_insert(data_path="location", index=-1, frame=duration * bpy.context.scene.render.fps)

def create_meteor_with_particle_system():
    # Create a mesh object to serve as the meteor
    bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=4, radius=0.25, location=(random.uniform(-10, 10), random.uniform(-10, 10), random.uniform(-10, 10)))
    meteor = bpy.context.active_object
    meteor.name = "Meteor"
    meteor_material = bpy.data.materials.new(name="MeteorMaterial")
    meteor.data.materials.append(meteor_material)
    meteor.active_material.use_nodes = True
    nodes = meteor.active_material.node_tree.nodes
    emission_node = nodes.new(type='ShaderNodeEmission')
    emission_node.inputs[0].default_value = (0.0, 0.0, 1.0, 1)  # Blue color
    output_node = nodes.get("Material Output")
    material_link = meteor.active_material.node_tree.links.new
    material_link(emission_node.outputs[0], output_node.inputs[0])

    bpy.ops.mesh.primitive_uv_sphere_add(radius=random.uniform(0.01, 0.04), location=(random.uniform(-10, 10), random.uniform(-10, 10), random.uniform(-10, 10)))
    partone = bpy.context.active_object
    partone.name = "ParticleOne"
    
    particle_settings = meteor.modifiers.new(name="EnergySpheres", type='PARTICLE_SYSTEM')
    particle_settings.particle_system.settings.count = 100
    particle_settings.particle_system.settings.lifetime = random.uniform(10, 20)
    particle_settings.particle_system.settings.frame_start = 1
    particle_settings.particle_system.settings.frame_end = 20
    particle_settings.particle_system.settings.use_emit_random = True
    particle_settings.particle_system.settings.render_type = 'OBJECT'
    particle_settings.particle_system.settings.instance_object = bpy.data.objects["ParticleOne"]

    meteor.keyframe_insert(data_path="location", index=-1, frame=1)
    meteor.location = (random.uniform(-10, 10), random.uniform(-10, 10), random.uniform(-10, 10))
    meteor.keyframe_insert(data_path="location", index=-1, frame=20)

def create_scene():
    scene = bpy.context.scene
    render = scene.render
    render.resolution_x = 1920
    render.resolution_y = 1080
    render.engine = 'BLENDER_EEVEE'

    ##world = bpy.context.scene.world
    ##bg_node = world.node_tree.nodes['Background']
    ##bg_node.image = img

    ##env_data = bpy.data.worlds['World'].node_tree.nodes['Background'].input
    ##env_data.default_value = img

    ##tex_environment = bpy.data.worlds['World'].node_tree.nodes.new('ShaderNodeTexEnvironment')
    ##tex_environment.image = img
    ##world = bpy.context.scene.world
    ##bg_node = world.node_tree.nodes['Background']
    ##world.node_tree.links.new(tex_environment.outputs[0], bg_node.inputs[0])

    ##img = bpy.data.images.load(image_path)
    world = bpy.context.scene.world
    if not world.use_nodes:
        world.use_nodes = True
    tree = world.node_tree
    bg_node = tree.nodes.new(type='ShaderNodeTexEnvironment')
    bg_node.image = img
    tree.links.new(bg_node.outputs[0], tree.nodes['Background'].inputs[0])

    ##world.light_settings.use_ambient_occlusion = True
    ##world.light_settings.ao_factor = 0.5
    ##world.light_settings.ao_factor = 0.5
    ##world.light_settings.use_environment_light = True
    ##world.light_settings.environment_energy = 0.5

    bpy.data.objects['Cube'].select_set(True)
    bpy.ops.object.delete()
    bpy.data.objects['Camera'].select_set(True)
    bpy.ops.object.delete()
    
    light_data = bpy.data.lights.new(name="NewLight", type='SUN')
    light_data.energy = 30
    light_object = bpy.data.objects.new(name="NewLight", object_data=light_data)
    scene.collection.objects.link(light_object)
    light_object.location = (3.0, 5.0, 11.0)

    camera_data = bpy.data.cameras.new(name='Camera')
    camera = bpy.data.objects.new('Camera', camera_data)
    bpy.context.collection.objects.link(camera)
    bpy.context.scene.camera = camera
    camera.location = (0, 0, 10)
    camera.rotation_euler = (0, 0, 0)
    ##planet1 = add_planet("earth", 2.5, 1, 0)
    ##planet2 = add_planet("mars", 1.75, 0.5, 1.5)
    add_planet("earth", 2.5, 1, 0)
    add_planet("mars", 1.75, 0.5, 1.5)
    ##bpy.context.active_object=None



    add_animated_space_rocks()
    create_meteor_with_particle_system()
    create_particle_effects_animation()
    ##create_planet_flyby_animation(planet1, 4, 2)
create_scene()

def export_blend():
    ##bpy.ops.wm.save_mainfile(filepath='./path_to_exp.blend')
    bpy.ops.wm.save_as_mainfile(filepath='./exp_scene.blend')
    ##bpy.ops.export_scene.obj(filepath='./exp_scene.obj', export_format='OBJ', export_materials='EXPORT')
    ##bpy.ops.export_scene.gltf(filepath='./exp_scene.glb', export_format='GLB', check_existing=False, export_image_format='AUTO', export_materials='EXPORT', export_cameras=True, export_lights=True)
    ##bpy.ops.export_scene.gltf(filepath='./exp_scene.gltf', export_selected=False)
    ##cntxt = bpy.context
    ##bpy.ops.export_scene.gltf(filepath='./exp_scene.glb', export_format='GLB')
    ##bpy.ops.export_scene.gltf(cntxt, RenderSettings)
    last_created_time = 0
    last_created_file = None
    apol=[]

    for root, dirs, files in os.walk('.'):
        for file in files:
            file_path = os.path.join(root, file)
            created_time = os.path.getctime(file_path)
            if created_time > last_created_time:
                last_created_time = created_time
                last_created_file = file_path

    ##imoge = load_image(last_created_file).convert('RGB').resize((512, 512))
    apol.append(last_created_file)
    ##return last_created_file
    ##return fin_rend
    ##return apol
    return last_created_file

def render_scene(blk,sny):
    bpy.context.scene.render.filepath = './rendered_scene.png'
    bpy.ops.render.render(animation=False, write_still=True)
    ##bpy.ops.render.opengl(animation=False, render_keyed_only=False, sequencer=False, write_still=True, view_context=False)
    ##imoge = load_image(fin_rend)
    ##imoge.save('./rendered_scene.png', 'PNG')
    ##imoge = PIL.Image(fin_rend)
    ##imoge = load_image().convert('RGB').resize((512, 512))
    last_created_time = 0
    last_created_file = None
    apol=[]

    for root, dirs, files in os.walk('.'):
        for file in files:
            file_path = os.path.join(root, file)
            created_time = os.path.getctime(file_path)
            if created_time > last_created_time:
                last_created_time = created_time
                last_created_file = file_path

    imoge = load_image(last_created_file).convert('RGB').resize((512, 512))
    apol.append(imoge)
    ##blk=gr.HTML(value="""<html><head><title>Three.js Blender Scene Viewer</title><style>body { margin: 0; } canvas { display: block; } </style></head><body><script src='https://threejs.org/build/three.js'></script><script src='https://threejs.org/examples/jsm/loaders/GLTFLoader.js'></script><script> var scene, camera, renderer; function init() { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5; renderer = new THREE.WebGLRenderer({antialias: true}); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); var loader = new THREE.GLTFLoader(); loader.load('"""+sny+"""', function(gltf) { scene.add(gltf.scene); }, undefined, function(error) { console.error(error); }); }; function animate(){ requestAnimationFrame(animate); renderer.render(scene, camera); }; init(); animate();</script></body></html>""")
    pckg = f"/file={sny}"
    moog = gr.Model3D(value=sny)
    return apol, f"""<iframe src="file=frame.html" width="100%" height="200px" data-glb="exp_scene.glb"></iframe>""", sny, moog
    
    ##blk=gr.HTML(value=html)
    ##return last_created_file
    ##return fin_rend
    ##return apol,blk,sny

def export_obj():
    ##bpy.ops.wm.save_mainfile(filepath='./path_to_exp.blend')
    ##bpy.ops.wm.save_as_mainfile(filepath='./exp_scene.blend')
    ##bpy.ops.export_scene.obj(filepath='./exp_scene.obj', export_format='OBJ', export_materials='EXPORT')
    bpy.ops.export_scene.gltf(filepath="./exp_scene.obj", export_format='OBJ', export_selected=False, export_apply=False, export_texcoords='TANGENT', export_normals='FACE', export_materials='EXPORT', export_colors='EXPORT', export_cameras='EXPORT', export_lights='EXPORT', export_displacement='NONE', export_animations=True, export_frame_range=True, export_frame_step=1, export_force_sampling=False, export_current_frame=False, export_extras=True)
    ##bpy.ops.export_scene.gltf(filepath='./exp_scene.glb', export_format='GLB', check_existing=False, export_image_format='AUTO', export_materials='EXPORT', export_cameras=True, export_lights=True)
    ##bpy.ops.export_scene.gltf(filepath='./exp_scene.gltf', export_selected=False)
    ##cntxt = bpy.context
    ##bpy.ops.export_scene.gltf(filepath='./exp_scene.glb', export_format='GLB')
    ##bpy.ops.export_scene.gltf(cntxt, RenderSettings)
    last_created_time = 0
    last_created_file = None
    apol=[]

    for root, dirs, files in os.walk('.'):
        for file in files:
            file_path = os.path.join(root, file)
            created_time = os.path.getctime(file_path)
            if created_time > last_created_time:
                last_created_time = created_time
                last_created_file = file_path

    ##imoge = load_image(last_created_file).convert('RGB').resize((512, 512))
    apol.append(last_created_file)
    ##return last_created_file
    ##return fin_rend
    return apol

def export_glb():
    ##bpy.ops.wm.save_mainfile(filepath='./path_to_exp.blend')
    ##bpy.ops.wm.save_as_mainfile(filepath='./exp_scene.blend')
    ##bpy.ops.export_scene.obj(filepath='./exp_scene.obj', export_format='OBJ', export_materials='EXPORT')
    ##for ob in bpy.context.scene.objects:
    ##    ob.select_set(False)
    ##bpy.ops.export_scene.gltf(filepath='./exp_scene.glb', export_format='GLB', export_image_format='NONE', export_materials='NONE', export_cameras=True, export_lights=True)
    bpy.ops.export_scene.gltf(filepath='./exp_scene.glb', export_format='GLB')##, export_image_format='AUTO', export_materials='EXPORT', export_cameras=True, export_lights=True)
    ##export_settings = {
    ##'filepath': './exp_scene.glb',
    ##'export_format': 'GLB',
    ##'gltf_current_frame': 1,
    ##}

    ##gltf2_blender_export.save(bpy.context, export_settings)
    ##bpy.ops.export_scene.gltf(filepath="./exp_scene.glb", export_format='GLB', export_selected=False, export_apply=False, export_texcoords=True, export_normals=True, export_materials=True, export_colors=True, export_cameras=True, export_lights=True, export_displacement=False, export_animations=True, export_frame_range=True, export_frame_step=1, export_force_sampling=False, export_current_frame=False, export_extras=True)
    ##bpy.ops.export_scene.gltf(filepath='./exp_scene.gltf', export_selected=False)
    ##cntxt = bpy.context
    ##bpy.ops.export_scene.gltf(filepath='./exp_scene.glb', export_format='GLB')
    ##bpy.ops.export_scene.gltf(cntxt, RenderSettings)
    last_created_time = 0
    last_created_file = None
    apol=[]

    for root, dirs, files in os.walk('.'):
        for file in files:
            file_path = os.path.join(root, file)
            created_time = os.path.getctime(file_path)
            if created_time > last_created_time:
                last_created_time = created_time
                last_created_file = file_path

    ##imoge = load_image(last_created_file).convert('RGB').resize((512, 512))
    apol.append(last_created_file)
    ##return last_created_file
    ##return fin_rend
    ##return apol
    return last_created_file

def export_gltf():
    ##bpy.ops.wm.save_mainfile(filepath='./path_to_exp.blend')
    ##bpy.ops.wm.save_as_mainfile(filepath='./exp_scene.blend')
    ##bpy.ops.export_scene.obj(filepath='./exp_scene.obj', export_format='OBJ', export_materials='EXPORT')
    ##bpy.ops.export_scene.gltf(filepath='./exp_scene.glb', export_format='GLB', check_existing=False, export_image_format='AUTO', export_materials='EXPORT', export_cameras=True, export_lights=True)
    ##bpy.ops.export_scene.gltf(filepath='./exp_scene.gltf',export_format='GLTF_SEPARATE')
    bpy.ops.export_scene.gltf(filepath='./exp_scene.gltf',export_format='GLB')
    ##cntxt = bpy.context
    ##bpy.ops.export_scene.gltf(filepath='./exp_scene.glb', export_format='GLB')
    ##bpy.ops.export_scene.gltf(cntxt, RenderSettings)
    last_created_time = 0
    last_created_file = None
    apol=[]

    for root, dirs, files in os.walk('.'):
        for file in files:
            file_path = os.path.join(root, file)
            created_time = os.path.getctime(file_path)
            if created_time > last_created_time:
                last_created_time = created_time
                last_created_file = file_path

    ##imoge = load_image(last_created_file).convert('RGB').resize((512, 512))
    apol.append(last_created_file)
    ##return last_created_file
    ##return fin_rend
    ##return apol
    return last_created_file

def render_anim():
    bpy.context.scene.render.image_settings.file_format = 'FFMPEG'
    bpy.context.scene.render.ffmpeg.format = 'MPEG4'
    bpy.context.scene.render.ffmpeg.codec = 'H264'
    bpy.context.scene.render.ffmpeg.constant_rate_factor = 'HIGH'
    bpy.context.scene.frame_start = 1
    bpy.context.scene.frame_end = 20
    bpy.context.scene.render.filepath = './animation.mp4'
    bpy.ops.render.render(animation=True)
    
    last_created_time = 0
    last_created_file = None
    apol=[]

    for root, dirs, files in os.walk('.'):
        for file in files:
            file_path = os.path.join(root, file)
            created_time = os.path.getctime(file_path)
            if created_time > last_created_time:
                last_created_time = created_time
                last_created_file = file_path

    ##imoge = load_image(last_created_file).convert('RGB').resize((512, 512))
    apol.append(last_created_file)
    ##return last_created_file
    ##return fin_rend
    return apol[0]
    
    ##return fin_anim

##export_glb()
##export_gltf()
##export_blend()

with gr.Blocks() as iface:
    with gr.Column():
        # HTML block to view the exported scene using Three.js
        
        moog = gr.Model3D()
        ##zery = gr.Button("create Scene")
        ony = gr.Button("render Image")
        twy = gr.Button("render Animation")
        rani = gr.Video()
        rdr = gr.Gallery(columns=1)
        sny = gr.File(value=export_glb(),interactive=False)
        ##sey = gr.File(value=export_gltf(),interactive=False)
        siy = gr.File(value=export_blend(),interactive=False)
        blk=gr.HTML(value="")

    ony.click(render_scene, [blk,sny], [rdr,blk,sny,moog])
    twy.click(render_anim, None, rani)

iface.launch()