Creating addon for rotating fbx model in python This is the code I wrote for rotating the .fbx model I imported from Rhino.

bl_info = {
    "name": "Reture Z axls",
    "category": "Object",
}

import bpy

class ObjectRotateX(bpy.types.Operator):
    """My Object Rotate Script"""
    bl_idname = "object.rotate_x"
    bl_label = "Rotate X by 90"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):

        scene = context.scene
        for obj in scene.objects:
            obj.rotation_euler = (0,0,0)

        return {'FINISHED'}

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

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

if __name__ == "__main__":
    register()

The problem is that it will rotate everything in the scene including the camera. I wonder if there is better way to do this? Also is there anyway I can rotate each object seperately?
Thank you!

This sounds like a task that should be performed by the import FBX addon. The addon does include some options for rotation.

The first set of options allow you to define which axis is up and which is forward, if those two don't resolve the placement you may also need to try turning off the last option Use Pre/Post Rotation


Correctly applying new materials to the object I have a  blender object , a chair specifically. Below is the image of the chair -

Now I use the following script to change the texture of one of the component -

def createMaterial(material):
    tex = bpy.data.textures.new('ColorTex', type = 'IMAGE')
    tex.image = bpy.data.images.load(realpath_of_image)
    tex.use_alpha = True
    # Create shadeless material and MTex
    mat = bpy.data.materials.new('TexMat')
    mat.use_shadeless = True
    mtex = mat.texture_slots.add()
    mtex.texture = tex
    mtex.texture_coords = 'UV'
    mtex.use_map_color_diffuse = True
    return mat

def make_chnges(components, randomno):
    ob = bpy.data.objects[0]
    mat = createMaterial(material)
    ob.data.materials.append(mat)
    ob.active_material = mat

Now the output image that I get is -

As you can see the rendered texture looks like a flat surface. What changes should be there to show up a similar surface?

Edit 1

This is the blender screenshot of what I see when I add a new material to the polygon.

Here the object component looks allright(doesnt look like a flat surface), except that the new material doesnt show up. Just the white color is seen.

Edit 2

The material I am applying is -

It's a little difficult to test since you didn't provide a .blend, but this should give you a solution.

First of all, remove this line from your script:

# mat.use_shadeless = True

Shadeless is what is making it look flat.

Second, the texture. You had it right in your first post: you want it to be UV mapped.

# this is correct:
mtex.texture_coords = 'UV'

But in order for it to show up properly, you need to UV unwrap your model. You can find an abundance of tutorials for it online, and if you already know how to do it you can disregard the rest of this answer.

Imagine this is your chair back:

Go into edit mode with Tab, and select where the seams of the texture will go. This will make sense in a second. Here's approximately what I'd recommend, for a chair.

Notice that if you took scissors and cut along these lines, you would be left with a bunch of more or less flat pieces. This is exactly what you want. Now press CTRL + E and click Mark Seam.

If you deselect all (A) then you'll see red marks where you "cut" your mesh.

Press A to select all agaain, and press U and click Unwrap. In the bottom left corner of the 3D view, change it to a UV/Image editor.

Press ALT + O, and browse to the texture you want, and then using R G and S, position the unwrapped model the way you want it. You may want to line the grain up with the vertical axis for example.

And you will be left with a gorgeous chair back.

If you look around at the backside, you can see the seams too.


texture splatting - mix multiple (4) textures In my game I'm trying to use texture splatting technique which allow me to have up to 5 textures on landscape chunk. For this I need to generate blend map so my game engine know how to blend those textures. I was googling a lot and found few tutorials describing how to mix 2 textures with one stencil. But I need to mix 4 textures and since I'm very new in Blender and design I'm experiencing few problems:

For beginning I added 3 textures (grass, dirt and sand) and 2 stencils between them. But with this approach I can only draw sand on dirt, I cant add sand on grass because first stencil block it. It does change stencil but I can't see sand over grass.

how can I solve this?

At least I can paint on stencils and now I have to combine them to get one colored texture with each channel intensity of some texture. I was manage to achieve this using node editor:

but now, how do I export this to external image file so that I can use this blend map in my game?

Maybe in common I moving in wrong direction and there are better ways to generate blend map for 4 textures, while painting on landscape mesh in Blender?

You basically had the right idea about breaking it down by color channel.

Here's one example of how you can solve this:

Using RGB and black to create a 4-texture blend map

I could have used the alpha channel, but opted for the absence of color (black) instead to represent the fourth channel because you can't see the alpha channel in the 3D Viewport or paint it in Texture Paint Mode.

This is what the node setup looks like (Blender Internal):

What's happening in the node setup

From the 'Blend Map' texture the RGB channels are separated and each one used to additively factor in the color of the texture against solid black.

The RGB Curves node just gives enough of a boost that the transitions between regions won't look dark. (Mute the node in the .blend to see the difference it makes.)

The ColorRamp and Invert nodes isolate the darker parts of the blend map and that becomes the fourth channel mask (black).

The Material node receives the final additive mix of color data (the four textures) and applies it to a material created just for this node setup that I named 'NodeComponent'. This is just the quirky way of doing things in BI's nodes so that the material will receive specular highlights and not be shadeless.

For cases when you need more than four textures, you can repeat the blend mapping process iteratively. So for example, within the red region of the blend map there could be another blend map with its own red, green, blue, and black regions. So you could use the first blend map to control what kind of terrain (grass, sand, snow, stones), and then the second level blend map to map out the grass textures within the grass region. In such a case it would be best to create a Group node and reuse it for each blend map, to keep your nodes manageable.

Getting it into your game

As for exporting, you can bake your blend map to a new massive texture, but it wouldn't be good for a game because such a large image would need to be generated. It's better to use the individual tiling textures and the blend map to combine them. I don't know what game engine you plan to use, but if you are using the BGE or Blend4Web you can use this node setup as-is. For other engines you should look into what kind of data those engines expect for a blend map.

 *Terrain material is set to 'Shadeless'. Turn off 'Shadeless' to see lighting.


Why are the render files ordered wrong? I am rendering a video as png's, because I need transparency, but even though each frame in the folder is called "file001, file002, file003," etc, it orders it as "file358, file 359, file356, file 357, file354"etc, but it only does this in the blender file view and in the video editor. In windows file explorer, it is fine, but when I put it into blender, the frames are not in order.

make sure to sort it, by clicking this button on blender's file viewer.
selecting it to Name will sort it by name


Sequential channeling in Node Editor (no PBR workflow) I'm trying to make a functional sequential channeling/masking without any external media. To make my point clear, I made this quick .blend where a traffic light goes to red > yellow > green when the input value rises.
This is the effect I've got so far:

This is my node setup:

And this is the desired output:

I know that in a PBR workflow I could just make an image for channeling/masking the output colors via UV mapping, but I wonder if I can achieve the same effect without external data
Objective:

Achieve the desired sequential effect with different color output on each element (see example above)

Rules:

No external media or UVs for channeling/masking (PBR workflow)
No external add-ons or plug-ins
No animation/keyframe use

Extra points for:

Optimizing node setup
Finding and explaining a better way to achieve the desired effect
Is there a binary value input? like an ON/OFF for each individual element instead of setting a math conditional by numeric values?

Thanks in advance for your help!
Edit: here's the original .blend file

You can use "texture coordinate" input node and a "color ramp".
The X output is between 0 and 1. So if we split the color ramp in three constant steps at 0, 0.3333 and 0.6666 we'll have the color we want for the good disk.
For the grey part, we just compare the input value (0, 0.1, 0.2, 0.3) to X clamped into 0 and 0.3.


How to move non-rotating objects together with the rotating ones on the same axis? I ultimately want to import into Unity a wheel that rotates, turns, and adjusts to the terrain. I'm wondering how to keep the frame and plate with the actual wheel that is spinning, while keeping everything but the wheel rigid. I also need to figure out how to animate the suspension/piston in relation to the hinges, but that is for a different question.

Thanks for any tips!

Here's the file if it helps:

Id make it one whole object and then parent the wheel to the solid objects, everything needs to be parented. You can then use paint weights and constraints to get the different parts to animate correctly with bones/nodes.

Parenting should be some thing like a web tree. This is a over simplification but i think it works.

Hull has no parent, Doors and Mirrors is parented to the hull, Axel is parented to the hull, suspension is parented to the Axel and the wheels are parented to the suspension.


Blender 2.8 OpenGL requirements and Render Farms I am currently theory crafting with my IT team about getting Blender installed on our render farm.  However the render blades we have do not have GPUs currently installed.  I was wondering if this would be an issue with 2.8 due to the Hardware requirement?

These blades already handle Vray stand alone which we are eventually going to utilize once the 3D program we are using gives us a released build with Vray.  But in the mean time I am trying to utilize blender for Deadline based farm rendering.

You should be able to render from command line without the graphical user interface without trouble. You can find more info on that in the documentation


All white render in Cycles I have a big problem my render F12 is all white, while my preview render is working.

Please help me guys, thanks.

If the answer isn't something to do with the post that Mark posted, it might be something to do with the planes you have in your object view, many are enabled in rendered mode, but disabled in view mode:

Alternatively, make sure you don't have a crazy bright lamp enabled in render but not in view.


Can I use gt1030 for rendering while useing igpu for my vga display? I want to edit videos and create animation in blender. My budget is very low and able to use gt1030 and a vga display. I have a 240 watt PSU which I can't replace, Just because I am using dell vostro 3668 with cpu intel g4560. Now my question is, in this circumstance Can I use my igpu's vga port for my display and gt1030 for rendering stuff in windows 10?

