How to remove all only rotation keyframes from current action with Python? How to remove only rotation keyframes from current action with Python? Or location keyframes? Or scale? Is it passible?

Using FCurve.remove

The curve, as shown in graph editor,  with keyframe points for each keyframe value pair is an fcurve.  Removing an fcurve Will remove all keyframes for that FCurve.data_path, Fcurve.array_index pair

Similarly to this related (possible duplicate) question.  Example script removes all Location, Rotation and Scale fcurves from an action.  It tests the FCurve.data_path against the keyframe type list ["location", "rotation", "scale"].  Note "rotation" will match "rotation_euler" or "rotation_quaternion" etc, which will be the actual datapath (as there is no Object.rotation).

Avoided using the FCurves.find method with a list comprehension, and used pop to avoid possibly referencing a removed fcurve later.

import bpy

context = bpy.context
ob = context.object
ad = ob.animation_data

if ad:
    action = ad.action
    if action:
        remove_types = ["location", "scale", "rotation"]
        # select all that have datapath above
        fcurves = [fc for fc in action.fcurves
                for type in remove_types
                if fc.data_path.startswith(type)
                ]
        # remove fcurves
        while(fcurves):
            fc = fcurves.pop()
            action.fcurves.remove(fc)

To remove only y axis Loc, Rot and Scale also test for the Fcurve.array_index property which is 0, 1, 2 for x, y, z respectively.

        fcurves = [fc for fc in action.fcurves
                for type in remove_types
                if fc.data_path.startswith(type)
                and fc.array_index == 1
                ]


Unable to move a mirrored part of an object Can anyone assist me in getting a part of a mirrored object to move without overlapping into itself?

In 3DSMax it consisted of changing the view from global to local and then the whole thing moved instead of overlapping. In Blender I've tried all the local views and they aren't working.

Below is what is happening -

A mesh data is fed through the modifier stack from top to bottom, and what's accessible through Edit mode is only the original data, not the result of the modifier stack. Modification of a modifier's output is only possible by applying it first, or through another modifier lower down the stack.

In your example, vertices generated on-the-fly by Mirror modifier can't be moved past the modifier's mirror axis, even if Clipping is disabled and the modifier is applied to editing cage. That's because it's not in the original mesh data, and its position is not stored independently but calculated by the modifier:

Modifying those vertices manually is possible after applying it, because those new vertices are now available in the original mesh data. Other modifier can also modify them if placed below the Mirror modifier, for example an Armature modifier (note the modifier stack):

or a Lattice modifier:


How to show the normal of a face How do you show the normal of a face in Blender 2.8.

It used to be in the properties panel (n to show) but now where has it gone?

Figured it out

Expand Overlays (top-right)
Tick Face Orientation

Now blue faces are one way (presume forward) and red are other (presume backwards)


Animation nodes for geometry line art? I am trying to see if Animation Nodes can be used to create geometry line art, similar to the various Line Set options in Freestyle. I am not very familiar with animation nodes, so I don't know if the functionality is there, or if it is feasible. So I'm not looking for a detailed explanation, just a simple yes or no of it it works, and perhaps a rough explanation of where to start.

Specifically, here's what it would need to be able to do:

1) Create a spline/curve/vertex strand on marked edges, similar to freestyle's Edge Mark features

2) Create spline/curve/vertex strand on edges based on face angles, similar to Crease.

3) Create them based on contour/external contour, probably based on normal facing on external faces of the mesh.

4) Merge the above together and add modifiers, materials, etc.

Are any of these possible?

UPDATE: Picture examples as requested.

1 and 2 were made as noted, by manually duplicating a selection, separating the object, and converting to a curve. 3 was made by copying the object, fattening it, and moving it back behind the first object. This works for the example of the look, but what I really want to do is draw an outline curve around it based on the view angle.

FreeStyle Edge Mark

Animation Nodes have a node Splines From Edges that takes a list of edges and vertices an returns splines that represents those edges. All we have to do is filter the edges by whether they are marked as freestyle or not. The blender API provide access to this data through the edge.use_freestyle_mark where it returns True if the edge is marked as a freestyle and False otherwise. To generate a boolean list of this property, we can use such list comprehension:

[e.use_freestyle_mark for e in object.data.edges]

Animation Nodes have a node Mask List which returns a filtered version of the input list if for each element its corresponding element in the input boolean List is True. So we can use the Mask List node to filter our edges based on the boolean list we generated before using such a node tree:

Edge Crease

The same workflow can be used, however, the boolean list used in filtering will change to be based on an angle threshold. Let us define the angle of the edge as the angle between the normals of the two faces the edge is part of, that, of course, fails for boundary edge that is part of only a single polygon. The problem reduces to finding the indices of the two polygons that each edge is part of. The internal structure of meshes in Blender stores loops which are vertices of polygons, something that you may remember from our study in this answer. A loop also corresponds to an edge that is part of the polygon as well as share the vertex that the loop represents in the polygon, you can study this from the Design Document of the Bmesh structure. So, loops can be used to identify which edges are in each polygon, but we want the inverse of that, we want a function that takes the edge and returns the polygons, this is something that we can solve by using a simple look up table. We can get the indices of the loops through polygon.loop_indices and we can get the index of the loop edge through loop.edge_index, you can study those form the API.The implementation is nested and not direct, so take your time to understand it.

We crate a list of n empty lists where n is the number of edges in the mesh, this can be done by the list comprehension [[] for _ in range(n)]. We will append the index of the polygon to those lists indicating that the polygon is composed of that edge. We will create two loops, the first loop iterates over the polygons and gets the indices of the loops it contains through polygon.loop_indices, that loop in turn hands the indices to another loop which gets the small initially empty list at each of the loop indices and append the polygon index to it, set the new list to the generic list and reassign the generic list. Notice that the polygon index is the loop (iterator) index of the upper loop. Also notice that to get the list after we appended it, we have to enable Output option for the input list:

Now that we have computed the look up table, we can loop over it, get the polygons, compute the angle between them using the dot product or the axis quaternion, if the angle is smaller than a threshold, append True and false otherwise, note that we have to check of the edge is a boundary or not as well. the implementation is simple, if the list contains two elements (It is not boundary) AND if the dot product between the two polygon normals at the two list indices is less than cosine some angle, return True and false otherwise:

Which if we used in filtering the edges, yields:

Blend file for study and practice:

Layering Filters

Layering filters is as easy as combing the boolean lists using what ever logic you want to use, for instance, if I want to use the edge mark OR the Crease, we can add the two boolean lists (Addition is OR in boolean algebra):

Sky is the limit when it comes to Animation Nodes.

External Contour

As for External Contour, a screen space processing might be your best option. For instance, construct a signed distance field in screen space and them march a spline starting from a known edges point, or use marching squares algorithm to polygonize it, project point on the surface and convert it into a spline. I don't have enough time to research the topic further, so i will leave it to you.


How to shrink curve thickness I have bunch of curve with similar thickness with different color. I want to shrink or make the thickness of the tube low. Manually doing makes a lot of time. Any trick or quick way to make the tube thickness smaller. Any suggestion or help. Thanks

To change a property of multiple objects simultaneously, press ⎇ Alt will adjusting it.

⎇ Alt LMB drag will change the property of all objects relative
⎇ Alt LMB click, entering a value and pressing ⏎ Enter will change the property to the same absolute value for all objects


Leaves not appearing when making a particle system of trees I'm following the forest tutorial by CG Geek(this one: https://www.youtube.com/watch?v=72LPW4S8bns). i want to put the trees over the landscape, but when i choose the collection to display, the laeves re not coming with the tree(i think because they are also a collection on the tree).
The tree looks like this normaly:

but in the collection instance they look like this:

how do i make the leaves appear?

Without knowing your file I would say you're already on the right path... I guess the leaves are a particle system of the tree, not a collection? The problem is, the trees you are using in the particle system for the landscape cannot have their own particle system to be displayed - you have to convert and apply it. CG Geek doesn't make this really clear in his tutorial, he's just mentioning when creating the dead tree without leaves, that this one has not yet its particle system applied (implying that it is applied on the other tree).
So, what you have to do:

Go to Modifiers section of the tree.
On the Particle System modifier, hit Convert. This creates single meshes from the leaves so you have a bunch of new objects.

Now you can remove the Particle System modifier by applying it or deleting the Particle System.
Select all leaves objects via Box Select B and the tree object at last with Shift+LMB so that it's highlighted as active object (brighter outline than the leaves).
Hit J to join all meshes into one object.

Now your trees distributed over the landscape should have leaves.


How to get sculpting to stop mirroring? I have a model I am trying to sculpt on and the only modifier I have is multi-res. I am trying to sculpt, and when I do it keeps mirroring. In the picture, you see two strokes, but I only want one stroke.

In the tool panel, T if it is not open find Symmetry/ Lock and disable mirror there. It is directly under Dynotopo.


Center of gravity for an object How can I reset or place the center of gravity for an active ridged body object? I am having an issue where the center of gravity for an object is placed far too high for accurate physics.

The center of gravity is placed at the object origin. To put move the object origin, press ⎈ Ctrl⇧ Shift⎇ AltC.

Center of Mass will put the origin (center of gravity) at the center of mass, assuming a uniform density.

3D cursor will put the origin at the 3D cursor, allowing for more customized setups.


Camera render overwrites material color I have placed a camera with the following world properties

The scene looks as following

Now when I try to render, all I get is

And that is of course what I do not want. I simply want the colors to appear as they are given and that the blue is merely the background (such that I can easily remove it in Photoshop for a transparent image). I've also tried without placing a spot light but to no avail.

Blue background is not just a paper that is blue. It basically means that the scene is filled with blue light thus your object seems blue.
You can set a transparent background from Render Properties panel under Film from the Transparent checkbox.


In Python is it possible to change the background color of a property ui? I want to be able to change the background color of a property ui.

At the moment it does:

Green = has an Fcurve
Yellow = has a keyframe
Purple = has a Driver

I want to to be able to change the color of the background depending my own conditions. IE I don't want to change the color theme, I want to add a new color and define its condition.

For Example:
If a property is above 500 it changes to red!

Is this possible?

The colors are controlled by C code, you can't set it to arbitrary colors with python.

However, you can change the background to alert color (=red) by setting the alert property on the layout block:

