New answers tagged

1

The problem can be solved by using a persistent application handler that is executed once the project file has been fully loaded. bpy.app.handler.load_post allows you to append functions that shall be executed once the loading is completed. The annotation @persistent is required in order to keep the application handler registered even though a different ...


1

Setter / Getter on property Something like this can be done with an update, or setter and getter on a blender property. The operator has been ditched altogether. Because the compositor is being used, the Scene type is a natural choice. For shader nodes choose Material. The getter returns how many math nodes are in the node tree. The setter adds more if ...


2

Pathlib Here is a script that writes all text files in blend with suffix .py to a designated folder. IMO there is no need to timestamp a file name, since it is given a date when written to or touched. Timestamp a containing folder name if need be. import bpy from pathlib import Path destination_folder = "/tmp/texts" df = Path(destination_folder) #...


0

Found a solution: import bpy from bpy.props import IntProperty class AddManyNodesOP(bpy.types.Operator): bl_idname = ".add_many_nodes" bl_label = "Adds many Nodes" bl_description = "Adds many Nodes" def execute(self,context): tree = bpy.context.scene.node_tree for i in range(context.scene.number_Nodes_Prop): ...


5

Each collection has a children (collection) property. Easy to figure out using the python console: >>> C.scene.collection. all_objects animation_data_clear( animation_data_create( as_pointer( bl_rna ...


1

Object distance between frames and total movement length can be done. Set frame_start and frame_end variables. It calculates selected object distance. import bpy o = bpy.context.object total = 0 frame_start = 0 frame_end = 10 bpy.context.scene.frame_set(frame_start) for frame in range(frame_start+1,frame_end+1): loc1 = o.matrix_world.to_translation() ...


1

For anyone coming upon this question in 2020, I had a similar want and wanted to use Blender from a Jupyter Notebook. I made a Jupyter Kernel to do this for Blender 2.8 here. It uses asyncio so the Blender UI is not locked when using the kernel.


1

You can add File Output nodes to the compositor to get multiple files saved from any point of your compositing without the need for any Python: You can also use Python to add more nodes: import bpy bpy.context.scene.use_nodes = True tree = bpy.context.scene.node_tree for every_node in tree.nodes: tree.nodes.remove(every_node) RenderLayers_node = ...


5

These scripts will create two nodes. The first one is for the grid and the second one for the circle. By changing the size of the grid, you will have more or less circles. By changing the radius, you will have bigger or smaller circles. shader Tiles2D( point Vector = P, float Size = 1, float Offset = 0, output vector Tiles = vector(0,0,0) ) ...


0

Finally, I managed to combine image parts together with looping nested arrays. Although the script itself is not the most beautiful... I mark this answer to correct now, but if somebody is doing better that works in this context, I'll change it. So here is "monster" that I've used in this case: # First I need to order rendered part names correctly ...


0

This does it, though it uses a separate python script instead of something automated in Blender. Use it with python3 script.py [subfoldername] [framecount]. This is based on my setup, where each render pass has its own subfolder. This will search through all the files in a subfolder, determine their frame step, and generate duplicate frames based on the ...


0

well I come up with this script: import bpy context = bpy.context scene = context.scene bpy.ops.object.select_all(action='SELECT') for ob in scene.objects[:]: bpy.ops.object.editmode_toggle() bpy.ops.mesh.select_all(action='SELECT') bpy.ops.mesh.remove_doubles() bpy.ops.object.editmode_toggle() any suggestions for improvments? Ideally I ...


-1

Thanks everyone for you time. I manage to write a usable script with your insights and suggestions. Robert: I was able to save the lists of names to variables. But I did not find a way to use those lists for joining the objects. I guess I need more study. I ended up using the collections system as temporal holders for the objects. That way blender wont ...


2

Somehow, I figured out myself, this is quite a newbie mistake. The generated image should be created with float_buffer. from: bpy.data.images.new(IMAGE_NAME, WIDTH, HEIGHT) to: bpy.data.images.new(IMAGE_NAME, WIDTH, HEIGHT, alpha=True, float_buffer=True) One more thing is that the alpha value should be 1.0 since it will be used as masks for other. Ref ...


0

Using Operator override Here are a couple of examples. This one finds all the mesh objects in the scene, sorts them alphabetically by name, then groups them by if they start with the first. meshobs ['Cone', 'Cone.001', 'Cone.002', 'Cube', 'Cube.001', 'Cube.002', 'Cylinder', 'Cylinder.001', 'Cylinder.002'] Join ['Cone', 'Cone.001', 'Cone.002'] Join ['Cube',...


0

Finally after investigations I got something to work. Here is example blender file where is script that exports merged image. It works properly when using images that are rendered with "full final size" where is transparent section included and other with "cropped borders". Look below for a better understanding. And here is script that is also included in ...


2

Test code out in the console. Even if you are going to use a script from command line always (IMO) a good idea to test it out in the python console. (D = bpy.data, C = bpy.context) When adding an object via operator, the new object added is the context.object Notice the name below is not "Area" as there are already other area lights in the scene. Using ...


0

OK. This answer doesn't necessarily use python, but it achieves the same result. Say we have 4 pictures, and want to combine it into one image in Blender. There are many ways to do it. I'll give a few examples: 1) Individual faces for individual materials You can assign the images to individual faces in Blender. I'll use the example you provided. I have ...


1

Assigning to Existing Classes Custom properties can be added to any subclass of an ID, Bone and PoseBone Neither are bones, so leaving that aside, can see below ID is subclass of Object not FCurve, and as such is the property is not "wired up" as a property on the fcurve. >>> issubclass(bpy.types.Object, (bpy.types.ID,)) True >>> ...


2

I've coded a fair amount of scripts that use Blender's layout api, but i've never ventured into subpanels. So i may be misunderstanding the intent here. try class General_sett_subpanel(bpy.types.Panel): bl_idname = "SUB_PT_Gensett" bl_label = "General Settings" bl_space_type = "VIEW_3D" bl_region_type = "UI" bl_parent_id = "...


0

There are a few things to know, some of which are Python specific. Firstly, text probably won't exist anymore by the time you call execute() because text is merely a local variable, not a class member. To make it a class member, simply declare it as self.text = bpy.props.StringProperty(name="Name", default=""). If you're familiar with C++ or C#, self is ...


0

Turns out I just wasn't accessing the right object type. The movie clip node contains a clip parameter, which contains the data I needed. The frame end range can then be set like this: frameCount = bpy.data.scenes['Scene'].node_tree.nodes["MovieClip"].clip.frame_duration bpy.context.scene.frame_end = frameCount Full specification of the MovieClip datatype ...


0

The solution was quite simple, though not found answer on the Internet. import bpy bpy.data.images.load("D:/badge/temp/1.png", check_existing=True) mat = bpy.context.view_layer.objects.active.active_material tex = bpy.data.images.get('1.png') image_node = mat.node_tree.nodes["Image Texture"] image_node.image = tex At the same time, the desired node must be ...


1

import bpy from bpy.props import StringProperty, IntProperty, BoolProperty from bpy.types import ( Operator, GizmoGroup, ) # CUTOM PANEL IN PROPERTIES OUTPUT PANEL class CUSTOM_PT_menupanel(bpy.types.Panel): """Creates a Panel in the Output Properties of the properties editor""" bl_label = "Test" bl_idname = "SCENE_PT_layout" ...


0

OKAY ! So finally, after playing around with various scripts found on this website, assembling them, we found out we had taken it the wrong way, as blender workflow is different from maya. The material is applied after in maya, and before in blender. The solution is a simple script that asks objects from the scene to be applied a premade material. In maya, ...


2

Only use bpy.types.PropertyGroup for the registered class type. The property group and bpy.props properties are wired up as properties through the "rna voodoo magic" internally with blender when registered. Similarly as often seen with operators and panels, only give the registered class the type you are registering. For want of a more technical ...


3

Script of Witold Jaworski generates intersection of two selected meshes. Select two objects Press W (in 2.79), for 2.8x search Intersection Press P (Separate) > Selected Version for 2.79 Version for 2.8x For more detailed instructions visit his site. For future broken links – blend with script for version 2.79 For complex mesh like terrain is better ...


1

The function recalculate_text which you're having run every frame, is also setup to create a new object every time. Pull the object creation out of the def function. Check this out. import bpy scene = bpy.context.scene font_curve = bpy.data.curves.new(type="FONT",name="Font Curve") font_curve.body = 'Current Frame: ' + str(scene.frame_current) font_obj =...


0

Just a reminder of Bisect tool in Blender 2.8x (as native tool) that can do similar kind of job (cut by plane). Duplicate your object Search Bisect Enable Clear Inner and Clear Outer in tool properties in left-down corner Adjust cut position (can be set numerically in properties too) Done For horizontal cut set Plane Normal values to 0/0/1 and move only ...


1

wip Answer Via the Particle Edit Mode it is possible to subdivide single Hairs, therefore it should be possible to recreate this via python. One Constraint here is that the hair system is locked after editing it. You have to tweak it a bit, but the basics are here, namely doing it via the depsgraph: devtalk.blender.org/t/manipulating-particles-in-python/...


1

I solved this by using winsound. As it is for windows, it is not available to all blender user. https://docs.python.org/2/library/winsound.html#module-winsound I do a distinctive beep like this. I don't have to search for an suitable mp3. import winsound frequency = 2500 # Set Frequency To 2500 Hertz duration = 1000 # Set Duration To 1000 ms == 1 ...


1

Maybe you can consider starting with a new blend file (empty), then you pass to addon the source blend file. The addon can link the scene/collection from the source file, render and remove linked. Then repeat the process. Or, to follow your initial setup, you could put the whole scene in a "root" collection and then call bpy.ops.outliner.collection_delete (...


3

Example of assigning custom normals based on vertex selection. It's just a slight modification of the code given in this answer and assigns a custom vector to vertices in selection. Run the script in Object Mode and enable show_split_normal property in Edit Mode: import bpy context = bpy.context ob = context.object me = ob.data me.use_auto_smooth = True ...


5

Bmesh bisect plane. Here is a script that bisects one mesh with a plane and creates a new mesh object with the intersecting edges. In test example Grid is a 100 x 100 grid displaced with a cloud texture via a modifier (not applied). Plane is a single face default plane, named "Plane". Move plane to desired location and run script. New object "Bisect" has ...


1

import bpy context = bpy.context scene = context.scene active_camera = scene.camera if active_camera: print(active_camera.name) else: print("No Active Camera Selected")


0

Not sure what you want the name to display. If you print the object of camera, python will treat it as an object and print the structure by default. You can retrieve the name(class <str>) properties inside the camera object, which is the name of the object in outliner panel. print(activecamera.name) should display the desired thing. In 1 line: ...


0

Okay I found an alternative situation. I wanted to make a dropdown menu that added all armature objects in the loaded file. My idea was for it to update every time an object is imported. I was able to achieve this based on dynamic list examples of this website: https://elfnor.com/drop-down-and-button-select-menus-for-blender-operator-add-ons.html#dynamic-...


6

These are blender properties https://docs.blender.org/api/current/bpy.props.html In defining, for example a float type property bpy.props.FloatProperty can set its hard and soft minimums and maximums. A soft setting is the first range you force the property past up till the hard setting. As an example using the Principled BSDF node >>> ...


3

Using API methods takes away the need for context Inserting a keyframe on a node, adds an fcurve to the scene nodetree action. From the datapath, find the fcurve and add a new modifier of type 'NOISE' and set the appropriate settings. For example def execute(self, context): sc = context.scene tree = sc.node_tree gamma_node = tree.nodes.new(...


1

Link to collection bpy.context.collection.objects.link(stuck) or for < 2.8 link to scene bpy.context.scene.objects.link(stuck)


2

Pass a globals dict to exec Not sure of the reason why it doesn't work.. only have some inklings. However can populate a dictionary and pass as globals to the exec function. if event.type == 'TIMER': mydict = {"a":4} myglobals = {"testDict": eval(json.dumps(mydict)), "mylist": ["a","b","c"] } ...


1

Looking at the blender sources, the colors seem to get rounded. static void rna_MeshLoopColor_color_set(PointerRNA *ptr, const float *values) { MLoopCol *mlcol = (MLoopCol *)ptr->data; mlcol->r = round_fl_to_uchar_clamp(values[0] * 255.0f); mlcol->g = round_fl_to_uchar_clamp(values[1] * 255.0f); mlcol->b = round_fl_to_uchar_clamp(values[...


1

Cursor location is global The location of the cursor can be considered as "global coordinates". The cursor has no parent. When the cursor location is set to zero, it sits at the scene origin. An object's location is relative to its parent. Its "global" or "world" transforms can be gleaned from obj.matrix_world. To get an object in the scene by name ...


0

I would recommend writing a little function that copies the cursor's location and sets it for the active object. import bpy def snap_active_to_cursor(obj: bpy.types.Object, copy_rotation=False): cursor = bpy.context.scene.cursor active_object = bpy.context.view_layer.objects.active active_object.location = cursor.location if copy_rotation: ...


Top 50 recent answers are included