Python API script, why does extruding verts behave in this way? I run into this issue when writing Python scripts. When I am selecting several individual verts and I make an extrusion, I get some odd behavior I cannot explain.  It doesn't happen if I am working with edges or faces.
For example, I open a fresh instance of Blender, select the default cube, go into edit more, deselect all, and run

import bpy, bmesh
# have cube as active object, in edit mode, no verts selected
mesh = bmesh.from_edit_mesh(bpy.context.object.data)
for v in mesh.verts:
    if v.co[2] > 0.0:
        v.select = True
bpy.ops.mesh.extrude_region_move(
    MESH_OT_extrude_region={"use_normal_flip":False, "mirror":False},
    TRANSFORM_OT_translate={"value":(0.0, 0.0, 2.0),
                            "orient_type":'GLOBAL',
                            "orient_matrix":((1, 0, 0), (0, 1, 0), (0, 0, 1)),
                            "orient_matrix_type":'GLOBAL',
                            "constraint_axis":(False, False, False),
                            "mirror":False,
                            "use_proportional_edit":False,
                            "proportional_edit_falloff":'SMOOTH',
                            "proportional_size":1,
                            "use_proportional_connected":False,
                            "use_proportional_projected":False,
                            "snap":False,
                            "snap_target":'CLOSEST',
                            "snap_point":(0, 0, 0),
                            "snap_align":False,
                            "snap_normal":(0, 0, 0),
                            "gpencil_strokes":False,
                            "cursor_transform":False,
                            "texture_space":False,
                            "remove_on_cancel":False,
                            "release_confirm":False,
                            "use_accurate":False})

I get this  where the verts are extruded but they are just lines, not connected to each other, as if I had went around and extruded each vert individually.

I don't generally want that though. I found this odd little "hack" to get around the issue. I get the verts selected as desired, and then toggle out and back into edit mode before doing the extrusion, like this

import bpy, bmesh

mesh = bmesh.from_edit_mesh(bpy.context.object.data)
for v in mesh.verts:
    if v.co[2] > 0.0:
        v.select = True
bpy.ops.object.editmode_toggle()
bpy.ops.object.editmode_toggle()
bpy.ops.mesh.extrude_region_move(...)

and then the extrude behaves like this

So I have a couple questions. Why does it do this? And is there a better way? What should I be doing instead?

Use bmesh operators.

Here is an edit mode script that finds any face in the mesh that has an upward facing normal (locally) and extrudes.

Notice there is no element selection (e.select = True) required, it's done purely on face normal.  When  using bpy.ops operators in edit mode need to keep in mind, and set, select mode  (the issue above suggests vertex. Toggling modes flushes the selection, selecting the edges and face implied by your vert selection.  ie Even though you have all verts of a face selected, the face isn't yet.)

>>> C.tool_settings.mesh_select_mode[:]
(False, False, True) #  vertex, edge, face

Recommend ditching edit mode bpy.ops whenever possible.

import bpy
import bmesh

ext = (0, 0, 2)
TOL = 1e-7

context = bpy.context
ob = context.object
me = ob.data
bm = bmesh.from_edit_mesh(me)
#  bm.normal_update()

# select the top face

faces = [f for f in bm.faces if f.normal.angle((0, 0, 1)) < TOL]

if faces:  #
    ret = bmesh.ops.extrude_discrete_faces(bm,
            faces=faces,
            )
    verts = list(set(v for f in ret['faces']
            for v in f.verts))

    bmesh.ops.translate(bm,
            verts = verts,
            vec = ext,
        )

    bmesh.update_edit_mesh(me)

I've used bmesh.ops.extrude_faces_discrete(...) however could also use

if faces:
    ret = bmesh.ops.extrude_face_region(bm,
            geom=faces,
            )
    verts = list(set(e for e in ret['geom']
            if isinstance(e, bmesh.types.BMVert)))

    bmesh.ops.translate(bm,
            verts = verts,
            vec = ext,
        )
    bmesh.ops.delete(bm,
            geom=faces,
            context='FACES')

    bmesh.update_edit_mesh(me)

when using edit mode bmesh, can often use the users selection

[f for f in bm.faces if f.select]

or

f = bm.select_history.active

and check that is of type bmesh.types.BMFace.


I want to make the block's a little bit transparent and bright I want to make a lyric video. On the picture their
is something like a frame where the text then flies through. I want these blocks to be a bit transparent, but you still see them. It would also be cool if they were a bit like glowing. Thx for our help.

Change to cycles render
Select the object and make a new material for it
Open node editor and delete the diffuse material
Add a mix shader, emission node and a transparent BSDF and connect them like they are connected in the image
The strength on the emission node is the glow strength of the object
The Fac on the mix shader is the transparency of the object: 1.0 is invisible and 0.0 is not any transparent


Particle rotation normal issue with particle orientation Is there a way to get the particles in the correct orientation to the emitter and not rotated at varying angles? (see image)

eg. butterflies sitting on a cube's surface.

My relevant settings are:

Emit From > Faces
Rotation > Initial Orientation > Normal
Render > Group > Rotation (selected)

v2.73

In the image example it looks like the normal interpolates between each adjoining face's normal to rotate the particle. I'm also noticing that when the object rotates the particles spin which is also an unwanted effect. Is the normal acting as the axis for a quaternion?

I cannot recreate this interpolation problem with a cube primitive (gives correct behavior) but when rotating the cube (emitter), the faces with the z-axis, causes the particles to move. cube created in v.276.

Some Suggestions

I have experienced some latency and strange behavior with Particles.  Yet I do not want to produce a defect report.  Sometimes I have closed and reopened file.  Move the timeline to frame 0 and switched from Vertex to Face to Volume emission.  I have been very hesitant to inquire about this.  I have felt this latency has suddenly function as expected.  Misleading latency.  Could be interpreted as superstitious.
For the text to mesh.  Edit Mode, Use vertex remove doubles.
Object Mode,  Remesh Modifier and Apply.  So your faces are even size and no tedious hand modeling.
Edit Mode, With the faces from above in Faces Mode.  Select all Faces.  Sort Elements Randomize.
Note my Emission Panel Setting are a bit different than yours.
For the current settings and the simple scaled cube ... a rotation in EDIT mode can rotate the particle.

Image above shows the results of Remesh Modifier with Apply.

Other Edits May Follow.


Is the playback maximum 60 fps? Say I want to make a 100 fps video, can I not preview it at 100 fps over the timeline? Playback over 60 fps always displays "60 fps" on the playback screen.

Meaning I can create 1000 fps videos but I can only preview it in 60 fps in blender? Any work arounds or addons to fix this? I'd want up to 100 fps playback.

The maximum fps that can be played back will depend on your computer and the complexity of the scene in blender.

The syncronze playback option tells blender to play every frame or drop frames to keep playback in sync with time. You set the fps at the 100 you want in the final output video, then if the scene can be played at 100 fps it will be, otherwise frames will be dropped so that playback will be in sync timewise.

The interface preferences can be set to display the fps that are being played, when frames are being dropped the fps will be drawn in red.


Weird rendering in blender When I import this 3d-model from the internet, it looks fine in 3ds Max but weird in Blender. Is there any quick way to fix this?

I downloaded the OBJ file and imported it, and sure enough;

I've seen this issue before. I don't know if it's the default in blender, but my "Clip Start" value was incredibly small (0.01m). I changed it to 1m, and the model looks fine now;

Edit: It's also worth noting that this model is massive. I scaled it WAY down to work with it originally. However, I started with a fresh file, imported it, and the following settings work with the original scaling;

The "Clip start" was making the surface look weird. The "Clip end" was cutting off the back of the model.


How can I change the size of a modal operator popup dialog box? I have a modal operator that invokes itself and is called from an AddonPreferences PT. I have been trying to scale_x without success. A row.scale_x works within the size of the entire modal, it is 3.35" on my screen. None of the options I've tried, examples below, have changed the width of the modal itself.
def draw(self, context):
    layout = self.layout
    scene = context.scene
    layout.scale_x = 20

    row = layout.box()
    row.scale_x = 20
    layout.label(text="scaled_x_space?")
    row = layout.row()
    row.scale_x = 20
    layout.label(text="scaled_x_space?")
    split = layout.split()
    col1 = split.column()
    col1.scale_x = 20
    layout.label(text="scaled_x_space?")

I'm not really trying to scale by a factor of 20, I was using that number just to be sure it wasn't changing by some amount I wasn't noticing.

Just pass a custom width (integer) when calling invoke_props_dialog(operator, width=300) or invoke_popup(operator, width=300). The height is determined dynamically by the size of elements placed onto the props_dialog and there is no option to set it. From the docs:

Parameters

operator (Operator) – Operator to call
width (int in [0, inf], (optional)) – Width of the popup

Demo based on the code of How to call a confirmation dialog box?

import bpy

class SimplePropConfirmOperator(bpy.types.Operator):
    bl_idname = "my_category.custom_confirm_dialog"
    bl_label = "Do you really want to do that?"

    prop1: bpy.props.BoolProperty()
    prop2: bpy.props.BoolProperty()

    def execute(self, context):
        self.report({'INFO'}, "YES!")
        return {'FINISHED'}

    def invoke(self, context, event):
        return context.window_manager.invoke_props_dialog(self, width=750)

    def draw(self, context):
        row = self.layout
        row.prop(self, "prop1", text="Property A")
        row.prop(self, "prop2", text="Property B")

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

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

if __name__ == "__main__":
    register()

    # test call
    bpy.ops.my_category.custom_confirm_dialog('INVOKE_DEFAULT')


