Blender script for import minetest nodes

minetesprogramercor
New member
 
Posts: 2
Joined: Tue Oct 08, 2019 18:49
In-game: None

Blender script for import minetest nodes

by minetesprogramercor » Tue Oct 08, 2019 18:55

First i don't speak English(i speak Spanish)
Hello i am “minetesprogramer” and first i want to say sorry for all the errors in the code,the first time who create this post i don't notice so many errors in my script,but now i fix this and work “correctly”.
Requirements:
1-You need to have installed “Blender 2.79”(I dont know if functions in “2.80”)
2-Your operative system must be Linux(only probe in Linux)
Instructions
1-Open Blender.
2-Change the render mode to “Cycles Render”(“Blender Render” is the default).
3-Copy the script in the Blender text editor
4-Run the script(mouse over the blender text editor and (Alt+P) or in the Blender text editor:text>Run Script )
5-Open the new Minetest Panel.
6-Press the Import button.
6.5(Optional:Configure the import whit:The align selector(Line,2DCube),and the Layer option)
7-Select the file from you want to import the nodes(and activate this)
0.1
.Puede importar nodos./Can import nodes.
.Puede representar estos tipos de nodos:plantlike ,node-box./Can represent this types of nodes:plantlike ,node-box.
0.2 (Grandes correciones)/Big Corrections.
.Al importar los nodos,crea un "grupo para cada nodo"./Importing the nodes,create a group for each node.
.No me habia dado cuenta que sin importar que archivos seleccionaras,siempre importaba los nodos del mismo archivo./
.Esto ya esta arreglado
.Se arreglo un error,que sucedia si no se usaba la opcion separar por tipo./Fix a error who appear if not using the option “separate by type”.
.Se arreglo un error a la hora de crear las texturas./Fix a error creating the textures for the nodes


Code: Select all
The Script(V0.2):
#Este script puede importar los nodos del minetest desde la fuente principal del Minetest(game:minetest_game/mods/default/nodes.lua).
#This script can import the minetest nodes from the main source of Minetest(game:minetest_game/mods/default/nodes.lua).

import os
import bpy

#if os.sys.platform == "linux":
 #   path = "/usr/share/games/minetest/games/minetest_game/mods/default/nodes.lua"
  #  texture = os.path.dirname("/usr/share/games/minetest/games/minetest_game/mods/default/nodes.lua") + "/textures"