Yes of course it's possible.
Blender used openGL. It's very old API and utilizing different GPU on it is hard. So most of the time blender use single GPU for normal usage. Note, if you useing motherboard's VGA port to open blender. It want to use iGPU instead of discrete GPU. As I am using windows, the OS smartly want to use the powerful graphic-card. Because powerful one is better then.
This two different requirements makes blender to crush before opening. This can be solved by silencing Windows's smartness.
To do that :---   Open setting in windows 10 -> Search Graphics Setting -> Open it -> Below the classic app click on browse -> Find and select Blender.exe (executable) -> Click OK/Open -> Then on Graphics Setting goto blender -> options -> set Power saving ( for motherboard's display connection) else automatic -> Save it -> Reboot and Check.
This solved my problem. But this tweak is OS specific. What about linux / MacOS? Question remains and testing needed. This problem should be solved on blender or openGL level.
Any suggestions or improvements is welcome.


How can I make two objects share the same vertex? How can I make two objects share a vertex, so that when I translate the vertex both objects are deformed? I want to keep two objects, so joining the objects into one is not an option.

Vertices can't be shared unless they are on the same object.

For what you want to do you can use hooks.

On the first object enter Edit Mode (Tab) and select the vertex you want to control. Press the Space Bar, type Hook and select Hook to New Object

That will create an empty in the same place as the vertex. The empty controls that vertex now.

Next step is to make a vertex on the second object control that hook.

Exit Edit mode (Tab) Select the second object and enter edit mode. Press A to deselect everything and select the desired vertex to make it the active vertex.

Exit Edit Mode

Now you need to parent the empty to the active vertex on object two.

To do that select the Empty and while pressing Shift select the 2nd object (Both objects should now be orange), press CtrlP and choose Set Parent to Vertex

Now if you move the vertex on the second object (or the whole object) will make the vertex on the first object move as well.


How do I create a 10-sided die as one object? What I'm looking to do is create a 10-sided die, specifically in the shape of a 'pentagonal trapezohedron', i.e., a polyhedron that has 10 kite shaped sides.

With the following link I was able to produce a d4, d6, d8, d12, d20, & d30:
How do I create an 8 sided die from one object?

What I'm looking for is something similar for a 10-sided die.

Thanks

Fastest manual method for me so far, can be done under a minute with ease (faster if the settings in operators have been pre-saved):

Add a Cone with such settings:

Select the base vertices (Z for wireframe mode), move them 1.0 units up in Z, hit . for 3D cursor Pivot center, duplicate all with CtrlD and rotate with R 180°. Remove doubles with W5. This is what you should have:

Select every other vertex on the perimeter and the bottom vertex. Move 0.19 units up in Z.

Select all faces, hit AltJ to merge to quads. For Max Shape Angle input 50°:

Center the thing in object mode with CtrlShiftAltC Origin To Geometry and AltG. You are done with the dice:


Shadow catcher casts light (?) on the floor I'm using Cycles render to render footage with camera tracking and video in the background. I had marked "Shadow Catcher" under Ray Visibility in Cycles Settings in "Rendered" viewport view (SHIFT + Z) everything looks fine (but the video seems a little bit too dark) but when I render frame I can see this:

3D ground plane enlight the floor. How can I fix it?

It's a problem in Compositor. Seems like by mistake you connected AO pass instead of Shadow pass of Background layer to Add node in Compositor. The same issue as yours:

And correct one:


Why is "create snapshot (ghosts)" disabled? (baked sound F-Curves in Graph Editor) In VSE I have inserted a sound clip and added two custom properties.
This is purely so I can bake different frequencies as F-Cruves which greatly helps with aligning video with music.

I want those two F-Curves to be always visible in the Graph Editor. There seems to be an option that should do exactly that. In Graph Editor on the bottom bar (with menu) at the very end there is a button with a ghost icon (a second one in that row, first one is to show channels from not visible objects) that has a tooltip saying:

  Create snapshot (Ghosts) of selected F-Curves as background aid for active
  Graph Editor bpy.ops.graph.ghost_curves_create()

However this button is disabled and there is no indication why.
I have my sound clip selected, with two custom properties keyed and F-Curves for those selected.

How do I make snapshot of those baked sound F-Curves?

P.S. If it makes any difference I have Blender v2.77

The button you are after I believe is on the left of the ghost button.

Graph editor with 16 channels baked to sound to custom properties AA0 - AA15

Click on the cursor button (show_only_selected = False)  and it wont matter if the object you have baked the fcurves onto is selected or not.

Lastly I've added AA9 to the search field, and filtered to only show Speaker animations.  Now that is all this graph editor will display. If I used "AA1" as the filter string it would show AA1, AA10 ... AA15.

The BGL overlay is from my Sound Drivers Addon and can be drawn on top of graph editor, 3D view and timeline.


How to align bottom of picture to ground when loading it? I'm planing to do a simple animation of my drawings (scrolling and parallax effects with a camera).
Each time I'm loading a new Image as Plane, Blender align the center of the picture to the cursor, like this:

I was wondering if there's a way to automatically load the image ABOVE the Z axis, like this:

For now, i have to do this manually, which add quite many extra steps. Since I'm planning to load quite a lot of pictures, it would be a time saver.
I'm planning to have this type of result, just so you have a better idea of my humble project:

Current import Images as Planes addon doesn't have this feature ... so before some pythonist comes to help ... Blender is bundled with Align Tools addon. If you import all Images as Planes you can use addon to adjust them at once ...
Search for Align Operator
(or go to side panel (N) > Item > Align Tools > Advanced)

choose Object / X, Z / Min / Min it aligns all objects to left-bottom corner

then switch to Pivot / Active / Min to place Origin (Pivot point) also to left-bottom corner

Or use any other option ... to move all object to a World Origin (X0/Y0/Z0) press Alt+G


How to inset faces down to edges rather than faces I'm trying to inset faces so that I end up with a row of edges along the faces, so that I get something like this:

Here of course I just get a really thin row of faces, when I wanted edges...

If you're just wanting to make an edge in the middle:

Simple process: i >> 1 >> Enter >> W >> Remove Doubles:


Render looks different to screen view Any quick thoughts why the render through camera viewport (right) looks completely different to the on-screen render (left)?

Could be:

you have changed the "exposure" in the "Film" panel the Render Tab
and you have not re-rendered yet (i don't think is the case anyway)
there is a lamp, or a plane, or something that is hidden in the viewport but is still marked as
"rendered" as seen in the screenshot below:


How do I give a completely black object a glow effect? I am trying to give an all-black object a glow effect. Is this achievable? I have seen how to create glow effects using emission and world bloom, however, this obviously has no effect on a black object.

I am using Blender 2.82 and am rendering with Eevee in case that info helps. Thank you in advance for any assistance you can provide and please note that I am day 1 into Blender.

Here is an example of the effect I am trying to achieve:

It looks like you want Eevee for easy bloom?
You can repurpose an edge lining technique for it.  Give your object two materials and a solidify modifier with a material offset.  Make one material black, and for the other, give it emission for backfaces, but transparency for front faces:

Note that you'll need to enable some sort of blending (alpha clip is fine) and make sure you're not culling bakfaces, in material settings as shown.
There are a number of additional ways you could achieve this, constraint-placed shadowing meshes, render layers, and probably others.  But this is previewable, simple enough, and should get you what you're after.


Animating sphere squash and stretch I am trying to animate a sphere for a small project I am making that involves the sphere "talking". I know it sounds weird, but I need help on this. My problem is that I am trying to animate the spheres to scale down on the zed axis, but also move downwards to the floor at the exact same time. I could just move the sphere downwards while scaling it, but that is time-consuming. Is there an easy method for scaling the sphere while moving it downwards at the same time? Here are some pictures.
What I want to be able to animate quickly:
Normal resting position

I actually discovered a way to fix this: moving the origin point of the sphere to the bottom. Now it moves up and down on the origin point.


How to create a distorted reflection glass? How to distort a glass reflection to make it look the same as pictured below?

I don't know about the physics of such glass, But it can be created using standard bump mapping.

The light path is not necessary here, but just to be cautious ...


Displacement is blocky I am trying to do some Moon renders using NASA's CGI Moon Kit: https://svs.gsfc.nasa.gov/4720

Said kit has super high-res color and displacement textures (27000x13000), but this is what I'm getting up close:

Is there a way to smooth it out?
Even though a 27k displacement texture which weighs 1,06 GB shouldn't even look like that in the first place...
Shade Smooth is (of course) enabled. Auto Smooth is off.
I tried adding a bunch of Subdivision Surface modifiers, but they didn't help at all.
Someone said I should use Adaptive Subdivision, but I couldn't find it in the Subdivision Surface modifier panel.
I also tried plugging the same displacement texture in the Normal input of the Principled BSDF through a Bump node, but the result was even worse.
Please help me!

These lines are visible also in the original texture. So to get rid of this you would have to use some image editor to compensate it. Here I used Photoshop's Box Blur filter with range 1 px that wasn't enough so I used it twice, but you loose some details.
Original

Box Blur 1 px

Box Blur 1 px applied twice

There are probably better algorithms for reconstruction or pattern removal like some FFT Fast - Fourier Transform (they are like a magic in some cases) ... so here are some examples

https://www.youtube.com/watch?v=D9ziTuJ3OCw
https://www.wirebiters.com/salt-pepper-image-denoising-using-matlab/
https://www.cs.unm.edu/~brayer/vision/fourier.html

Ten years ago I used some FFT script for Photoshop, but it is too far to remember anything, sorry :)


Can I use OSL shaders with Eevee in Blender 2.8? I was trying to create a custom OSL shader to use with the 'shader' node in the material node editor.  However, I noticed that none of the scripts worked when I was using the default Eevee rendering engine selectedin the Render tab.  Switching the render engine to Cycles make the script nodes compile correctly.

Are there any plans for supporting the shader node in Eevee?

To be clear, OSL evolved from Renderman and has always been about Monte Carlo ray tracing, much like Cycles. It makes little sense to implement it for Eevee, as Eevee is a rasterizing renderer meant to run in real time or very close to it; while Cycles is designed to take its time once and provide a very detailed and realistic-looking result for playback later. I want to emphasize that Sony designed OSL with specifically this use in mind, it was made for (and continues to be used for) Hollywood productions; you can use it with other rendering engines, sure, but they have to be ray tracers for a large portion of its functionality to even make any sense.
Eevee would be better suited to GLSL or HLSL, built more for games, than it would OSL, so no, it isn't possible to implement them (you would have to completely redesign them to work in this context) and it's unlikely to become so. I do think it is a possibility that some form of shading language will be implemented in the future, though.


How to make a texture interact with scene lighting and shadows in cycles I have a texture UV mapped on to an object (the logo decal), but it doesn't interact with lights or shadows as it should. How can I make it behave as it would naturally?

You do not need the Transparent BSDF node. Just plug the alpha from the image texture into the Fac of the Mix node.

The Transparent BSDF is a shader node, and the Fac on the Mix node is looking for a value 0 through 1, a black and white map.

Your logo will "interact with light", it just will not be glossy because of the way you are mixing the glossy nodes.

This is a simple node setup to mix the diffuse logo with a glossy node, yet still have the logo partially glossy.
Use the "white" end of the ColorRamp node to control how glossy the logo will be. White (a value of 1) will have no gloss, and black (a value of 0) will be full gloss, and you would not see the logo.


Eyes not moving with body So i have a character with just 3 bones going through the middle of his body. The eyes (separate objects from the body) also have bones as shown in the picture. The bigger middle bones control the smaller ones for moving the eyelids and the eyeball.
The only thing i don't understand is how to get the eyes to move with the body but still be able to move the eyelids and eyeball. I tried parenting the eyeball to the body but then the eye moves inside the body and still doesn't do anything in pose mode. The picture shows the character with the top eyelid on the right eyeball and the bottom eyelid on the left eyeball. It's in X-ray view.
The armature for the body and eyes are separate armatures.
What i tried so far:

joining the eyeball and body. This stops the eyeball from moving individually though.
Parenting the eyeball bones to the body. This moves the eyes to a really weird spot and doesn't make them move with the body. When placed back at their original spots, the eyeball bones don't function properly anymore.

I am going to redirect you to a similar question that I answered which I think will fix your problem, let me know if not. Similar question


Letting the camera move along different paths What I want:

I have a model of a room with several objects in it. I want to see the objects in the room from several camera positions on three of the four walls. Basically, I want to let my camera follow predefined paths along these walls.

What I did:

I could not figure out how to make a path looking like an open rectangle, so I decided to create three different paths, one for each of the three walls. I managed to let my camera follow one of the paths nicely. However, I do not manage to let my camera jump to the next path/wall once its done with the previous one. According to this thread http://blenderartists.org/forum/showthread.php?204414-Follow-one-path-after-another-in-Blender-2-5 it should work with object constraints and the influence value, but since the blender file given there is not available anymore, I can't figure out how to do it. So, how would you animate the camera for this purpose?

No need to use multiple curves:

Add a circle (ShiftA> Curve > Circle)
Switch to edit mode (Tab) and set the handles to vector (V> Vector)
Delete one segment by selecting two of the control vertices on one side and pressing Delete> Segments.

To align the curve to the axes, rotate it 45° on the Z (RZ 45).


How does the Inset Boundary option work? Insetting the two faces shown on this mesh (which has a mirror modifier) and pressing B seems to work as intended, toggling whether the middle edge is inset or not.

However, when insetting the face shown here, toggling the Boundary option does nothing.

Why is this?

The boundary option on an inset faces operation will only inset new faces where the mesh doesn't have a boundary (where the edges connect 2 or more faces).  Where face edges have only a single edge, no new edges will be created:

Any difference in behavior from toggling "boundary" on the operation depends on whether the edges of the inset face are manifold-- which is not apparent in either of your flat shaded example images.


Troubles when using Pause in the game from "New Game" Pause works great in the Main and "Are you sure want to quit?" scene
But if i press "YES, i want to quit" - i go to main menu and if i start New Game
there are always problems with graphics and if i press Pause in this New game - the scene "Are you sure want to quit?" freezes forever every time!

This is problem and screenshots of logic from Main "Scenebasic" and "Are you sure want to quit?" Scene

Solved the problem by adding Remove scene - Main scene every time before setting new Main scene when clicking New Game.
It can be seen on the screenshot that Main scenes double!
Yay for me


What are the formulas to define the camera's view cone? What are the formulas to calculate the 4 half-planes that define the camera's view volume?

The inputs should be the camera's world matrix, focal length (and maybe sensor size?) and anything else I overlooked.  I am not interested in the clipping start/end, but extra credit if you include them.

I plan to use this to calculate if an object would be visible to the camera, (which is slightly harder since the origin could be off-camera, but polygons could still be on-camera, but I can fudge that).

After a couple of quick experiments I determined that for a square camera the following coordinates (expressed in the camera's local coordinate system) would appear in the corners of the image:

x = y = sensor_width/lens /2
[±x, ±y, -1]

For a rectangular image, whichever dimension is larger becomes sensor_width/lens/2, and the smaller dimension is proportionally adjusted.

To define the half-planes in the camera's coordinate system, it's enough to calculate the cross products of the vectors pointing at the vertices of each edge, so

lr = [ x,-y,-1]
ur = [ x, y,-1]
ll = [-x,-y,-1]
ul = [-x, y,-1]
n1 = | lr × ll |
n2 = | ll × ul |
n3 = | ul × ur |
n4 = | ur × lr |

We normalize the vectors to length 1 so that we can use them in distance calculations later on.

When you want to determine if a particular coordinate c is in the camera's view cone convert it to camera local coordinates using

M = cam.matrix_world.inverted()
c2 = M c

Now that we have c2 (in the camera's coordinate system) we can compute the dot product between it and the various half-plane normals.

zi = ni ∙ c2

If all those zis are >=0 then the point is in the camera's view cone.  If the original coordinate is for an object, it's useful to incorporate a fudge factor like the radius of the object's bounding sphere (centered on the coordinate) and make sure that zi >= -fudge .

And this is the python class based on all that math:

class CameraCone:

    def __init__(self, matrix, sensor_width, lens, resolution_x, resolution_y):
        self.matrix = matrix.inverted()
        self.sensor_width = sensor_width
        self.lens = lens

        w = 0.5* sensor_width / lens
        if resolution_x> resolution_y:
            x = w
            y = w*resolution_y/resolution_x
        else:
            x = w*resolution_x/resolution_y
            y = w

        lr = Vector([x,-y,-1])
        ur = Vector([x,y,-1])
        ll = Vector([-x,-y,-1])
        ul = Vector([-x,y,-1])
        self.half_plane_normals = [
            lr.cross(ll).normalized(),
            ll.cross(ul).normalized(),
            ul.cross(ur).normalized(),
            ur.cross(lr).normalized()
        ]

    def from_camera(cam, scn):
        return CameraCone(cam.matrix_world, cam.data.sensor_width, cam.data.lens, scn.render.resolution_x, scn.render.resolution_y)

    def isVisible(self, loc, fudge=0):

        loc2 = self.matrix * loc

        for norm in self.half_plane_normals:
            z2 = loc2.dot(norm)
            if z2 < -fudge:
                return False

        return True


How to get rid of white edge artifacts when using alpha texture? I would like to understand methods to solve this issue; in the next picture the grass has white color around the edges, I would like to create a billboard grass with the foliage technique with alpha-planes.

However, in gimp this issues does not exist , I think this problem is from blender and the alpha channel.

What's the cause of the problem

The problem with this is how the transparent texture was created. Some pixels of the image are fully opaque (0% of transparency), some are semi-transparent and some are fully transparent (100% of transparency).

However even the 100% transparent areas have color. Because each pixel of image (when it has alpha channel) has color defined by 4 values = RGBA.

So let's say first color would be rgba(255, 0, 0, 0) and the second would be rgba(0, 255, 0, 0). They are both fully transparent, however the first is red and the second is green.

And the compression algorithms in most programs and game engines take into account also color of transparent areas. Mostly around edges where it is used for anti-aliasing, filtering, ...

Most graphics editors (like Gimp) put completely white color to fully transparent areas, which causes artifacts like in your case.

Solution

To solve this problem there is a pretty cool plugin for gimp. Download it from here (it is part of this thread). Save it into your .gimp-2.x/scripts folder (In my case the folder is located here C:\Users\Stefan\.gimp-2.8\scripts). Restart Gimp, open your texture, and select Layers > Transparency > Bleed Colour into Transparent Areas .... Leave the default settings and wait til it finishes. Now export the result to PNG. And that's it, now the artifacts are gone.

Sources

This answer was inspired by another answer here. Check it for more detailed explanation and alternative for Photoshop users.


Tweening an object's world orientation In my game I have a script that when I press W on the keyboard, the camera's rotation is set to my character's rotation. That works fine, but is there a way I can sort of "tween" the camera's rotation? Right now it's instant and doesn't look very good.

The script:

import GameLogic

cont = GameLogic.getCurrentController()
own = cont.owner # Camera
scene = GameLogic.getCurrentScene()

target = scene.objects['CharacterCollision']
up = cont.sensors['PressUp'] # Keyboard sensor

if up.positive:

     own.worldOrientation = target.worldOrientation

Over three years since you asked, and with the BGE now dead, I will finally answer your question :-)

I understand what you mean by "tweening", but actually what is required is called lerping. Lerp means linear interpolation, and it is used to create a smooth transition between one value and another. One of its uses is making one object's rotation copy another object's rotation by some specified amount.

Here is the documentation on BGE's lerp()

It takes two parameters: other and factor

Other is the other thing to interpolate to, of like data type (in this case two object rotation matrices).

Factor is by how much - a float value in the range 0.0 to 1.0.

As for what to lerp, in this case it would be the worldOrientation of two objects.

In this simple example, let's take two cubes - one controlled by mouse movement, and the other lerping to match it. (Cube2 starts off rotated so you can immediately see it rotate to adjust)

Here's my script lerp.py containing my function lerp_fn(), being called through a Python Module Controller as lerp.lerp_fn:

import bge
scene = bge.logic.getCurrentScene()

def lerp_fn():
    target = scene.objects['Cube']
    lerper = scene.objects['Cube2']

    always = lerper.sensors["Always"] #Enable TRUE level triggering

    #'target' object also must have a Sensor conected to this Module in order to be recognized

    drag = 0.05 #How closely to copy the target rotation each tick (range 0~1)

    if always.positive:
        lerper.worldOrientation = (lerper.worldOrientation.lerp(target.worldOrientation, drag))

'Cube' logic:

'Cube2' logic:


Problem exporting model from Blender to 3DS Max I'm having some trouble exporting a model with textures to be imported into 3DS Max. I decided to use the OBJ exporter. For some reason the model is all screwed up when I import it into 3DS Max.

How it looks in Blender:

How it looks in 3DS Max:

I had the same problem. I solved the problem by changing the export settings


How would you curve the edges of a 3D shape? I have a basic shape that at one end is wider than the other, the object gets thinner basically but the edges of the shape are straight, instead i want them to bow inwards.

Picture to demonstrate what i have and the red lines show what i am aiming for:

Is there some modifier for me to do this? Not sure i can see an easy way to do it manually.

Here's a 3D version of your Plane.

Add some subdivisions by pressing CTRL + "R" The more subdivisions you use the smoother the curve you are after will be.

Select two edges (You could also do one at a time). Turn on Proportional Editing and choose a "Falloff" type. I choose "Smooth" here.

Press "S" to scale and the Axis you want to scale on. I pressed "S" + "Z". Use the mouse wheel to affect more or less vertices.

Add a Subsurface Modifier and "Smooth Shading" if you want a smoother look. *You can use the same method with a plane.

EDIT You could also do this with a "Bezier Curve". Create your shape and change the curve to 2D to fill the shape.


Forged Carbon Material Maybe someone can help me. I've been trying for some time now to get Forged Carbon as realistic a texture as possible. Are there shaders that can be combined, or do I have to create an image texture? How do I get some parts to gloss and reflect and others to be matt?

Thank you in advance :)

I'm sure you could do it procedurally, but if you want to use an image texture you could go this way:

Unwrap your object with the Smart UV Project mode. Give it a black image texture.

Switch to Texture Paint mode, load a forged carbon image texture, choose Brush Mapping > Stencil (Cmd to move, CmdMaj to scale, CmdCtrl to rotate), paint the surface of your object, it will paint over your black image.

Mix your image texture with a Glossy node, play with the Glossy value and the Mix factor.

If the glossiness depends on the grey value, use the image as a factor in the Mix factor. I don't know forged carbon but you might also want to play with Clearcot, in that case use a Principled instead of a Diffuse.


Merging two car bumpers I want to put an M2 (blue) bumper on an F30 (red). I downloaded 3d models for the cars, and I have everything lined up, now I just need to merge them somehow into a single seamless bumper. Do I just try to match topographies and vertex weld everything? I think that way I will get a visible line at the merge point. Anything else you could recommend?

What you suggested is probably the best option. Line up the edge loops, selected the two vertices across from each other and press "m" on your keyboard and select whichever option you wish. "At center" will bring the vertices closer to a midpoint and merge them, "at first will merge them at the location of the first selected, and "at last" will merge them at the location of the last one selected.
If the two parts are from different models though, there is no guarantee that you will have the right number of vertices to merge without messing up the topology, it may be worth it to re-model the smaller piece.


Importing mesh as a blend shape I have two versions of the same object, with one morphed in a different shape. Is there a way to import the base obj in Blender, and the other one as a shape key?

After importing the two objects in the same scene, select the shaped, shift select the base object and in the properties panel, shape key tab, select "Join as shapes".
The two objects must have the same list of vertices in order to work properly (they have to be one the modified copy of the other).


Raytraced transparency not showing other transparent materials beneath? I've tried and tried to figure out what setting I'm missing, and I'm starting to believe that maybe it just doesn't work. I'm using the internal Blender Render. I have a subtle blend transparency for my eyelashes on this model, and a "wet" transparent sphere around the eyeballs (separate from the eyes). When the lens of the glasses, with raytraced transparency for refraction, are in front of the eyelashes and eyespheres they don't render at all. If I change from raytraced to z-transparency, they render properly, but I don't have that nice refraction to make the lenses look more realistic. Any idea on how to solve this? I'll upload the .blend if requested.

Here's a render of each uploaded to imgur for reference.

Z-Transparency:

Raytraced:

You should check the Traceable property on the Eye_transparent material. This allows the material to be evaluated during raytracing calculations and will therefore let the specular highlight on the Eye_transparent geometry be seen through the raytraced glass.

This isn't strictly related to your original question, but I'd also recommend enabling mirror raytracing on your lens material to increase their realism. I recommend setting reflectivity to 1, fresnel to 3.5 and blend to 1.15. Fresnel reflectivity is really important to capture accurately for a realistic render, particularly for glass and water materials. I also think that your skin material could benefit from lowering the subsurface scattering radius a little bit. This is just my two cents and of course for a glass material to look really good it has to have an environment to reflect.


The shadow looks like a wave. How do I fix it? I can't solve it in 3 hours...

I'm assuming you're talking about the floor under the table.  It looks like the denoiser doesn't have enough samples to give you an accurate representation of the shadow.
You can enable viewport denoising and draw a render region around the trouble area to watch it render and determine how many samples you'll need to get the desired result.


Should I convert my quad mesh to triangles? If so, can I do it in this script? I have topographical data which is height on a square lat/lon grid and I've generated a mesh with the script shown below. My polygons are all quadrangles (close to, but not quite squares in this case) and some are potato-chip bent pretty badly. I think this causes problems with vertex or face normals during rendering.

Is dividing each rectangle to two triangles likely to address this problem? Is there a magic way to convert to triangles with a simple python method?

I could probably modify the script loop to generate pairs of triangles as well if necessary, just need to make sure to go around each triangle in the same direction.

But a quad can be cut into triangles two different ways, and there is probably a good way and a bad way, depending on the particular shape of the potato-chipped quad. So if I did it manually in my loop, I'd have to test each one first...

verts = list(zip(scale_x*X.flatten(), scale_y*Y.flatten(), scale_z*Z.flatten()))

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

name = 'topo'
me = bpy.data.meshes.new(name)
ob = bpy.data.objects.new(name, me)

bpy.context.scene.objects.link(ob)
me.from_pydata(verts, [], faces)

bpy.data.objects[name].select = False
bpy.data.objects[name].select = True

bpy.ops.object.shade_smooth()

Wireframe, Rendered, Texture

Is there a magic way to convert to triangles with a simple python method?

Yes, there is a method.

Based on @gandolf3's suggestion in chat I've tested bpy.ops.mesh.quads_convert_to_tris() and indeed it shows an improvement.

Subdivisioning the quad mesh first can be explored as well, either everywhere, or in some optimized way because the final topographic map is pretty big.

# from https://blender.stackexchange.com/a/35437/5334
bpy.ops.object.select_all(action='DESELECT')
ob.select = True
bpy.context.scene.objects.active = ob

bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.quads_convert_to_tris(quad_method='BEAUTY', ngon_method='BEAUTY')  # Convert to Triangles
bpy.ops.object.mode_set(mode='OBJECT')

bpy.ops.object.shade_smooth()

Initial quads, final triangles


Combine all Lists from nested Subprogramm [Animation Nodes] I got two lists from other calculations, one with a count (ex.: 6, 11, 16, 19, 20)
and a second list witch gives me degrees as a step with which i want to instance objects around a circle (60 , 32.7, 22.5, 18.9, 18).
Specific I want to to instantiate 6 objects along a circle (radius from separate list) in steps  of 60 degree z axis, then 11 Instances with 32.7 degree… etc.
From my little programming experience i wanted to do it with a nested loop because it should work parametrically for even longer lists then list.length 5, so i couldn't build a loop for every list.element by hand.
My Problem ist that from the VectorList.outs of the lower one of the nested loops i only get the last Vector List and cant combine them to a final list in which there are all location at once for instantiation.
I hope my problem is clear enough yet,
maybe i will try to explain it better  in the evening.
But I thought maybe ist just difficult for me as an Animation Nodes Beginner
Greetings AM

Solution 1 but not with AN:
Found a way to do it with Python(Beginner) script inside AN, maby its clearer know what i wanted to do with AN than in my description. Question is still open because i want to learn AN and not do it with Python.
#node_in: Count_List [6, 11, 16, 19, 20]
#node_in: Degree_List [60 , 32.7, 22.5, 18.9, 18]

tempList = []

for index, item in enumerate(Count_List):
    value = Count_List[index]
    for index2, x in enumerate(range(int(value))):
        result = Degree_List[index] * (1 + index2)
        tempList.append(result)

return tempList

this List then goes to the instantiator-node

Just loop over all the lists you have and do your computation:


Transform manipulator is no longer in center of selection I am new to Blender and i have a very frustrating issue. I find it difficult to get used to all the shortcuts so i may have pressed something i didn't mean to :

XYZ axis should be in the center of the object / face / vert (like in the first picture), not in the center of the 3D cursor (like mine is in the 2nd picture).
How can i achieve that ? And how can I return it back ?

Ah yes, an easy fix.

To fix this problem click the small button on the bottom of the screen, in your case it should look like this:

Click on the button and click the default, "Median point"

Your manipulator should be fixed then.


Removing triangles and ngons Apparently -- amazingly -- no other question seems to have a similar title to this one.

I will retopologise later, so please don't think this is the final topology.

I'm trying to remove triangles and ngons in my mesh, but when I remove ngons, it creates a triangle.

When I remove triangles, by turning them into ngons, it turns any neighboring quads into ngons.

Using this method doesn't remove triangles and ngons.

How can I do what I'm trying to do?

Thank you.

Just for consideration, you have many T-splines around your hole which automatically makes neighboring geometry N-gons (N-gon is every face consisting of 5 or more vertices)

If you want less messy geometry you should get rid of T-splines. You can do this by dissolving unnecessary edges (some of them are marked in orange on the image below (x -> dissolve edges)). Dissolving edges (also dissolving vertices or faces) is really handy in cases when you are cleaning your own geometry. Also, you should merge some vertices.

And, most important. Next time you are doing something like this just do this:

Make sure that the shape in the middle has same edge count (number of vertices) as a hole that the hole that you are trying to connect it to. If not, fix it by dissolving verticies.

Select both and connect them via bridge edge loops (Ctrl+E -> Bridge edge loops).

Then if you want more geometry just add subdivision surface (you probably don't have that tight poly budget).

And one last thing. Don't be so afraid of triangles. It s true that quads are usually better, but sometimes you just gotta do what you gotta do.


How can I make a warning sign appear when an enemy is behind my character in game engine? I have a First person shooter game with enemies that are constantly seeking my character. How can I make a warning sign appear when an enemy is behind me? I have tried the near sensor, but it didn’t work.

The near sensor is checking if an object is near.

You requirement is to detect if the enemy is behind the character. Either you use a radar (looking behind the character), or you use the near and check if the detected objects are behind the character.

Nevertheless the near sensor should detect objects already. Are you sure the enemies are in range and detectable (dynamic, or rigid body)?


Weird shadow colors / saturation in a Copper material (Principled BSDF) I feel like an idiot right now for not knowing what's causing this. I have been saving out some metal shaders and ran into this problem:

If you look at the interior of the ball, the shadows are extremely saturated (almost red). I have nothing fancy going on like SSS or translucency / whatever.
It's even worse at low roughness values:

Do any of you know what's causing this and how to fix?
Thanks much.

Filter Glossy
After doing a little bit of testing, I found that the problem seems to stem from this little booger in the render settings.

Filter Glossy is designed to reduce noise in reflective caustics by "adaptively blurring glossy shaders," but it seems that one of the side effects is very inaccurate recursive reflections.
Tests:

All 32 samples and denoised with OpenImageDenoise.
12 glossy bounces
Glossy BSDF set to Multiscatter GGX
Color: RGB (1.0, 0.485, 0.352)
Roughness: 0.15

Filter Glossy set to 10.0 (maximum):

Filter Glossy set to 1.0:

Filter Glossy set to 0.1:

Filter Glossy set to 0.0:


Filling in Grease Pencil Shapes via Python Script I am trying to fill enclosed shapes in Grease Pencil using Python Script, as if using the fill tool. There seems to be a Grease Pencil operator, but I haven’t been able to figure out how to use it in the script (bpy.ops.gpencil.fill()).
Any help would be much appreciated.

bpy.data.grease_pencil["GPencil.001"].palettes["GP_Palette"].colors["Color.002"].fill_alpha = 0.6

-should do the trick.
Hover the mouse of the Fill -> Opacity slider in the properties panel(N)
and take a look at the command that shows in the popup. Change the names
of the "GPencil.001" and the "Color.002" to the ones that the command is pointing
to(the ones you are using).


How do you create mask and "give it a diffuse shader" in this tutorial? https://blenderartists.org/forum/showthread.php?287130-Quick-Tutorial-How-to-Model-a-Damaged-Planet

I am working on this tutorial but I am stuck on creating mask to the sphere or something.
I have the main sphere (planet) in layer 1 and have created an atmosphere in the layer 3. Now this tutorial says :

  Now to give the Atmosphere in the separate layer a mask you duplicate the 1st Sphere (Surface Sphere) again and move it to the same layer as the atmosphere, now give the mask a Diffuse Shader and set the color to Black.

Even if I decide to skip this part, I am unable to start compositing. I have rendered planet on slot 1 and the atmosphere in slot 2. I can't get these two renders on the same node setup. They always duplicate each other.
This is my blender window:

Also can you please try looking at the node setup from the tutorial page. and explain a few things.

This image is on photobucket so I cant see a high res image. You all must be experienced to guess a few things. Both of my render layers nodes are of same size but here, the first layer(planet) seems to have more options on its nodes. There are even 2 outputs from that layer.

1) How to get such node?

2) Can you guess the 2 look alike nodes next to the blur nodes?