How to make Cycles default? Is there a way to make Cycles Render the default in Blender instead of Blender Render? (I hope this hasn't been asked before.)

Here are the steps to do that.

Open Blender.
Change the Render Engine to Cycles in the pull down menu (top center)
Then go to File - Save Startup File.

Thats it. Next time you start with a new file, it is gonna be Cycles Engine by default.


I used cylinder projection on this cylinder, but now there is a noticeable seam when i apply any texture, How can I make it seamless? -Cylinder Projection used for Unwrapping-

You can't make a non-seamless texture seamless, but you can find workarounds by using photoshop, or another program to make the texture seamless. I would either find a new texture, or use another program to make it seamless. There aren't too many other options, but finding a truly seamless texture should be pretty easy.


Rotating a bezier path I'm trying to make a graphic that describes how to orient a planetary orbit in 3D.  I animate my planet going around in an ellipse on a Bezier curve.

Next, I want to perform several rotations on the ellipse in space.

What is a simple 30deg x-rotation for the ellipse cylinder object is a -90 x, -30 y and 90 z rotation for the Bezier curve, which it accomplishes at a different rate. In this image you can seem them both rotating, but the Bezier ellipse lagging behind the cylinder.

Any idea what might be going on and how to fix it so they all rotate together at the same speed?

I'm using Blender 2.79 on Windows 10.

No idea why they behave this differently. But you could try parenting you curve to your object by selecting the curve first then the object (with Shift held down) and hitting Ctrl+P on the keyboard. Then you can animate your cylinder object and the curve will follow automatically.


Circle hole bevel defect When I tried to bevel a square it doesn't give me the perfect circle I wished for.
this is the result:

and the image below is before beveling:

Can you help me to solve this problem? Because when I remove the face of the defect it would remove some of the faces below that I did not wish to be removed. Thanks.

Doubles are one thing, but topology is bad as well. Make it look like the other one and dissolve diagonal edges and their verts on this imperfect circle. These vertices are obsolete. To have a perfect bevel circle you must have exactly four vertices, or a pure square. Also check Clamp Overlap option.In the example I used a plane with edges 4m in length.


Imported .FBX file from fusion opens with multiple dotted lines and empties, I can't remove them without changing the objects' allignments After adding joints on my model, I imported it as an .fbx file into Blender 2.8 to create an assembly animation.
But when Blender opens the file, there are multiple dotted lines which are centered in point, also there are lines (I found out they are called "empty") that I can not remove without messing up the positions of the objects.
I removed the joint in Fusion and tried again, but they're still there.
Do you know how can I fix this problem?

The dotted lines are relationship lines. They mean that one of the object is the parent of the other, which in turns means that if you transform (move, rotate, scale) the parent object, all its child objects will have the same transformation applied.
You can "unparent" objects by selecting them and then using either :

The shorcut ALT + P then choosing "Clear and keep transformations"
Object (top or bottom bar of you 3d view) > Parent > "Clear and keep transformations"

Then, the relation lines should disappear and you can freely delete your empties.

I would advise selecting ALL your objects in the scene and unparenting them all at once while keeping their transform.


Low Poly Style Fire Tutorial/Tips the help I got last time was so great I figured it was time to reach out to the community again haha. I am trying to make a lowpoly style campfire. I've got the logs done but now I am trying to figure out how to make the fire. I don't know what it is, maybe its the tags i'm using to search google, but I can't find a single tutorial for making low poly stylized fire. Not a single one. I'm a newbie with blender so I am not really sure where to begin. If anyone could offer some tips or even a link to a tutorial i've managed to miss I would be very grateful. The fire won't be animated but used for a still so it needs to look great. I'd love to be able to figure out how to add sparks to it too.. I've seen a few photos online of some great looking fires, but no tutorials anywhere haha.

Thanks everyone. As far as what i've got, so far i've got nothing but the logs made.

The easiest, low-poly fire I can think of is the same setup done for trees and plants in many video games: Setup a plane textured with a fire image PNG (with transparency) and create duplicates that you rotate on the Z-axis.

This tutorial can serve as a starting point: https://www.youtube.com/watch?v=6dsP7N3l7kY

A different style with the same principle: https://www.youtube.com/watch?v=hkc-0YUz-Y4

Here is another quick an easy one that can be combined with ones above: https://www.youtube.com/watch?v=OYxb8F5moUo

This last one is about making solid-looking low poly trees, rocks and grass: https://www.youtube.com/watch?v=rtO9maU709k

Finally, it doesn't hurt to lean about particles, they can be simple or complex, realistic or stylized and can even enhance the low-poly ones with sparks. https://www.youtube.com/watch?v=jLjwN_JqUGU


"Install from File" not working to install addon I'm facing a problem with the installation of a downloaded addon. I press Ctrl+ALt+U to access preferences panel in addons I select INSTALL FROM FILE

Then a choose caliper script and press INSTALL FROM FILE

After that I go back to the preferences panel and type CALIPER in search bar to find a new installed caliper addons to activate it no such addons among installed !!!

What am I doing wrong?

Sometimes when you download add-ons from the internet the files are saved as HTML code and not as text files, so Blender has no way to interpret them.

The error might be caused by using the save otpion from the browser and not using the link on the page that triggers the download of the correct file.

To make sure your Python scripts are in the right format you can open them in a text editor, which preferably supports python syntax highlighting.

It should look like:

And not like this:

Another common error is when the addon is contained in a .zip file instead of on a single .py file. If you unzip (or decompress) the file, you are left with a folder that contains many more files that are not easy to install manually. In such cases install directly from the .zip file instead of decompressing.


Should I model a humanoid body as separate body parts? Well I am working on my own game and I was wondering if it is a good move to make the humanoid in separate parts? Let's say I create the head and paint it separately, I create and paint separately the legs, hands, accessories...etc and then combine the UVs and make an atlas with those textures. I find it easier for me at least and I do not get lost in a big mesh.

Generally speaking it's not how 3D game artists are building their models. Separating the head and the limbs from the body might make things easier in the beginning of the modeling process but later on it will be harder to produce a good result.

Separate limbs always result into seams. You can hide them under garments but you cannot get rid of them by painting over them.

As for the aspect of rigging and animating them you might want to take into account that most of the rigging tools (for Blender and otherwise) are designed to work with single meshes. At one point you will have to weight-paint your mesh to get a good result. Having two separate meshes even in the same model leads to gaps and deformities which cannot be fixed. It's just the way inverse kinematics work.

About that "getting lost in a big mesh" part - you can always hide parts of your mesh in edit mode. Select the part you want to hide, then hit H to hide it and Alt+H to unhide it.


Is there a way to fit the viewport to the current field of view? Since there seems to be no direct way to get the camera's projection matrix, I'm hoping that it's possible to fit the viewport to the current field of view (the area encompassed by passepartout), because then the viewport projection matrix would in effect be the camera projection matrix, and that matrix can be retrieved via region_3d.perspective_matrix.

So, in pictures, I'm looking to do the following via Python:

Before:

After:

Is that possible?

I'm looking to export the projection matrix for an external application, so that my view there matches blender's camera view.

For that purpose, this is a roundabout way to ask, but my previous question was (in my view, incorrectly) marked as a duplicate.

While trying to figure out how to manipulate bpy.context.screen.areas[5].spaces[0].region_3d.view_camera_zoom , I accidentally discovered that the Home key will make the camera bounds fill the viewport.  If you try 'View All' from the spacebar menu it doesn't work exactly like the Home key (could not be bothered to hunt down why).

While not exactly useful, the examples at http://web.purplefrog.com/~thoth/blender/python-cookbook/screenshot-sequence.html might get you a little closer to the solution.  Specifically

def viewMatrixFromCamera(cam):
    """
    :param cam: the camera whose point of view is of interest
    :return: the view matrix suitable for use in region_3d.view_matrix
    """
    m2 = cam.rotation_euler.to_matrix()
    m2.resize_4x4()
    m3 = mathutils.Matrix.Translation(cam.location)
    return (m3*m2).inverted()

def viewFrom(screen):
    """
    :param screen:
    :return: the "first" area in the specified screen that is a 3D view.
    """
    for obj in screen.areas:
        if (obj.type == 'VIEW_3D'):
            return obj
    return None

v3d = viewFrom(bpy.context.screen)
m1 = viewMatrixFromCamera(bpy.context.scene.camera)
print(m1)
v3d.spaces[0].region_3d.view_matrix = m1

Unfortunately this exact code is NOT what you need when you are actually looking through the camera.  It only works to set the view when you are NOT looking through the camera.

Another problem is that while the code does move your focal point to the camera position, and gives you the correct orientation, it is highly unlikely to match the focal length of the camera.  I have not been able to find any setting on the 3D view that allows you to adjust the focal length when you are not looking through the camera.  When you "zoom in" you really just move the 3d view's focal point closer to the center point.


How to change color of action editior an graph editor selected items This image is screenshot of my problem:

This colour is influenced by the bone groups color theme. After you change it you'll have to exit the action editor and re-enter (i.e. hovering over the action editor and pressing Ctrl-Tab 2 times, to update the colors).


How to curve the mesh without using bezier? i have a little problem in blender. How can i curve the mesh like the image below without using bezier.

Thanks !

Various Features you can explore

Proportional Edit with a suitable vertex density so there are more vertices to bend
Use a portion of a torus
Use a portion of Cylinder with Solidify Modifier
Curve Modifier and apply on top portion first and isolated
Link to Tutorial https://www.youtube.com/watch?v=MrNVVHdKd3E


Cycles viewport render blank Hi so I'm completely lost on why this is happening in my viewport render in cycles but the image comes out completely grey. I've tried about every setting I can find and through these posts Render result is completely blank?, Why does my object not show up? but nothing seems to fix it. The weird thing is that this only happens in the rendered viewport shading. Not in look dev or solid in cycles, nor in EEVEE.  Any help would be appreciated.

I had the same problem and here is what I discovered: Under 'Properties > Output properties > Dimensions' I accidentally had the option 'Render region' checked. Once I unchecked this option, Cycles was back in bussiness. A simple solution but it can be very confusing if you don't know what's going on, since Eevee would render with this option checked. Hope some day this helps someone out there.


How to preserve shape keys with decimate modifier? I want to use the decimate modifier to make some LODs of a mesh, and this mesh has a very huge number of shapekeys which I must preserve.
I can't apply the decimate modifier with a mesh with shapekeys.

For this you must re-create all shape keys for each LOD-version of your mesh. You can try to do this. First making LOD-version by applying Decimate modifier to copy of your high-poly mesh with all shape keys deleted.

Then, sequentially turn on each shape key on your original high-poly mesh and apply Shrinkwrap modifier to previously made LOD-version as a shape key targeting that high-poly mesh with shape key turned on.

That is, add Shrinkwrap modifier to low-poly ('decimated') mesh. In your high-poly mesh turn on particular shape key by set it value to 1. Select your high-poly mesh as a target in Shrinkwrap modifier. Click 'Apply as Shape Key' on Shrinkwrap modifier. If all went good you would had particular shape key transferred from high-poly to low-poly model.


Make Bezier Curve look like Torus Array I am just sitting here at my very first own project and just thinking if it is possible to make a bezier curve look like a torus array like seen in example picture. Hope anyone can tell me how to do if possible.
I have already tried using a simple torus array and made it follow a bezier curve but first of all it got pretty stretched out at some point but second and most important it was nearly impossible getting this thing into exact position I need, which is pretty difficult. But at all other ideas are welcome.

Thanks for the attention. :)