import bpy

class HelloWorldPanel(bpy.types.Panel):
    """Creates a Panel in the Object properties window"""
    bl_label = "Hello World Panel"
    bl_idname = "OBJECT_PT_hello"
    bl_space_type = 'PROPERTIES'
    bl_region_type = 'WINDOW'
    bl_context = "object"

    def draw(self, context):
        layout = self.layout

        obj = context.object
        if obj is None: return

        col = layout.column()
        col.alert = True
        col.label("Alert state NOT supported:")

        box = col.box()
        box.label("Labels", icon="X")
        box.menu("VIEW3D_MT_object", text="Menus")
        box.prop(obj, "layers", text="Not all properties")

        col.separator()
        col.label("Supported:")
        box = col.box()
        box.operator("mesh.primitive_cube_add", text="Operators (Buttons)")
        box.prop(obj, "name", text="Many properties")
        box.prop(obj, "location", index=1, text="Vector props: only single")
        box.label("also with emboss=False, but...")
        box.prop(obj, "name", text="read-only?!", emboss=False)
        box.label("template_list() sort of (needs materials):")
        box.template_list("UI_UL_list", "foobar", obj.data, "materials", obj, "active_material_index")

def register():
    bpy.utils.register_class(HelloWorldPanel)

def unregister():
    bpy.utils.unregister_class(HelloWorldPanel)

if __name__ == "__main__":
    register()

Run the above code in Text Editor and check out the Object tab.


cloth draped on a mirrored mesh: how to do it properly? I had an interesting experience draping cloth over a mesh.  The mesh was a biped, x axis mirrored.  The mesh was given the Collision attribute, however... the cloth draped correctly over the "master" side of the mirrored mesh, but fell right through the other (mirrored) side.  In the end I had to Apply the Mirror modifier to get the cloth to drape properly, but this seemed to mess up the rigify armature and handles for the biped, so I was rather discouraged.  Is there a Right Way to create a biped with rigify and put clothing on it without losing the pose capability?  really weird and bad things happened when I tried to pose it after Applying the Mirror mod :-)

I'm getting the hang of (primitive) clothing but am a long ways yet from being able to clothe an animated biped, even in a simple cloak.

Check your modifier stack. The collision has to be applied after the mirror (and after the armature if you want to move it).

Use the little arrows on your modifier to change its position in the stack.


No vertext but looks like there is I have an invisible vertex or something wierd and I dont know what it is.
I added an image of what happened:

One arrow shows a bend where there is no vertex - How?
The other points to a darker color around a vertex, which reminded me of normals but I dont realy know what it is..?
Anyone knows what this is and how to fix it?
Thank you!
Here is alink to download the file: https://www.mediafire.com/file/6jmqdfvvtrfman0/Test.blend/file

It might be related to this issue
Limited Dissolve leaves unused Vertices
I find it easier to dissolve edges - as it will delete the vertices along with it
As a solution you can probably use the knife tool to make a new single edge and use dissolve edges on the other two edges to remove them.
the colouration is most likely from the amount of connections (6) to that vertex. as you have another edge pulling at it. wire mode help to visualise or showing all edges on mesh in object property settings


From Blender to UE4 : armature bone I'm exporting my file with a mesh and its relative rig from blender to ue4 using FBX. After the export in ue4 it appears that my skeleton has one more bone, called Armature (it's the highest in hierarchy, above root). When i export my file i use these preferences

I have already check this question
Blender ascii fbx adds a Armature bone before root bone UE4
but i can't still remove that additional bone from my skeleton in ue4. Is it a problem of blender? Is there a solution?

There are a lot of "fixes" to this problem. For me, this one do the trick Blender (2.83, UE 4.20):

As things stand right now, the importer for fbx is effectively patched (a nice word for hacked) to allow as exception for Blender made fbx files if the name of the root node is 'Armature'.

Source: https://forums.unrealengine.com/deve...blender-export


Unable to rotate multiple spheres in a circular pattern Greeting, am totally new to blender and I was trying to do a animation by circling the spheres along the Z axis.While rotating it shows correctly however after inserting the LocRot keyframe, the animation turns out as blow. Was wondering what I was doing wrong and what the solution to this could be?

Thankyou !!

The way animation with key frames works is that only specified data values (e.g., location and rotation) AT the key frames are remembered, not how they got there.

If you focus on just one of your spheres -- say the one at the top left -- at the first key frame, it's in the top left position with a particular orientation.  At the second key frame, it's in the bottom right position having been rotated 180 degrees.  The way Blender animates between these two keyframes is to, roughly, linearly interpolate between those locations and rotations, so it moves the sphere in a straight line from the top left to the bottom right, and it smoothly rotates it 180 degrees around its axis while doing so.  It does this separately for all 10 spheres, so they look like they all just move independently to their new positions along separate straight lines, ruining your animation.

There are two approaches to fixing this.

First, you can add more key frames.  If you added key frames each rotated an additional 30 degrees for a total of a 180 degree rotation of your arrangement, then Blender would interpolate between those states and show you a pretty smooth rotation.  This is probably the easiest method to incorporate into your current animation.  It's straightforward and flexible, though a little tedious.

Second, you can change the structure of your arrangement so Blender's method of interpolating object data between two key frames leads to the correct result.  Hypothetically, if you selected all ten of your spheres and typed Ctrl-J to join them into a single mesh, and then set the origin to the center, then they would rotate as a unit based only on the rotation of that new, single object.  If you had two key frames, one with a rotation of 0 and another with a rotation of 180, then a smooth linear interpolation between those two rotations would give an animation that smoothly rotates the entire arrangement.  (There would still be an ambiguity -- Blender wouldn't know if you wanted to rotate clockwise or counterclockwise, so you'd probably want to add a keyframe at the halfway point to break the tie.)

Now, this method wouldn't work for you.  Once the spheres had been joined into a single mesh, you couldn't easy animate them independently any more, so it would ruin the rest of your animation.

There are ways around those, though they may be a little advanced.  You could parent the ten spheres to an invisible rotation object that only gets used when they need to rotate together.  Or, you could keep two copies of your objects around -- one with ten separate spheres, and another joined mesh for rotations, and then swap them out (make one invisible and the other visible) between frames as needed.  I don't have a lot of experience with animation in Blender, so maybe someone has some better ideas.

In the meantime, extra key frames are probably the easiest way to go.


How to merge two hand perspectives? Using 123D catch (creates 3d models from picures) I created two mesh obj of an hand in dorsal perspective (palm down), and another in the palmar perspective (palm up). I'm trying to come up with procedure to merge them together and create a whole hand model.

I had a look at stiching UVs but it seems that I need the same number of vertices in both hands meshes. Bolean operations seem a reasonable option but the result requires some further modelling I don't have much experience.

Any insights to this project would be much appreciated. E.g. Which prodecure is best bolean vs. stiching, how to change vertices at boundary loop to the same number in both meshes. Or any other aspect for this. Scripting advice for these would also bee nice. I.e. what kind treatment do I need to give meshes to create a script for this.

Kind Regards,
Miguel

edit:picture of the hands added if more clarification needed let me know. This is a rough model based on a old picture I have of my own hands

I would just go for some retopo scheme.  If you overlap and align them both you can then build up a new mesh using conventional methods for generating clean meshes from ones that are not so clean.

The problem you are facing is very similar to the issues facing Dynatopo sculpts so the solutions you have are pretty much the same as well.

Once they are aligned properly with each other, you can select them both and merge them into one object, Ctrl-J.  Next you can use the CG Cookie Contours tool to rough out most of the new mesh that will be based on these two as one base.

There are also other methods that you can employ without using Contours.  You can just start with a point in edit mode and extrude it out along the surface of the scanned models and by using the Magnet tool you can keep the points moving along the surface of the base mesh.

Also, if you model a low-poly, rough hand shaped model, you can use the Shrink Wrap modifier to project the new mesh onto the scanned models.


Blender use texture on cube side I am here in blender trying to Paint this selected side with the texture i made. I am completely new to this. Can someone explain to me how to do this ? I want to color to be saved with the .fbx, not separately or anything complicated. Just paint this side with this texture. Please guide me.

I have selected texture003 on the left panel. What else i am supposed to do ? I am lost here.

I am no specialist for exporting other formats (like .fbx), but in general it's like this:

To add a texture only to the side you will need a second material.

Click the material tab and click + to add a new material.
Then click + New.

Get into Edit-Mode and select the face you want to apply the material to.
With it selected click Assign under the materials.

This will assign the new Material only to that specific face.

Keep the new material selected in the material tab.
Then click the texture tab and add your texture to it by clicking + New, selecting Image or Movie(should be default) and sroll down to Image and Open your Image Texture.

Positioning of the texture can be performed by the options below the Image part.


Painting multiple textures at once I'm curious whether it's possible or not to clone paint on multiple texture slots at once? I want my clone painting to affect all the maps I have on an object. If that's not possible is it possible to copy clone strokes to the other maps somehow?
Thanks,
Mitchell

if u use the same picture on both materials its supposed to work like this:
and dont forget to set the uvs correctly :)


How to add trailing light effect to finger tips? (as advised I deleted my previous question)

I would like to add a light streak effect to the finger tips of this animated dancer.

I am using a particle emitter that is assigned to a vertex group (finger tips) but I am unable to get them to give me a streak effect.

So far I can only get this:

and I would like something closer to this: (I'd be delighted with something far more simple)

I've seen tutorials on line but they were in Blender Render and not Cycles. Is there a way to get the streak effect with a particle emitter in cycles?

You can achieve this by using particles to trace out the path of the motion and converting each particle system into a Curve object. The curves can then be used to draw the trails and animated using keyframes to match the motion.

Start by adding particle systems to the mesh. It's important to have a separate particle system for each 'trail'. The order the particles are emitted will control the order of the points in that trail.

There are two ways of achieving this.

Create a mesh with a single vertex and add a particle system. This can then be duplicated, positioned, and parented to the moving mesh so that it follows the motion. You can create as many of these 'trace' objects as are required.
Emit the particles directly from the mesh being traced. It's important that each particle system emits from a single vertex - so use Vertex Groups to limit the emission for each particle system, adding a particle system for each.

Ensure the particle systems are set to emit the particles with no initial velocity and that the relevant Field Weights are set to zero so they are not affected by any forces present. This should result in the particles 'hanging' at the point they are emitted.

Once you have the emitted particles, open a Text Editor window and paste the following python code :

import bpy

def particles_to_path(objName, tracks=1, particleSystem=0, curveResolution=0, bevelDepth=0.1):

    object = bpy.context.scene.objects[objName]

    particles = object.particle_systems[particleSystem].particles

    trackNo = 0
    trackPoint = 0
    curves = []
    splines = []

    for p in particles:
        if trackPoint == 0:
            # Create new track
            curve = bpy.data.curves.new('particlePath', type='CURVE')
            curve.dimensions = '3D'
            curve.resolution_u = curveResolution
            curve.bevel_depth = bevelDepth
            spline = curve.splines.new('NURBS')
            curves.append(curve)
            splines.append(spline)

            #set first point
            print(spline.points[0])
            print(spline.points[0].co)
            spline.points[0].co = (p.location[0], p.location[1], p.location[2],1)
        else:
            # Add point
            splines[trackNo].points.add()
            splines[trackNo].points[trackPoint].co = (p.location[0], p.location[1], p.location[2],1)

        trackNo += 1

        if trackNo >= tracks:
            trackNo = 0
            trackPoint += 1

    # deselect all
    for curve in curves:
        curveObject = bpy.data.objects.new('particlePath', curve)
        bpy.context.scene.objects.link(curveObject)
        #...select it?

particles_to_path('Trace',particleSystem=0, curveResolution=8)

The code defines a function (particles_to_path) which will use the particles emitted by a particle system on an object to create a Curve object. Note the last line in the script which invokes the function, specifying the object 'Trace'. This will use the first particle system on the 'Trace' object and will create a Curve. To invoke the function on multiple particle systems, simply duplicate the last line and change each as appropriate.

For example, for multiple objects named 'Trace', 'Trace.001', 'Trace.002', 'Trace.003', etc. use the following lines :

particles_to_path('Trace',particleSystem=0, curveResolution=8)
particles_to_path('Trace.001',particleSystem=0, curveResolution=8)
particles_to_path('Trace.002',particleSystem=0, curveResolution=8)
particles_to_path('Trace.003',particleSystem=0, curveResolution=8)

If you have multiple particle systems on the same object, each emitting from a single vertex then you can use the 'particleSystem' parameter to indicate which particle system to use (0 = the first one, 1 = the second one, 2 = the third one, etc.) :

particles_to_path('myMesh',particleSystem=0, curveResolution=8)
particles_to_path('myMesh',particleSystem=1, curveResolution=8)
particles_to_path('myMesh',particleSystem=2, curveResolution=8)
particles_to_path('myMesh',particleSystem=3, curveResolution=8)
particles_to_path('myMesh',particleSystem=4, curveResolution=8)

Once you have generated the curves, simply adjust the curve properties to generate the required trails. For example, set Resolution and Fill in the Shape settings to generate a curved shape...

...and use the Geometry Bevel settings to adjust the 'trail' - setting Start and End to position it along the curve :

Note that the Taper Object can be used to specify an additional curve object which defines the shape of the bevel along the curve (with Map Taper enabled to taper the bevel along the Start-End interval rather than the whole curve).

Carefully keyframing the Start and End will allow the trail to be animating. Ensure to set the Interpolation of the animation curves to Linear so it matches the motion of the particle emitting mesh.

For the material, you can use a combination of Emission and Scatter on the Volume. This will allow the trails to be partially opaque while still emitting light. Mixing in a Transparent shader based on the light path allows them to be hidden from all but the camera (so they don't reflect off of the surfaces). Including variation based on the Random object info provides automatic variation for each trail (you could assign individual materials manually in you prefer more control).

This can produce the following result :

Blend file :

Applying this to the example 'dancer' mesh can produce the following effect :

EDIT: I have since packaged the above script as an add-on as part of this answer, available from here. This makes it much simpler to run and avoids the need to create and edit a custom script.


File format with per face colors I am trying to export a mesh from some scientific experiment (in MATLAB) and load it in blender for rendering. I'd like to assign per-face colors (as opposed to per-vertex with interpolation over faces), and am willing to use any suggested solution (i.e., any file format, some trick with UV coordinates etc.).

What is the simplest way to go with this?

Short answer:

.x3d, an xml based format. Color can be either specified

per vertex of face
per face ( colorPerVertex='false' )

When imported via Blender's importer either method get converted to a per vertex  per face scheme for the vertex_color layer.
Stanford .PLY format. (vertex colours are shared over all faces that use the vertex, only way to get color-per-face with this format is  wasteful duplication of each vertex)

or

homegrown code: essentially this code. all you need to write is the part where you map the current polygon.index to a color, so all vertices of that loop are assigned the same colour.

Take a cube.

import bpy

indexed_colors = [
    (1,0,0), (1,1,0), (1,0,1),
    (0,0,1), (0,1,1), (0,1,0)]

obj = bpy.data.objects['Cube']
mesh = obj.data

# you probably know how to create the color layer..
if not mesh.vertex_colors:
    # creates one 'Col' by default
    obj.data.vertex_colors.new()

color_layer = mesh.vertex_colors['Col']

i = 0
for poly in mesh.polygons:
    # print(poly.loop_indices)
    color = indexed_colors[poly.index]
    for idx in poly.loop_indices:
        # loop = mesh.loops[idx]
        # v = loop.vertex_index
        color_layer.data[i].color = color[:3]
        i +=1

More elaboration on mesh generation is here: How to create a mesh programmatically, without bmesh?

from_pydata (docs link) :

mesh = bpy.data.meshes.new("mesh_name")
mesh.from_pydata(vertices=[], edges=[], faces=[])
mesh.update()

obj = bpy.data.objects.new("obj_name", mesh)

scene = bpy.context.scene
scene.objects.link(obj)

Showing vertex colors

For both methods you still need to configure the Object's material once imported, if you want it to show the vertex_color layer. This configuration is relatively painless but slightly different depending on which render engine you intend to use.

For Cycles you use a node based material, shown here

For Blender's Internal renderer the process is covered here


How to make grass respond to an object hitting them How can i make the grass bend when this cube hits it?

Here's the picture:

Final:

Overview:

Whole process is very easy. You will only need to make your grass object as Cloth or Soft Body (with Weight Paint) then Convert Particle System to mesh and delete Particle Emitter as it will not longer be needed. Then add to your Cube Collision.

First of all you will need to choose if you want to use Cloth or Soft Body. Quick test shows me that Cloth simulation is fairly faster, but Soft Body will give you probably more options, as Plastics, Edge Stiffness and such.

Secondly I don't know why (and maybe someone can correct me) when your object is in Particle System simulation works, but Pinning/Soft Body Goal won't. Maybe it's a bug or maybe there is an explanation.

  Note: Below steps could vary from your scene setup so don't take them
  as granted. I will point out most important settings and you could
  tweak them for your needs.

Steps:

Grass strand.

You will need to Weight Paint your grass strand. Red is stiff, green is... less stiff. You can experiment with this as you like to make grass really soft or hard.
Add to your object Cloth Simulation. I have used settings as you can see on the image. Most important things here are:

Mass - it should be really low, higher will make grass to lay on the ground,
Pinning - from Weight Paint, it will keep grass strong at the bottom and weak at the top, or not if you painted it differently,
Velocity - how fast grass will return to base position,
Cloth Collision - check also Self Collision, there are lots of them so it will make simulation more realistic.

Particle Emitter.

Nothing special here, only after setting your grass go to Modifier Tab and Convert Particles then delete Particle Emitter.

Blend file:


How to bend only selected vertices? I have the following problem which I do not know how to resolve by using blender.

I want to bend a bit of an object but I don't know how to achieve this result by just selecting few faces and not the entire object.

Below there is an image to explain myself better:

How can I do this?
Also, is it posible bending just by using Y/X axis blocking the Z axis ?

Thanks

The Bend Tool can be used to do what you are trying to achieve.  Select the components  you want to bend, position the 3D cursor at the point where the bend will pivot then press ShiftW


Is there a way to restore the cycles render settings to default? I need to start afresh. I'm having a problem with alpha transparency and volume scatter.

If I understand your question, I don't think there is.

You can load a .blend file without the saved UI, but this doesn't include settings in the render property panel (which is what I think you are getting at). These cannot (as far as I know) be divorced from the other data in the file.

You would probably need to create a new empty file (which should load default settings for everything), and then use File->Append to import the objects from your other .blend file into that new file.


When rendering, Cycles and Eevee only renders some materials I was following along with a tutorial and finally finished my first model, when I try to render however it only renders some of the materials.
The render I get.

Screenshot of the materials that go missing.

Sword.blend1

I’m not sure the materials go missing. Are you talking about what look like reflections of the surroundings on the sword? I have repeatedly thought something was wrong with my metallic materials when that happened in material preview but disappeared in render, but it turns out that’s just because the world background in the material preview is automatically an HDR texture, and in cycles or EEVEE render it defaults to flat gray which makes no reflections.
Just change the World background to something interesting (an environment texture from blender’s own data files works great) and metallic materials should look much better .
As for the glow effect, this is likely because you enabled bloom while using EEVEE, but then switched to cycles render. The bloom will still appear in material preview. You can create a bloom like effect for cycles using the glare node in the compositor .


When I use the "Boolean" modifier it doesn´t make new faces I am new to Blender and I´ve decided to watch Blender Guru´s video on how to make an anvil. I´ve come to the second part where he uses a boolean modifier and
that´s where my problem appeared. When I use the boolean modifier to curve a cylinder shape into the anvil it also deletes the faces which in the video it does not. I think I followed every step so I can´t really tell where I´ve made the mistake but I can´t find a solution.

Here´s a link to the video: https://www.youtube.com/watch?v=WxMwa0njGSM

And a screenshot:

Thanks for help.

Just found a solution.. Instead of selecting BMesh I selected carve and as operation I chose union. Works fine.


OSL Script node: Slider with value range between 0 and 1 (like Fac) I am currently writing my own shader using a Scriptnode in Blender, and I cannot figure out how to limit the range of a slider between 0 and 1.

I basically want something like the "Fac" slider in a Mix Shader, but whatever I try in my custom shader, I always can enter values < 0 or > 1 when I use my script node in the node editor.
(I tried to clamp the value, and to do annotations for min and max as in the OSL doc.)

Does anyone know how to limit the input range of a float slider to 0...1 ?

March 14 2016
The markup enclosed in the [[  ]] is known as "suggested metadata", it's shown in the OSL specifications pdf, something like this:
surface wood
            [[ string help = "Realistic wood shader" ]]
    (
        float Kd = 0.5
            [[ string help = "Diffuse reflectivity",
                float min = 0, float max = 1 ]] ,
        color woodcolor = color (.7, .5, .3)
            [[ string help = "Base color of the wood" ]],
        color ringcolor = 0.25 * woodcolor
            [[ string help = "Color of the dark rings" ]],
        string texturename = "wood.tx"
            [[ string help = "Texture map for the grain",
                string widget = "filename" ]],
        int pattern = 0
            [[ string widget = "mapper",
                string options = "oak:0|elm:1|walnut:2" ]]
    )

is not currently supported, it gets ignored.
Until someone implements the parsing of suggested metadata the best you can do is implement the clamp yourself in your OSL code. The UI would still allow you to input values outside that range, therefore cosmetically this isn't a good solution, but if you make your code  deal with unwanted extreme values appropriately you'll still get stuff done.
Later when metadata parsing is implemented it's easy enough to strip away your clamping code.

related: Can a Script node using OSL have a checkbox?


Avoid curve modifier distortion when making a chain I am aware that this has already been asked here, but in this case I am using a chain, which has been made using tori offset by 90° each time using an empty object.

However, when I do this, you can see that the chain links are distorted:

One idea I had for a solution was making the array come from two linked links, so that no rotation was needed, but this made it look a lot worse when only every two links could rotate.

I tried using the bone method shown in the link above, but this did not allow for duplicates.

How can I make it so that each link retains its original proportions whilst having the 90° offset each time?

By the way, having it going in a circle wouldn't work as the shape I intend to wrap it around is irregular.

Also, I'm quite new to Blender so I might be missing something obvious.

I have solved it!
Using this video, I made the vertical links and then duplicated and rotated it to make the horizontal links and set the right number of them by changing the frames in the data tab of properties of the bezier. The links used DupliFrames to do this with 'speed' unticked.

Here I'm using a bezier circle (although the concept remains the same).


Where can I find Blender 32 bit version? On the blender.org Download page it only says 64 bit installer. I have a Windows 7, 32 bit computer and OS.

Here it is:

Blender 2.78c Windows 32 bit Download (clicking this link will start the download)

To find it in the future, click on the "macOS, GNU/Linux, and other versions" button to find alternate versions, including 32 bit versions.

Hope this helps.


Expand specular map across multiple disconnected faces I work with a lot with LEGO blocks and the last variable in creating photo realistic scenes is getting the specular mapping to look right across the surface of all my blocks. When I apply smooth shading each block gets its own lighting gradient which looks bad. Even after I join the objects together the smoothing stays the same.

Is there a way to work some node magic so that the surface of the two right blocks is more similar to the cube on the left? I'm just using basic colors with the Principled BSDF.

I've tried messing with flat normal maps, tangents, unwrapping, and plugging everything into everything with no luck.

Gradient across object:

We can map a gradient to generated texture coordinates on the joined object to smoothly display a gradient on the surface of our mesh.

You may also choose to make a material that has the gradient mapped to the height of the object. This method allows for each lego brick to be an idividual object as long as the have the same origin. The drawback of this method is that when transformed(scaled, translated, or rotated) the gradient will remain the same and not move with the objects transformation.

Post on Auto-Smooth:

I believe the problem you're encountering is not a material or UV issue but rather a modeling issue. Blender is shading the whole object as if it was smooth not retaining sharp edges. This is what is adding this specular highlight in the middle of your faces. By either using custom normals, marking sharps, using auto-smooth, an edge-split modifier, or a combination of these techniques, you can define and preserve what you want as sharp edges.

One of the easiest and most convenient ways to achieve this is auto-smooth which the Blender manual describes as

  Auto Smooth:
  Edges where an angle between the faces is smaller than specified in the Angle button will be smoothed, when shading of these parts of the mesh is set to smooth. This is an easier way to combine smooth and sharp edges.

The edge-split modifier works very similar but it actually 'rips' the edges from one another according to given angle.


Missing textures in imported .fbx I grabbed a model from models resource model i grabbed from models resource but when I put the .fbx into blender, the model just shows up white.

I think it is because you are in textured view. In textured view, you are supposed to see the model with the texture applied on it but it looks like the textures are not saved in the file by it's maker. You should change your viewport to solid view to view the model. You can find this option here.


How can I connect two seams on a mesh? They come apart while posing but not while modeling I am learning how to rig properly using this simple molecule character.  I joined all the spheres and created seams by using ctrl-F and self-intersect.  I then deleted the internal faces.  The molecule now comes apart when I am testing the armature.

However, when I am modeling, there is no break in the seam; it is connected:

What can i do to make the seams remain connected while i am posing the character?

Here is the .Blend file:

Thank you!

Idle Chit-chat

Ok, I switched to answer to give a more detailed, well, answer! It appears that your mesh is not actually one piece, despite appearances.

Problem

I am not familiar with the self-intersect tool you described (or Ctrl + F if those are one and the same), but the spheres are separate. I proved this by selecting a single verticy of one of the spheres and keying L. If the mesh were a whole, like rigging requires, everything would select. Everything, obviously, did not.

Solution

Luckily, there is a simple solution! Select the entire mesh with A, key W, and select Remove Doubles:

This will join all the seemingly joined edge loops. Now you can continue on and rig!


Save every object in scene as individual .blend files via python? There is an excellent example here: https://blender.stackexchange.com/a/63000/37272 which saves all objects as .fbx files, but how do I get the script to save to .blend files instead?

EDIT: This line exports the selected objects to fbx: bpy.ops.export_scene.fbx(filepath=exportName, use_selection=True)

How does the command look for saving the selected objects to a .blend file?

Take a look at my add-on Splode. It can export individiual objects into individual blend files, and then link those blend files into the current file, replacing the existing objects. You should end up with the same scene, except that the objects are now linked from their respective blend file.


What is the low level alternative for bpy.ops.object.material_slot_add()? I have a script which adds a material to an object. The script is using  bpy.ops.object.material_slot_add(). However, this only works when the script is used from the text editor. It has polling/context errors when used differently.

What Blender 2.75a API commands provide the low level equivalent to bpy.ops.object.material_slot_add()?

Example code

Adds two material slots, m1  (if there is already an active material slot it will replace it with m1) and  m2

import bpy

mat1 = bpy.data.materials.new("m1")
mat2 = bpy.data.materials.new("m2")

ob = bpy.context.object

ob.active_material = mat1
ob.data.materials.append(mat2)

An empty slot can be added with

ob.data.materials.append(None)

Hence can add either data or object materials this way by setting the slot link.

import bpy

materials = (
    (bpy.data.materials.new("RED"), 'DATA'),
    (bpy.data.materials.new("BLUE"), 'OBJECT'),
    )

ob = bpy.context.object
me = ob.data

for m, link in materials:

    # add a material adds a slot
    print(m.name)
    me.materials.append(None)

    slot = ob.material_slots[-1]
    slot.link = link
    slot.material = m

Thankyou to @Lambdadelta for pointing out

  Note if "Link Materials to" set to "Object" instead of default "Object
  Data" in the blender preferences, then ob.data.materials.append(None)
  adds a slot to all linked objects, whereas
  bpy.ops.object.material_slot_add() adds only to the active object


How do I fix distortion in Render? My render shows a horizontal line distortion during playback. Increasing the render samples to 500 did not improve the quality at all. How can I make it smooth throughout?

Animation

Blend file

It looks to me like a problem occurring during playback, it's not part of the file.

The distortion is inconsistent between playbacks, and I've only seen it (sometimes) when using VLC. mplayer has no problems.

I don't know if there is anything you can do, this looks like a problem with the program doing the decoding.


How to properly export scene to 3ds Max? How can I export 3D geometry object/scene, camera and textures to a .3DS format? I tried importing the file I created into 3DsMax but it didn't work properly.

As of Blender 2.8x you can export your entire scene using Alembic or USD (Autodesk is working on adding USD support).

Layout in Blender

Alembic file imported into 3ds Max 2019

3ds is a deprecated file format. For Blender 2.7x export your scene to FBX 6.1 ASCII, this should work immediately. In some cases you have to adjust the settings because it also depends on your 3ds Max version and the version of the fbx plugin installed.

Suzanne in Blender 2.73a

Suzanne in 3ds Max 2012

Other options

Collada (.dae) - For instructions, see: How to export a motion tracked camera to 3ds Max?
Wavefront (.obj) - For exporting multiple obj files, see Export multiple objects to .obj


Python Script for Armature Scale - I was wondering what the python script the following sequence would look like. I'd like to be able to run the code in the text editor instead of manually doing it every time I need a new animation.
For a selected armature > clear all keyframes for scale x,y,z > and change the scale values to .011? In order to make sure that the scale is .011 through the whole animation.
Thank you very much for your time, I'd really appreciate the help!

Try this. Select the armature before running it (but the mode shouldn't matter this time).
import bpy
ob = bpy.context.active_object
assert ob.type == 'ARMATURE'
assert ob.animation_data and ob.animation_data.action
action = ob.animation_data.action
for fc in [*action.fcurves]:
    if fc.data_path == "scale":
        action.fcurves.remove(fc)
ob.scale = [0.011] * 3


Select faces depending on material I try to remove all the faces of different objects that have a certain material assigned to its face. But I can't get the select part to work.

import bpy
import bmesh

scene = bpy.context.scene

mat1 = bpy.data.materials['c1'] #This is the material name that I want

for ob in scene.objects: #For all objects
    if ob.type == 'MESH':
        for mat in ob.material_slots:
            if mat.material == mat1:
             bpy.ops.object.editmode_toggle()

             mat.material.material_slot_select() # This doesnt work and i dont know if the later code work aswell
             me = ob.data

             bm = bmesh.from_edit_mesh(me)
             faces_select = [f for f in bm.faces if f.select]

             bmesh.ops.delete(bm, geom=faces_select, context=5)

             bmesh.update_edit_mesh(me, True)
else:
    ob.select = False

What is wrong, what shall I write?

Br

import bpy
import bmesh

mat_c1 = bpy.data.materials['c1']

for ob in bpy.context.scene.objects:
    if ob.type == 'MESH':
        # get all the slot indexes to which mat_c1 is assigned
        c1_slots = [id for id, mat in enumerate(ob.data.materials) if mat == mat_c1]

        # you can also change active_material with
        # ob.active_material_index = some_number
        # and then run operators to deselect all faces and select material with
        # bpy.ops.material_slot_select()
        # but operators are bad so we will do it differently

        faces_mat_c1 = []
        bm = bmesh.new()
        bm.from_mesh(ob.data)
        # no need to swith into edit mode

        for face in bm.faces:
            if face.material_index in c1_slots:
                # face has mat_c1 assigned
                faces_mat_c1.append(face)

        # delete faces with mat_c1
        bmesh.ops.delete(bm, geom=faces_mat_c1, context=5)
        bm.to_mesh(ob.data)
        bm.free()
    else:
        ob.select = False


Create new object from selected faces while retaining faces on old object I have the following model:

What I'm trying to do is for each face create a new object.  I found out how to do that here, Splitting pieces of a mesh into a new object
The problem is, that method removes the faces when I select them from the original object (refer to my screen shots)

How do I create a new object from the selected faces without taking them away from the other object?
I am doing this because I need to make another part that fits into the main object for 3D printing later.

Check this .GIF:

Select faces
Shift-D then right click to duplicate
Press P to separate


Modelling a sphere with holes on it I am a hobby Blender user and I would like to model a robot. I want to model its face with a hole for the eyes. Something like on this picture:

First I wanted to solve this problem with a boolean modifier.

My second try was modelling it manually.

I also tried to use shrinkwrap modifier but none of them were really well. So I am looking for an efficient solution which does not destroy the topology. I really hope someone has an awesome idea.

I think it is not necessary to combine these two models in the first place unless there is a specific reason why you would not model them separate.

Assuming there is a reason, I would do the following:

Start with a cube
Add and apply subdivision surface modifier level two
Shift-Alt-S + 1-Key in edit-mode to make the resulting shape a sphere
Shape the model according to you needs by insetting and extruding the corresponding faces.
Add subdivision surface modifier but don't apply this time unless you want to add even more detail the current topology does not cover.


How to export Bone matrices for animation? I'm trying to export armature bone matrices (relative to parent), but fail miserably, because sometimes rotations and translations are getting applied to different axes, in comparison to Blender's preview.

I know there are already questions on Blender SE about exporting bone matrices (like this one), but most of these questions are dealing with exporting frame-by-frame matrices based on pose bone data (PoseBone structure), meanwhile I'm trying to export those matrices from Bone (because I'm using keyframes for animation).

Here is the code I'm using to export the matrices, at the moment:

# Write armature
def write_armature(fw, armature, global_matrix):
    fw('# Armature data\n')
    fw('arm_name %s\n' % armature.data.name)

    if armature.animation_data is not None and armature.animation_data.action is not None:
        fw ('arm_action %s\n' % name_compat(armature.animation_data.action.name))

    for bone in armature.data.bones:
        if bone.parent is not None:
            parent = name_compat(bone.parent.name)
        else:
            parent = ''

        mat = calc_matrix(bone, armature, global_matrix)
        euler = mat.to_euler()

        tail = bone.matrix_local.copy()
        tail.translation = bone.tail_local
        tail = global_matrix * armature.matrix_world * tail

        x, y, z = (mat.translation[0], mat.translation[1], mat.translation[2])
        vx, vy, vz = (tail.translation[0], tail.translation[1], tail.translation[2])

        ox = euler.x
        oy = euler.y
        oz = euler.z

        fw('arm_bone %s %s %f %f %f %f %f %f %f %f %f\n' % (name_compat(bone.name), parent, x, y, z, vx, vy, vz, ox, oy, oz))

def calc_matrix(bone, armature, global_matrix):
    return global_matrix * armature.matrix_world * bone.matrix_local

Where global_matrix is a matrix responsible for converting to different coordinates system (like from XZY to XYZ).

Currently, I export bone's head and orientation in euler angles (plus bone's tail, but that's for debug rendering). I know it's not relative-to-parent approach, but I wasn't been able to make it work otherwise.

Here is how I multiply this information in the game:

public Matrix4f computeMatrix(Matrix4f m)
{
    float x = this.x;
    float y = this.y;
    float z = this.z;

    if (this.parentBone == null)
    {
        x += this.head.x;
        y += this.head.y;
        z += this.head.z;
    }
    else
    {
        x += this.head.x - this.parentBone.head.x;
        y += this.head.y - this.parentBone.head.y;
        z += this.head.z - this.parentBone.head.z;
    }

    this.mat.identity();
    this.mat.translate(x, y, z);
    this.mat.scale(this.scaleX, this.scaleY, this.scaleZ);

    Quaternionf quat = new Quaternionf();
    Vector3f orient = this.orient;

    quat.rotateLocal(orient.x, orient.y, orient.z);
    quat.rotateLocal(this.rotateX, this.rotateY, this.rotateZ);
    quat.rotateLocal(-orient.x, -orient.y, -orient.z);

    this.mat.rotate(quat);

    if (this.parentBone != null)
    {
        m = this.parentBone.computeMatrix(m);
    }

    return m.mul(this.mat);
}

I hope you could help me with this, because I've been bashing my head with this for half of month, haha. I'm using Blender 2.78, by the way.

Thank you for attention!

After another few days of frustration, I finally was able to make it work. Basically, I gave up on exporting euler angles, head and tail, instead, I just exported the bone matrix itself like this:

mat = global_matrix * armature.matrix_world * bone.matrix_local

And in the game's code, I use this exported matrix for computing inverse and for relative to parent matrices (by multiplying bone's matrix by inverse of parent's).


Why does the frame range setting behave differently when using multiple scenes in the Video Sequence Editor? I am having trouble to understand how Render > Dimensions > Frame Range works when used together with Video Sequence Editor.

Start a new scene. Create 2 keyframes for the default created box at position 0 and 100. Have the box make a simple movement. Now under Render menu > Dimensions > Frame Range, set the Start Frame to 50 and End Frame to 80. Render this frame range as video file. It renders correctly.
Create a new scene. Use the above setup but now also go to the Video Sequence Editor and do Add > Scene > Scene to add your scene stripe in channel 0.

If you now try to render the same frame range (50-80) to a video, you will see that the rendering starts from frame 100 and finishes at 130.

If I change the frame range to 20-40, then the rendering starts from frame 40 and finishes at 60.

In other words, when the Video Sequence Editor is involved, and I setup a frame range X to Y, the rendering starts from 2*X (twice as many frames after it should start).

I cannot work this out. Can you please help me?

In your first scene you have an animation that plays from frame 50 to 80. Frame 50 is the first frame this scene outputs.

When you use that scene in a scene strip in the VSE, this strip plays that output of the scene, the first frame that the VSE scene strip receives is frame 50 from the first scene. This first frame of the scene strip will show up where the scene strip starts, which may be frame 24 of the new scene.

This would give the same result as if you rendered the first scene to disk then added the file on disk to the VSE.

The frame range in scene two has no connection to the original scene frame range.


How to make stylized hair from curves with flat tips? I will be honest. I suck with curves and don't get how they work but for now i don't have motivation to learn it. Unfortunately it seems to be the easiest way to make stylized hair. I've seen this tutorial ( https://www.youtube.com/watch?v=Nn7mISvVzJk ), the workflow looks super efficient, but my character hair are not pointy on the tips. I want them to be flat (or flat on one end and pointy at another) and still easy to edit as it was in tutorial. How to do that?
I tested few addons but in this case they weren't good (or I also suck at using them). I'm posting example of hair I have in mind:

I suck with curves and don't get how they work but for now i don't
  have motivation to learn it.

This will have to change in order to understand this answer.

Create three curve object. ⇧ ShiftA > Curve > Bezier

Taper
Bevel
HairCRV

 RMB select HairCRV and go to the properties panel and to the data section. In the Geometry settings set the other curves as the Bevel and Taper object respectively.
 RMB select the taper curve and go into edit mode ↹ Tab. Manipulating the curve will increase the depth of the tapered curve hairCRV.    This is, how a sharp ending can be achieved.
The Bevel curve influences the shape of the cross section along the curve.
Position the curve. ⎈ CtrlD to duplicate, E to extrude, ⎈ CtrlT to change the tilt. ⎇ AltS to scale.

You can still change the taper or bevel curve. In the tutorial, there are multiple different bevel curve, to achieve a variety of shapes.
Don't forget to increase the resolution of the hairCRV in case of small detail along the taper curve.


Remove individual instances in an array? Hey guys

I'm somewhat new to blender and modeling in general.

I'm trying to find a way to remove some instances in this array without having to apply the modifier. I want to have just the twelve spikes (marked green) but still have the benefit of only having to edit one to change all of them.

Is there a way to do this?

How about using the Array modifier for one side (8 of the spikes) and then a Mirror modifier to replicate that on the other side?


How to make rounded edges of a face I want to make these 2 inner faces with rounded edges like the left image

At the right image I used Ctrl+B to make the outer edges of this board rounded but I can't apply this to  inner face as the board itself is a cube with some modification

For your example this could do the job:

Enable LoopTools addon in the User Preferences (CtrlAltU > Addons)
Select the outer vertices
Apply Relax function with Linear Interpolation


Can I permanently deform a mesh with a rig? The title might be a little confusing, so let me clarify. I want to 3D print a model. However, rather than modeling the 3D print in a certain action pose, I would like to model it in the standard T pose and then deform the mesh with a rig and 3D print that deformed mesh. I currently have a completed 3D model than I successfully 3D printed through Shapeways, but when I rigged it and tried to get a different pose it just wan't possible. Shapeways would not recognize the rig deform and the mesh would be in its default stance.

Apply the Armature Deform modifier to the mesh object by clicking the Apply button:

If your object has multiple modifiers, you may want to apply them all. To do this quickly, ensure the correct object is selected and press ⎇ AltC > Mesh.


How to add a lattice on cube's surface? I made a single lattice around a cube in the following way:

Added a cube on scene.
In Edit mode I added loopcut with Ctrl+R.
Removed corner vertices.
Converted the cube to curve.
In Object Data tab I changed geometry properties and received next object:

Now I need to make double lattice like this(left side):

But when I made double lattice by previous way I have got object shown in the right side of previous picture.
How can I get a required object?
May be exists better way to make this objects?

You can either use the wireframe modifier or the skin modifier:

For Wireframe modifier:

Add Cube
Subdivide with 2 divisions
delete edge vertices
add wireframe modifier

For skin modifier:

Add Cube
Subdivide with 2 divisions
delete edge vertices
delete all faces (faces only!)
apply skin modifier
Scale with ctrla


Blender Texture Brush Paint Doesn't have Variety/ Falloff I’m wondering, I have the newest 2.90.1 Blender.  My Texture Paint Brush doesn’t seem to give me any variety of falloff/ strokeà as shown in the owl tutorial. Wondering if this is a GPU issue (I have GTX 970) or possibly just missing an option in Tools Tab?
**Also SHIFT + S does nothing on my end.
*The purple owl is mine, his is the brown in tutorial
Link to Tutorial: https://www.youtube.com/watch?v=eX3skhOOmco
Thank you for your time, be safe,

In the video there is Size Pressure for the radius activated. You can see it in the screenshot. It's the little icon behind the radius editbox on the top of the screen. Size Pressure only works with drawing tablets where you can control the pressure with the pen.
Shift+S activates Stabilize Stroke under Stroke settings. It adds a delay between the cursor and the stroke shown by a line. Painting with it feels like dragging a plow and you can draw smoother lines.


How to reassign the textures to my imported obj in blender? Recently Ive downloaded my maximo character created from blender with animations but when i reimport it back in blender, it does not show the textures.

The animations for the character were fine but it is in white color. Can someone shade some light on how i can reassign back my texture maps in blender? I am using cycles render.

OBJ files can contain your UV layout. So, providing you have made your UV layout on the character, just apply your texture maps and the projection to the corresponding UV. If you haven't made uv's, create them.


Physics in tracked scenes, not working I've already made plenty of Blender physics simulations in my life but when i try physics in a camera tracked scene, literally nothing happens. Always. All setup is the same as in other scenes but when there's a tracked camera, simulations don't work for me :/
For example, my current problem is :
I simply tracked a camera motion (and in addition also object motion - my hand) and I'm trying to make a cube fall off my hand on the table. But as i mentioned, physics doesn't work. I add a rigid body, passive, active, mesh, animated for hand blablabla but no active objects are falling. I also tried to add a completely new, casual cube, also added rigid body to it and still nothinng happened. I made the object tracking from Jonathan Kron's YT tutorial
His Cube is falling but mine is not :(
Appreciate any help

After I converted Constraint to F-curve it start to simulate.
Why it is not working like in tutorial from 2020 ... hm ... a bug?


How to bridge edge loops with a twist of .5? I'm trying to make a 3D model of a twist-cut torus, like this one:

https://youtu.be/3_VydFQmtZ8?t=3m39s

The current version of the model costs about $50 in Shapeways.
I'm trying to get that down by cutting both of the half-tori into two hollow pieces, so 4 pieces total. Then I would make them tight fitting so I can assemble it later.

The problem is that the 'Bridge Edge Loops' -tool pairs the vertices up wrong,

and I can't cut the tori straight:

How would I go about making this possible?

It just so happens I modeled a Mobius strip a little while back, and I'm sure the technique I used can address your case as well.

Model a plane, or some variation of a plane. Best to keep it simple at first.
Place an Empty at the end of your object. Actually, it should be a little further from the end of your object, but we'll adjust it later.
Select the Empty, then the mesh object.
In Edit Mode, with the end vertices selected, Hook those verts to the Empty Ctrl + H (Hook to Selected Object).
Add an Array Modifier to your plane/mesh object. Choose Object Offset and point it to the Empty. Set the Count to 3 or 4 iterations so you can see the effect.
Now in Object Mode rotate that Empty and you'll see that mesh twist like a DNA double-helix.
This will probably need some fine-tuning, so in Edit Mode with those same end verts selected you can un-hook the verts (also Ctrl + H]). Then move the Empty and re-hook the verts. You can play with it until the positioning is right. It's hard to describe this part, but if you try it you'll get it.
Finally, you should have a strip that you can twist and stretch using the Empty.
Once you've twisted the strip to the degree suitable for your design, save your file, then apply the modifiers.
Place your 3D cursor where the center of your ring will be and align your view accordingly, then use the classic warp tool - Mesh > Transform > Warp to wrap your mesh into a ring shape. Remove Doubles.

Another way to to this would be to use the Curve Modifier, but it won't give you an evenly incremented twist like this technique does.

For anyone creating a (Mobius strip like) twist where the normals oppose each other where they meet, there is the additional challenge of how to merge these, which I will briefly address. Here, the vertices at the edge where the normals are opposite have been ripped with pressing V.

Halving the Solidify Modifier's Thickness value, then duplicating the object and making the value negative on the duplicate is one way to fix this. Then you can apply the Modifiers, join the two objects, and merge the vertices at the seam. After that, additional clean-up of of the mesh, such as the deletion of internal faces may also be necessary.

Once the two objects have been joined, and vertices welded, here is the final result:

Two .blend files for reference:

http://www.pasteall.org/blend/36552

http://www.pasteall.org/blend/36553


Blender 2.8 : python code to switch shading mode (between wireframe and solid mode) If i switch between solid and wireframe mode, i can see in the info window that these commands are invoked :

bpy.data.screens["Layout"].shading.type = 'WIREFRAME'
bpy.data.screens["Layout"].shading.type = 'SOLID'

Now i want to execute this command using python console. So i cut and paste the codes into python console but i got this error :

>>> bpy.data.screens["Layout"].shading.type = 'WIREFRAME'
Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
AttributeError: 'Screen' object has no attribute 'shading'

>>> bpy.data.screens["Layout"].shading.type = 'SOLID'
Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
AttributeError: 'Screen' object has no attribute 'shading'

Does anyone know why ? and what the correct script should i use in python console ?

Thanks

As to why the script generates an error:
When directly clicking on a button on the screen Blender understands the context of which workspace (tabs across the top of the screen) and area (window within the screen) you are accessing.
Your code fails to identify where exactly you want to apply the change.

import bpy

my_areas = bpy.context.workspace.screens[0].areas
my_shading = 'WIREFRAME'  # 'WIREFRAME' 'SOLID' 'MATERIAL' 'RENDERED'

for area in my_areas:
    for space in area.spaces:
        if space.type == 'VIEW_3D':
            space.shading.type = my_shading


Color Ramp Particle System Not Working With Age I am new to blenders particle system and I am pretty bad at texturing, but I decided to do a particle system anyway. I trying to get the color to change over time but every solution I find does not help. Am I doing something wrong?!?! I have tried the image below, adding another divide and changing view port shade mode but nothing is helping!

You need to be in both CYCLES rendering engine and in RENDERED preview. I can't tell from your picture, but the material must be on the object being used as the particle instance. I made a test file and I'll post it here. I can confirm this is working 100% on my machine.

File is here --


Preserving shading after cutting a hole I'm trying to cut a hole in a mesh to create torpedo tubes on a spacecraft, and am running into a bit of trouble. I can get the hole cut out just fine using Knife Project, the problem, however, is that it completely screws with the shading of the mesh.

Here are the target and pattern meshes:

Here's a detail of the pattern that creates the shape of the outer tube:

and the target mesh:

Now, as I said I can cut the hole in the target mesh just fine. The problem is, I get this:

As you can see, cutting the hole in the mesh throws off the smoothing of the mesh, leading to some odd shading which is just unacceptable.

I'm trying to do this with as few extra polys as possible.

Prior to cutting the new geometry the transitions are smooth because the shading is a function of the average face normals connected to each vertex. Because each of those adjacent face normals is different as you go around the surface of the object, the transition is relatively smooth. It's a cheap but effective trick.

Once you start cutting into a face, you get new geometry which has a number of vertices which are surrounded by faces which have the same face normals, therefore the shading is 'flat' on those sections. The transition from surrounding faces onto that flat area is also abrupt, and more prominent with transitions between quads and triangles.

Read Blender docs about custom normals

possible solutions

A way out of that is to carefully adjust the positions of the new vertices such that they follow the inferred curvature, this doesn't have to be exact. as long as you get away from the faces all having the same normals on that spot.

The dark area just below the blue arrow indicates the flow that your geometry would need to have (seen from the side of that edited face). If you can move the internal vertices to match the curvature you'll get reasonable smoothing.
or adjust the vertex normals to follow the curvature, but (May 2015) this is not exposed to the UI, but can be scripted. Manual changes  might be overwritten by operations such as remove doubles / recalc normals.

Normal Edit modifier.  It takes a vertex group, and an object, and modifies the normals of the vertices in the vertex group to follow as if they eminated from the center of the object (radial) or directionally if you use a mesh object to help guide the normals.

Blender's Proportional Editing feature can help get nice curvature, but you'll have to experiment with it.


How to merge all vertices by distance and remove all inner faces? I have a bunch of 3D objects adjacent one to another (they all have a coincident face). I want to merge them all without having inner faces. I can achieve this by doing the following:

Object Mode an select all objects, then I join them with Ctrl+J.
Edit Mode -> Select -> All -> Vertex -> Merge Vertices -> By Distance
Select All by Trait -> Interior Faces -> then I delete all of them

That way I end up with a single object with no inner faces.

I would like to do the same exact thing but through a Python Script. I have thought about a couple of options which I do not know how to apply:

Emulate the process mentioned before with python commands
Doing boolean operations over and over (there are more than 100 objects), but for some reason the result is very messy and a bit slower

Any help will be highly appreciated, thank you very much in advance! :)

First of all if you want to write your own basic scripts you should go to Edit -> Preferences -> Interface and enable "Python Tooltips".

After that you will see pop-up hints with python references for certain buttons, menus and values commands every time you place a mouse cursor over them. Also you can press Ctrl+C (or Cmd+C on mac) when your cursor is over the button and it will copy the python command for that button to the buffer, so you can paste it in your script.

Also you can open up the Info Window in Blender, many commands appear there right after executing and you can copy them from there. Also you can open Console Window in Blender and start typing in commands you know - and use an autocomplete option (shortcuts may be different but you can easily find it).

A little bit of theory before the script. Note that in most cases copying python commands from the buttons will give you a Blender operator starting with bpy.ops. It is not prohibited to use those operators in the scripts, but it is not very stable and may cause errors because all Blender operators rely on context (exact window, screen, area and region from which it is called). There are hints to override a context, here for example. But generally the more efficient way is to use direct access to blender data and change it directly without using the operators. Unfortunately direct editing of the mesh data with Blender API is pretty... let's call it strange and unpredictable (in my opinion). There is bmesh module which has been written specially for this purpose, but I'd say it is pretty complex especially if you are a beginner not recommended. Anyway, if you are not writing a very complex program, using bpy.ops is ok.

According to your algorithm a script may look like this:

import bpy

merge_threshold = 0.05 # here you can define Merge By Distance threshold

if bpy.context.mode != 'OBJECT':
    bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='SELECT')