3) And what is the second last node?

I guess you are confusing some concepts here.
You CANNOT combine the results you "save" in different render slots in the composite. (Unless you save them to a file and import them later on. But that's not what you want to do here.)
These Slots are mostly for comparing versions/settings of your render.

What you want to do, however, is add another render layer. (look at the right in your screenshot.) Use the [+]-Button to add a new render layer. You need separate layers for the planet and the atmosphere.

You should have something like this:

In this example, the first layer contains the Planet and the second contains the Atmosphere.

If you render this, that's what you'll see in the compositor:

THEN you can combine the results in Compositing.

HERE you can read more on render layers in Blender.

Hope this helps!

EDIT (answering the additional part of your question)

1)

To get more outputs from the first node, you need to select more render Passes for the render Layer, like so:

Here I selected all of them, just to show you.
However, to get the node, as seen in the Screenshot, just select "Emission".

The rest seems to be unnecessary. But I selected them as well, just to show you. (Note: Z = Depth in the current version of Blender)

2)

Those are Glare Nodes, set to "Fog Glow":

2a) The Add Nodes are NOT math nodes! - These are Color Mix nodes. Get them here:

You can click on the top right icon of the node to toggle the preview.

3) This node is a Lens Distortion

Find it here:


Texture paint color is the wrong shade I'm trying to make a carpet for a bedroom I'm making but when I got to paint it a color very close to white, it comes out dark gray. I set it to the right color in the color wheel and everything but it doesn't seem to be painting like that. Any help?