The easiest way to do this is the Curve modifier.

In the following screenshot you can see a torus mesh to which I added an Array modifier and a Curve modifier.  The curve modifier refers to the Bezier curve.

I had to rotate the torus array 90 degrees around the Y axis because it seems the curve array defaults ton the X axis.  I guess I could have picked a different deformation axis if I had noticed that radio button array earlier.


How To Carve a Design I'm trying to model this sword, and I'm having trouble making the base of the sword (the grip). How would I go about doing this?

I'd suggest modelling the basic shape and then sculpting, then you can retopo a low poly and bake the detail from the sculpted piece to the low poly, if you are planning on it being a game ready asset.

If you aren't, just stopping after the sculpting phase is OK.


yellow dotted line grab tool I'm a beginner.  Everything was going along fine. I was using click, hold, grab to pull and push on vertices without striking the G key.  For some reason now it's not working and when I hit the G key a small dotted yellow line appears and extends and contracts with my mouse movement.  What did I do?

In Blender you can begin to grab either using the right mouse button or the G key.

After that you can move the wanted vertices, but if during this movement you hit G again, the movement is limited to the edges connected to the displaced vertex.

In complement, that can be used with more than one vertex, here are some behaviors :


Pose mode- can't change transform location of root bone? I'm able to rotate and scale the root bone of my armature in order to affect my model, but changing its position does not appear to do anything. The location appears to be changed, looking at the bone's transform, but it does not visually affect anything.
-location is not locked
-Auto IK is not on
-manipulate center points is not selected
-duplication in object properties is set to none

Looking at your file this problem is because the root bone Bone.27 is set to Connected. You need to unset this. To do this follow the below steps:

Switch to Edit Mode
Select the root bone Bone.27
Go to the Bone tab in the properties window
Uncheck the Connectedcheck box in the relations panel

This will fix the problem and you will be able to grab the root bone and move the character using it as shown below:

Updated .blend file can be found here:


Bake an fcurve with visual transforms I want to duplicate an existing animation and bake it with visual transforms applied, something like what the default nla baker does. For simplicity's sake say I need to do this for a single bone. This is how I tried to do it.

sourceAction = bpy.data.actions["myAction"]
action = bpy.data.actions.new("newAction")
fcurves = action.fcurves

poseBone = object.pose.bones["bone"]
bone = object.data.bones["bone"]

curveLocX = fcurves.new('pose.bones["bone"].location', 0, "bone")
curveLocY = fcurves.new('pose.bones["bone"].location', 1, "bone")
curveLocZ = fcurves.new('pose.bones["bone"].location', 2, "bone")
curveRotX = fcurves.new('pose.bones["bone"].rotation_euler', 0, "bone")
curveRotY = fcurves.new('pose.bones["bone"].rotation_euler', 1, "bone")
curveRotZ = fcurves.new('pose.bones["bone"].rotation_euler', 2, "bone")

#iterate through each frame somehow
    #get the matrix for current frame
    matrix = bone.matrix_local.inverted()*poseBone.matrix
    loc = matrix.translation
    rot = matrix.to_euler()

    curveLocX.keyframe_points.insert(frame, loc.x)
    curveLocY.keyframe_points.insert(frame, loc.y)
    curveLocZ.keyframe_points.insert(frame, loc.z)
    curveRotX.keyframe_points.insert(frame, rot.x)
    curveRotY.keyframe_points.insert(frame, rot.y)
    curveRotZ.keyframe_points.insert(frame, rot.z)

I'm not sure how to iterate through the frames to get the correct matrix for that frame. Also I'm not sure if there's a better way to get the visual transform channels.

Convert Space

An example of using Object.convert_space  to test.  Add a bone constraint, run script in pose mode with at least one pose bone selected. Should see that the bone remains in place and all constraint influences are zeroed. Note have used the default quaternion rotation

import bpy
context = bpy.context
ob = context.object

for pb in context.selected_pose_bones_from_active_object:
    M = ob.convert_space(
            pose_bone=pb,
            matrix=pb.matrix,
            from_space='POSE',
            to_space='LOCAL_WITH_PARENT',
            )

    if pb.constraints:
        for c in pb.constraints:
            c.influence = 0
        loc, rot, scale = M.decompose()
        pb.location = loc
        pb.rotation_quaternion = rot
        pb.scale = scale

Baking to fcurve

Similarly will set frames for each in scene frame range, and store the matrix calculated as above for each frame for each selected pose bone.

Then create an action, and keyframe it from the data.  I have only added location

import bpy
import numpy as np
from collections import defaultdict

context = bpy.context
scene = context.scene
ob = context.object
frames = np.arange(scene.frame_start, scene.frame_end + 1)

data = defaultdict(list)

for f in frames:
    scene.frame_set(f)
    for pb in context.selected_pose_bones_from_active_object:

        M = ob.convert_space(
                pose_bone=pb,
                matrix=pb.matrix,
                from_space='POSE',
                to_space='LOCAL_WITH_PARENT',
                )
        data[pb].append(M)

action = bpy.data.actions.new(f"{ob.name}_BAKE")
action.id_root = 'OBJECT'

fcurves = action.fcurves

def flatten(a, b):
    c = np.empty((a.size + b.size,), dtype=b.dtype)
    c[0::2] = a
    c[1::2] = b
    return c

for pb, mats in data.items():
    # remove or de-infuence constraints
    for c in pb.constraints:
        c.influence = 0
    locs = np.array([M.translation for M in mats]).T
    for i, d in enumerate(locs):
        fc = fcurves.new(pb.path_from_id("location"), index=i, action_group="Bake")
        fc.keyframe_points.add(len(frames))
        fc.keyframe_points.foreach_set("co", flatten(frames, locs[i]))
    # similarly as above for rots etc..
    rots = np.array([M.to_euler() for M in mats]).T

ob.animation_data_create()
ob.animation_data.action = action

Note  tested this with constraints rather than NLA stack, in concept "should" be the same and create one animation based on visual transform.  Might need to ob.animation_data.use_nla = False to turn off the influence of NLA. (Similar to setting constraint influences)

Note the flatten method was quickest method suggested here https://stackoverflow.com/questions/5347065/interweaving-two-numpy-arrays


How do I activate the editing box at bottom of "Tools" section? When I add a new item (sphere, cube etc) the lower left hand editing box is no longer activated....it is clouded over and unresponsive. For example: I add a UV Sphere but can no longer change the segments, rings, size etc. It was working in the past which makes me wonder if I have inadvertently turned it off....I have closed and reopened Blender but cannot rectify this issue.

in 3D view, use T to make the toolshlef appear/disapear.

You can also use F6 to get the specific toolbox for new objects


How can I model an irregular object made from laser cutting metal sheet I'm new user of Blender and I have a question about modelling. I would like  to create the model of this object:

It starts from a metal sheet cut with a laser-cutting machine, then manually deformed into the shape in the photo.

I have no idea about how to model this. Searching I found  "How can I create a hollow sphere with regularly spaced holes?"
but that isn't my situation.
Can someone help?

You could easily do this with the classic combination Array + Curve modifiers.

Since your metal sheet seems to be cut in a repeating pattern start by defining a mesh shaped as one module of said pattern.
Make use of a Mirror modifier, if it is symmetrical.

Add two Bezier Curve objects to your scene, one defining the larger radius of the desired shape, the other defining the shorter radius and the section of the torus like object.

Make sure the smaller curve is set to 2D in the Properties Window so it doesn't accidentally create gaps. Also make sure both curves are at the same scene position and world coordinate as the pattern mesh.

It also helps if the curve origin is set at one of the end vertex for the section.

Now to the pattern mesh add one Array modifier set to Fit Curve, and pick the smaller "section" curve. Then add Curve modifier pick the same Bezier object.

Adjust spacing and rotations as necessary if the deformation is unexpected.

Repeat the above steps of Array + Curve for the larger curve.

Now adjust the shape and deformations of the mesh by entering Edit Mode in either of the curves and playing around with its shape. Move vertex around or alter their Radius property for a scaling or collapsing effect.

Disclaimer: The gaping deformations that naturally happen by stretching a metal mesh won't be recreated using this technique, but you can manually model them while defining your base pattern object, or apply the modifiers and sculpt them over (a copy of) the final mesh if you don't need a non destructive workflow.

Also see related How to model braided nylon sleeve


How to animate shape keys in Blend4Web I would like to export some shape key animations to Blend4Web. How should I do it?
I tried several times. But those were not work. Of course I checked "Export Shape Keys" before exporting. Please teach me how to get a success.
Thanks! ;-)

The way to animate Shape Keys in Blend4Web is to use Logic Nodes. It has been implied that in the future the Blend4Web team may add even more ways to animate them. (An alternative approach is to do vertex baking on models that have Shape Key animation on them.) I will give an overview of the steps for animating Shape Keys with Blend4Web's Logic Nodes.

Things you've done correctly already:

Set the render engine to Blend4Web
Create shape keys
In the Object Context, enable "Export Shape Keys" for that object.

Things you still need to do:

In the Scene Context enable the Logic Editor. Click the [+] button to add a new one.
Open the Node Editor and set the node tree type to Blend4Web logic nodes.
Select your new logic node tree from the drop-down list.
Create the kind of logic node tree necessary for the kind of animation you want to make.

Enabling the Logic Editor and creating a new node tree:

Setting the node tree type and selecting your logic node tree in the Node Editor:

Creating your node tree

Here is a very basic example of how you can make your object switch Shape Keys when clicked:

For examples of how to make your Shape Keys animate gradually over time, as well as how to animate back and forth, see this thread on the Blend4Web Forums.

Also, you can reference the Blend4Web Manual for more info on Logic Nodes.

Good luck!


Circle Mesh - Can't Adjust Vertex Count I recently tried to create a circle mesh, which works fine. However I cannot change any of the Add Circle settings. It is all grayed out, so I cannot change how many vertices there are in the circle with the sliders.

Is anybody else having this issue? Is there a way to fix it?

