Blender script Operator, blenderoperator

Source: Internet
Author: User

Blender script Operator, blenderoperator


The addon (plug-in) is used to extend the Blender function. Like plug-in other software, removing the plug-in will not affect the running of the software. The plug-in can be added to the user preference setting directory of the Blender, or in the. blend file you edited. The former requires you to manually enable it. The latter selects the Register option in Text Editor and Blender is enabled during loading, or click Run Script next to the Register selection box (shortcut: Alt + P) to Run.

The path of the Blender plug-in is C: \ Program Files \ Blender Foundation \ Blender \ 2.76 \ scripts \ addons. I assume that you are using the 64-bit Blender 2.76 software, the installation path is not modified. For example, if io_import_images_as_planes.py is used as the plug-in file for plane loading, the Add-ons Tab of user preference settings (shortcut: Ctrl + Alt + U) is enabled to search and filter, check the box that follows, and add an additional line of Images as Planes in File> Import in the menu.

One or more operators are defined in the plug-in, so I will not translate them into mathematical operators or operators in C ++. All UI functions of Blender are implemented through operator. operator can be bound to menus, buttons, or shortcut keys for calling. The base class of operator is bpy. types. Operator, which must be inherited from a custom operator.

 

Now, let's learn how to write plug-ins!
Open the Blender Text Editor. I suppose you have a preliminary understanding of the Blender interface layout. Text Editor can be used when README is used. When a programmer comes into contact with a new project, he can use README to understand its functions. Similarly, when the Blender project exits, the current interface is saved, and when others open it, you can see the text at first glance. You can write your own blog address and name to let others learn.

Our first Operator, say hello to Blender!

import bpyclass HelloWorldOperator(bpy.types.Operator):  bl_idname = "wm.hello_world"  bl_label = "Hello World"  def execute(self, context):    print("Hello World!")    return {'FINISHED'}bpy.utils.register_class(HelloWorldOperator)

Operator must be registered before use. bl_idname, as the name suggests, is the operator name. It is written like a package name. It is separated by a dot. The name on the left of the dot must belong to bpy. one of ops, In the Python console inside Blender, dir (bpy. ops) to list all names. Bl_idname is used internally; bl_label is visible externally. Python can enclose strings without separating single quotes and double quotes. In other words, C/C ++ uses single quotes and double quotation marks to distinguish characters from strings, but Python is interpreted as strings in a unified way.

>>> Type (bpy. ops)
<Class 'bpy. ops. BPyOps '>

>>> Dir (bpy. ops)
['Action', 'anim ', 'armature', 'boid', 'paush', 'buttons', 'cama', 'clip', 'braw ', 'console', 'straint', 'curve', 'cycles ', 'dpaint', 'ed', 'export _ anim', 'export _ mesh ', 'export _ scene ', 'file', 'fluid', 'font', 'gpencoding', 'graph', 'group', 'image', 'import _ anim ', 'import _ curve', 'import _ image', 'import _ mesh ', 'import _ scene', 'info', 'lamp ', 'lattice', 'logic ', 'marker', 'mask', 'material ', 'mball', 'mesh', 'nla ', 'node', 'object', 'outliner', 'paint ', 'paintcurve', 'paster', 'particle ', 'pose', 'poselib ', 'ptcac', 'render', 'rigiidbody', 'safe _ areas ', 'scene', 'screen', 'script', 'sculpt', 'sequencer ', 'sketch', 'sound', 'surface ', 'text', 'text ', 'time', 'transform', 'ui', 'U', 'view2d ', 'view3d', 'wm ', 'World']

>>> Print ("Hello World! ")
Hello World!

>>> Bpy. ops. wm. hello_world ()
Hello World!
{'Finished '}

>>>

Print ("Hello World! ") Output Hello World! Information to the console, directly running can not see the output results. You can enter bpy. ops. wm. hello_world () in the console for testing, as shown in the preceding figure. Do not have leading spaces.


Next, let's make a slight modification to the UI version of HelloWorld.

import bpyclass HelloWorldOperator(bpy.types.Operator):  bl_idname = "wm.hello_world"  bl_label = "Hello World"  def execute(self, context):    #print("Hello World!")    self.report({'INFO'}, "Hello World!")    return {'FINISHED'}  def invoke(self, context, event):    wm = context.window_manager    return wm.invoke_props_dialog(self)bpy.utils.register_class(HelloWorldOperator)

 

Replace self. report ({'info'}, "Hello World! ")
Press the Space key in the 3D view and enter "Hello World" to search. Note that you can search in real time and enter a few letters to view the entries. Click this entry and a dialog box will pop up. The title is bl_label. Click OK and the page will disappear. "Hello World! "Message. You can also enter bpy. ops. wm. hello_world () in the Python console to test the new operator.

>>> Bpy. ops. wm. hello_world ()
Info: Hello World!
{'Finished '}