So (full credit to S. Visser here) I went to where it said 'Blend' underneath the strength slider an then changed it to 'add'. Hope this helps!


Sending object data from blender with urllib very slow I am sending object loc rot and scale every keyframe to http address using urllib but the frame rate drops significantly.
Thats the code I am using:

import bpy
import urllib
import mathutils
from bpy import context
from urllib import request, parse
from math import sin, cos, radians
from mathutils import Matrix

def RunPerFrame(scene):
    for obj in bpy.data.objects:
        mat = bpy.context.object.matrix_world
        loc = mat.to_translation()
        rot = mat.to_3x3().to_quaternion()
        scale = obj.dimensions
        qtX = round(rot.x,3)
        qtY = round(rot.y,3)
        qtZ = round(rot.z,3)
        qtW = round(rot.w,3)
        loX = round(loc.x,3)
        loY = round(loc.y,3)
        loZ = round(loc.z,3)
        scX = round(scale.x,3)
        scY = round(scale.y,3)
        scZ = round(scale.z,3)

    url = ''
    values = { 'msgInstruction=' : 'MOVE_OBJ',
        'rotQuat=' : str(qtX) + ',' + str(qtY) + ',' + str(qtZ) + ',' + str(qtW),
        'objLoc=' : str(loX) + ',' + str(loY) + ',' + str(loZ),
        'objScale=' : str(scX) + ',' + str(scY) + ',' + str(scZ) }

    data = urllib.parse.urlencode(values)
    encoded_data = data.encode('ascii')
    req = urllib.request.Request(url, encoded_data)
    response = urllib.request.urlopen(req)
    the_page = response.read()