Oh, I found the answer! Go to File > User Preferences > Editing > Undo, and enable Global Undo. Problem solved! :)


SCULPTING: Is it possible to keep base mesh vertices in place while subdividing? What I'm looking for: a way to stop the starting mesh from melting into an unidentifiable blob of vertices when applying a MultiResolution modifier.

Background: I'm currently following a Game Design course, which involves Maya, ZBrush and Substance Painter.
Soon or later I'll run out of trial/student licenses, which means I'll have to either buy these softwares or find cheap/free alternatives.
Now, allegedly, Blender can easily replace Maya for nearly everything, and Substance Painter is actually already quite cheap (only 20$ a month for the indie license).

ZBrush, on the other hand, is a bitter pill to swallow, because it costs a lot!
Fortunately, Blender seems to integrate a sculpting feature that might even be good enough to efficiently replace ZBrush.
My concern, though, is with the subdivision method/results: I've just tried to subdiv a cylinder by using MultiResolution, and now it looks exactly like a hot-air balloon.

The lump-ish result was expected, but I'm a bit upset because I can't seem to find a way to revert this result to something that even just resembles the original shape.

In ZBrush, by using "Morph Targets", one can easily revert the most deformed/shrinked model to its original volume, while still getting that nice, smooth look subdivisions usually bring. A final touch of Crease here and there where needed and you basically have a smoother version of your original model, but without any loss in volume/shapes.
The routine is: store target, subdiv, down to previous level, restore target, move onto higher level, store target, subdiv, etc etc....

So my question is: is there any way to emulate the same process in Blender? Is there a way to achieve the same result?

[UPDATE - 2018.04.13]

As you can see, there's nearly no difference between Maya's, Blender's and ZBrush's smoothing, they're all a basic application of the Catmull-Clark method.
BUT! If you store the vertices' position in a "morph target" before creating a new subdivision level, and then re-apply it on the same source-level, the new level's vertices' position is recalculated on that scaffolding, hence restoring the previous volumes and shapes.

In addition to what Mr Zak mentioned, you could try:

Both Subdivision Surface and Multiresolution have a Simple option,
when you turn it on, each subdiv will add vertices between already
existing ones without averaging the general shape.
Secondly you could make a
copy of a basemesh, then add ShrinkWrap modifier on the mesh you will
subdivide and pick the copy as a target. This way you will keep the
mesh shape the way you want it. Both copy and subdivided mesh must be in the same location.


Switch off the lamp in imported VRML In my VRML file, I have lights switched off. But when I render it in blender (by using the import tool), the lights are switched on.

I looked at the code:

def importLamp_PointLight(node, ancestry):
    ....
    # is_on = node.getFieldAsBool('on', True, ancestry) # TODO
    ....

As I can see in the code, lamp's is_on has not been implemented.
But I need this to work. How can I contribute to the code and make this work?

I see the this is implemented in bpy.data.lamps, but it uses C code _bpy imports types.

Thanks.

You could try uncommenting the is_on line and add something like

bpylamp.hide = not is_on
bpylamp.hide_render = not is_on

Another option could be

if is_on:
    bpylamp.energy = intensity
else:
    bpylamp.energy = 0

The X3D/VRML2 import script was written by Campbell and Bart so you might want to contact them and ask what they planned to do with the lights and whether they want some help. It's possible they left it like that because there is no on/off light switch in blender (maybe adding one is a TODO somewhere).


How do I get my screencast keys to stay by my world axes when I open & close my Tools panel? How do I get my screencast keys to stay by my world axes when I open & close my Tools panel? I don't want them to stay out in the middle of the screen when I close my Tools if I'm doing a screencast.

Here's another scenario I want to avoid: having the screencast keys beneath the Tools panel:

I was slightely confused by your question, since you didnt mention that you are using non-default settings.

Easy solution:

Disable "Region Overlap" in "User Preferences - System"

Fix:

If you want to use "Region Overlap" here is a small hackish patch to space_view3d_screencast_keys.py that should roughly do what you want:

def getDisplayLocation(context):
    scene   = context.scene
    mouse_size = scene.screencast_keys_mouse_size

    tool = context.area.regions[1] #coughs.. we just assume its there
    w = 0
    if bpy.context.user_preferences.system.use_region_overlap:
        w = tool.width

    pos_x = int( (context.region.width  - mouse_size * MOUSE_RATIO) * \
        scene.screencast_keys_pos_x / 100 + w)
    pos_y = int( (context.region.height - mouse_size) *
        scene.screencast_keys_pos_y / 100)

    return(pos_x, pos_y)

Whole file is here: space_view3d_screencast_keys.py

Just find your scripts/addons folder, move the old file and place this one there.

Slightly safer might be to query for the tools panel but it comes with some overhead:

w = 0
for region in context.area.regions:
    if region.type == 'TOOLS' and bpy.context.user_preferences.system.use_region_overlap:
        w = region.width
        break


Insert video to sequence editor with python Script i want to create a button for insert a video to video sequence editor.
i have written a script :

import bpy, os

class insertVideo(bpy.types.Operator):
    bl_idname = "scene.invideo"
    bl_label = "Insert Video"

    def execute(self, context):
        episode_path = "F:\\Dokumen\\Target\\Develop Apps\\addon_blender\\tes"
        bpy.ops.sequencer.movie_strip_add(episode_path)

class MyPanel(bpy.types.Panel):
    """Creates a Panel in the Object properties window"""
    bl_label = "My Tools"
    bl_idname = "my.panel"
    bl_space_type = 'SEQUENCE_EDITOR'
    bl_region_type = 'UI'

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

        obj = context.object

        row = layout.row()
        row.label(text="Movie File")
        row = layout.row()
        row.operator("scene.invideo", text="Insert Video")

def register():
    bpy.utils.register_class(MyPanel)
    bpy.utils.register_class(insertVideo)

def unregister():
    bpy.utils.unregister_class(MyPanel)
    bpy.utils.unregister_class(insertVideo)

if __name__ == "__main__":
    register()

In episode_path = "F:\\Dokumen\\Target\\Develop Apps\\addon_blender\\tes"

I have 3 videos :

file1.mov
file2.mov
file3.mov

I hope, when i click this button :

It will insert all videos from episode_path. But, i have a problem. When i click the button, it always show error :

Maybe you can help me, What did i miss?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

@cmomoney @sambler Thanks for your answer guys. Finally, i can finish my first addon in blender. I add this in execute function :

def execute(self, context):
        episode_path = bpy.path.abspath("F:\\Dokumen\\Target\\Develop Apps\\addon_blender\\tes")
        episode_list = os.listdir(episode_path)
        episode_sort = sorted(episode_list)
        first_frame=0
        last_frame=0
        for v in [f for f in episode_sort if f.endswith('.mov')]:
            movs = os.path.join(episode_path,v)
            start_frame = last_frame+first_frame
            bpy.ops.sequencer.movie_strip_add(filepath=movs, frame_start=start_frame, channel=1)
            first_frame = bpy.context.scene.sequence_editor.sequences_all[v].frame_start
            last_frame = bpy.context.scene.sequence_editor.sequences_all[v].frame_final_duration
        return{'FINISHED'}

Thanks for your help guys

When invoking an operator in python, there are three positional arguments that are generic to all operators, all other arguments that pass settings specific to the operator must use keyword arguments.

So to call the operator you should use -

bpy.ops.sequencer.movie_strip_add(filepath=video_file)

Note that movie_strip_add will add one video file as a strip, so to add a directory of movies you will want to use a loop.

def execute(self, context):
    episode_path = "/path/to/videos/"
    for v in [f for f in os.listdir(episode_path) if f.endswith('.mov')]:
        bpy.ops.sequencer.movie_strip_add(filepath=os.path.join(episode_path,v))
    return {'FINISHED'}


Creating floors for an SVG floorplan converted to 3D and exported for use with Unity My plan is to convert some floorplans into a map for a simple FPS game in Unity. The building I'm doing has three floors.
My workflow is as follows;