# This is to make sure that there is an active object in the scene:
#----------------------------------------------
if not bpy.context.active_object.hide_viewport:
    for object in bpy.context.scene.objects:
        if not object.hide_viewport:
            bpy.context.view_layer.objects.active = object
            break
#----------------------------------------------
bpy.ops.object.join()
bpy.ops.object.convert(target='MESH') # Here I've added an option which will
                                      # apply all modifiers by converting object
                                      # to mesh
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.remove_doubles(threshold = merge_threshold)
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_mode(type = 'FACE')
bpy.ops.mesh.select_interior_faces()
bpy.ops.mesh.delete(type='FACE')
bpy.ops.object.mode_set(mode='OBJECT')

UPD. Info Window and Python Console Window can be opened as any other window in Blender:

Toggle System Console in Windows opens up a system console where you can find detailed information about errors, results of your print() functions, etc.


switching curve 3d to 2d getting flat Watching this reference video @ 2.50
After creating the profile shape. When he switch from 3d to 2d the face get fill. I created a simple triangle shape and trying to switch from 3d to 2d why my curve get flat and not get fill.

Any suggestion whats going wrong or why i cant fill the face switching to 2d. Thanks

EDITED: Rotate on X 90 degrees and apply rotation. 2D is truncating the Z axis.