bpy.app.handlers.frame_change_pre.append(RunPerFrame)

Currently testing with one object and the frame rate drops below 2 fps
Is there a way to make this faster with this code?

using Mike Pan answer i have tried to split the code and put the networking part on a different thread see if this helps with the speed

import bpy
import urllib
import mathutils
from bpy import context
from urllib import request, parse
from math import sin, cos, radians
from mathutils import Matrix

import time
import threading

class Worker(threading.Thread):

    def __init__(self, values):
        self.values = values
        threading.Thread.__init__(self)

    def run(self):
        url = ''
        data = urllib.parse.urlencode(self.values)
        encoded_data = data.encode('ascii')
        req = urllib.request.Request(url, encoded_data)
        response = urllib.request.urlopen(req)
        the_page = response.read()

def RunPerFrame(scene):
    for obj in bpy.data.objects:
        mat = bpy.context.object.matrix_world
        loc = mat.to_translation()
        rot = mat.to_3x3().to_quaternion()
        scale = obj.dimensions
        qtX = round(rot.x,3)
        qtY = round(rot.y,3)
        qtZ = round(rot.z,3)
        qtW = round(rot.w,3)
        loX = round(loc.x,3)
        loY = round(loc.y,3)
        loZ = round(loc.z,3)
        scX = round(scale.x,3)
        scY = round(scale.y,3)
        scZ = round(scale.z,3)

    values = { 'msgInstruction=' : 'MOVE_OBJ','rotQuat=' : str(qtX) + ',' + str(qtY) + ',' + str(qtZ) + ',' + str(qtW),'objLoc=' : str(loX) + ',' + str(loY) + ',' + str(loZ),'objScale=' : str(scX) + ',' + str(scY) + ',' + str(scZ) }
    thread = Worker(values)
    thread.start()

bpy.app.handlers.frame_change_pre.append(RunPerFrame)


How to create a parametric wood facade Hello guys,
can anyone give me a quick heads up on how to create this kind of warped facade? Need this for an architectural visualization as in the pictures above.
Thanks a lot!!
Niklas
EDIT: I just want to let everyone know how this community continues to amaze me every time I have a question with the offered amount of kindness and quick support!

A procedural approach would be to scale a cube into single plank and give it an array modifier.

Next add a cube (or anything) and give it an Ocean modifier and a Solidify modifier. Ocean can be modified as you wish and even animated. Resolution doesn't need to be high but you can do as you wish.

Give the original cube a Boolean modifier with difference from the ocean. Everything is still easily modified at this point.


How do I turn on brush diameter display in texture paint mode? I'm not sure if this is new to 2.7 or not, but I can't seem to figure out how to make my cursor display as the width of the paint brush when I'm in texture paint mode.  I can muddle through all right- I mean, it technically works- but since the cursor is alwyas a pointer arrow, figuring out exactly what's going to be painted and where is kind of a crapshoot until I press the mouse button.

I know from tutorials that isn't how it ought to be, but can't for the life of me figure out what preference or setting might be flipped.  (NB: I'm brand new to Blender with this release, so following tutorials and trying to discern the weird bits that are me-fucking-up versus what's simply different in the new release is rough...)

Any advice would be very much appreciated!

In Texture Paint Mode, Go to Options Panel >> Appearance >> and Select the Show Brush check box.


How to pick a true color from a texture in vertex paint mode? I can't pick a true color from a vertex paint texture, because its colors depends on perspective of view. I've tried this in vertex paint mode with material shading, but what I get is not a true color. How can I achieve that?

If you're using 2.80, you can go to the shading menu in the 3d view (in solid shading mode) and choose flat instead of studio lighting.

If you're using 2.79 or earlier, wireframe view will actually give you a shadeless view.


Blender crashes when running trying to overlap() After a few runs, it is quite certain that the overlap() function is causing blender to quit unexpectedly, I am not sure if the for loop is making blender to run on an infinite loop that cause that.

Or is there a way to write overlap() in a more elegant way to detect if an object is overlaping with another and get the the overlaping object in return.

import bpy
from mathutils.bvhtree import BVHTree
dgraph=bpy.context.evaluated_depsgraph_get()
for obj in bpy.context.scene.objects:
    if obj.name.startswith("M"):
        for obj2 in bpy.context.scene.objects:
            print(BVHTree.FromObject(obj, dgraph).overlap(BVHTree.FromObject(obj2, dgraph)))

there's only 6 objects in the scene with some cubes and cylinders for test.

The script iterates over all objects, including those that aren't meshes. Only determine the overlap for objects with type set to "MESH" and it will work properly.

Your script with the suggested fix:

import bpy
from mathutils.bvhtree import BVHTree

dgraph = bpy.context.evaluated_depsgraph_get()

for obj in bpy.context.scene.objects:
    if obj.name.startswith("M") and obj.type == "MESH":
        for obj2 in bpy.context.scene.objects:
            if obj2.type == "MESH":
                print(BVHTree.FromObject(obj, dgraph).overlap(BVHTree.FromObject(obj2, dgraph)))


