Importnodes a script for Blender

Post Reply
JALdMIC
Member
Posts: 116
Joined: Tue Oct 08, 2019 18:49
In-game: None

Importnodes a script for Blender

by JALdMIC » Post

Importante/Important
Yo hablo espanol,para los que no,he "traducido" el contenido al ingles por esto veran con lo escrito
en espanaol tambien lo traducido al ingles.PSDT :Mi ingles es bastante malo.
/I speak spanish,for those who don't, i "translate" the content to english for this you will see whit the writte in spanish,
the translate to english.PSDT:My english is very bad.

Esto no es un mod, si no un script para blender que le permite:
/This is not a mod,is a addon for blender who:
Puede importar nodos del minetest a blender
Can import nodes of minetest to blender.

En las versiones anteriores de el scripts use mi apellido : Jova
In the old versions of the script i used my family name : Jova

!!! Solo funcionan en la version 2.79 de Blender o compatible !!!
!!! /Only works in Blender version 2.79 or compatible !!!
!!!Antes de cualquier cosa deben saber que estos scipts no funcionan en la rama 2.8 de blender !!!
!!!/Before anything you need to know what this scripts don't work in Blender 2.8 branche !!!
!!!Solo probados en linux!!!
!!!/Only tested in Linux!!!
!!!Estos scripts solo han sido probados en Linux(Ubuntu 18.04 con KDE Plasma 5.12.9)y puede que no funcionen en Windows !!!
!!!/This scripts only as ben tested in Linux(Ubuntu 18.04 whith KDE Plasma 5.12.9) and is possible what they don't work in Windows !!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Copyright (C) 2020 theScaredThief
Este scripts esta licenciados bajo los terminos de:
Atribution-NonCommercial-Share Alike 4.0 International (CC BY-NC-SA 4.0)

This scrips is licensed under the terms of:
Atribution-NonCommercial-Share Alike 4.0 International (CC BY-NC-SA 4.0)

Atribution-NonCommercial-Share Alike 4.0 International
(CC BY-NC-SA 4.0)

This is a human-readable summary of(and nor a
substitute for) the license Disclaimer.

You are free to:

Share - copy and redistribute
the material in any medium or format.

Adapt - remix,transform,
and build upon the material.

The licensor cannot revoke these freedoms
as long as you follow the license terms.

Under the following terms:

Attribution - You must give appropiate credit,provide a link to the license,
and indicate if changes were made.You may do so in any reasonable manner,
but not in any way that suggest the licensor endorses you or your use.

Non Commercial - You may not use this material for commercial purpose.

Share Alike - If you remix, transform, or build upon the material,you
must distribute your contributions under the same license as the original.

No additional restrictions - You may not apply legal terms or technological
measures that legally restrict others from doing anything the license permits.

Notice:

You do not have to comply with the license for elements of the material in the
public domain or where your use is permited by an applicable exception or limitation.

No warranties are given.The license may not give you all of the permissions necessary
for your intended use.For example, other rights such as publicity,privacy or moral rights
my limit how you use the material.