Can I use the distance between two objects to animate a property? I would like to make the value of a node, say a blur node, influenced by the distance between two objects (say a camera and a cube) with blender render engine.
How would you achieve that?

Yes, with Drivers

You can animate a property with a combination of values of other chosen properties.

To set up a Driver, just right click in the parameter field and choose "Add Driver"->"Manually create later" from the pop up menù. In the following example I added a "value" node and linked and added a driver to control it's value (the purple one), but I might have directly controlled the Size parameter of the Blur node itself:

In the Graph editor, under the Driver editor type, you can easily set up a Distance Driver Type and pick the two objects (camera and cube in the following example):

Here's the result:


How to retrieve value from StringProperty? I'm trying to create an addon for Blender.  The addon will have an operator part that builds a mesh and also a panel part that lets the user configure it.

One thing I want to do with the panel is have a drop down property that lets the user select the name of a reference object in the scene.  I found some examples showing how to add this to your panel using the layout.prop_search() method.  However, I wasn't able to find any information on how you are supposed to retrieve the value after the user sets it.  Right now I'm just trying to have my operator fetch the value the user set and print it to the console.

When I try, I get the message

(<built-in function StringProperty>, {'attr': 'theChosenObject'})

Also, is this the best way to go about doing this?  It looks to me that I'm cluttering up Blender's object space by having my addon insert all it's 'global' variables into bpy.types.Scene.