bpy.context.scene.render.engine = "CYCLES"
def importnoddesexec(path,aligopt="linear",slayers = "False"):
    texture = os.path.dirname(path) + "/textures"
    #print(texture)
    #Funcion que crea las texturas
    #Function who creates the textures.
    def importtexture(archivo = texture):
        def importimage():
            for archives in os.listdir(archivo):
                if archives.count(".png") == 1:
                    if bpy.data.images.find(archives) != -1:
                        bpy.data.images.remove(bpy.data.images[archives])
                    bpy.ops.image.open(filepath = archivo + "/" + archives)
        importimage()
        for archives in os.listdir(archivo):
            if archives.count(".png") == 1:
                if bpy.data.textures.find(archives) == -1:
                    if bpy.data.textures.find("Textura") == -1:
                        bpy.ops.texture.new()
                        bpy.data.textures["Texture"].image = bpy.data.images[archives]
                        bpy.data.textures["Texture"].name = archives
                    else:
                        bpy.data.textures["Texture"].image = bpy.data.images[archives]
                        bpy.data.textures["Texture"].name = archives
                elif bpy.data.textures.find(archives) != -1:
                    bpy.data.textures.remove(bpy.data.textures[archives])
               
    importtexture()
    #Funcion que "importa" el nodo.
    #Function who "import" the node.
    def importnode(archivo = path):
        o = open(archivo,"r")
        #print(archivo,"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
        nodecount = 0
        e  = 0
        inicp = False
        tileini = False
        texturelist = []
        ndrawtype = None
        d = 0
        nodo = ""
        texture = None
        lx,ly,lz = (0,0,0)   
        for lines in o.readlines():
            #print(lines)
            if lines.find("minetest.register_node(") == 0 and inicp==False: #and d == 0:
                texturelist = []
                inicp= True
                e = e+1
                nodo = lines.split('"')[1]
                #print("Se ha encontrado un nodo",lines)
            elif inicp== True:
                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]
                    #print(ndrawtype)
                if tileini == True:
                    if lines.find(".png") >0:
                        #print("Se ha encontrado una imagen",lines)
                        #print(lines.split('"').__len__())
                        if lines.split('"').__len__() >= 3:
                            if lines.split('"')[1].find("^")>0:
                                texturelist.append(lines.split('"')[1].split("^")[1])
                            else:
                                texturelist.append(lines.split('"')[1])
                    if lines.find("},")>0:
                        #print("Se para el proceso (tile)")
                        tileini = False           
            if lines.find("})") == 0 and inicp== True:# and texturelist != []:
                d = 1
                inicp= False
                #print("Fin del nodo")
                if bpy.data.objects.find(nodo) == -1:
                    #print("Creando el material que usara el nodo.")
                    #Creating the material who uses the node.
                    def cmaterial(mname = nodo):
                        #print("#Comprobando si el material a modificar existe.")
                        if bpy.data.materials.find(mname) != -1:
                            #print("Ya existe el material")
                            bpy.data.materials.remove(bpy.data.materials[mname])
                            #return False
                           
                        if bpy.data.materials.find("Material") == -1:
                            print("No existe el material")
                        else:
                            bpy.data.materials.remove(bpy.data.materials['Material'])
                           
                        bpy.ops.material.new()

                        material = bpy.data.materials["Material"]

                        material.node_tree.nodes.new("ShaderNodeMixRGB")

                        def linknodes(input,output):
                            material.node_tree.links.new(input,output)
                           
                        material.node_tree.nodes['Mix'].location[1] = 300
                        material.node_tree.nodes['Mix'].location[0] = -300

                        material.node_tree.nodes.new("ShaderNodeMixRGB")

                        material.node_tree.nodes['Mix.001'].location[1] = 300
                        material.node_tree.nodes['Mix.001'].location[0] = -600

                        linknodes(material.node_tree.nodes['Diffuse BSDF'].inputs['Color'],material.node_tree.nodes['Mix'].outputs['Color'])
                        linknodes(material.node_tree.nodes['Mix'].inputs[1],material.node_tree.nodes['Mix.001'].outputs['Color'])

                        material.node_tree.nodes.new("ShaderNodeTexImage")
                        material.node_tree.nodes['Image Texture'].location[1] = 600
                        material.node_tree.nodes['Image Texture'].location[0] = -900

                        material.node_tree.nodes.new("ShaderNodeTexImage")
                        material.node_tree.nodes['Image Texture.001'].location[1] = 300
                        material.node_tree.nodes['Image Texture.001'].location[0] = -900

                        material.node_tree.nodes.new("ShaderNodeTexImage")
                        material.node_tree.nodes['Image Texture.002'].location[1] = 0
                        material.node_tree.nodes['Image Texture.002'].location[0] = -900

                        linknodes(material.node_tree.nodes['Mix.001'].inputs[1],material.node_tree.nodes['Image Texture'].outputs['Color'])
                        linknodes(material.node_tree.nodes['Mix.001'].inputs[2],material.node_tree.nodes['Image Texture.001'].outputs['Color'])
                        linknodes(material.node_tree.nodes['Mix'].inputs[2],material.node_tree.nodes['Image Texture.002'].outputs['Color'])

                        material.node_tree.nodes.new("ShaderNodeCombineXYZ")
                        material.node_tree.nodes['Combine XYZ'].location[1] = 600
                        material.node_tree.nodes['Combine XYZ'].location[0] = -1200

                        material.node_tree.nodes.new("ShaderNodeCombineXYZ")
                        material.node_tree.nodes['Combine XYZ.001'].location[1] = 300
                        material.node_tree.nodes['Combine XYZ.001'].location[0] = -1200

                        material.node_tree.nodes.new("ShaderNodeCombineXYZ")
                        material.node_tree.nodes['Combine XYZ.002'].location[1] = 0
                        material.node_tree.nodes['Combine XYZ.002'].location[0] = -1200

                        linknodes(material.node_tree.nodes['Image Texture'].inputs[0],material.node_tree.nodes['Combine XYZ'].outputs[0])
                        linknodes(material.node_tree.nodes['Image Texture.001'].inputs[0],material.node_tree.nodes['Combine XYZ.001'].outputs[0])
                        linknodes(material.node_tree.nodes['Image Texture.002'].inputs[0],material.node_tree.nodes['Combine XYZ.002'].outputs[0])

                        material.node_tree.nodes.new("ShaderNodeSeparateXYZ")
                        material.node_tree.nodes['Separate XYZ'].location[1] = 300
                        material.node_tree.nodes['Separate XYZ'].location[0] = -1500

                        linknodes(material.node_tree.nodes['Combine XYZ'].inputs[0],material.node_tree.nodes['Separate XYZ'].outputs[0])
                        linknodes(material.node_tree.nodes['Combine XYZ'].inputs[1],material.node_tree.nodes['Separate XYZ'].outputs[1])

                        linknodes(material.node_tree.nodes['Combine XYZ.001'].inputs[0],material.node_tree.nodes['Separate XYZ'].outputs[1])
                        linknodes(material.node_tree.nodes['Combine XYZ.001'].inputs[1],material.node_tree.nodes['Separate XYZ'].outputs[2])

                        linknodes(material.node_tree.nodes['Combine XYZ.002'].inputs[0],material.node_tree.nodes['Separate XYZ'].outputs[0])
                        linknodes(material.node_tree.nodes['Combine XYZ.002'].inputs[1],material.node_tree.nodes['Separate XYZ'].outputs[2])

                        material.node_tree.nodes.new("ShaderNodeTexCoord")
                        material.node_tree.nodes['Texture Coordinate'].location[1] = 300
                        material.node_tree.nodes['Texture Coordinate'].location[0] = -1800
                       
                        linknodes(material.node_tree.nodes['Separate XYZ'].inputs[0],material.node_tree.nodes['Texture Coordinate'].outputs[0])
                       
                        material.node_tree.nodes.new("ShaderNodeMath")
                        material.node_tree.nodes['Math'].location[1] = 900
                        material.node_tree.nodes['Math'].location[0] = -900
                        material.node_tree.nodes['Math'].operation = "ABSOLUTE"
                       
                        linknodes(material.node_tree.nodes['Mix'].inputs[0],material.node_tree.nodes['Math'].outputs[0])
                       
                        material.node_tree.nodes.new("ShaderNodeMath")
                        material.node_tree.nodes['Math.001'].location[1] = 1200
                        material.node_tree.nodes['Math.001'].location[0] = -900
                        material.node_tree.nodes['Math.001'].operation = "ABSOLUTE"
                       
                        linknodes(material.node_tree.nodes['Mix.001'].inputs[0],material.node_tree.nodes['Math.001'].outputs[0])
                       
                        material.node_tree.nodes.new("ShaderNodeSeparateXYZ")
                        material.node_tree.nodes['Separate XYZ.001'].location[1] = 1200
                        material.node_tree.nodes['Separate XYZ.001'].location[0] = -1500
                       
                        linknodes(material.node_tree.nodes['Math'].inputs[0],material.node_tree.nodes['Separate XYZ.001'].outputs[1])
                        linknodes(material.node_tree.nodes['Math.001'].inputs[0],material.node_tree.nodes['Separate XYZ.001'].outputs[0])
                       
                       
                        linknodes(material.node_tree.nodes['Separate XYZ.001'].inputs[0],material.node_tree.nodes['Texture Coordinate'].outputs[1])
                       
                        material.node_tree.nodes['Image Texture'].interpolation = "Closest"
                        material.node_tree.nodes['Image Texture.001'].interpolation = "Closest"
                        material.node_tree.nodes['Image Texture.002'].interpolation = "Closest"
                        material.node_tree.nodes['Image Texture'].extension = "EXTEND"
                        material.node_tree.nodes['Image Texture.001'].extension = "EXTEND"
                        material.node_tree.nodes['Image Texture.002'].extension = "EXTEND"
                       
                        if texturelist.__len__() == 1:
                            material.node_tree.nodes['Image Texture'].image = bpy.data.images[texturelist[0]]
                            material.node_tree.nodes['Image Texture.001'].image = bpy.data.images[texturelist[0]]
                            material.node_tree.nodes['Image Texture.002'].image = bpy.data.images[texturelist[0]]
                        elif texturelist.__len__() == 2:
                            material.node_tree.nodes['Image Texture'].image = bpy.data.images[texturelist[0]]
                            material.node_tree.nodes['Image Texture.001'].image = bpy.data.images[texturelist[1]]
                            material.node_tree.nodes['Image Texture.002'].image = bpy.data.images[texturelist[1]]
                        elif texturelist.__len__() > 2:
                            material.node_tree.nodes['Image Texture'].image = bpy.data.images[texturelist[0]]
                            material.node_tree.nodes['Image Texture.001'].image = bpy.data.images[texturelist[1]]
                            material.node_tree.nodes['Image Texture.002'].image = bpy.data.images[texturelist[2]]
                       
                        material.name = mname
                        #print(material.name,mname)
                                       
                    #print("Tipo",ndrawtype)
                    #Layers
                    glayers=(True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False)
                    grllayers = bpy.context.scene.layers[0:]
                    sgtlayers = bpy.context.scene.layers[0:]
                   
                    if slayers == True:
                        grllayers = (False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False)
                        sgtlayers = (False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False)
                       
                    if ndrawtype == ' "plantlike"':
                        #print("Se ha encontrado un tipo planta")
                        #print(nodo)
                        bpy.ops.mesh.primitive_plane_add(location = (lx,ly,lz),radius=0.5, view_align=False, enter_editmode=False, layers=glayers)
                        bpy.ops.object.editmode_toggle()
                        bpy.ops.transform.rotate(value=-1.5708, axis=(0, 1, 0), constraint_axis=(False, True, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1)
                        bpy.ops.mesh.primitive_plane_add(location = (lx,ly,lz),radius=0.5, view_align=False, enter_editmode=False, layers=grllayers)
                        bpy.ops.transform.rotate(value=-1.5708, axis=(0, 1, 0), constraint_axis=(False, True, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1)
                        bpy.ops.transform.rotate(value=-1.5708, axis=(0, 0, 1), constraint_axis=(False, False, True), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1)
                        bpy.ops.object.editmode_toggle()
                        bpy.ops.object.move_to_layer(layers=(False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False))

                    elif ndrawtype == ' "signlike"':
                        bpy.ops.mesh.primitive_plane_add(location = (lx,ly,lz),radius=0.5, view_align=False, enter_editmode=False, layers=sgtlayers)
                    else:
                        #print("Un nodo normal(nodebox)")
                        bpy.ops.mesh.primitive_cube_add(radius = 0.5,location = (lx,ly,lz))
                    ndrawtype = ""
                    cmaterial()
                    if aligopt == "linear":
                        lx = lx+1
                    elif aligopt == "2dcube":
                        lx = lx+1
                        if nodecount > 10:
                            lx = 0
                            nodecount = 0
                            ly = ly+1
                    nodecount = nodecount+1
                    bpy.context.object.name = nodo
                    #Creando el grupo.
                    #Creating the group.
                    #Verify if the group exist in this case,is remplaced by the new group.
                    if bpy.data.groups.find(nodo) != -1:
                        bpy.data.groups.remove(bpy.data.groups[nodo])
                    bpy.ops.group.create(name=nodo)
                   
                    grupo = bpy.data.groups[nodo].dupli_offset
                    grupo[0],grupo[1],grupo[2] = bpy.context.object.location


                    if bpy.context.object.material_slots.items() == []:
                        bpy.ops.object.material_slot_add()
                        bpy.context.object.material_slots[''].material = bpy.data.materials[nodo]
               
        o.close()
    importnode()
    return {'FINISHED'}

bl_info = {#Metadato que contiene informacion sobre el script o add-on.
    "name": "Import Nodes",
    "author": "Lazaro",
    "version": (0, 1),
    "location": "View3D > Properties > Minetest",
    "description": "A buton to 'Minetest Panel' who inmports nodes of Minetest from a .lua file ",
    "category": "Minetest"}


from bpy_extras.io_utils import ImportHelper
class ImportMinetestNodesfromfile(bpy.types.Operator,ImportHelper):
    """My Object Moving Script"""      # Use this as a tooltip for menu items and buttons.
    bl_idname = "minetest.impornodes"        # Unique identifier for buttons and menu items to reference.
    bl_label = "Minetest:Import Nodes"         # Display name in the interface.
    bl_options = {'REGISTER', 'UNDO'}  # Enable undo for the operator.
       
    from bpy.props import StringProperty, BoolProperty, EnumProperty
   
    filename_ext = ".lua"
   
    filter_glob = StringProperty(
            default="*.lua",
            options={'HIDDEN'},
            maxlen=255,  # Max internal buffer length, longer would be clamped.
        )
    option1 = EnumProperty(
            name="Alig",
            description="Form in whit location the nodes",
            items=(
                ('linear', "Linear", "Form of Line"),
                ('2dcube', "2D Cube", "Form of 2DCube"),
            ),
            default='linear',
        )
    option2 = BoolProperty(
            name="Separate by type",
            description="Separate the create nodes by layers",
            default=False,
        )
   

    def execute(self, context):        # execute() is called when running the operator.
        print("Final")
        importnoddesexec(self.filepath,self.option1,self.option2)           # Lets Blender know the operator finished successfully.
        return {'FINISHED'}


   
class MinetestImportNodesPanel(bpy.types.Panel):
    bl_space_type = 'VIEW_3D'
    bl_context = "objectmode"
    bl_label = "Import Nodes"
    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 = "Import")
   


# Only needed if you want to add into a dynamic menu
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__":#Esto permite correr el script desde el editor de texto de Blender.
    register()
 

Return to Modding Discussion



Who is online

Users browsing this forum: No registered users and 2 guests