Instrucciones del script y una breve descripcion:/Intructions of the script and a small drescription.
Importnodes0.8.py,Se beneficia de:Ordernodes0.4,Nodesmaterials0.4,Createnodes0.4/It benefit from Ordernodes0.4,Nodesmaterials0.4,Createnodes0.4.
Annade un panel con un boton que sirve para importar nodos los archivos.lua.
/Add a pannel whit a button who can import the nodes from a lua file.
Boton:/Button
Nodes:Muestra un menu en el que se puede seleccionar un archivo .lua (o una carpeta si quieres revisar varios a la vez)
del cual se importaran nodos de haberlos.
/Show a menu in what you can select a lua file(or a folder if you can revise various at the same time)
from what import the nodes(if have)
Menu:
Solo explicare lo relacionado con el script:/
I only explain the the specific from the script.
En la parte inferior izquierda se pueden encontrar unos cuadrados de seleccion que sirven para definir cuales seran los
tipos de nodos a importar y si quiere organizar los nodos.
/In the low lef you can find a selection squares who serves for define
who are the node types to import and if you can organize the nodes.
Cuadrados de Seleccion:/Selection squares.
Normal:De estar marcado se importaran los nodos de tipo "normal"
/If this is mark the "normal" nodes are imported.
Plant:De estar marcado se importaran los nodos de tipo "plantlike"
/If this is mark the "plantlike" nodes are imported.
Glass:De estar marcado se importaran los nodos de tipo "glasslike"
/If this is mark the "glasslike" nodes are imported.
Sign:De estar marcado se importaran los nodos de tipo "signlike"
/If this is mark the "signlike" nodes are imported.
Allfaces:De estar marcado se importaran los nodos de tipo "allfaces"
/If this is mark the "allfaces" nodes are imported.
Order the nodes:De estar marcado se organizaran los nodos de la escena una vez que la importacion se halla terminado.
/If this is mark the nodes in the scene will be organised when the import is finished.
Create_group_instances:De estar marcado se crearan instancias grupales de los nodos de la escena una vez que la importacion se halla terminado.
/If this is mark will be create group instances of the nodes in the scene when the import is finished.
Instrucciones:(Ten en cuenta que con archivo me refiero a los de extension .lua
/Instrucctions:(You need to have in count who when i talk of file i refer to .lua extension)
1-Si lo que quieres es revisar un solo archivo,simplemente busca el archivo que quieres revisar en el menu,seleccionalo y luego
dale dobleclick o dale al boton que dice:Minetest:Import Nodes
/If what you whant is revise only a file,simply search the file what you whan revise in the menu,select and after
make doubleclick or click in the button who says:Minetes:Import Nodes
2-Para examinar varios archivos a la vez en busca de nodos,ve a la carpeta que quieres revisar y una vez que te hallas asegurado
de que el campo de nombre esta vacio dale al boton que dice:"Minetest:Import Nodes".
/For exam various files at the same time in search of nodes,go to the folder what you whan revise and when you are sure
of the name field is empty click the button who says:"Minetest:Import Nodes".

Changelog:
0.1
.Puede importar nodos/Import nodes
.Puede representar estos tipos de nodos:plantlike ,node./Only this types of nodes:plantlike ,node.
0.2
.Al importar los nodos,crea un "grupo para cada nodo"./When import the nodes,creates a group for each nodes.
0.2.1(Grandes correciones)/(Big corrections)
.No me habia dado cuenta que sin importar que archivos seleccionaras,siempre importaba los nodos del mismo archivo.
.Esto ya esta arreglado.(No se como traducir correctamente esto/I don't know how to correctly translate this)
.Se arreglo un error,que sucedia si no se usaba la opcion separar por tipo./Fix a error whith the function separate by type.
.Se arreglo un error a la hora de crear un "grupo para cada nodo"(el de la posicion)./Fix a error when creating a group for the nodes(the position)
.Se arreglo un error a la hora de crear las texturas./Fix a error when creating the textures
0.3
.Ahora tambien puede representar los siguientes tipos de modos:plantlike_rooted,glasslike_framed_optional,glasslike(en realidad ya lo representaba).
Now can represent this node types to:plantlike_rooted,glasslike_framed_optional,glasslike
0.3.1
.Arreglados algunos bugs./Fix some litle bugs.
.Pequennas mejoras./Less improvements
0.4
.Ahora puede representar materiales transparentes./Now represent transparents materials,
0.5Grandes cambios en el codigo,/Big changes in the code.
He decidido remover las funciones que le permitian al script generar los nodos y darles texturas/I decide remove the functions que generates the nodes an give then textures
y en cambio usar las funciones de otros scripts para esto("createnodes","nodesmaterials")/and in change now uses the functions of others scripts for this("createnodes","nodesmaterials")
.Removidas las funciones que ordenaban los nodos y les creaban un grupo/Removed the functions who creates the nodes and make the groups.
.Nota:El codigo aun existe en el script/The code still exist in the script.
0.6
Arreglando errores/Fixing errors.
0.7
Limpiando el codigo/Cleanin the code.
Regresa una opcion para ordenar los nodos y crear grupos, pero depende del script "ordernodes"/Returns a option for order the nodes and create the groups,but depends of the script "ordernodes".
Ahora tambien crea el tipo the nodos :allfaces_optional/Now can create the node type:allfaces_optional.
Arreglados algunos bugs/Fix some bugs.
Compatibilidad con las nuevas opciones para el BGE de "nodesmaterials","createnodes"
0.8
Puede importar puertas(incluyendo trampillas y puertas de cerca)/Can import doors(include trapdoors and fencegates)
Pero depende de el script "createnodes"?But depends of the script "createnodes".
Annadidas opciones para seleccionar que tipos nodos importar./Add options for select the node types to import.
Muy importante,ahora el modulo "importnodes" no necesita los otros modulos para funcionar,
(pero para varias funciones internas si)
/Very important,now the module importnodes don't need the other nodes for function,
(but for many inner functions yes)

Codigo:

Code: Select all

"""
This code is available  under the therms of the CC-BY-NC-SA 4.0 Licence
Copyright (C) 2020 theScaredThief

Atribution-NonCommercial-Share Alike 4.0 International
(CC BY-NC-SA 4.0)

This is a human-readable summary of(and nor a 
substitute for) the license Disclaimer.

You are free to:

Share - copy and redistribute 
the material in any medium or format.

Adapt - remix,transform, 
and build upon the material.

The licensor cannot revoke these freedoms
as long as you follow the license terms.

Under the following terms:

Attribution - You must give appropiate credit,provide a link to the license,
and indicate if changes were made.You may do so in any reasonable manner,
but not in any way that suggest the licensor endorses you or your use.

Non Commercial - You may not use this material for commercial purpose.

Share Alike - If you remix, transform, or build upon the material,you
must distribute your contributions under the same license as the original.

No additional restrictions - You may not apply legal terms or technological
measures that legally restrict others from doing anything the license permits.

Notice:

You do not have to comply with the license for elements of the material in the
public domain or where your use is permited by an applicable exception or limitation.

No warranties are given.The license may not give you all of the permissions necessary 
for your intended use.For example, other rights such as publicity,privacy or moral rights 
my limit how you use the material.

"""
#Este script puede importar los nodos del minetest desde un archivo "lua".
#This script can import the minetest nodes from a "lua" file.
import os
import bpy
import time
import glob   

bl_info = {
    "name": "Import Nodes",
    "author": "theScaredThief",
    "version": (0, 8),
    "location": "View3D > Properties > Minetest",
    "description": "A buton to 'Minetest Panel' who inmports nodes of Minetest from a .lua file ",
    "category": "Minetest"}


def confiratrr(obj):
    try:
        return obj.__dir__()
    except:
        return False

def debugprint(text = "Text",value = True):
    if value == True:
        print(text)
        
gvalue = True
engine = bpy.context.scene.render.engine
startime = time.clock()
#Function who import the nodes from a file/Funcion que importa los nodos de un archivo.
def importnoddesexec(path,impdefault = True,impplant = True,impglass = True,impsign = True,impallfaces = True):
    debugprint("Examinando el archivo/Exam the file: "+str(path))
    nodestotalfind = 0#Total of registreds nodes/Total de nodos registrados
    e  = 0
    inicp = False
    tileini = False
    texturelist = []
    ndrawtype = None
    nodo = ""#Nombre del nodo encontrado/Name of the node
    plantheig = None
    register = "none"
    acepteds = ("minetest.register_node(","doors.register(","doors.register_trapdoor(","doors.register_fencegate(")
    o = open(path,"r")#First they open the file to exam/Primero abre el archivo a examinar. 
    lineslist = []
    for lines in o.readlines():#Search in the lines for works usefuls for the program/Busca en la line palabras utiles para el programa.
        if inicp == False:
            for reg in acepteds:
                if lines.find(reg) == 0: 
                    register = reg
                    if reg != acepteds[0]:
                        ndrawtype = "other"
                    texturelist = []
                    inicp= True
                    e = e+1
                    try:
                        nodo = lines.split('"')[1]
                    except:
                        nodo = lines.split('(')[1]
                        nodo = nodo.replace(",","")
                        nodo = nodo.replace("{","")
        if inicp== True:
            lineslist.append(lines)
            if lines.find("tiles = {") > 0 or lines.find("tiles={") > 0 or lines.find("tiles= {") > 0 or lines.find("tiles= {") > 0:
                tileini = True
            if lines.find("drawtype ") > 0:
                ndrawtype = lines.split("=")[1]
                ndrawtype = ndrawtype.split(",")[0]
            if lines.find("local height ") > 0:
                plantheig = [n for n in lines if n.isnumeric()]
            if tileini == True:
                if lines.find(".png") >0:
                    if lines.split('"').__len__() >= 3:
                        for a in[i for i in lines.split('"') if i.endswith('png')]:
                            texturelist.append(a)
                if lines.find("},")>0:
                    tileini = False   
        #################################################         
        if lines.find("})") == 0 and inicp== True:
            inicp= False
            #See if the node to import exist in the scene/Ve si el nodo ha importar existe en la escena.
            if bpy.data.objects.find(nodo) == -1:
                #Function who changes the image|s who have a material in the node/Funcion que cambia la imagen|s que tiene un material del nodo.
                def changematerialimage(slotlist=[None],imagelist=[None]):
                    if "createsimplematerial" in confiratrr(bpy.ops.minetest):
                        index = 0
                        for slot in slotlist:
                            engine = bpy.context.scene.render.engine
                            bpy.context.object.active_material_index = slot
                            if engine == "CYCLES":
                                if imagelist[index].find("^")>0:
                                    bpy.ops.minetest.createmixmaterial()
                                    bpy.context.object.active_material.node_tree.nodes['Image Texture'].interpolation = "Closest"
                                    bpy.context.object.active_material.node_tree.nodes['Image Texture'].image = bpy.data.images[imagelist[index].split("^")[0]]
                                    bpy.context.object.active_material.node_tree.nodes['Image Texture.001'].interpolation = "Closest"
                                    bpy.context.object.active_material.node_tree.nodes['Image Texture.001'].image = bpy.data.images[imagelist[index].split("^")[1]]
                                else:
                                    bpy.ops.minetest.createsimplematerial()
                                    bpy.context.object.active_material.node_tree.nodes['Image Texture'].interpolation = "Closest"
                                    bpy.context.object.active_material.node_tree.nodes['Image Texture'].image = bpy.data.images[imagelist[index]]
                            elif engine == "BLENDER_GAME":
                                if imagelist[index].find("^")>0:
                                    bpy.ops.minetest.creategamematerial()
                                    texture1 = bpy.context.object.active_material.texture_slots[0]
                                    texture2 = bpy.context.object.active_material.texture_slots[1]
                                    texture1.texture.image = bpy.data.images[imagelist[index].split("^")[0]]
                                    texture2.texture.image = bpy.data.images[imagelist[index].split("^")[1]]
                                else:
                                    bpy.ops.minetest.creategamematerial()
                                    texture1 = bpy.context.object.active_material.texture_slots[0]
                                    texture1.texture.image = bpy.data.images[imagelist[index]]
                            index = index+1
                    else:
                        print("El modulo nodesmaterials esta desactivada,no se puede crear la textura/s")
                        print("The module nodesmaterials is desactive,can't create the textures")
                #Function who uses the changematerialimage function for add the textures in the materials of the nodes    
                def addnodetextures(texturelist = texturelist):
                    if "createsimplematerial" in confiratrr(bpy.ops.minetest):
                        if texturelist.__len__() == 1:
                            try:
                                changematerialimage(slotlist = [5,4,3,2,1,0],imagelist = [texturelist[0],texturelist[0],texturelist[0],texturelist[0],texturelist[0],texturelist[0]])
                            except KeyError:
                                print("KeyError")
                        if texturelist.__len__() == 2:
                            try:
                                changematerialimage([5,4,3,2,1,0],[texturelist[0],texturelist[0],texturelist[1],texturelist[1],texturelist[1],texturelist[1]])
                                            
                            except KeyError:
                                print("KeyError")
                        if texturelist.__len__() == 3:
                            try:
                                changematerialimage([5,4,3,2,1,0],[texturelist[0],texturelist[1],texturelist[2],texturelist[2],texturelist[2],texturelist[2]])
                            except KeyError:
                                print("KeyError")
                        if texturelist.__len__() == 4:
                            try:
                                changematerialimage([5,4,3,2,1,0],[texturelist[0],texturelist[1],texturelist[2],texturelist[2],texturelist[3],texturelist[3]])
                            except KeyError:
                                print("KeyError")
                        if texturelist.__len__() == 5:
                            try:
                                changematerialimage([5,4,3,2,1,0],[texturelist[0],texturelist[1],texturelist[2],texturelist[3],texturelist[3],texturelist[4]])
                            except KeyError:
                                print("KeyError")
                        if texturelist.__len__() == 6:
                            try:
                                changematerialimage([5,4,3,2,1,0],[texturelist[0],texturelist[1],texturelist[2],texturelist[3],texturelist[4],texturelist[5]])
                            except KeyError:
                                print("KeyError")        
                    else:
                        print("El modulo nodesmaterials esta desactivada,no se puede crear la textura/s")
                        print("The module nodesmaterials is desactive,can't create the textures")
                #The next section create a node in the scene using the data substracted from the file.
                #La siguiente seccion crea un nodo en la escena  usando los datos substraidos del archivo.
                if ndrawtype == None and impdefault == True:
                    if not "nodo:nodo" in bpy.context.scene.objects:
                        try:
                            bpy.ops.minetest.createcube()
                        except:
                            bpy.ops.mesh.primitive_cube_add()
                            bpy.context.object.name = "nodo:nodo"
                            try:
                                bpy.ops.minetest.createsimplematerial()
                            except:
                                print("")
                    new = bpy.context.scene.objects["nodo:nodo"].copy()
                    bpy.context.scene.objects.link(new)
                    modificar = new
                    new.name = nodo
                    bpy.context.scene.objects.active = modificar
                    modificar.select = True
                    bpy.ops.object.make_single_user(type='SELECTED_OBJECTS', object=True, obdata=True, material=True, texture=False,animation=False)
                    materialslots = modificar.material_slots.items()
                    addnodetextures()
                    #Modificando el material
                    #try:
                    #    addnodetextures()
                    #except:
                    #    print("Ha ocurrido un fallo al crear las texturas,lo mas probable es que los modulos createnodes y nodesmaterials no estan activados")
                    #    print("There is a error in the creation of the textures,probably the modules createnodes and nodesmaterials don't be actives")
                if "createcube" in confiratrr(bpy.ops.minetest):
                    print("El modulo sdasjfndsjkabfhadbkshfbaskdjbhfkjabshdfkhbsdbkfjbaskdfjhbasbf")
                    if ndrawtype == ' "allfaces_optional"' and impallfaces == True:
                        if not "nodo:allfaces" in bpy.context.scene.objects:
                            try:
                                bpy.ops.minetest.allfaces()
                            except:
                                bpy.ops.mesh.primitive_cube_add()
                                bpy.context.object.name = "nodo:allfaces"
                                try:
                                    bpy.ops.minetest.createsimplematerial()
                                except:
                                    print("")
                        new = bpy.context.scene.objects["nodo:allfaces"].copy()
                        bpy.context.scene.objects.link(new)
                        modificar = new
                        new.name = nodo
                        bpy.context.scene.objects.active = modificar
                        modificar.select = True
                        bpy.ops.object.make_single_user(type='SELECTED_OBJECTS', object=True, obdata=True, material=True, texture=False,animation=False)
                        materialslots = modificar.material_slots.items()
                        if texturelist.__len__() >= 1:
                            try:
                                changematerialimage([0],[texturelist[0]])
                            except KeyError:
                                print("KeyError")
                    
                    elif (ndrawtype == ' "plantlike"' or ndrawtype == ' "plantlike_rooted"') and impplant == True:
                        if not "nodo:plantlike" in bpy.context.scene.objects:
                            try:
                                bpy.ops.minetest.plantlike()
                            except:
                                print("Ha ocurrido un error")
                        new = bpy.context.scene.objects["nodo:plantlike"].copy()
                        bpy.context.scene.objects.link(new)
                        modificar = new
                        new.name = nodo
                        bpy.context.scene.objects.active = modificar
                        modificar.select = True
                        bpy.ops.object.make_single_user(type='SELECTED_OBJECTS', 
                        object=True, obdata=True, material=True, texture=False,animation=False)
                        materialslots = modificar.material_slots.items()
                        if texturelist.__len__() == 1:
                            try:
                                changematerialimage(slotlist=[1,0],imagelist=[texturelist[0],texturelist[0]])
                            except:
                                print("KeyError")
                        if texturelist.__len__() == 2:
                            try:
                                changematerialimage(slotlist=[1,0],imagelist=[texturelist[0],texturelist[1]])
                            except :
                                print("KeyError")
                    
                    elif ndrawtype == ' "signlike"'and impsign == True:
                        if not "nodo:signlike" in bpy.context.scene.objects:
                            try:
                                bpy.ops.minetest.signlike()
                            except:
                                print("Ha ocurrido un error")
                        new = bpy.context.scene.objects["nodo:signlike"].copy()
                        bpy.context.scene.objects.link(new)
                        modificar = new
                        new.name = nodo
                        bpy.context.scene.objects.active = modificar
                        modificar.select = True
                        bpy.ops.object.make_single_user(type='SELECTED_OBJECTS', 
                        object=True, obdata=True, material=True, texture=False,animation=False)
                        materialslots = modificar.material_slots.items()
                        if texturelist.__len__() == 1:
                            try:
                                changematerialimage([0],[texturelist[0]])
                            except :
                                print("KeyError")
                    
                    elif (ndrawtype == ' "glasslike"' or ndrawtype ==' "glasslike_framed_optional"')and impglass == True:
                        if not ("nodo:glasslike(X)" and "nodo:glasslike(I)" and "nodo:glasslike(T)") in bpy.context.scene.objects:
                            try:
                                bpy.ops.minetest.glasslike()
                            except:
                                print("Has ocurred an error when importing a plantlike node")
                        ########################################################
                        new = bpy.context.scene.objects["nodo:glasslike(X)"].copy()
                        bpy.context.scene.objects.link(new)
                        modificar = new
                        new.name = nodo + "glasslike(X)"
                        bpy.context.scene.objects.active = modificar
                        modificar.select = True
                        bpy.ops.object.make_single_user(type='SELECTED_OBJECTS', 
                        object=True, obdata=True, material=True, texture=False,animation=False)
                        materialslots = modificar.material_slots.items()
                        addnodetextures()
                        ########################################################
                        new = bpy.context.scene.objects["nodo:glasslike(I)"].copy()
                        bpy.context.scene.objects.link(new)
                        modificar = new
                        new.name = nodo + "glasslike(I)"
                        bpy.context.scene.objects.active = modificar
                        modificar.select = True
                        bpy.ops.object.make_single_user(type='SELECTED_OBJECTS', 
                        object=True, obdata=True, material=True, texture=False,animation=False)
                        materialslots = modificar.material_slots.items()
                        addnodetextures()
                        ########################################################
                        new = bpy.context.scene.objects["nodo:glasslike(T)"].copy()
                        bpy.context.scene.objects.link(new)
                        modificar = new
                        new.name = nodo + "glasslike(T)"
                        bpy.context.scene.objects.active = modificar
                        modificar.select = True
                        bpy.ops.object.make_single_user(type='SELECTED_OBJECTS', 
                        object=True, obdata=True, material=True, texture=False,animation=False)
                        materialslots = modificar.material_slots.items()
                        addnodetextures()
                    
                    #/usr/share/minetest/games/minetest_game/mods/doors/
                    ########################
                    #Ruta del mod "doors"
                    try:
                        doorspath = bpy.Minetest.mainpath + "/games/minetest_game/mods/doors/models/"
                    except:
                        if os.name == "posix":
                            doorspath="/usr/share/minetest/games/minetest_game/mods/doors/models/"
                        
                    if register == "doors.register(":
                        bpy.ops.import_scene.obj(filepath= doorspath + "door_a.obj",
                        axis_forward='-Z', axis_up='Y', filter_glob="*.obj;*.mtl",use_edges=True, use_smooth_groups=True, use_split_objects=False,
                        use_split_groups=True, use_groups_as_vgroups=False, use_image_search=True, split_mode='ON', global_clamp_size=0)
                        for obj in bpy.data.objects:
                            if obj.name.find("door_a") > -1:
                                modificar = obj
                        
                        bpy.context.scene.objects.active = modificar
                        modificar.select = True
                        modificar.name = "door:"+ nodo
                        materialslots = modificar.material_slots.items()
                        if texturelist.__len__() == 1:
                            try:
                                changematerialimage([0],[texturelist[0]])
                            except :
                                print("KeyError")
                    if register == "doors.register_trapdoor(":
                        for lines in lineslist:
                            if lines.find("tile_front") > 0:
                                textura = lines.split('"')[1]  
                        if not "nodo:signlike" in bpy.context.scene.objects:
                            try:
                                bpy.ops.minetest.signlike()
                            except:
                                print("Ha ocurrido un error")
                        new = bpy.context.scene.objects["nodo:signlike"].copy()
                        bpy.context.scene.objects.link(new)
                        modificar = new
                        new.name = "door:"+ nodo
                        bpy.context.scene.objects.active = modificar
                        modificar.select = True
                        bpy.ops.object.make_single_user(type='SELECTED_OBJECTS', 
                        object=True, obdata=True, material=True, texture=False,animation=False)
                        materialslots = modificar.material_slots.items()
                        try:
                            changematerialimage([0],[textura])
                        except :
                            print("KeyError")
                        bpy.ops.object.modifier_add(type='SOLIDIFY')
                        bpy.context.object.modifiers["Solidify"].thickness = 0.1
                    #doors.register_fencegate(
                    if register == "doors.register_fencegate(":
                        for lines in lineslist:
                            if lines.find("texture") > 0:
                                textura = lines.split('"')[1]  
                        bpy.ops.import_scene.obj(filepath= doorspath + "doors_fencegate_closed.obj",
                        axis_forward='-Z', axis_up='Y', filter_glob="*.obj;*.mtl",use_edges=True, use_smooth_groups=True, use_split_objects=False,
                        use_split_groups=True, use_groups_as_vgroups=False, use_image_search=True, split_mode='ON', global_clamp_size=0)
                        for obj in bpy.data.objects:
                            if obj.name.find("doors_fencegate_closed") > -1:
                                modificar = obj
                        
                        bpy.context.scene.objects.active = modificar
                        modificar.select = True
                        modificar.name = "door:"+ nodo
                        materialslots = modificar.material_slots.items()
                        try:
                            changematerialimage([0],[textura])
                        except :
                            print("KeyError")
         
                        #########################
                lineslist = []
                ndrawtype = None
                nodestotalfind = nodestotalfind+1
          
    o.close()
    debugprint("Se han encontrado un total de "+str(nodestotalfind))
    debugprint("There is a total of: "+str(nodestotalfind))
    return {'FINISHED'}


#########################

#Funcion que crea las texturas
#Function who creates the textures.

def importtexture(archivo = ""):
    def importimage():
        for im in list([ip for ip in glob.glob(archivo+"/**",recursive = True) if os.path.splitext((os.path.basename(ip)))[1] == ".png" ]):
            if bpy.data.images.find(im) != -1:
                bpy.data.images.remove(bpy.data.images[im])
            bpy.ops.image.open(filepath = im)
    importimage()
    for im in list([ip for ip in glob.glob(archivo+"/**",recursive = True) if os.path.splitext((os.path.basename(ip)))[1] == ".png" ]):
        if bpy.data.textures.find(im) == -1:
            if bpy.data.textures.find("Textura") == -1:
                bpy.ops.texture.new()
                bpy.data.textures["Texture"].image = bpy.data.images[os.path.basename(im)]
                bpy.data.textures["Texture"].name = os.path.basename(im)
            else:
                bpy.data.textures["Texture"].image = bpy.data.images[os.path.basename(im)]
                bpy.data.textures["Texture"].name = os.path.basename(im)
        elif bpy.data.textures.find(os.path.basename(im)) != -1:
            bpy.data.textures.remove(bpy.data.textures[os.path.basename(im)])

#########################

from bpy_extras.io_utils import ImportHelper
class ImportMinetestNodesfromfile(bpy.types.Operator,ImportHelper):
    bl_idname = "minetest.impornodes"    
    bl_label = "Minetest:Import Nodes"   
    bl_description = "Import diferent types of minetest nodes from a file/Importa diferentes tipos de nodos de un archivo"
    bl_options = {'REGISTER', 'UNDO'}  
    
        
    from bpy.props import StringProperty, BoolProperty, EnumProperty
    
    filename_ext = ".lua"
    
    filter_glob = StringProperty(
        default="*.lua",
        options={'HIDDEN'},
        maxlen=255,)   
            
    optionA = BoolProperty(
        name="Normal",
        description="",
        default=True,
    )
    optionB = BoolProperty(
        name="Plant",
        description="",
        default=True,
    )
    optionC = BoolProperty(
        name="Glass",
        description="",
        default=True,
    )
    optionD = BoolProperty(
        name="Sign",
        description="",
        default=True,
    )
    optionE = BoolProperty(
        name="Allfaces",
        description="",
        default=True,
    )
    
    ##############3
    option1 = False
    option2 = False
    
    if "ordernodes" in confiratrr(bpy.ops.minetest):
        option1 = BoolProperty(
            name="Order the nodes",
            description="Only avaiable with my 'Order'script for the nodes)Separate the create nodes by layers",
            default=False,
        )
    
    if "nodesgroups" in confiratrr(bpy.ops.minetest):
        option2 = BoolProperty(
                name="Create group_instances",
                description="(Only avaiable with my 'Order'script for the nodes)Separate the create nodes by layers",
                default=False,
            )    
    ##############
    
    def execute(self, context): 
        if os.path.splitext((os.path.basename(self.filepath)))[1] == ".lua":
            texture = os.path.dirname(self.filepath) + "/textures"
            importtexture(os.path.dirname(self.filepath))
            importnoddesexec(self.filepath,self.optionA,self.optionB,self.optionC,self.optionD,self.optionE)  
        else:
            prpath = os.path.dirname(self.filepath)
            importtexture(os.path.dirname(prpath))
            revlist = list([f for f in glob.glob(prpath+"/**",recursive = True) if os.path.splitext((os.path.basename(f)))[1] == ".lua" ])
            debugprint(("Se examinaran un total de :"+str(revlist.__len__())))
            examinetfiles = 0
            for i in list([f for f in glob.glob(prpath+"/**",recursive = True) if os.path.splitext((os.path.basename(f)))[1] == ".lua" ]):
                importnoddesexec(i,self.optionA,self.optionB,self.optionC,self.optionD,self.optionE)
                debugprint(("Se han examinado :"+str(examinetfiles) +"  de "+str(revlist.__len__())))
                examinetfiles = examinetfiles +1
        debugprint(("Se han terminao de importar los nodos,duro la ejecucion unos:","%.4fs"%(time.clock()-startime)))
        debugprint(("The script finish of import the nodes,in a time of:","%.4fs"%(time.clock()-startime)))
            
        ###
        if self.option1 == True:
            bpy.ops.minetest.ordernodes()
        if self.option2 == True:
            bpy.ops.minetest.nodesgroups()
        return {'FINISHED'}



class MinetestImportNodesPanel(bpy.types.Panel):
    bl_space_type = 'VIEW_3D'
    bl_context = "objectmode"
    bl_label = "Import Panel"
    bl_region_type = "TOOLS"
    bl_category = "Minetest"    
    
    def draw(self,context):
        layout = self.layout
        row = layout.row()
        row.scale_y = 1.0
        row.operator("minetest.impornodes",text = "Nodes")
        
def menu_func_import(self, context):
    self.layout.operator(ImportMinetestNodesfromfile.bl_idname, text="Text Import Operator")

def register():
    print("The Minetest Panel was created")
    bpy.utils.register_class(MinetestImportNodesPanel)
    bpy.utils.register_class(ImportMinetestNodesfromfile)
    bpy.types.INFO_MT_file_import.append(menu_func_import)
def unregister():
    print("Closing the Minetest Panel")
    bpy.utils.register_class(MinetestImportNodesPanel)
    bpy.utils.unregister_class(ImportMinetestNodesfromfile)
    bpy.types.INFO_MT_file_import.remove(menu_func_import)
    
if __name__ == "__main__":
    register()
    

Post Reply

Who is online

Users browsing this forum: No registered users and 7 guests