Here's my source:

bl_info = {
    "name": "Build It",
    "category": "Object"
}

import bpy

class BuildItPanel(bpy.types.Panel):
    bl_label = "Build It"
    bl_idname = "VIEW_3D_TOOLS_build_it"
    bl_space_type = "VIEW_3D"
    bl_region_type = "TOOLS"
    bl_category = "Tools"

    def draw(self, context):
        layout = self.layout

        scene = context.scene

        col = layout.column(align=True)
        col.prop_search(scene, "referenceMesh", scene, "objects")
        col.operator("object.build_it", text="Do Build")

class BuildItOp(bpy.types.Operator):
    bl_idname = "object.build_it"
    bl_label = "Build It"
    bl_options = {"UNDO"}

    def invoke(self, context, event):
#        print(BuildItPanel.bl_category)
        print(bpy.types.Scene.referenceMesh)
        return {"FINISHED"}

def register():
    bpy.utils.register_class(BuildItPanel)
    bpy.utils.register_class(BuildItOp)
    bpy.types.Scene.referenceMesh = bpy.props.StringProperty()

def unregister():
    bpy.utils.unregister_class(BuildItPanel)
    bpy.utils.unregister_class(BuildItOp)
    del bpy.types.Object.referenceMesh

# This allows you to run the script directly from blenders text editor
# to test the addon without having to install it.
if __name__ == "__main__":
    register()