Import svg into Blender
Convert to mesh
Extrude walls to desired height (each path creates 4 vertexes creating nice, thick walls, each with an "inside" and "outside" face
Set each wall to a face for texturing inside Unity (normals are something I'm expecting problems with later on and am yet to deal with)
Import into Unity as OBJ

My problem is creating ceilings and floors. My idea was to simply select the vertices and hit F to fill with a plane, then extrude to the same thickness of the walls created with extruding from the SVG but this isn't a very exact process.
What would be the ideal way to achieve this? Any tips would be greatly appreciated. Needless to say I'm learning as I make this and am a n00b. :)
Thanks!

Maybe just add planes on top and bottom? Nice polycount, easy to hide in Unity if you need so.


How to have 2 windows display different modes in the 3D Viewport I can open a new window and move it to the second monitor but it will only display the same editor screen as the original window.
How can I get it to show a different one e.g. layout on one and modelling on the other? I am running windows 10.
Sorry I should have said show OBJECT MODE in one and EDIT MODE in the other, when I click the mode button on one monitor the mode changes on both monitors

Sure you can do that! I do it all the time.
When you drag out a new window, simply hold down Shift, at the same time, and that will tear that window away from the main interface! You can then move that new window to your other monitor and set it to what you like.
To change it to what you like, simply select this icon here:
Example


How can I find holes in a mesh? I'm trying to vet the correctness of my mesh object, and I'm trying to find a method that will detect holes in my mesh. I define a hole as either of the following (these definitions are almost equivalent):

An area between faces that should be divided by another (missing) face.
A face who's front and back are on the same side of the mesh, i.e. it is impossible to tell which side of the face is on the inside of the mesh
A hole is indicated by a face that has at least one edge that is not shared by another face.

How can I automatically identify such holes/affected edges?

The following image demonstrates what I mean by this. The selected vertex has accidentally been ripped, and it is now loosely dangling in 3D space:

A similar image that easily illustrates definition 3 is this:

I found this answer, but this only proposes using a "magic fix everything" tool, while I'm looking for a way to find the problems, and correct them myself.

Use Select > Select All by Trait > Non-Manifold option in 3dView header (or Ctrl+Alt+Shift+M) and in options of operator located in Last Operator panel (they appear there after executing it) deselect everything but Boundaries.

Select all and choose Select > Select Boundary Loop.

This will select boundary loops around selected edges.

Use shipped with Blender MeshLint addon (by default not activated). It allows choosing which categories of wrong topology to select, including non-manifold (however I think it will select wire, multiple faces etc. as well but still for completeness).


How do you remove frames in Blender? I created an animation... I put too much time between 2 keyframes. How do I remove some of that time from the timeline? I don't want to remove the keyframe... just some of the normal frames between the 2 keyframes?

I don't think you can remove frames. However, you can go into the "Animation" screen and move your keyframes closer together.

Go to the top of the window where it says "Default" and from the drop-down choose "Animation". You'll get a Dope-sheet on your left. You have to find your keyframe, select it and move it. Normal keys for selecting and moving, thus A for toggling selection, right-click for selecting, and G for moving.


When is it acceptable to use roughness without a map input in the Principled BDSF node? For a PBR material setup, one usually have map inputs for the color, roughness, normal nodes. If a material has an undefined roughness, but it's not perfectly smooth either, is it okay to use the roughness slider as a substitute for a map input? Would such a technique have an impact on the photo realism of the object?

It is perfectly normal to use a single value for roughness in all the cases when roughness is uniform across the surface for example with smooth clean objects made of the same material.


A Fold-like Brush in Sculpting? There's something I'm struggling to pull off in Sculpt Mode, I'm trying to create a type of, heavy fold, if you will. It's less like the folds or creases in clothing, and more of the type of fold you'd get if you, well, I don't know how to explain it, but this picture on Dictonary.com kind of is similar to what I'm trying to hit.

Those sharp, deep, weighed over folds in E, with the top of the mesh folding over the bottom part of it, still keeping an opening, but being, more like what's in the picture.

I've given three types of sculpting a shot, the left is thumb, with a smooth afterwards, the middle is grab with smooth, and the right is Snake Hook with smooth. None of them are, what I'm going for. The inward fold is non-existent, it's more like the top of the is melting over the bottom instead of creating a fold like the picture.

Perhaps you could play with the Gravity factor in the Options tab, and that might enable you to get the kind of fold you want - I also suggest maybe using the Crease brush in opposite direction to raise the fold out of the mesh with the ctrl key and pressure stroke.


How to make the skeleton move relative to the bone that is touching the floor using animation nodes I am trying to make the skeleton to move relative to the bones that are touching the floor using animation nodes.

What I did is calculate the difference between the current and previous positions of the bones and apply the difference of the lowest bone to the root bone.

Here is the blend file:

Always Touch The Floor

In this section, we shall position the root bone of the armature such that the lowest bone is touching the floor. Since the ankle/heel bone's local z axis is perpendicular to the global z axis, the head and tail z locations are identical and since the tip/tail of the toe bone will be the last bone touching the floor, to identify the lowest bone, we shall use the location of the tail instead of the head.

First, we compute the index of the bone with the lowest tail z value by using numpy's argmin() function, the input of the function should be a memory view of the values computed using the asMemoryView() method, so the expression becomes:

numpy.argmin(z.asMemoryView())

To get the minimum value itself, we simply get the value at that output index as follows:

Now, we should move the armature along the global z axis—By moving the root bone Spine—to make the lowest bone touch the floor, this is done by subtracting the lowest z value from the z value of the root and assign the new location by using the expression:

object.pose.bones["spine"].matrix.translation = location

The result is the lowest bone always touching the floor which concludes this section.

Root Displacement

In this section, we shall displace the armature—By displacing the root/spine bone—based on the displacement of the bone that is touching the floor, that is, the lowest bone which we know from the foregoing section. To compute the displacement of all bones, we shall use the method I described in this question. Note, however, that all bones are children of the root bone and thus any displacement in the root bone causes further displacement on all the children, so, to get the actual displacement of the bones without the displacement caused by the root, we should add the displacement of the root to the displacement of the bones. Now that we have the displacement of all bones, we can get the displacement of the lowest bone using the index we already computed in the foregoing section.

Notice that the Get List Element node with zero index is the one that gets the the position of the root bone and the subtract gets the displacement, also notice how we add that displacement to the displacement of the bones.

Now, all we have to do is displace the root by the displacement we computed by adding it to its original position (Or subtracting depending on how we computed the displacement, which is the case here). Note that we already have the z location of the root from the foregoing section, so we just need the x and y locations. One last thing to do is reset the location of the root bone to some initial location of your choice at the initial frame, zero location for instance. This is done by checking if the current frame is the start frame and use a Switch node to switch between the current and the initial location.

And the result is as you might expect.

Blend file for study:


Merge Two Separate Equal Objects to Edit Them at the Same Time Is it possible to modify two same objects at the same time (placed in different zones) as when using the array modifier? I tried to split them using Alt + D, but nothing happens. If I modify one of the two objects the other remains unchanged. Using  an array modifier would be a bit complicated for me as the objects are facing each other but in the opposite direction. The objects are windows placed on two walls facing each other.

When you select one of the objects, selecting one object as your root object, then you are going to want to select your secondary object to link.
Then by pressing Ctrl + L, it will allow you link the object's data to the main object. That will let you edit the main mesh you selected as the root, meanwhile the other mesh will be edited as well.
But please be mindful that it likely has to have the same topology.

and apply the object data to the mesh and it should allow you to edit both meshes.


How should I model this? I am finding it hard to model this curved neck of the guitar since it is carved from a single piece of wood and am unable to keep a nice and clean topology. It would be great if someone could help me regarding this.
Thanks.

Instead of trying to model the curves manually, you could instead let the subsurf modifier do most of the heavy lifting for you.

An example of this might be something like:


How to fix boolean cut failures? I refer to the Blender built-in boolean tool described here.

I am cutting a complex surface > 30 000 facets.  All the cuts are along coplanar surfaces.  About 50 % of the cuts fail.

In the detail of the cut file posted, you can see that the boolean cut seems to be done, but that the tris are not removed.

What can I do to ensure that the boolean cuts do not fail, or is there an easy way to remove the tris after the cut failed?

See this large sample cut file.

Overall shape

Detail

Thanks.

To repair this kind of damage I would select all and press X (Delete) to start from scratch.

Very similar result you can get easier without booleans and with clean topology by shrinkwraped edges over your terrain.

Add plane, slice it by Ctrl+R with value of desired amounth of cuts
Select one short edge, search for Select Similar > Lenght and delete them (X)
Subdivide all long edges in amount of desired detail
Rotate in desired angle of Z axis
Add Shrink Wrap modifier with Projection type, Target your terrain, Z axis, Positive, Apply
Select all vertices, Extrude (E) in Z axis, move below terrain level, Scale in Z to 0
Add Solidify modifier to get thickness

Simplified sketch of proces

Hires model (1000 slices)


Config blender to save backup files in subfolder Blender is by default config to save backup file from previous saves like .blender1, .blender2 and this is a good thing in case you mess up. What i want is to config blender to place this specific files in a subdirectory. Right now they show up in the list of blender files and make the list really long if you have a few scenes. Is it possible to config blender to do this?

Illustration of the structure.

.blender_folder
..Backup
...file1.blender1
...file1.blender2
...file2.blender1
...file2.blender2
..file1.blender
..file2.blender

I took a little time writing an addon for Blender, which will move the backup save files to a sub directory every time you save. You may change it however you want it to work.

I hope it works for you guys. :)

Simply save the code below into a file called something .py, I called mine "blender_move_backup_save_files_to_a_sub_directory.py".

Then import the file by clicking: File > User Preferences > Addons > Install From File... > Finally select the file and activate the addon.

bl_info = {
    "version": (1, 3),
    "blender": (2, 68, 0),
    "name": "Move Backup Save Files To A Sub Directory",
    "author": "Jonathan Stroem",
    "description": """Move the backup save files to a sub-directory instead of the Blender-file's current directory. A new folder called "backup.blend" will be created and all save-files will be moved there instead of the default folder.""" ,
    "category": "System",
    "location": """The backup folder will be named "backup.blend". Under 'File > User Preferences > File > Save Versions', you can change how many backups that'll be used.""",
    }

#IMPORTS
import bpy, os
import shutil
from bpy.app.handlers import persistent

import time
from stat import *

#When enabling the addon.
def register():
    bpy.app.handlers.save_post.append(move_handler)

#When disabling the addon.
def unregister():
    bpy.app.handlers.save_post.remove(move_handler)

#So that Blender recognize it as an addon.
if __name__ == "__main__":
    register()

@persistent
def move_handler(dummy):

    #fullpath = Full path to the data file.
    #directory = Directory the data file is in.
    #name = Name of file, without extension.
    #extension = Extension of files.
    #backup_amount = Max amount of backups to store.
    #backup_directory = The name of the backup directory. (Where the files should be moved.) So change this if you want to change where the backups are saved.

    file = {"fullpath":bpy.data.filepath, \
            "directory":os.path.dirname(bpy.data.filepath), \
            "name":bpy.path.display_name_from_filepath(bpy.data.filepath), \
            "extension":".blend", \
            "backup_amount":bpy.context.user_preferences.filepaths.save_version, \
            "backup_directory":"backup.blend" \
            }

    #Create backup directory if it doesn't exist.
    if file["backup_directory"] not in os.listdir(file["directory"]) :
        os.chdir(file["directory"])
        os.mkdir(file["backup_directory"])

    #Get current save files from the backup directory.
    currentFiles = []
    for f in [ f for f in os.listdir(file["directory"] + "\\" + file["backup_directory"]) for c in range(1, int(file["backup_amount"]) + 1) if f == file["name"] + file["extension"] + str(c) if os.path.isfile(os.path.join(file["directory"] + "\\" + file["backup_directory"], f)) ] :
        currentFiles.append(f)

    #All this is moving the correct file.
    if len(currentFiles) < 1 : #If no files, then no need to check.
        if os.path.isfile(file["fullpath"] + "1") :
            shutil.move(file["fullpath"] + "1", file["directory"] + "\\" + file["backup_directory"] + "\\" + file["name"] + ".blend1")
    else : #If the max backup amount has been reached, then check for the oldest file and overwrite that one.
        if file["backup_amount"] <= len(currentFiles) :
            replaceFile = {"modified_date":None, \
                           "fullname":""}
            for f in currentFiles :
                stats = os.stat(file["directory"] + "\\" + file["backup_directory"] + "\\" + f) #Get attributes from a file.
                if replaceFile["fullname"] == "" : #This will happen only the first time.
                    replaceFile["fullname"] = f
                    replaceFile["modified_date"] = time.asctime(time.localtime(stats[ST_MTIME]))
                else : # Is the previous file older or newer? If it's older, then you'd want to overwrite that one instead. Go through all backup-files.
                    temp_modified = time.asctime(time.localtime(stats[ST_MTIME]))
                    if replaceFile["modified_date"] > temp_modified :
                        replaceFile["fullname"] = f
                        replaceFile["modified_date"] = temp_modified

            #When the loop is finished, the oldest file has been found, and will be overwritten.
            shutil.move(file["fullpath"] + "1", file["directory"] + "\\" + file["backup_directory"] + "\\" + replaceFile["fullname"])
        else : #If the max backup amount hasn't been reached, and the folder isn't empty.
            #Then check for the next number, and then just move the file over with the correct number.
            replaceFile = "" #Location.
            for f in currentFiles :
                for c in range(1, int(file["backup_amount"]) + 1) :
                    if not os.path.isfile(file["directory"] + "\\" + file["backup_directory"] + "\\" + file["name"] + file["extension"] + str(c)) :
                        shutil.move(file["fullpath"] + "1", file["directory"] + "\\" + file["backup_directory"] + "\\" + file["name"] + file["extension"] + str(c))
                        replaceFile = f
                        break
                if replaceFile != "" : #File to replace has been found, break out.
                    break

#This document is licensed according to GNU Global Public License v3.


How to flood fill a color in texture paint? In texture paint mode how do I fill a single colour (solid or transparent) on existing paints?
I currently paint with large brush filling complete area. Is there any faster method?

You can use the recently added Fill brush:


What is a more Pythonic way of setting the value of multiple attributes? When a custom property is updated, this function is triggered and changes the boolean value of all the 10 others. It's a long and dirty code... is there better way to do it ?

def swap(prop):
    s = bpy.context.scene
    if prop == 'meshes':
        v = not s.meshes
        s.meshes = not v
        s.lights = v
        s.cameras = v
        s.nurbs = v
        s.lattices = v
        s.empties = v
        s.texts = v
        s.bones = v
        s.surfaces = v
        s.metaballs = v
        s.fields = v
    elif prop == 'lights':
        v = not s.lights
        s.meshes = v
        s.lights = not v
        s.cameras = v
        s.nurbs = v
        s.lattices = v
        s.empties = v
        s.texts = v
        s.bones = v
        s.surfaces = v
        s.metaballs = v
        s.fields = v
    elif prop == 'cameras':
        v = not s.cameras
        s.meshes = v
        s.lights = v
        s.cameras = not v
        s.nurbs = v
        ... and so on (11 times)

something like this

def swap(prop):
    s = bpy.context.scene
    v = not getattr(s, prop)

    attributes = 'meshes lights cameras nurbs lattices empties texts bones surfaces metaballs fields'.split(' ')
    for attribute in attributes:
        setattr(s, attribute, not v if prop == attribute else v)

but achieving pythonic code is a quest for a different stack exchange site, like stack overflow


How do I flatten a selection of a terrain map? How would I make this selection flat and later modify its elevation? The elevation map is represented in 3 dimensions and is a high-poly, computationally generated product of dronedeploy.

To flatten a part of your mesh:

Go to edit mode.
Select the bits you want to flatten.
Change the pivot point to "Active Element" through the pivot point menu.

Deselect and reselect an element (vertex/edge/face) that represents the height for your flattened selected. This will set this element as the active element. The entire mesh will be flattened to this height.
Scale to 0 on the Z axis via: S-->Z-->0.

That's it!


Snap to cursor on only one axis How can i move selected edges/vertices to the cursor on only one axis?

The selected edge in the image should have the exact Y position like the cursor while retaining the X of the two vertices.

I know i can copy the Y information over to the vertices but this seems tedious. Is there a more simple solution?

With cursor positioned as desired and vertices / edges selected scale it while choosing axis which you'd like to affect on scaling (in this case Global X):

Select vertices, set Pivot Point to 3D Cursor.
Press S to scale, then X to scale to 3D Cursor by X axis axis.
Enter amount of effect of scaling. In this case it will be 0.


How can I fix the rotation for this hand? I'm making the rigging for a hand, but for some reason after I do the Ctrl+N, choose the Global +X. Not all of my bones stay on the same orientation, how can I fix this?

I want all of the Z axis to point to the same direction.

you have to rotate them in edit mode by pressing R + the axis to rotate (you are wanting to align the bone rotations so you have to select if i am not mistaking the Y axis must be) and rotate the by a value of 90  or -90. ensure that the armature its not assigned to a mesh because it may get really bad bug in your mesh if you are editting it (the armature) with it, so you have to clear the parent and when you are done fixing it parent it again.


Whole mesh rotates with armature, not just the arms I want to only make the arms of my armature move so I added an armature and parent the mesh to the armature using automatic weight. However when I rotate the armature the whole mesh moved, not just the arms. (Mesh arm is already at a 90 degree angle, I want to bring it to the mouth)
Is it because i only have one armature? Do I have to do the whole body? Do anyone know how to fix this? I've inserted my blend file below
https://pasteall.org/blend/46f7daae2bb24d3fa65997dddea99977

If you use automatic weight, Blender can only "take" what it has. Since there is only one bone in your armature, Blender takes all vertices to do it, so your whole person moves.
If you add bones like this:

it works:

blend file (but be aware, i just made "rough" bones, and just on one side to prove it works):


Fix overlaps on a bent mesh - any automatic method? I use Array & Curve modifiers to create roads & surrounding terrain for my racing tracks.

This is the model that gets instantiated (horizontally) along a curve:

Because the instantiated object is quite wide, I get a lot of overlapping geometry in every sharp turn (especially in so called "hairpins", where the road turns at 180 angle), like in this example:

I can deal with this manually by selecting & removing the superfluous polygons, merging vertices (using vertex slide + automerge, merge by distance etc.), cutting new topology etc. And after some hours I finally get some usable mesh like this:

As you can imagine, this workflow isn't especially effective and the results are also far from being perfect, so I would like to ask - does anyone have an idea how to automatize this tedious fixing process? Any addon, modifier that could be useful?

Thank you

I see you are using a blender version <2.80 but if you think this method can save you some time, you can always do it in a newer version and export the mesh in an earlier version.

We will use the "Weld" modifier introduced in blender 2.82 and its new "Vertex group" option. Basically the weld modifier will merge the vertices under a certain threshold distance. We will use a vertex group only in the outer area of your road, which has more sparse geometry, because else the main part of your road will vanish.

So basically, add a vertex group and set the value to 1 in the outer part, which bends atrociously when the curve turns. Set the central part to 0.

Add a weld modifier after your other modifiers, set the vertex group to the one you created. Tweak the distance and set the duplicate limit to 0. The weld threshold has a soft limit to 1 but you can enter a higher value.

Result :

This is not the prettiest mesh, but a big part of the job is done and it is non-destructive.

Edit : I noticed that this doesn't work for U-turns. I propose a slightly different method but the results are a bit mixed. We will mask the faces which are overlapping on the road.

Add a plane, make it follow the curve with an array and curve modifier. Hide it.
Back to your road, add a new vertex group. Name it "Mask".
Between the "curve" modifier and the "weld" modifier, add a "Vertex Weight Proximity" and a "Mask" modifier.
Set your new modifiers like so (don't forget to invert the vertex group in the mask modifier with the double sided arrow on the right of the field :

The result will have a few artifacts but it is much more usable than before :

To try to correct the uvs, add a "UVProject" modifier in the end of your modifier stack, and set it to your UV map, and use your curve or your arrayed plane to project :

I assumed you used different materials for the road and its exterior but you may have a visible seam there... I don't know much more about this.

Note : the "vertex group" option did not work in my 2.82 version although the field is here, I had to use a 2.83 beta version, if it was a bug it was fixed by the team inbetween.


How can I extrude an edge along the local axis? I have been searching for a solution and it should not be that hard. This is what I tried:

I created a cube and rotated it along the Z axis in object mode.
In edit mode I switched to the local transform orientation, which looks like this:

Which is exactly what I wanted.
Next I Extrude, and press X twice to presumably lock to the local X axis. However it ends up pointing in the wrong direction and in the bottom left it says "along normal X" which is not what I want:

How can I get blender to extrude along a local axis?
Any help is much appreciated!

This is because the Extrude and Move operator seems to always use Normal orientation.

To use the selected orientation (in this case Local), cancel the operator (Esc or  RMB), then press GZZ in order to use the normal Move operator:


Artifacts in Render which actually don't exists geometrically I have a plane which had a Boolean with a text converted to mesh.
This is the render
There are visible imperfections in this which i think are called artifacts but i can be wrong

These imperfections don't exist in the geometrical form , which means there is no geometry there , just a flat plain
All modifiers on the planes are applied
im using the Cycles rendering engine

Also visible there are no other objects in the scene causing any interceptions , so how is this happening.
Imerfections are also not visible in the render mode in blender

This could come from having to little geometry on your plane.
Basically Blender shows you editable points which we consider geo but uses triangles to compute the mesh. (not the most accurate description but oh well...)
Your boolean creates very long triangles which aren't displayed in the viewport but create problems in the render.
To fix this you can just subdivide the plane a bunch of times before applying the boolean.
Hope this helps :)


Why doesn't "bpy.ops.wm.save_as_mainfile()" work in UI panel? Why doesn't

bpy.ops.wm.save_as_mainfile(filepath="D:/ddd/test_v1.blend")"

work in UI panel?

I need to add a new button in the render panel which sends the current file to a network location.

Use backslashes (\) instead of forward slashes (/). Also you need to either escape special characters, or use (') instead of (").
The following code should work:

bpy.ops.wm.save_as_mainfile(filepath='D:\ddd\test_v1.blend')

or escaping characters

bpy.ops.wm.save_as_mainfile(filepath="D:\\ddd\\test_v1.blend")


I want a double layered material, with the outer layer being glass, how can I achive that? I'm new to blender and I'm wondering if there is a way to make a shader covered in glass, using only materials.
I've just tried mixing glass with a diffuse using a radial gradient, but it didn't pull off the effect very well.
I want something like this but with a single mesh, is that possible?

Viewing-Angle Based Solution
This setup works well for curvy objects.

But on a cube, for example, it is far less convincing.

I'm sure that with some serious noding you could get much closer, but it may not be worth the effort.

Node Explanation
Inner Material
The Diffuse BSDF node is the plug'n'play part of the node tree. Whatever shader is put in its place will look like it is coated in glass.
The normals of this part are slightly warped by the Reflection coordinates to approximate the refraction of the glass coating.

Glass Mix Factor
This part creates a mask at grazing viewing angles that is either black or white.
To keep the glass bright, all back faces are added to the mask. If this is not done, the glass will often look dark.

Clearcoat Mix Factor
Once the glass has been mixed in, there is no reflection above the inner material. To add this only where the glass is not already part of the shader, subtract the glass' mix factor from the Fresnel (which should have the same IOR as the Glass BSDF).


How can I make an object's tip position exactly where the IK controller bone is? So I have this robot leg I made. This is the current setup I have

The selected bone is the IK controller bone. When I tried to move the IK bone to the 3D cursor in edit mode I get this.

So as a work around I instead created 2 bones. The upper one has a copy transforms with the lower one as a target.

This works kinda fine but I wanted to know if there is a way to make it so that the IK bone is always on the lower part of the leg. For example when using my rig ( I moved the controller IK slightly up and to the left) I get this

What I want is for the controlller IK to always be within the highlighted region, is this possible?

Add one more bone from top controller to bottom:

Add new IK to it with target to bottom controller and chain length 1

Finally, reparent this part of leg to this bone


Is it possible to append a camera? Is it possible to append a camera from another Blend file? I have tried file > append > camera > camera and nothing happens.

Append > object > and your camera should be in the list. Are you sure you haven't renamed the camera and are looking for the wrong name? I've appended many cameras this way. Can you post a blend?


Point of origin at 0,0,0 I want to design furniture.

I've got measures from the front wall, side walls and the floor.
When I draw a table of 2.20m long, it is centered in the frame and is positioned at X axis -1.10 to 1.10m.

I need a non centered draw, and the x axis must go from 0 to 2.20m.
How can I do this?
Thank you.

You can either move your origin (1),
or move your vertices in edit mode (2).

Solution 01. Move the origin
Set Transform to only affect Origins
Sidebar > Tool > Transform only Origins

Then you can move Origin point as any other object.
Disable it again to move your object back to 0,0,0.

Solution 02. Move vertices
Switch to Edit mode, select and move vertices.
This will keep the origin point in place.

Note:
You need to do this for each new object.


Wierd problem with textures turning white I have a strange problem that I have been hammering for 6 hours now. All primitives with texture assigned to them turn white.

So far I have tried:

The texture tab I viewport shading
Cycling through all render modes
Everything in the shading tab
Object color in Object tab
Made sure new primitives had UV coordinates

Nothing will effect the primitives, I can't assign material or a texture.

In texture view, you you will see the image from the UV editor, not the image(s) from the texture(s) assigned to the material, as illustrated in the image below.

Open up your texture image in UV editor while you have the UV map open (if that image is already assigned to a texture, you need not load it again, just click the arrows to the left of the word New, and a drop down list with already loaded images will appear).

You can make the same image visible in solid view as well, if you enable Texture Solid in the Shading panel.


Eevee output low res When I render animation and output to mpeg4 it's a very very low res file and quality. How do I fix this? I'm using Blender 2.8 and I'm new. 1920 1080 is what I have entered, I have also selected ff and h.264. I've also noticed it outputs it to an mkv file and not mp4.

Thanks

For .mp4 output you need to select the MPEG-4 container. The output quality can be changed by setting the "Ouput Quality".


Exporting a GLB file to share it on Facebook I have tried "glTF Blender Exporter", "blendergltf" and "glTF 2" to try and export a Cycles model I made to .GLB format for Facebook upload, however nothing I tried worked.

Only "glTF Blender Exporter" seemed to add options in the "Export" menu, but even though I packed my textures, applied modifiers and followed the slim instructions given with it, I couldn't get it to export a model with the textures.

If anyone has made this work, I'd love to hear how they did it!

UPDATE: For Blender 2.80, see the Blender Manual 2.80 glTF/GLB documentation.

These instructions are for Blender 2.79x with the Khronos Blender Exporter:

https://github.com/KhronosGroup/glTF-Blender-Exporter

In addition to installing this plugin, you will also need a copy of the glTF2_Principled.blend file that ships with the plugin, for a custom node group it contains.  Future versions of this plugin (glTF-Blender-IO for Blender 2.8) will not depend on these custom nodes, and use the Principled BSDF node instead, but it will target the same channels in the glTF output file.

First, select Cycles as the rendering engine.  Then click File -> Append -> glTF2_Principled.blend -> NodeTree -> glTF Metallic Roughness.  This imports a custom node group into your blend project, that the exporter will look for when exporting materials.

Create a new Cycles material, and turn on "Use Nodes".  Then, select the newly appended node group, the "glTF Metallic Roughness" node, like this:

The inputs on this node correspond almost exactly to the various channels available inside the glTF 2.0 format, and the glTF exporter will specifically look to see what's attached to this node when creating the glTF file.

Note that some are named "Factor" or "Strength".  For example there is a "BaseColor" and also a "BaseColorFactor".  In Blender, these are just node inputs and you can attach anything.  But in glTF, the "BaseColor" is specifically a texturemap, that can be present or absent, and "BaseColorFactor" is a solid color (including alpha) that can either multiply against the BaseColor Texture, or be used in lieu of a BaseColor texture for cases where the base color is solid.

So keep that in mind when hooking up node inputs:  Connect only texture images to the primary inputs, and set solid colors on the "factor" inputs.

glTF can also pack Occlusion (Red), Roughness (Green), and Metallic (Blue) values into a single image.  Thus, a single image node can be connected to both the "MetallicRoughness" and "Occlusion" inputs, to allow that image to drive all three channels.

A tangent-space normal map can also be connected, and optionally an emissive map.  If you connect an emissive map, be sure to change the EmissiveFactor to white, as that gets multiplied by the map.  The default EmissiveFactor is black so that models don't emit light when the emissive map is missing.

A typical PBR wireup may look like this:

With these textures wired up, you're ready to export a full PBR model to glTF format.  If your target is Facebook, they currently have a size limit of 3 MB including textures, so keep it small!  Using JPG images may help get under that limit.  glTF supports both PNG and JPG image formats, but not arbitrary formats.

Use File -> Export -> GLTF.  There are two choices, one will save a text-based glTF file with binary mesh and separate texture image files, the other will save a combined ".glb" with mesh and textures all rolled into a single binary file.  Facebook wants the latter, the .glb file.  You can save a tiny bit more space by un-checking "Export Tangents" from the export options.  Facebook uses ThreeJS as its renderer, and the tangent vectors are easily recomputed on the client, so no need to clutter the export with them.

I hope this helps!


Making a chain with changing size I want to make a chain with an increasing thickness or a increasing size.

Increasing thickness would be better, but a changing size is also okay because it effects also the thickness.

What I have so far is a closed curve with an array which follows a helix spline.

The helix spline is needed because I want to print a rather long chain (800mm).

All what is needed is an Array Modifiyer and an empty.

Add an array modifier to the oject.
Add an empty to the scene at the red dot.
Scale and rotate the empty slightly. Thats to get a spiral and a decreasing size.

Adjust the fine tuning with the relative distance. (Y und X values in my case).

If the empty is rotated, it creats a chain ring.
If you want to print it: move the empty downwards, until all segments ar on the same hight.

Also there is an advantage because there is no curve modifier wich deformes the single sements of the chain.


Symmetrize Weight Paint Inconsistency (Video Included) I have a model and rig that I'm trying to mirror to the other side. When I try to perform the operation it works totally fine on last weeks file. But when I do it on my most recent file, it doesn't seem to work. Even though I'm doing the exact same sequence. I've included a video displaying the issue and here are google drive links to the files in question.

https://www.youtube.com/watch?v=6ukst9GTwqg&feature=youtu.be

https://drive.google.com/file/d/1T0eq1GBg3X13GHiGopB8vjoIRtUHeGw3/view?usp=sharing

If anyone has any idea how to transfer the weight paints properly from one side to the other in my recent file, I'm open to all ideas. Thank you very much for your time!

I think your problem is that in the old file you had consistent naming convention and in the latest file you have small and large letters mixed:


Can’t select vertices on torus I am very new to blender and can’t select vertices on any shapes/objects. I am in edit & vertex mode. When I click on the torus it doesn’t turn grey, it stays orange. When I click on a vertex with the pointer, nothing happens. My torus is the only thing selected on the grid. I am trying to shape the torus but can’t because of this conflict. It won’t let me select any edges when i’m in edge mode or faces when i’m in face mode either. I have tried to press control & tab but when I do and switch my mode & then click the vertexes, edges, or faces,still, nothing happens. Please help me!

Orange marks everything that is selected. You can press Alt + A (Blender 2.8) or A (Blender 2.79) to deselect everything and then click on whatever edge or face you want to select. Keybindings have changed between these two Blender versions, which can cause some confusion.

Fully selected torus, press Alt + A to deselect
Select faces by left clicking (Blender 2.8) or right click (Blender 2.79)


Adding Bend Modifier for a parent object and treating as if it's a single object I just learnt how to bend planes into a sphere from here. But now I have created curves for few countries just on top of a plane, and I do not know how to make all of them (plane, curves and meshes on top) bend into a sphere

What I tried:

1) Made all the countries children of the plane [ocean] and applied a modifier to the parent.

Result: Modifier doesn't apply to children, but only to the plane got bent; Found an explanation that modifiers are not intended to be applied on children :(

2) Added two bend modifiers (after a subdivision modifier) for one country and tried applying to all countries using Ctrl+L and each country is bending into a globe :/