" ***stack smashing detected***:  terminated" on choosing an object Blender 2.79b in ArcoLinux 19.01.4:

Upon choosing an object, Blender terminates, with
" stack smashing detected:  terminated"
Any ideas about what may cause this problem?

Well, I've learned much. I wanted to report a bug, and on the website, one of the suggestions was to download the newest version before reporting a bug, so I downloaded 2.79.7. When I opened my project and selected an object, Blender still crashed, but it rewarded me with new information...as I remember, the information said something about sRBG display not supported, defaulting to "NONE.", and I needed to check my User Preferences file. I looked through the User Preferences thoroughly several times, but found nothing relating to sRBG or any choices regarding that. So I downloaded 2.78c, which still supported sRBG, evidently, because when I selected an object, it didn't crash.
Joel Gomes da Silva was correct with his answer about using older versions, but curiosity and stubbornness prevailed, and I learned a lot. Thank you Joel!


Any idea how to get the location and bounds of object in the image? I am drawing a line of vehicles on the image, how could I get the coordinates and bounds of each vehicle in the image, since I want to crop the these vehicles one by one from this image?

I found a snippet, but the values (x , y, width, height) seem to be like the global coordinates rather than the pixel position on the image.

def get_bounds(ob):
    mat = ob.matrix_world
    bbox = [mat * Vector(b) for b in ob.bound_box]

    min_x = min(b.x for b in bbox)
    max_x = max(b.x for b in bbox)
    min_y = min(b.y for b in bbox)
    max_y = max(b.y for b in bbox)

    top_left = Vector((min_x, max_y))
    bottom_right = Vector((max_x, min_y))

    # make flat tuple, x y width height
    return top_left.to_tuple() + tuple(map(abs, (top_left - bottom_right)))

You can do this by analyzing each isolated object in the compositor after rendering, via an object ID mask.

The compositor gives you access to the pixels of the viewer node, which can be manipulated quickly in Numpy.

Blendfile here

This is the rendered image:

I gave each of the objects a different pass index, so we generate a mask that isolates each in turn with the ID mask node.

By changing the index in the ID mask node you can iterate between the objects. Here's object 1's mask:

Now, to get the bounding box coordinates all you need to do is run this script (partially based on this nice method for producing a bounding box):

import bpy
import numpy as np

S = bpy.context.scene
width  = int( S.render.resolution_x * S.render.resolution_percentage / 100 )
height = int( S.render.resolution_y * S.render.resolution_percentage / 100 )
depth  = 4

pixels = np.array( bpy.data.images['Viewer Node'].pixels[:] ).reshape( [height, width, depth] )

# Keep only one value for each pixel (white pixels have 1 in all RGBA channels anyway), thus converting the image to black and white
pixels = np.array( [ [ pixel[0] for pixel in row ] for row in pixels ] )

bbox = np.argwhere( pixels )
(ystart, xstart), (ystop, xstop) = bbox.min(0), bbox.max(0) + 1

Output I got for this image:

>>> ystart
157

>>> xstart
273

>>> ystop
380

>>> xstop
398


Varying shadows with object thickness I'm trying to create semi-transparent objects which cast shadows whose intensity depends on the thickness of the the object itself. A simple example would be a wedge shaped object which casts a light shadow on it's thin side, which gradually becomes darker as the thickness increases. I'm guessing it would be similar to adding an adsorption effect to the light ray.
I tried using the normal blender render but had no luck. So I tried adventuring in the cycles and nodes, playing with the light path is shadow ray. But again to no avail.
I suppose I actually have to change something in the receiving object but can't figure out what.
Does anyone have an idea of how I could achieve this effect

You can use volume shaders to achieve a shadow that varies with the thickness.

I used the light path 'is shadow ray' to 'disable' the shadows of the glass shader, and to set to 0 the density of the volume inside the glass, although this is actually not necessary.

The thickest part of the model is 1 BU (1 meter).

Bear in mind that this is not realistic.


Why is moving a vertex messing up my mesh? I am doing a lesson from the Blender Guru (Making a donut).
When I move a part of the icing, my mesh gets totally messed up.

The icing had a bit of sculpting. I made it a bit thicker.
Would it be better to move the vertex in position and than do the sculpting?

When I did the tutorial I had the same problem. I think I solved it by rotating it along one axis.
See if that makes a difference.


How to project picture onto hair particles? Here I have a basic plane with hair particles (just for example)
And here is something i want ,this black line, it should be visible when looking from angle in case when there is more particles on image up hair it’s too infrequent to be visible.

How can I do this? Also I would want to be able to move object and not change pattern while doing so.
This line is just an example I would like to add something different if this is even possible.

Add an image texture to hair-emitter-object and use object-coordinates. Then change the rotation (location and size if needed) of texture with mapping node to get the required result (In this example, for side projection, x or y = 90).