You have one small mistake: you are reading the function that creates properties for new classes, while you should be accessing the property itself in the current scene, which has the value you have stored:

print(context.scene.referenceMesh)   instead of print(bpy.types.Scene.referenceMesh)


how do i change my shortcuts for zoom, move the view, and rotate? my old shortcut for zoom was ctrl, alt and mouse, left (this is on laptop) however when i try to do this it wont let me drag the zoom,

second my old rotate was alt and mouse, left.

and last my move view was shift alt mouse.

(all mouse buttons you click and drag).

I can't change these and if i try, for example i tried o fix my zoom. I couldn't drag I could only click. I need help with this

I think this will help you

go to 3d view

And now you have to do the same thing for the 2d view etc and the rotation


How to animate a bike chain with a low poly chainring? I need help with animating my chain, the chain isn't able to stick with the chainring because its quite low poly(both the chain and chainring) as shown as in the pic and the gap is very obvious I can't animate the chainring rotating with it like this.
How will I rig this to remain like tensioned while the chainring is rotating?

What you could do is create a mesh that looks like the chain, with only the necessary amount of edge loops, hook these edge loops to empties, make the ring rotate 1/7 of 360°, move the empties and keyframe them so that they follow the ring rotation. Make the empties rotate a bit on themselves so that the chain keeps an even thickness. You can now make the rotation cyclic to give the illusion that it rotates 360° and more. I haven't hooked the left part of the chain but it's the same process.


Save Render and Shadow Layer Separately I am trying to create a very simple product mockup using blender. I want to be able to save the actual product (cards) and the shadows as separate png files. I know this is possible, but I am just learning blender. Here is a link to the file I am working with: http://www.bestideabox.com/test.blend

Can anyone tell me why this is not working the way I am expecting?

EDIT:

OK; I have changed the blender file to represent the chosen answer and it does work. The shadows are saved to a separate layer. However they are different than when rendered altogether. I have placed the revised blender file here: Blender File Here is all layers rendered together: All Layers. Here is each individual layer: Cards and Shadows and here is the two individual layers laid on top of each other using photoshop: Merged Layers. As you can see the shadows layer does not line up at all. Infact they are a different shape all together. I also am having trouble exporting the plane texture by itself if anyone can help with that.

The file output node has two properties that determine the file that the image is written to, the base path (in red) which is the folder to save in and the subpath (in green) which could be a filename or a folder/filename combination.

In your example file you have two file output nodes that use the same base path and subpath, the second file gets saved over the top of the first one.

You also don't need two file output nodes, you can add multiple inputs to one node that have their own subpath and optionally image type settings. This can help as it prevents two inputs using the same subpath.


Best way to load image from list python script For some reason i have append images , now i want load all image by step.

image_path  = C:
image_list= []
for fn in os.listdir(image_path):
    image_list.append(fn)
    ###first_image = bpy.data.images.load(image_list[0])  <----?
    ###second_image =  bpy.data.images.load(image_list[1])   <----?

Try this to batch load a list of images in a folder:

import bpy
from os.path import join, isfile
from os import listdir

imageObjects = []
imagePath = '/users/you/yourImagePath'
imgFiles  = [
    join( imagePath, fn )                    # Create full paths to images
    for fn in listdir( imagePath )           # For each item in the image folder
    if isfile( join( imagePath, fn ) )       # If the item is indeed a file
    and fn.lower().endswith(('.png','.jpg')) # Which ends with an image suffix (can add more types here if needed)
]

# Load entire list of images
for imgFile in imgFiles:
    # Add to image object list to use later
    imageObjects.append( bpy.data.images.load( imgFile ) )

# Load a specific index from the list (5th in the list in this example)
imgObj = bpy.data.images.load( imgFiles[4] )


Issue with packed texture images I've just ran into something annoying when packing textures. As you can see when texture image is packed it is all over the place. This just started to happen today and I'm completely lost as of what would cause this... I read on another forum that it might have to do with file directory so I tried different locations on my hard drive but no change.

Did anyone encounter this issue before? I would really appreciate any help/pointers as I'm completely stuck and unable to send off things to render farm.

Thanks!!

image unpacked

image packed

nodes

SOLVED

The color mode in the properties panel was still set on sRGB and over-riding the texture node set in non-color data. Still don't know why it started to happen only now. But all sorted!