3) Tried Alt+Click, but it doesn't seem to work! Do I need to set the hotkey in the preferences?

UPDATE:

4) Lattice Modifier on Parent doesn't work too, sub-objects are not obeying to the stretch and skew of the lattice

Clearly, the ocean layer is obeying, but the countries continue to stay the same regardless of the lattice's shape

So, here's my question: How do I apply a modifier that would treat the parent object as a single object [as if it was just a plane with countries embedded on it]?

As explained in the comment, you can use a lattice to do that.

The idea is the following:

Create a lattice and scale it appropriately (1x2, as for the plane mentioned in this answer). Scale it in object mode (edit mode will give a bad result deforming the curves later).
Give it the resolution you want, ie 20x40x1

Bend it using 2 empties

Now add your curves, rotate and scale them to fit the same size as the lattice
Add a lattice modifier to one of the curves
Then link the modifier to the others CtrlL then 'modifiers'

edit the blend file:

Concerning Russia, I think this is due to that:

If you convert it to mesh, lines are going east/west for a long distance, so when bent, that does not work: "these lines are like the string of a bent bow"


Root bone and walking cycles (how to keep armature in place) I'm animating a character for a game and I need help. I can animate static actions just fine because the character stays in place (like breathing or pointing a finger), but I'm completely lost as to how to proceed with animations like walking or jumping where the character has to move forward.