How to create a sphere with different ring vertex count by scripting? This question is related to this one: How to distribute the objects on a sphere evenly? I wonder if there's a way to create a sphere, in which every vertex loop's count is decreased according to its vertical position by scripting (let's say every ring count starting from the top of the sphere to the midlle of it is decreased by 6 vertices- as pictured below)? Is there a way to create a sphere and define it's individual ring's count by scripting?

P.s. I don't know if a tittle of my question is right. If not feel free to change it.

I think, there is no perfect solution to this problem, though:

What is the problem:

Chords of each circle need to be regular in both directions (latitude, longitude)
But this chords length need to correspond to a latitude of this sphere
And this latitude may not correspond to an entire amount of the chord length

So the result is only an approximation.

The code without the UI:

import bpy
from math import pi, cos, sin

#Create a new mesh from a geometry
def CreateMesh( scene, name, location, vertices, edges, polygons ):
    mesh = bpy.data.meshes.new( name )
    obj = bpy.data.objects.new( name, mesh )
    obj.location = location

    scene.objects.link( obj )
    scene.objects.active = obj
    obj.select = True

    mesh.from_pydata( vertices, edges, polygons )
    mesh.update()

    return obj

#Merge new vertices (a ring) to previous one
def MergeGeometry( vertices, edges, newVertices ):
    base = len( vertices )
    vertices += newVertices
    newVerticesAmount = len( newVertices )
    if newVerticesAmount > 2:
        edges += [(base + i, base + int((i+1) % newVerticesAmount) ) for i in range( newVerticesAmount )]
    elif newVerticesAmount == 2:
        edges += [(base, base + 1)]
    return vertices, edges

#Calculate a circle
def Circle( z, r, verticesAmount ):
    baseAngle = 2 * pi / verticesAmount
    return [(r * cos(i * baseAngle), r * sin(i * baseAngle), z) for i in range( verticesAmount )]

#Calculate the sphere
def HomogeneousSphereBySegments( segments, r ):
    vertices, edges = [], []

    if segments % 2 == 0:
        ringAmount = segments // 2
        baseAngle = pi / ringAmount
        chord = 2 * r * sin( pi / segments )
        arc = 2 * pi * r / segments
    else:
        #If odd we have to shift the angle from the 'equator'
        ringAmount = segments // 2
        baseAngle = pi / ringAmount
        chord = 2 * r * cos( baseAngle / 2 ) * sin( pi / segments )
        arc = 2 * pi * r * cos( baseAngle / 2 ) / segments

    #First pole
    vertices += [(0,0,-r)]

    for i in range( 1, ringAmount ):
        angle = (i * baseAngle) - (pi / 2)
        z = r * sin( angle )
        localR = abs( r * cos( angle ) )
        verticesAmount = int( 2 * pi * localR / arc )
        vertices, edges = MergeGeometry( vertices, edges, Circle( z, localR, verticesAmount ) )
        print( ringAmount, baseAngle, angle, z, localR )

    #Second pole
    vertices += [(0,0,r)]

    return vertices, edges

Blend file with code usable as an operator (add mesh, 'Homogeneous Sphere'):


How can I use the new BVH nodes to know if a certain object is inside a volume? The idea is to drive properties like scale if an specific objects is inside a give BVH volume.

In general if statements are a bit difficult to implement still, but checking wether are a point is inside a volume is (at least partially) possible.

Note: The solution I present here will give 'random' results if the mesh has no volume. Also it doesn't check if the whole object is inside the volume (it only checks the location vector of the object).

The main idea is to take the location of the object and shoot a ray in a random direction. If a polygon in the bvh tree is hit we have to compare the normal of the polygon with the direction of the ray. If the angle between both is lower than 90° we know that the location of the object is inside of the mesh. If it's larger the point is outside.

Let's model this idea with nodes:

Create a new group with the inputs and outputs that you'll need.

Make the shoot a ray in a random direction and calculate the angle between the normal and the ray direction.

Check if the angle is lower than 90°.

Due to the fact that the angle will be zero if the ray doesn't hit any polygon we have to check that both is true: The ray hits a face AND the angle is lower than 90°.

Here is an example on how you can use this group:

ps: For the next release of the Animation Nodes I'll write a node that does the same thing as the group here.


How do I fix line in character? I was trying to smoothen my character by pressing Ctrl + 5 ; it made it smoother but I ended up with a line and a crease in my character.

The first thing to try is enabling "merge" on the mirror modifier.

(Corrected/updated answer - initially had misread the question assuming you had applied 'smooth' operation, which actually changes the base mesh. Ctrl-5 does not actually change the underlying mesh.)

What's happened is that the smoothing is averaging vertex positions inwards, but the 'clipping' option of the mirror modifier is keeping vertices on the centre-line in place, so the center-line vertices don't move.

Note that pressing Ctrl-5 is shorthand for adding a Subdivision Surface modifier with 5 subdivisions in the Viewport (which is usually overkill). That Subsurf Modifier has a 'Render' level of 2 - which means you are seeing more smoothing in the viewport (5 levels) than you will when you actually render an image.


Get rid of dip in shirt I'm making a corset kind of thing and was using a mesh I downloaded. When I look at it in Object mode, there is this strange indentation slit. I want it to be flat, not have a strange indent.

But when I go into edit mode, the mesh looks fine, it doesn't look like there is anywhere I need to pull some vertices or edges out. Why is this problem there in Object mode and how do I get rid of it?

Oh gee, I figured it out. There was an extra edge in the back of the dip. The inside of the corset had some faces removed, but the ones kept were pulled back into the body so when looking down the corset you don't see space, you only see the edge of the corset. Must have happened when I was mirroring it in building. Maybe an extra edge snuck in there. Here is a view from the inside of the mesh, it was an extra edge. I selected it to be visible.


Blender does not set the alpha channel correctly As explained here, I use "glare" to add some bloom to my scene. The problem is that it creates emissive pixels, i.e. pixels that must both transmit all the light from object behind, AND add new light on top of it. However, as far as I understand, PNG format cannot deal with such objects because it uses non-premultiplied alpha. This is visible for example on this picture:

if I isolate the alpha channel I see its zero on all glared parts:

which explains why my final saved .png has no glare:

To mitigate that issue, I wanted to lighten the alpha channel with the value channel and write that into the alpha channel of the final .png. If I just isolate my new alpha channel, it looks fine into blender:

so I decided to replace the old alpha channel with this new one using "set alpha" in replace mode:

However, if I display the final png, it's not really what I'm after:

and if I isolate the alpha channel of this new layer, I can see that it is not at all the alpha channel that I chose above, it is not "blurred" enough:

I can't understand why the alpha I get is not the alpha I configured in blender. I'm thinking that it may be due to some premultiplied issues, but I'm not sure at all. Any idea what's wrong in my setup?
Here is my .blend file:

PS: in case it is of any interest, here are the color management settings:

This issue stems from the way Blender currently performs color management. HDR color management is a complicated subject, so I recommend some related reading first if you are unfamiliar:

Color Management in the Blender documentation
How to get accurate colors with Filmic Blender
Render with a wider dynamic range in cycles to produce photorealistic looking images
Blender 2.8 image texture node and color space

The problems of using color as alpha
The Blender compositor always works on scene-referred values in the Linear color space; this cannot be changed. This means that the RGB values of the rendered image are not in the range [0.0, 1.0], but rather [0.0, +∞), and they have not yet been mapped into the display color space (usually sRGB).
After compositing has finished, Blender applies the selected View Transform, which maps the scene-referred values into the display color space. The exact way this is done is outside the scope of this answer, but you can read the above links for more details.
Alpha makes the already-complicated color management story significantly more complicated. Importantly, the alpha channel is not affected by the view transform; alpha is always linear information stored in the [0.0, 1.0] range. Blender uses associated alpha (aka “premultiplied” alpha), so the meaning of these values is simply the amount that the background is occluded when using Alpha Over compositing.
This is a problem for your compositing setup, since you are trying to use color data directly as an alpha channel:

The color-to-scalar transformation is relatively well-defined—Blender just takes the luminance—but interpreting the result as alpha is more fraught. You are using a scene-referred value in the range [0.0, +∞) where a value in the range [0.0, 1.0] is expected. This has two problems:

Most obviously, the values above 1.0 are simply clipped.

More subtly, even inputs that are in the [0.0, 1.0] range will not be mapped to display-referred values.

The second point is tricky to understand, but its implications are severe. Scene-referred values don’t have any useful absolute interpretation, only a relative one, which means the set of values that fall into the [0.0, 1.0] range is largely arbitrary. In other words, the value you’ve ended up with is largely meaningless, and it only looks close to correct by sheer coincidence.
Imagining a better solution
The previous section outlines why using scene-referred color values as alpha is fundamentally the wrong approach, but what could a better one look like? The answer to that question is different depending on what you’re actually trying to do. Let’s address each of those in turn.
Rendering an image for further compositing
If the goal here is to generate an output image that is subsequently composited on top of another scene, converting to straight alpha at this point isn’t what you want, anyway. Instead, you should save your render in the OpenEXR format, which will save the raw scene-referred values using associated alpha.
This allows you to do your compositing in the scene-referred Linear color space, then convert to a display-referred format only as a final step. This sidesteps all of the problems that make color management of images with alpha channels so awkward to deal with, and it ensures you’ll get the highest-quality result.
Rendering an image for display
If you want your semi-transparent output to be the final render result, intended for direct display, things are more complicated. Converting from associated to straight alpha is not, in general, a lossless process, and doing it properly depends on what background the image will eventually be displayed against.
However, in this particular case, one reasonable interpretation would be to simply assume the image will be displayed upon a solid black background and calculate the appropriate straight alpha values from there. To do that, you would need to do calculations in the display-referred color space, since you care about which absolute color values are eventually produced.
Unfortunately, Blender currently does not currently provide any mechanism for converting from scene- to display-referred data in the compositor. Providing this functionality in a proper way would likely be tricky (since applying a view transform is a whole-image operation that depends on the overall light intensity of the image), but it isn’t in principle impossible. That said, that doesn’t help you much, since there’s no way to do it right now.
If you really want a straight alpha PNG that best captures the visual characteristics of your render, your best bet is probably to render to OpenEXR and use an external tool to “digitally expose” the image in a way that handles alpha more satisfactorily. I unfortunately do not know of such a tool to recommend, but maybe someone else can chime in if they do.
Sorry.


No sculping when the other side is hidden I wanted to model the arms, but I hid the whole body so that I can only see one arm. Unfortunately, the mirror effect is not applied if everything else is hidden. How can I make the mirror effect work?

Press Alt + b while in Sculpt Mode to bring up the Region Clipping tool. A box can now be drawn to define the area you want to keep visible. Everything else will be hidden. The brush symmetry will still work on the hidden parts.

Press Alt + b again to cancel this mode. Note that it's not always easy to see where the edge of this region is, though you can get a sense of it by orbiting your view. As this tool takes a slice out of the visible area, the affected region actually exists within 3D space, meaning that if you are working up a sculpt, and happen to work your way past one of the clipped boundaries, that part of your sculpt will now fall into a masked region. If this happens, you'll simply need to reuse the tool, and define a new region.


Exporting to Collada --> Loss of Transparency I created an object with glass-like appearance upon rendering using raytracing in blender, but when I export to collada, the material's transparency doesn't seem to be transferred. Is there any way I can preserve the transparency of the material when I export?

My material properties are as shown below:

If i am not wrong.. transparency is not imported into any software(May be bug in libraries).
Transparency is exported as expected but cannot be imported back.
You could verify by opening the exported file in web browser, and search for

  transparency

and see the value exported. you could also check by changing alpha value and re exporting..

Let me know if i am wrong..


How to convert STEP to Open Collada or other importable format My source models are from Creo (CAD application), and I have had fairly good success getting them into Blender as follows:

Export from Creo in STEP format.
Import into 3ds Max (30-day trial license).
Export from 3ds Max as Open Collada using the plugin.
Import into Blender.

However, my trial license for 3ds Max is ending soon, so I'm wondering if anyone knows of a good free tool that will convert STEP into something that Blender can import. Thanks!

I made good experiences with FreeCAD (0.16) both transforming to allow import into blender from step/iges data as also the other way around: exporting STLs from blender and then get them to be reshaped in FreeCAD and then exported as step or iges.
FreeCAD is fast, acurate, open source and available for windows, linux and macOS

(sometimes there are holes to stitch and most of the times when transform from step or iges into STL there are a few mesh operations and repairs needed, which work very well in FreeCad too.)

FreeCAD also understands, imports and exports DAE.

here's a little walkthrough for Blenders STL -> STEP/ IGES:
http://northernhope.blogspot.de/2013...h-freecad.html

(of course there are minor inadequaticies due to the transformation, but for me at least, these were always tolarable (below 0.1mm)) so at least for prototyping it proves to be suitable in both directions.


Wait until the action is done (in script) I'm writing a script to make playblast (animation preview) via OpenGL render. I want to start play back rendered frames right after rendering is done. How I can do it? For now my code looks like this =)

#start opengl render
bpy.ops.render.opengl(animation=True)

### TODO: WAIT UNTILL RENDERING IS DONE

#play rendered sequence
bpy.ops.render.play_rendered_anim()

AFAIK Blender still has no built-in facility to do this, without freezing the GUI. I was stuck with that problem before, and the hack I used in a production code is to query render result's filesize through os.stat, and check it at an interval using a TIMER event. If the size is unchanged from previous query, render is considered finished.

Querying filesize only works for video output; for image sequence output, try querying file count in the target directory. And depending on scene complexity, interval might need to be tweaked. Here's a sample code to test with:

import bpy
import os

class VIEW3D_OT_render_and_execute(bpy.types.Operator):
    """Render and Execute"""
    bl_idname = 'view3d.render_and_execute'
    bl_label = 'Render and Execute'
    bl_options = {'REGISTER'}

    prev_stat = None
    timer = None

    def modal(self, context, event):
        if event.type == 'TIMER':
            if not self.prev_stat:
                self.prev_stat = os.stat(context.scene.render.filepath)
                return {'PASS_THROUGH'}

            cur_stat = os.stat(context.scene.render.filepath)
            if self.prev_stat.st_size != cur_stat.st_size:
                self.prev_stat = cur_stat
                return {'PASS_THROUGH'}

            context.window_manager.event_timer_remove(self.timer)

            print("Render finished.") # POST-RENDER CODE HERE
            return {'FINISHED'}

        return {'PASS_THROUGH'}

    def execute(self, context):
        if context.scene.render.image_settings.file_format != 'FFMPEG':
            self.report({'ERROR'}, 'Only works for video output.')
            return {'FINISHED'}

        wm = context.window_manager
        wm.modal_handler_add(self)
        self.timer = wm.event_timer_add(2.0, context.window)
        bpy.ops.render.opengl('INVOKE_DEFAULT', animation=True)

        return {'RUNNING_MODAL'}

def register():
    bpy.utils.register_module(__name__)

register()

I'd be very glad if a cleaner solution is available, but haven't found it so far.


How to get rigify outlines in armatures I've been rigging my own models and lately I see a lot of models with weird outlines instead of the normal bones I use.(Like the ones shown below) How do I make these?

You can custom your bones. Create the new shape you want to see as bone, for example a circle. Then select your armature, go in Object or Pose mode, then Properties panel > Bone > Viewport Display, and select the object you've created. If you enable the Wireframe option you'll only see a wireframe object like in your picture.


What are the Change Brush Size shortcuts in Sculpt mode using Maya Navigation? I'm definitely struggling for this, I use Maya Navigation, and F and Shift+F keys are already bound.

Now in sculpt mode I can't find how to get those useful shortcuts to change dynamically size and strength of the brush, any idea how I can recover them and bind them to different shortcuts and continue using Maya Layout ?

Ok, I've found them; the keys were bound to B for the size, Shift + B for the strength and Ctrl + B for the rotation of the brush.

To find this, I first switched to the default layout and searched for the actions bound to F, noted the entries were named 'Radial Control', switched back to the Maya layout and searched for that name.


How to crop image based on Alpha in Compositor? I wonder if there is any way to crop a image based on alpha data like this:

The reason I want to do this is that I want to crop the White area of another image (of the same dimension to the Alpha image above), then stretch it to fill the whole area, or fit to other expected dimension. And this has to be done in Compositor.

For example, this is a MANUAL way to crop then fit to expected dimension:

Blend File

However, to decide the value in Crop node is not so easy in order to get rid of unwanted part. So I wonder if there is any way (math or something?) that can be smart enough to save that work.

Use this node setup:

In the texture node, you open the image you want to use as a mask, then plug the alpha output from that to the scale node's input for X and Y (the scale node's "Coordinate Space" is set to relative), you grab you RenderLayer and shove it in the image input for the sacle node, and finally connect that to the composite node.