>>>

After the invoke method is complete, a string set is returned, which is enclosed by {} to indicate a set. Tell the Blender operator in the RUNNING status {'running _ modal'}, or cancel the operation {'canonicalled'}, and return {"FINISHED"} indicates that the operation is successful.

 

The second operator is added with a regular tetrahedron ).
One advantage of Chinese-English comparison is that Monday-Day-Year-month-Year-year, there are 12 words in each month, and the English vocabulary is increased accordingly.
I hope you will remember the geometric nature of the positive and still-Red words. The positive triangle is the simplest ry in three-dimensional space. The molecular model of methane (methane) and methane (methane) can be interpreted as a positive triangle, with carbon atoms serving as the center of the outside. The angle of the two sides is arccos (1/3). If the carbon atom is taken as the coordinate origin, the coordinates of the four hydrogen atoms are, and the distance between any two hydrogen atoms is 2.

It is also easy to construct a positive triangle from the cube, and select the diagonal lines on the opposite side of the cube to connect these four vertices to form a positive triangle. Like this:


The Blender uses BU (Blender Unit) units. The edges of the positive triangle are 1 and vertices (0,-1/math. sqrt (3), 0), (0.5, 1/(2 * math. sqrt (3), 0), (-0.5, 1/(2 * math. sqrt (3), 0), (0, 0, math. sqrt (2/3 )). If the cube is constructed using the system (the side length is 2 bu), the side length is 2 * sqrt (2), vertex (1, 1, 1), (-1,-1, 1), (1,-1,-1), (-1, 1,-1 ),All vertices are integers.Oh!

import bpyfrom math import sqrtfrom mathutils import Vectorclass MakeTetrahedron(bpy.types.Operator):    bl_idname = "mesh.make_tetrahedron"    bl_label = "Add Tetrahedron"    def invoke(self, context, event):        vertices = \        [            Vector((0, -1/sqrt(3),0)),            Vector((0.5, 1/(2 * sqrt(3)), 0)),            Vector((-0.5, 1/(2 * sqrt(3)), 0)),            Vector((0, 0, sqrt(2/3))),        ]        edges = []        faces = [[0, 1, 2], [0, 1, 3], [1, 2, 3], [2, 0, 3]]                tetrahedron = bpy.data.meshes.new("Tetrahedron")        tetrahedron.from_pydata(vertices, edges, faces)        tetrahedron.update()        object = bpy.data.objects.new("Tetrahedron", tetrahedron)        context.scene.objects.link(object)        return {"FINISHED"}    #end invoke#end MakeTetrahedrondef register():    bpy.utils.register_class(MakeTetrahedron) def unregister():    bpy.utils.unregister_class(MakeTetrahedron) if __name__ == "__main__":    register()

 

If you cannot write more than one row of content, you may like to align the brackets. You need to add a backslash at the end of the row to indicate continued rows. If you do not write it, an error is returned. If you do not like this method, you can use the brackets in the next line.
Python supports UTF-8 encoding, that is, class name, method name, variable name can use Unicode characters, of course including Chinese. If you do not know that the English word of the positive triangle is tetrahedron, do not use Pinyin instead. I have seen some new handwritten Java code. If you are too lazy to look up the dictionary for words you don't understand, you can use Pinyin (for example, the factorial function is written as jiecheng). If you look at it, you can write Chinese, and the compiler won't blame you. But again, it is best to use ASCII characters. Note whether the Code project is in American or English. Other characters can be found in comments.

In the above Code, we first show the data of the positive triangle (if you only need a single triangle, you can select Mesh> Add Cone, Vertices 3), vertices/edges/faces. The Mesh. from_pydata function uses the V/E/F data to construct the network surface. Python is the same as C/C ++/Java. indexing starts from 0 and MATLAB/Lua starts from 1. Counting from 0 has many advantages. Faces data is provided above, and edges is left blank, indicating the Solid (Solid) model. If the following data is provided, the wireframe model of the positive triangle is obtained.

    vertices = ... # same as above    edges = [[0, 1], [0, 2], [0, 3], [1, 2], [2, 3], [3, 1]]    faces = []

 

Note that either edges data or faces data is provided, which may cause Blender to crash. (Well, I told you a way to crash the Blender .) After importing V/E/F, the Mesh data changes and needs to be updated.
After the network is created, the mesh is attached to the object datablock and finally linked to the scenario. Okay, we have finished. It is necessary to register register_class in the last sentence. Otherwise, it cannot be searched by space. The above can only be used through space key search. If you want to call it on the UI interface, you need to make bpy. types. Panel debut.

I suppose you are familiar with the Python language, know the method of class inheritance, and know the meaning of indentation. If a syntax error occurs during running, the Blender dialog box is displayed, which may be a mix of tabs and spaces or other small errors. Modify the statements correctly and execute them again.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.