It is my understanding that it's better not to animate the root bone if the animation is made for games, but I can't figure out how to make the walking animation stay in place. I'm moving the pelvis/hip bone forward with every keyframe, I mean that's the normal procedure right? Otherwise I don't understand how would you animate a walking cycle.

The question is, how can I make the armature/mesh in place like you see in your usual game animation like this? I'm trying to make it cycle by copying the cycle to the end of the current timeline, but because the armature is moving, it begins walking right at the start of the first animation instead of the place where the last frame is.

Here's a gif of my animation, can upload the .blend if you need it.

Thank you very much.

It's simple (if uncomfortable for an animator!).
You have to keyframe the pelvis bone's movement but ONLY on the up/down left/right axis. Don't move it back and forward at all, and your character will walk in place like on a treadmill.
This is annoying because you can't even perceive if the motion is right unless it's actually MOVING around!
So, to save your current project you can go to the timeline or dopesheet side list, pick the track that contains the bone's forward movement, and simply delete it. The bone will keep doing its job as usual, only now it shouldn't move forward anymore.

I tested this on a very complicated rig, full of IKs, so that's why it looks weird, but if you look only at the shoulder bone, after deleting the Z-location it keeps going up and down as normal, it just stopped moving forward.


How can I paint through a mesh while weight painting ? [Blender 2.8] So I found a few questions like this already, but none of them solves the problem in the 2.8 version of blender. How can I weight paint through a mesh in front view for example? In the image below I tried using the show x-Ray option and the front face only option, but none of them works.