no matter what I do, the hair net addon doesn't work (Blender 2.9) It doesn't wanna make hair from anything, It always gives me an error. Doesn't matter if its making it from a curve or from a sheet.
Here's the error it gives me after I try to convert from curve

And I also don't get any results from using sheets, they always give me an error that states "No seams were defined in X". I definately created seams where I wanted on the plane. as you can see down below

I feel like I'm at the end of my rope with this. Nothing works I followed the tutorials on this to the letter but it still doesn't work.

HairNet version
For Blender 2.90.1 you need HairNet 0.6.3. Version 0.6.2 is for Blender 2.90.0 (and older) and you will get this "mouse_event" error when you use it in a later version of Blender.
Sheets
A common mistake with the sheets is to use a sheet with only 2 "strand edges". The add-on needs at least 3 strand edges to work. Else you get this misleading "no seams" error.

Additionally

make sure that Location, Scale, and Rotation  is applied to the hair objects and to the head (Ctrl+A in Object mode).
make sure that you don't have accidentally checked the HairNet option [_] Emit Hair on Self when you have a head (sheet and head for example). Check both objects because the setting is not global but stored in the objects.
select the head/emitter object last (orange selection color)
the HairNet 0.6.3 (or Blender) has a bug the makes all hair of a random existing hair particles system move down on the z-axis if you add another hair particle system from sheets, curves, etc. You can prevent this if you turn off the previous particle systems in the viewport with the "monitor" icon before you add another one with the add-on.
don't forget to increase the number of Strand Steps (5) in the Viewport Display* settings for a better shape
and to "touch" the created particle guides in Particle Edit mode with a minimal strength brush as described in the manual


How to read vertices of quad faces using Python API? Preferable in object mode.

I have a mesh I know is made of quads only. I want my script to iterate through each quad and do something with the coordinates of each of the four vertices.

I have read the API documentation but I don't understand how faces are stored. I think what I want can be accomplished by looking at bpy.types.Mesh.polygons but the type MeshPolygon does not reference vertices directly, it references loops, and loops references a vertex and an edge, and edges, finally, references vertices.

For me this looks like a lot of guesswork to figure out what vertices form the polygon.

How to go from polygon to vertices?

The text editor has a useful template that may interest you:
Text Editor > Templates > Python > BMesh Simple

Each polygon stores a reference to the indices of the vertices it's made from.

object mode

import bpy

# obj = bpy.data.objects['Cube']  <-- depending how you want to access it.
obj = bpy.context.active_object

for f in obj.data.polygons:
    for idx in f.vertices:
        print(obj.data.vertices[idx].co)

or manipulate the mesh directly (this will affect all objects that reference this mesh). Meshes and Objects are different things.

import bpy

data = bpy.data.meshes['Cube']

for f in data.polygons:
    for idx in f.vertices:
        print(data.vertices[idx].co)

edit mode

import bpy
import bmesh

obj = bpy.context.active_object
bm = bmesh.from_edit_mesh(obj.data)

for f in bm.faces:
    for v in f.verts:
        print(v.co)

# if you make edits then you need to update at the end
bmesh.update_edit_mesh(obj.data)


Blender Shifts Audio Sometimes I apologize for the lack of information; I am new to Blender and am unsure why this is happening. I recently started using Blender for video editing as I wanted an open-source video editor. In general, it does an amazing job. I keep running into a big issue with is causing me not to use it, though.
When editing clips, sometimes, for no reason, Blender moves the audio track from the position where I clipped it. For example, if I have a video where someone is talking, and I clip just one scene from their speech and then edit other clips and come back to that scene, the audio would have shifted to a different point in the video where it was split.
I have no idea why this is happening, and it is driving me crazy. I just spent all day on something and didn't even want to restart as this is the second time it has done this. Does anyone know what may be causing this? I am on Blender 2.90. I do have av-sync on.
This could be how I am using, but I am just so new to Blender I have no idea.
SOLUTION:
Frame rate! When I was importing video clips from different sources it skewed the frame rate, use handbrake to fix it.

The solution to this issue is to make sure you use consistent frame rates. One of the videos I pulled in changed the frame rate from 30 FPS to a custom frame rate which screwed the other clips. Setting the frame rate back to 20 FPS fixed this issue for me. I know you can use handbrake to set all of your videos to the same frame rate; however, if you are like me and just want a simple solution of
setfps <video-name> <frame-rate>

or at least a handbrake-like program that uses mpv for previews instead of VLC, I am unsure what program to use.
As an update, you can use FFmpeg to reencode a framerate!


Print a timer in Python to see how long to run a script I want to print a timer in the console to optimize my script and see how long it takes to run the script.

This is one of the fastest way I know:

import time
import random

then = time.time() #Time before the operations start

#DO YOUR OPERATIONS HERE

now = time.time() #Time after it finished

print("It took: ", now-then, " seconds")

time.time() Will give you the current time in seconds.
There are other way of doing it, but this is one of the best. I have always used this and it gave me no problem at all.


Problems editing an STL for 3d printing I'm very new to blender and 3d modeling in general. I'm mostly using it for 3d printing for lost PLA casting. I don't think I should post any actual files since I paid for the original STL. I think it would be ok to PM it someone though?

I have this nice stl file of a book pendant:

but it's open at the back

I learned how to use edge loop selection and fill in order to make a back for it

Now, when I put this in Cura, it slices just fine, but the back I created isn't there. Thinking this was because of the back being a plane (0 thickness), I used the solidify modifier.

After doing that, when I put it into Cura it doesnt work. In the slicer preview it only shows it as printing 5 layers (pretty much just the raft)

I've tried:
1) extruding the plane(s) instead

2) doing clean-up - fill holes, merge by distance, decimate geometry, degenerate dissolve.

3) I also performed the checks using the print3d add-on. I'm able to do the "make manifold" on the original stl, but when I try to "make manifold" on my edited stl, my computer freezes. It's not an issue with power (I JUST finished my new PC build - ryzen 9, 64gb ram, etc).

I'm continuing to work on this. I'm now trying STL repair software. Using the windows 10 app 3D Builder to repair my edited file got a bit closer in Cura:

Can anyone help me out or point me in the right direction?

UPDATE/EDIT:

As per Mr. Zak's comment below, I tried extruding edges instead of using edge loops + fill. After doing that I recalculated my normals (just to be safe), cleaned up any vertices that extruded too far, and repaired the STL in 3D Builder. I've been alternating between repairing in STL and repairing in Builder, sometimes even repairing in one and then repairing the output in the other.

Extruding the edges leads to a much nicer looking back to the book:

As per Mr. Zak's comment, I tried extruding edges instead of using edge loops + fill. After doing that I recalculated my normals (just to be safe), solidified, cleaned up any vertices that extruded too far, and repaired the STL in 3D Builder

I have sliced and printed the model successfully! Thank you!


How to write an import script? I have searched and read scripting tutorials, but without any previous scripting experience it has presently proved to be difficult to write an import script.

I want to make a Blender import script for an ascii file format (.mdb). Could anyone be so kind as to show me where to begin?

Example file

You may use the Operator File Import template which is provided by default.

Open the Text Editor > Templates > Python

I hope, this template would give you good enough starting point and customize it as you go along with your specific needs and requirements.


Proper context attribute for a hotkey to toggle mesh display overlays? I'm lost here, F.I.:

object_data.show_edge_crease

or

active_object.show_edge_crease

doesn't work...

Also, I wonder why isn't there an "add shortcut" option in the RMB menu for this kind of toggable elements?...

The mesh is the data part of the active object hence,

active_object.data.show_edge_crease

or perhaps since it is the edit object:

edit_object.data.show_edge_crease

Sliding down the info area header at the top to reveal the messages gives you the context paths.

As for part ii) of your question adding an "add shortcut" menu, sounds like a good idea.  This can be "hacked" by overriding say the edit translations operator in the menu.


Noise issue when baking ambient occlusion to texture on spherical UV map I am trying to bake ambient occlusion to a texture using blender render on this model of a meteorite. It almost works, except for steep edges of holes, where I am getting a strange noisy / mottled pattern of black and white faces.

I did try using lightmap pack instead of spherical unwrapping, and it does make the mottled noisy areas go away. However, I need to use a spherical UV map shown because of requirements for scientific analysis later.

Can anyone explain what is causing this mottled pattern?

I figured it out. This effect occurs because these areas are "overhanging" from the point of view of a spherical projection. Pixels that would be on dark faces from inside the hole and light faces from the surface are all getting mixed up together because they share the same space on the UV map.

So, the solution is to choose a UV mapping where the projections of the faces do not overlap.


Python De-Linearize Colors I'm working on a custom exporter from blender to my iOS game engine, and all works fine and dandy, but I just noticed that all of the colors are messed up! I've looked at the Blender documentation and have searched google and found that the problem is that Blender works in a linearized color space.

How can I convert the colors to a format that other programs like? When I make a color in photoshop using the RGB values that blender gives me I get the skrewy colors, but when I copy the Hex code the color is right. I see that it says the Hex is Gamma Corrected. I'm using Mesh.materials[].diffuse_color, how can I correct this value?

Thanks for any help!

CoDEmanX's link had a way to fix this. It's more of a work around than a solution, but I can just change the display device in the "Scene" tab to None. This allows me to export the colors exactly as seen in Blender. It might mess up rendering a bit, but these are models for a game and in my case I don't need to render in Blender. One speed bump, though, is that any colors set before changing it will be messed up and will need to be corrected.