How to convert vertex colors to materials Title says it all
How do I convert vertex colors into materials?
I need this because .OBJ doesn't export the vertex colors with it
it doesn't need to be 100% accurate, if there were dark red and bright red then it'd assign something like normal red as the material(so if there are like 500 different colors per faces it wouldn't make 500 materials cuz it's inefficient instead it'd just round to the nearest color)
and no, im not planning on using textures

This is thankfully much easier than I originally thought it was. Vertex colors can be accessed with the vertex color input node. :-D


How to see a path transform graph for animated object I just want to see the transform graph for the selected object. For example I want to select one small cube and, after animating it, I want to display the path for this cube in a graph. Like on this image:

In the motion paths section of the properties window you can calculate the motion path for the selected object.

For 2.8:

Press the "calculate button"

A graph of the movement and keyframes will show on the 3d Viewport.

Note that any changes on the animation or keyframes will not update autmatically, you need to hit the "update" path every time you make any changes.

For more precise control on animation use the graph editor.


Exporting a mesh of specific dimensions Although I'm new to blender, creating a simple mesh (e.g. cylinder) of specific dimensions is easy.

However, when I export the mesh, open it with meshlab and measure the dimensions, I keep getting the same cylinder with default dimensions.

Is there any step I'm missing (something like "apply") before the export?

I think the mismatch that is giving you a challenge is between the default sizes of the dimensions. The default size of a unit in Blender is one meter. The default size of a unit of measurement in Meshlab is one centimeter. If you create a blender object that measures 4 blender units in one dimension, and 2 blender units in another, when imported to meshlab, it will be 4 centimeters in one dimension, and two centimeters in the other.

You either need to account for the difference in sizes when you create your model, or change the units in Blender so that one grid square is one centimeter, instead of one meter.


Why is my particle system rendering differently on my cloud rendering service? I'm making a little isometric low poly scene, and I'm using a couple of hair particle systems to scatter trees randomly over a plane. On my system I have them distributed pretty much how I want them to surround a little cabin I've modelled.
However, when I upload them to Render Street for final rendering, the trees are in an entirely different place. I have rendered it twice and they render in the same location each time on Render Street, but in a different place to my local version.
I also have an emitter system for smoke and that renders identically to mine.
Why is this happening, and is there some way I can 'bake' the hair particle distribution in so it's consistent?
EDIT: The following support page on Render Street goes through baking for particle systems, but this only seems to apply to Emitter systems. There is no cache tab for Hair systems:
https://support.render.st/portal/en/kb/articles/how-baking-works-with-blender-on-renderstreet

Ok, I found the answer to this. For hair systems, click the Convert button in the Modifier tab to convert the hair to meshes. Then delete the particle system itself from the Particles tab, otherwise they'll still render. Obviously save the file before you do this or you'll lose the ability to change your particle system.


How do I work with User Ops Nicely? How do I manage selection state? Based on all the helpful information in the answers to my previous question I have a new question. I will be generating a large number of meshes and animating them using just a script. In the following code, I use bpy.ops.mesh.primitive_uv_sphere_add to make a sphere, and bpy.data.objects.new to make a custom mesh. In both cases, it is sometimes necessary to access the object through bpy.context.active_object and also through bpy.ops.object. After the whole script runs, the fourth sphere is unintentionally smooth, because it is still active.

My question is partly how to fix this (make only the purple mesh smooth), but I want to check that these are really the most correct and safest and foolproof ways to do this. How do I "know" if bpy.ops.object really refers to the same object as bpy.context.active_object?  Assume this is in a large script generating and deleting a large number/variety of meshes and objects and materials, vertices are being adjusted, keyframes and shapeframes are doing their thing, etc.

Last question didn't have enough code, so maybe I've overcompensated with too much this time:

import bpy
import numpy as np

nx, ny = 20, 30
x = np.linspace(0, 3, nx)
y = np.linspace(0, 3, ny)
X, Y = np.meshgrid(x, y)
Z = np.cos(X**2 + Y**2)

verts = [tuple(thing) for thing in zip(X.flatten(), Y.flatten(), Z.flatten())]
corner_verts = [verts[0], verts[nx-1], verts[-nx], verts[-1]]

faces = []
for iy in range(ny-1):
    for ix in range(nx-1):
        v1 = iy*nx + ix
        v2 = v1 + 1
        v3 = v2 + nx
        v4 = v3 - 1
        faces.append((v1, v2, v3, v4))

purp = bpy.data.materials.new("PKHG")
cy   = bpy.data.materials.new("PKHG")

purp.diffuse_color = (1, 0, 1)
cy.diffuse_color   = (0, 1, 1)

puv_add = bpy.ops.mesh.primitive_uv_sphere_add
for vert in corner_verts:
    puv_add(segments=8, ring_count=4, size=1, location=vert)
    ao = bpy.context.active_object
    ao.active_material = cy

me  = bpy.data.meshes.new('timmesh')
ob  = bpy.data.objects.new('timobj', me)
sco = bpy.context.scene.objects
sco.link(ob)

me.from_pydata(verts, [], faces)

ob.active_material = purp

# the above script leaves the mesh unselected for some reason
ob.select = True
boo = bpy.ops.object
boo.shade_smooth()

ao = bpy.context.active_object
print("ao: ", ao.name)    # Sphere.003
print("ob: ", ob.name)    # timobj
print("boo: ", boo.name)  # <function bpy.ops.object.name at 0x117028470'>

edit (a question from the comments)

since a script does not use a mouse, why does it have to worry about selecting and deselecting and what is or isn't active. I am wondering how I can just give them a reference such as ob and then just do these things without having to constantly manage selection in the script?

I'm not certain there is a 'most correct' way, answers rarely exist in a vacuum. Settle for 'optimal' approach given a scenario.

A few take-aways:

The "Active object" is always selected, its .select attribute will return True.
Only one object can be Active in the scene at any given time.
it is possible that no object is active, yet several are selected.
A call to bpy.ops.object.shade_smooth() will shade all selected objects, not just active. (bpy.ops.object isn't a reference to an object, like bpy.context.active_object is )
bpy.ops.object.shade_smooth() doesn't take parameters, so it operates blindly on the current data.objects in your scene.
Adding objects using ops.mesh places that object in the active state
bpy.context.scene.objects.active = None, will remove the active state of an object, and it will become just 'selected'
bpy.context.scene.objects.active = bpy.data.objects[your_object], will set that object active. (it will not clear the select state of any previously active object)
bpy.context.scene.objects.link() does not place the object in an active or selected state, you must set that explicitly yourself.

A solution to the potential chaos?

Most flexible is probably an ID property, each object can have several  ID properties. You can pool objects by giving them each the same ID prop.

my_obj = bpy.data.objects['some_object']
my_obj['UHOH_ID'] = 'DONTSHADEME'  # attaches this ID property

A fast way to 1) un-select all objects, and 2) make sure none are active is the following two lines:

bpy.context.scene.objects.active = None  # turns active object to selected
bpy.ops.object.select_all(action='DESELECT') # properly unselects all.

Once you get your head around adding ID properties to objects, here's a list comprehension that returns the list of object references that have MY_ID.

objects = bpy.data.objects
objs = [o for o in objects if o.get('MY_ID') == 'SOME_VALUE']

Then to select just those objects with MY_ID

for o in objs:
    o.select = True

Why worry about selecting and deselecting and what is or isn't active?

In essence because the kinds of function you are calling are wrapped functionality intended to be triggered by the UI, and therefore don't need to supply return values, but do assume some state of the scene.

You've already encountered from_pydata, there is also bm.to_mesh(obj.data) which lets you assign the content of a bm into the mesh of an object. Getting away from the bpy.ops is a natural progression for someone who is learning bpy, they are great first steps.. but as soon as you need more control and complexity -- well.. a different approach is needed, and is available.

for instance, to make a uv sphere without bpy.ops

import bpy
import bmesh

bm = bmesh.new()
bmesh.ops.create_uvsphere(bm, u_segments=20, v_segments=20, diameter=1.2)
my_mesh = bpy.data.meshes.new("my_mesh")
bm.to_mesh(my_mesh)
bm.free()
ob = bpy.data.objects.new("mySphere", my_mesh)
bpy.context.scene.objects.link(ob)

You could wrap that in a function that returns the reference of the new object..


Copying objects in 3D view along with nodes and other stuffs while I am trying to copy a object (with nodes) (e.g. cube) to another blend file. The object that I am trying to copy was modified with nodes and I can't copy the object with nodes or manually copy the nodes. Can anyone tell me how to copy the object with nodes and other properties? Or copy the object to another blend file with all of it's modifiers and stuffs. Thanks!

I am assuming you are talking about material nodes etc. If you append the object into the new file, it will bring over anything attached to it automatically such as materials and any node setups associated with it. Use ShiftF1 or go to File > Append and navigate into the blend file as you would a folder, open the Object folder and select the object that you want to copy.

See How can I reuse existing materials, objects, etc from an existing .blend? for more info.

Alternatively, a much faster and easier way is to just copy paste the object directly into the new file by using CtrlC (Copy selection to buffer) and CtrlV (Paste selection from buffer). This will also bring over anything associated with the object.


sound_bake by script : unsupported audio format error I can't get the sound_bake function to work by script while it works fine from the menu (Unsupported audio format). Any idea ?

I have no backslashes in the path and my blender build includes ffmpeg... so I am out of idea... ?

Especially since it works when I bake manually from the menu with the same file !

Here's the piece of code :

# get the path from the sequencer
bpy.context.area.type = "SEQUENCE_EDITOR"
for s in bpy.context.scene.sequence_editor.sequences:
    if s.type == 'SOUND':
        file_path = s.filepath

# insert keyframe to the VU of the 3d object
bpy.context.area.type = "VIEW_3D"
bpy.context.scene.objects.active = bpy.data.objects['vu']

bpy.ops.anim.keyframe_insert_menu(type = "Scaling")
bpy.context.active_object.animation_data.action.fcurves[0].lock = True
bpy.context.active_object.animation_data.action.fcurves[1].lock = True

# bake
bpy.context.area.type = "GRAPH_EDITOR"
bpy.ops.graph.sound_bake(filepath=file_path, low=(0), high=(2000))

Thanks for reading !

So here's the trick : Blender internally use relative paths but provides a function to convert it to 'absolute'.

In my case, I just had to add the line :

absolute_path = bpy.path.abspath(s.file_path)

Thanks again Simon


How can I control when a camera starts moving along a curve I am making an animation for my senior project and although I have the actual animation done, I am having trouble with the camera paths. I have multiple camera paths set up (most of which will be following a path) and I wanted to transition between the different cameras as the animation progressed. However, when I start the animation, all the cameras start moving immediately. How can I make it so the cameras wait for a set amount of frames (time) before beginning to move?

Thank you for any help you can offer.

Just set keyframe where it is still, further in the timeline just before the other keyframes start moving the camera :)
Like, if you want it to be still in half a second, place a keyframe at frame 12, and then have the other frames placed afterwards. If it is in the middle of a move section, then you need to place a keyframe where you want the camera to be still, and then place the same keyframe at the frame of how long you want the still camera to last :)

If this didn't explain your issue, please tell me, and I will try to understand the issue :)