Update:
In the latest Blender version it looks like you need to open the N panel, click on the Tool tab and in Brush Settings:

Advanced > disable Front Faces Only
Falloff > switch from Sphere to Project
Front Face Falloff > disable the option


Chance of bigger sized particle? What I want is there to be a particle emitter which emits random sizes but also has a small chance of getting a really big particle. Is this possible? I don't mind if it's integrated, an addon, nodes, scripts or whatever.

use texture to control the size of the particles as follows :
 - add a texture to the particle system

in the texture tab change the influence to size

here is the result :

white regions -> full size particle
gray region -> small particles


How to install matplotlib for use in Blender 2.79? Mac OSX 10.11.6
Blender 2.79
CellBlender 1.1
MCell 3.4

I recently installed Blender, CellBlender and Mcell as described here:
http://mcell.org/tutorials/install_cellblender.html     http://mcell.org/tutorials/install_mcell_linux_osx.html

I have been working my way through the tutorials (http://mcell.org/tutorials/) and had success with diffusion and unimolecular reaction simulations, but when I tried to plot the results of the unimolecular reaction simulation with the MatPlotLib Plotter (see http://mcell.org/tutorials/unimol_reactions.html), it does not produce a plot.

I suspect this may be an issue with the backend associated with whatever version of Python and Matplotlib that Blender/CellBlender is accessing.

Until now I have done all of my python/matplotlib work using a Macports installation of Python 2.7/matplotlib 2.1, but I don't think my Blender/CellBlender installation is touching the Macports installation since I did not install Blender through Macports.

So is Blender just using the system Python? How do I find out the version/location of Python and matplotlib that Blender/CellBlender is accessing?  If the backend is indeed the problem, perhaps I can fix the problem by switching the backend in the appropriate matplotlibrc file?

UPDATE
The python interactive console in Blender tells me I am using Python version 3.5.3.  It appears that there is no matplotlib available for Blender to use.  For example, in the python interactive console I can find the version of numpy by typing

import numpy as np
print (np.__version__)

and I get 1.11.2 as an output.  But if I try the same for matplotlib:

import matplotlib as mpl

I get the following output:

Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
ImportError: No module named 'matplotlib'

So now my question is how to install matplotlib for use in Blender?  As I mentioned above, I already have Python 2.7/matplotlib 2.1 installed through Macports, but that is apparently a sandboxed version that is not touched by Blender.  Can I install a separate version of matplotlib that will only be used in Blender, and still use my Python 2.7/matplotlib 2.1 outside of Blender?

After a lot of digging and trial and error troubleshooting, I have resolved the issue myself.  This answer is specifically for the OS and software/package versions specified in the original question.

Blender 2.79 comes with Python 3.5.3 and Numpy 1.11.2 bundled with it.  Other Python packages (e.g. SciPy, matplotlib) are not bundled with Blender.

Install Python 3.5 using Macports, along with the appropriate matplotlib (and any other packages you want to add to Blender) then copy the desired packages from the Macports location to the Blender location.

You can keep python 2.7 as the default python for your system, and set python 3.5 as default for python3 commands:
sudo port select --set python python27
sudo port select --set python3 python35

For me the location of matplotlib in the Macports install is:
/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib

And the location that Blender accesses is:
/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/site-packages/

Note that the README file at this location states:

  This directory exists so that 3rd party packages can be installed here. Read the source for site.py for more details.

(Confirming that we have the right location)

So, to copy Macports matplotlib package(s) to Blender:
cp -r /opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/matplotlib /Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/site-packages/

You will probably want to copy numpy over as well (replace the existing one bundled with Blender), because the matplotlib you just installed with Macports was compiled with a newer version of numpy (1.13.3) rather than what is bundled with Blender (1.11.2). Matplotlib won't play well with the older version of numpy.

There are some additional packages that Blender needs in order to use matplotlib:
six.py
pyparsing.py
cycler.py
dateutil

These should be copied from and to the same locations specified above for matplotlib.

(See also this post by avocadohead:
http://eumenidae.blogspot.com/2015/09/adding-matplotlib-to-locally-installed.html)

(You can take my word for it, or avocadohead's, or you can find these dependencies yourself by trying to plot from the python console in Blender - you will get an import error telling you what it can't find. Then just keep copying over what Blender said it was looking for until the import errors stop).

Note: if you ever update Blender, the above process must be repeated (unless a new version of Blender fixes the issue by bundling these packages)

But there is also an issue with the backend.  Start Blender from the terminal so you can see what is going on behind the scenes (I recommend doing this from the beginning actually, because it provides answers a lot of the originally posted questions above regarding the versions and locations of python modules/packages used by Blender).  When you try to plot something using the 'Plot' button in 'Plot Output Settings' in CellBlender, you will see the following error in the terminal:

  RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.

We can fix this by changing the backend.  I recommend Qt4Agg.  But Qt4Agg requires an additional module, either PyQt4 or PySide.  Blender will only work with PySide.  So install py35-pyside using Macports, and copy it over to the Blender location as described above for matplotlib and the other packages.

Now we just need to make this the default backend for matplotlib in Blender.  This is done by editing the matplotlibrc file.  For me, the Blender matplotlibrc file is found here:
/Applications/Blender/blender.app/Contents/Resources/2.79/python/lib/python3.5/site-packages/matplotlib/mpl-data

Open it in your favorite editor and change backend from MacOSX to Qt4Agg
then uncomment the line backend.qt4 : PyQt4 and change PyQt4 in that line to PySide.

Now, (finally) when you try to plot something using the 'Plot' button in 'Plot Output Settings' in CellBlender, you will get a plot (and it is in a separate window)!

Other useful posts that helped me get to the bottom of this:
https://blenderartists.org/forum/showthread.php?304089-Install-Matplotlib-and-all-its-dependencies-to-use-within-Blender

Using 3rd party Python modules

Also, don't bother registering with mmbios.org with the intention of asking urgent questions on their forum - the  administrator will take days (still counting) to activate your account, if they activate it at all.


How could I import a game character from another .blend file in the bge during runtime? I've tried this in my games in the past with little success, but I want to give it another shot. So, let's say I have a character and an open world and I want that character to be able to enter into a building's interior or a cave and start a level from a new blend file. I know I could just put the same character into the new file, but that clearly can't be option if I want to have dozens of  levels as the characters will eat up a lot of file space. So how can I use just one character across all of my different .blend levels and simply spawn them into an empty there where they can continue their journey?

Thank you in advance for any help. As I've mentioned, this is a problem I've tried to tackle a few times before, but have had a lot of trouble finding the resources I need.

I suggest to link groups from different files.

You have one blend file with your character. It should contain all the object that initially belong to it (physics object, armature, skin meshes, etc.). Place them all in a group that you can create an instance from it.

In your game file you can link the group from the character file.

Then you can instantiate the linked group.

You can have as many instances as you like. You can link the group into any number of blend files you like.
When you update the character file the linking files will be updated when you open them (e.g. save+load = update).
This is a good option not just for a single character but for assets too (stones, trees, houses, rocks, NPCs, GUI, HUD, Menu, vehicles ...).
Be aware this method is static. It loads on file/scene load. It does not load dynamically (in this case you need LibLoad - which should work with linking blends too).

Hint:

You can create groups from instances too. This makes linkable groups that contain instances of other groups.
When you place instances in a separate scene, you can link all groups in one step by linking the scene (rather than linking each single group). This is very useful when you have a lot of assets in one file.
Be careful with naming. Groups with the same name are supported, but you have to guess which one is the one you want.


Is it possible to make Blender prompt to save on exit? Does Blender have a setting or addon that makes it prompt you to 'save unsaved changes' when you close the window like other applications? I cannot count the number of times I have lost small pieces of my work because I exited the program just to check if I had made any changes.

Yes, (But only on MS-Windows) open User Preferences and look under Interface, you should see a checkbox with Prompt Quit beside it.

Additionally, or preferably you can use CtrlAlt + U to save it and make it load with your other defaults.

About Macs:

Closing the app with CmdQ invokes the save prompt. Quitting with CmdW doesn't. (possible bug?)
The only indication that you haven't saved is the 'dot' in the red, close-window  button, top left of the window.