text:
How can I do a one-time Initialization?
In the following script I want to perform the loading of a DLL only once when initializing
import ctypes
import mathutils
from ctypes import *

hmd = None

def poll():
    if hmd is None:
        hmd = ctypes.WinDLL("C:\\Program Files\\Blender Foundation\\Blender\\2.68\\scripts\\addons\\game_engine_rift\\openhmd.dll")
    hmdPoll = hmd.poll
    hmdPoll.argtypes = ()
    hmdPoll.restype = ctypes.POINTER(ctypes.c_float)
    pos = hmdPoll()
    print(pos[0], pos[1], pos[2] ,pos[3])
    bge.logic.rotation = mathutils.Quaternion((pos[0], pos[1], pos[2], pos[3]))

poll()

But I get this error:
Python script error - object 'Camera', controller 'Python1':
Traceback (most recent call last):
  File "rift.py", line 21, in <module>
    poll()
  File "rift.py", line 12, in poll
    if hmd == None:
UnboundLocalError: local variable 'hmd' referenced before assignment

Note, this isn't specific to blender (its a general python question), could be moved to stack-overflow.

For initializing python scripts specifically in Blender (eg, after loading a file) see handlers

I'm voting to close this question as off-topic because it is a general Python problem which isn't specific to Blender.

It's because your variable hmd isn't global...
You can declare it as global, with global hmd in your function:
hmd = None

def poll():
    # declare hmd as global so that the function has (write) access to the global var.
    global hmd
    if hmd is None:
        hmd = ctypes.WinDLL ("C:\\Program Files\\Blender Foundation\\Blender\\2.68\\scripts\\addons\\game_engine_rift\\openhmd.dll")

Or send it as parameter when your call poll() (you have to declare it in the function too):
def poll(hmd):
    if hmd == None:
        # (...)

poll(hmd)

Thanks for your response, with first option I now get:"NameError: global name 'hmd' is not defined". The error occurs in the IF condition.

Well, I don't know what happens (you probably have not share the entire script in your question) , but if you want more info about global variables: http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them

this explained what I did wrong, I edited your answer to point this out.

The existing answer from @Polosson is correct, however Im a bit biased against globals since I have had to debug other peoples code with many globals - it can become difficult, if the code becomes complex and there are more then 2-3 of them used across multiple functions. It's a pain to keep track of them, forgetting to add a global keyword, it can fail in a non-obvious way.
Store in a global dictionary
Heres an alternative, which I prefer in some cases.
# store all runtime variables here.
runtime = {}
runtime["hmd"] = None

def poll():
    # declare hmd as global so that the function has (write) access to the global var.
    if runtime["hmd"] is None:
        runtime["hmd"] = ctypes.WinDLL("C:\\Program Files\\Blender Foundation\\Blender\\2.68\\scripts\\addons\\game_engine_rift\\openhmd.dll")

You can store the runtime state in a dictionary, and it has some advantages that you can easily print(runtime), runtime.clear()... etc. and pass it to other modules if you end up splitting your code across files.
Because the dictionary its self is never re-assigned, you don't have to define it as global.
Store in the function
Another trick, is you can store the variable in the function (and avoid using globals)
Note that this is not the functions local namespace, which is why it has to be accessed as an attribute of the function, even when inside the function body.
def poll():
    # declare hmd as global so that the function has (write) access to the global var.
    if poll.hmd is None:
        poll.hmd = ctypes.WinDLL("C:\\Program Files\\Blender Foundation\\Blender\\2.68\\scripts\\addons\\game_engine_rift\\openhmd.dll")
poll.hmd = None

Sometimes I use this for global variables that only the function ever accesses.
For more info on function attributes see:
Q: Python function attributes - uses and abuses

Rather than testing values, it's more pythonic to just try and deal with exception(s) when they arise (EAFP). You can also declare and assign your global variable in one step like so:
def poll():
    try:
        hmdPoll = hmd.poll
    except NameError:
        globals()["hmd"] = ctypes.WinDLL("/path/to/dll")
        return poll() # Retry
    # ...

Warning: Catching NameError exceptions in general is a bad idea, use with care.
Personally I'd recommend explicitly initialising hmd outside of the poll function.

Don't necessarily agree with this being more Pythonic, raising exceptions is OK but normally I only do this when its less involved to try/except then it is to check with an if/else (there are many cases where it is, but this isn't one of them), note that exception handling does have overhead in Python too. Using exceptions you run the risk of some real error in the try block becoming hidden and the except case running every time (without you being aware of it). Of course in this example its not likely to be a problem.

@ideasman42 Actually in cases where exceptions are not expected to occur often, it's normally faster. See here.

sure, though in this case I would recommend to use. hmd_poll = getattr(hmd, "poll", None) then check the result isn't None, rather then try/except


text:
Can I limit what IK bends? Need bones to only move certain way
I was working with a model of a robot arm type thing, and wanted to use an IK constraint with an empty as the target to assist in posing. I abandoned the idea because: The IK constraint seems to run over any kind of angle limits I put on the bones it affects. Though, that was back in 2.80, or maybe 2.79. On the chance that it hasn't changed, what can I do?

Select a bone in an IK armature in Pose Mode. Then click the Bone Properties tab in the Properties window and scroll down to Inverse Kinematics. There you can lock rotation around certain axes or check a box per axis to limit the rotation around this axis, and enter the desired degree values. There are also fields related to Stretch and Stiffness which can help control the movement of the IK armature.

Another thing than might cause similar issues: Normally one bone in the armature has the IK Constraint on it. This constraint targets the Armature and a Bone to follow (hand.L in the picture). Make sure this target bone is not parented to the armature. Select it in Edit Mode, press Alt + P and choose Clear Parent.

Thank you very much, :-)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
How do I make a 3D height map from this 2D heat map?
I would like to model this heatmap in 3D as a heigtmap where the brightest green points are the lowest and the brightest pink points are the tallest and black is in the middle. I have the numerical values that were used to generate the image. Also, the color information has to be maintained for the 3D printer to print it in color. I have very little 3D modeling experience and basically no programming experience but I am a fast and enthusiastic learner. I have also never used blender before. Any help would be greatly appreciated. Thanks!!

There are two obstacles here. First, make your image grayscale. White is high and black is low. Second, using that image, make it a 3D object. The first problem is not solved inside blender I think, rather photoshop.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to disconnect selected mesh geometry?
I don't know how to disconnect a face from the rest of the mesh in edit mode.
This isn't like pressing P to separate the selection into a completely different object. I just want to select a face and disconnect/rip it away from the rest of the mesh but keep it as a part of the original object.
One way to do it would be to duplicate the face with ShiftD and then delete the original face. But I suspect there is a "native" command for disconnecting selected faces and I would like to learn it.

The command I am looking for is "split" and you can select it with Mesh > Vertices > Split, menu or by pressing the keyboard shortcut Y.

@X-27 It seems to happen to me all the time, that right after I finally decide to write a question down, I also find the answer. I simply didn't understand earlier to search from the "vertices" category because I was thinking about faces. But after I asked the question, I searched some more and found it. First I considered deleting the question, but I guess it's better to leave it since it was hard to find the solution by googling.

It sounds like you want to rip the edges around the face.
It helps to go into edge select mode first by pressing Ctrl+Tab > edge select, since in vertex edit mode you may end up selecting too many edges.  Then select the edges around the face and hit V, this will rip the edges.
If you try to move these ripped edges you will actually move only the edges (any vertex located in the middle will remain fixed at its place). To move entire ripped piece you will need either to press Ctrl+L immediately after ripping to select geometry linked to selected edges or deselect all with A and then select the faces to move away.

Rip isn't meant for isolating entire selections, rather a vertex or edge loop.

Go into Edit Mode select a face press  P and click selection.

Please re-read the question. Stipulates not using P to separate selection into new object.

Only this answer let me to disconnection, so Mesh -> separate -> selection (or p) works for me, (not split). Thanks!

3.5 years later and still haven't re-read the question?

this is the correct answer

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to make objects draw transparent/wireframe in the viewport?
I have several objects in my scene. I want all the objects to be visible so that I can see how they relate to one another, but I want to focus on just one. To do this, I'd like to make the other objects translucent and non-selectable. I know I can disable selection from the Blender outliner, but there doesn't seem to be an easy way to make just that object transparent. The reason I am trying to do this is simply so that I can see objects in my scene but focus on just the object I am editing.
I'm using glsl with mapcap for rendering and am mainly working in sculpt mode at the moment, and would like to stick with glsl if possible.

You can make an object be displayed as a wireframe by setting the Maximum draw type to wire in Properties editor > Object > Display:

You make an object display as transparent by adjusting the alpha of it's material, and enabling Transparent in the display settings:

@MrFlamey, "That will do for now"  implies the answer isn't complete, please expand on that.

@ideasman42, Yes, it's not the most ideal solution, but I wanted to avoid saying "how do I replicate this feature from another package". Basically I would prefer to have a very simple way to focus on the selected object - make everything else in the scene transparent grey or wireframe (combo would be excellent) and non selectable, so that it is easy to see the relation of the selected object to the other objects in the scene, without the other objects obscuring my view of the active object too much.

@MrFlamey - if you wanted it would be trivial to make an addon to do this (and assign it a key binding). For the situation you describe I normally use local-view. though I realize they're different. One liner in the Python console for ob in C.visible_objects: ob.draw_type = 'TEXTURED' if ob.select else 'WIRE'

Thanks! I'll check out that local view thing. I'm fairly inexperienced with Blender, so there's a lot I don't know. I'll give the script a whirl.

@MrFlamey, np, in future try be a bit more clear - if the answer is bad, say so - if the solution proposed seems clumsy - explain why. Just because a tool doesn't work how you want doesn't mean the answer is bad.

This was the first Google result, and I came here looking for a Cycles answer but gandalf3's reply helped me realize.
First, on Material > Settings, change the alpha value (below Viewport Color)

Then, on Object > Display, make sure to check Transparency

For wireframe display it is the same method as gandalf3's answer.

Note that under the hood, the alpha value in cycles material settings and the Z transparency value in BI material settings are actually the same setting. I used the BI setting in my answer since the OP mentioned that they are using GLSL shading (and therefor BI). Still, useful in case you are using cycles :)

Thanks, but I was kind of looking for a solution that doesn't rely on changing material properties.

Oh, I see, I just added that in case someone comes here through google, like I did. Also just reminding that the alpha will change just on the viewport, not the material itself.

Gus, is there a way to make same thing, but in "Material" view mode? Because object loses its transparency in Material mode.

@IvanKartofanov If you want to just make the object transparent, I found a way to do that. Follow the same instructions on my post but on Maximum Draw Type, select Solid. See image. This will treat the object as solid on Material and Textured viewports. Hope it helps.

Also, if you are on Blender Internal check out this answer.

To manage many object you can use the layer manager addon.
You can lock selection and show in wire mode.
http://blender-addon.blogspot.it/2014/04/layer-manager-update-wire-mode-for.html

I will check that addon out, thanks. I'm coming from Maya, and used layers all the time, and found them so much more useful than layers in Blender, but this addon looks like it adds a lot of the useful features to Blender.


text:
switch to check if active object is mesh, curve or lamp?
Is there a way to check if an active object is either
an object
a curve
or a lamp?
Can this be done via a poll function?
The following poll works to checks if an object is object+mesh and then shows the shelf menu, and if not like an empty hides the shelf menu.
@classmethod
def poll(cls, context):
    return context.object and context.object.data

But if I have a curve or lamp selected / present in the layer this does not work because a curve for example has no autosmooth setting.
Empty Selected:

Object+Mesh Selected:

Curve Selected:

This is the code for object+data show:
# DATA ---------------------------------------------------------------------------
class ObjectData(bpy.types.Panel):
    bl_label = "Object Data and Relationships"
    bl_idname = "ObjectData"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = "Modeling Toolbox"

    @classmethod
    def poll(cls, context):
        return context.object and context.object.data

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

        obj = context.object

        col = layout.column()
        col.template_ID(context.scene.objects, "active")
        col.template_ID(obj, "data")
#---------------------------------
        row = layout.row()
        row.operator("object.make_links_data", text="Link Mesh Data")
        row.operator("object.make_single_user", text="Make Single User").obdata=True
#---------------------------------
        def draw_props(labelname, propname):
            c = layout.column()
            row = c.row()
            split = row.split(percentage=0.2)
            c = split.column()
            c.label(labelname)
            split = split.split()
            c = split.column()
            c.prop(obj, propname, text="")

        draw_props("Layers", "layers")
        draw_props("Parent", "parent")
#---------------------------------
        row = layout.row(align=True)
        if bpy.data.groups:
            row.operator("object.group_link", text="Add to Group")
        else:
            row.operator("object.group_add", text="Add to Group")
        row.operator("object.group_add", text="", icon='ZOOMIN')
        obj_name = obj.name
        for group in bpy.data.groups:
            group_objects = group.objects
            if obj_name in group.objects and obj in group_objects[:]:
                col = layout.column(align=True)

                col.context_pointer_set("group", group)

                row = col.box().row()
                row.prop(group, "name", text="")
                row.operator("object.group_remove", text="", icon='X', emboss=False)
                row.menu("GROUP_MT_specials", icon='DOWNARROW_HLT', text="")
        row = layout.row()
#---------------------------------
        if bpy.context.object.mode == "EDIT":
            row.operator("mesh.separate", text="Separate Mesh into new Object")
        else :
            row.operator("object.join", text="Join Objects into selected Object")
        row = layout.row()
#---------------------------------
        row = layout.row()
        if bpy.context.object.mode == "EDIT":
            self.layout.operator("set.origin")
        else :
            row.operator_menu_enum("object.origin_set", "type", text="Set Origin")

#---------------------------------
        obj = context.active_object

        if obj.type == 'CURVE':

            curve = context.active_object.data

            col = layout.column()
            col.label(text="Curve Data")
            col.prop(curve, "resolution_u", text="Preview U")
            col.prop(curve, "render_resolution_u", text="Render U")
            if bpy.context.object.mode == "EDIT":
                row = col.row()
                row.prop(context.scene.tool_settings, "normal_size", text="Normal")
                row.prop(curve, "show_normal_face", text="Normals")
            col.label(text="Extrude Cross Section")
            col.prop(curve, "bevel_object", text="")

This is the code for the object+shading:
# SHADING ---------------------------------------------------------------------------
class ObjectShading(bpy.types.Panel):
    bl_label = "Viewport Shading"
    bl_idname = "ObjectShading"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = "Shading Toolbox"

    @classmethod
    def poll(cls, context):
        return context.object and context.object.data

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

        obj = context.object
        mesh = obj.data
        mat = obj.active_material
        space = context.space_data

        scene = context.scene
        cscene = scene.cycles
        ob = context.object
        cob = obj.cycles
        visibility = ob.cycles_visibility

        row = layout.row()
        row.prop(mesh, "use_auto_smooth", text="Break Edges")
        row.active = mesh.use_auto_smooth and not mesh.has_custom_normals
        row.prop(mesh, "auto_smooth_angle", text="Angle")
        row = layout.row()

        if bpy.context.object.mode == "EDIT":
            row = layout.row()
            row.operator("mesh.faces_shade_smooth", text="Smooth", icon="SMOOTHCURVE")
            row.operator("mesh.faces_shade_flat", text="Sharp", icon="LINCURVE")
        else :
            row = layout.row()
            row.operator("object.shade_smooth", text="Smooth", icon="SMOOTHCURVE")
            row.operator("object.shade_flat", text="Sharp", icon="LINCURVE")

        row = layout.row()
        row.prop(obj, "draw_type", text="Draw Type")
        row = layout.row()
        row.label(text="Draw Option:")
        row.prop(obj, "show_transparent", text="Transparency")
        row.prop(obj, "show_x_ray", text="X-Ray")
        row = layout.row()

#---------------------------------

        if obj and obj.active_material:
            mat = obj.active_material

            if mat:
                layout.template_ID(obj, "active_material", new="material.new")
                row.prop(mat, "diffuse_color", text="Draw Color")
                row.prop(mat, "alpha")
            else:
                row.label('no active_material')
        else:
            row.label('Add a Material')
            layout.template_ID(obj, "active_material", new="material.new")
            #layout.template_ID(space, "pin_id")

        row = layout.row()
        row.operator("material.object", text="Set Object Material")
        row.operator("material.data", text="Set Data Material")

object.type returns the type of object , is it this ?

@Chebhou in the poll function via object.type a switch could be build in?

if you mean a check ( if statement ) then it is return object.type == 'MESH'

I have the feeling that the poll function can only check for something and then let you go on with the script. But it cannot check if you have an object, empty, curve, or lamp selected and then for each part only execute a certain part of the script.

for example lamp and curve will cause an py error

yes it will either let you do everything or nothing, for your case just check the the type inside the draw and skip the not wanted parts ( like you did withe the mode == "EDIT")

Let us continue this discussion in chat.

The above (self)answer is OK. Using object.type is the way. Still:

I think is recommended/somewhat better using things in this form:
objType = getattr(obj, 'type', '')

if objType in ['MESH','CURVE']: etc
elif objType in ... etc
elif objType in ... etc

get is the better way to get :)
when testing something (type) several times, may wanna have a variable first instead of reading type/ looking for a prop all the time (not a big deal for UI speed, but generally ..)
if/elif ensures they are alternatives, not working on top of each other(not the case here, you cannot have many types), generally if/if will make the last one valid even if 2 are valid.    And as alternatives, it also means it should stop when the condition is met, while if, if, if will go to test all of them, cause may just be about something else.

You may wanna test for the object if exists or another condition
not sure you need this, but if obj is not None and maybe other conditions may do
so the code above would become (without testing the obj):
class ObjectShading(bpy.types.Panel):
    bl_label = "Transformation"
    bl_idname = "Transformation"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = "Modeling Toolbox"

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

        obj = context.object
        unit = context.scene.unit_settings

        objType = getattr(obj, 'type', '')

        if objType  in ['MESH','CURVE']:
            row = layout.row()
            row.column().prop(obj, "location")
            row.column().prop(obj, "rotation_euler", text="Rotation")
            row.column().prop(obj, "scale")
            row = layout.row()
            row.operator("object.transform_apply", text="Apply Rot").rotation=True
            row.operator("object.transform_apply", text="Apply Scale").scale=True
            row = layout.row()
            row.column().prop(obj, "dimensions")

        elif objType  in ['CAMERA','LAMP']:
            row = layout.row()
            row.column().prop(obj, "location")
            row.column().prop(obj, "rotation_euler", text="Rotation")
            row.column().prop(obj, "scale")

        elif objType  == 'EMPTY':
            row = layout.row()
            row.column().prop(obj, "location")
            row.column().prop(obj, "rotation_euler", text="Rotation")
            row.column().prop(obj, "scale")

        col = layout.column()
        col.label(text="Unit System")
        col.row().prop(unit, "system", expand=True)
        col.row().prop(unit, "system_rotation", expand=True)

hope this is of help here or in other places to "improve" the code :)

So as it seems instead of using a poll function here, best is to check for object type and then based on what type is present/selected render specialized UI parts:
# Transformation ---------------------------------------------------------------------------
class ObjectShading(bpy.types.Panel):
    bl_label = "Transformation"
    bl_idname = "Transformation"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = "Modeling Toolbox"

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

        obj = context.object
        unit = context.scene.unit_settings

        if obj.type in ['MESH','CURVE']:
            row = layout.row()
            row.column().prop(obj, "location")
            row.column().prop(obj, "rotation_euler", text="Rotation")
            row.column().prop(obj, "scale")
            row = layout.row()
            row.operator("object.transform_apply", text="Apply Rot").rotation=True
            row.operator("object.transform_apply", text="Apply Scale").scale=True
            row = layout.row()
            row.column().prop(obj, "dimensions")

        if obj.type in ['CAMERA','LAMP']:
            row = layout.row()
            row.column().prop(obj, "location")
            row.column().prop(obj, "rotation_euler", text="Rotation")
            row.column().prop(obj, "scale")

        if obj.type == 'EMPTY':
            row = layout.row()
            row.column().prop(obj, "location")
            row.column().prop(obj, "rotation_euler", text="Rotation")
            row.column().prop(obj, "scale")

        col = layout.column()
        col.label(text="Unit System")
        col.row().prop(unit, "system", expand=True)
        col.row().prop(unit, "system_rotation", expand=True)


text:
How to add transparency/alpha (material) value slider + viewport color
Sofar I replicated all the needed shading tools for an object inside the tool shelve.

The transparency function however only makes sense when the UI also allows you to change the alpha value which is part of the material menu

This is the code I have sofar:
class ObjectShading(bpy.types.Panel):
bl_label = "Shading"
bl_idname = "ObjectShading"
bl_space_type = 'VIEW_3D'
bl_region_type = 'TOOLS'
bl_category = "Claas"

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

    obj = context.object
    mesh = obj.data

    row = layout.row()
    row.label(text="AutoEdgeBreak:")
    row = layout.row()
    row.prop(mesh, "use_auto_smooth", text="BreakEdge")
    row.active = mesh.use_auto_smooth and not mesh.has_custom_normals
    row.prop(mesh, "auto_smooth_angle", text="Angle")
    row = layout.row()
    row.label(text="ManualSmooth:")
    row = layout.row()
    row.operator("object.shade_smooth", text="Smooth", icon="SMOOTHCURVE")
    row.operator("object.shade_flat", text="Sharp", icon="LINCURVE")
    row = layout.row()
    row.prop(obj, "draw_type", text="Draw Type")
    row = layout.row()
    row.prop(obj, "show_wire", text="Wire")
    row.prop(obj, "show_transparent", text="Transparency")
    row.prop(obj, "show_x_ray", text="X-Ray")

Looking into UI.py I discovered this but I fail to figure out how I could extract the proper code to add to my script so it only renders the viewport color and alpha slider.
class CyclesMaterial_PT_settings(CyclesButtonsPanel, Panel):
bl_label = "Settings"
bl_context = "material"
bl_options = {'DEFAULT_CLOSED'}

@classmethod
def poll(cls, context):
    return context.material and CyclesButtonsPanel.poll(context)

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

    mat = context.material
    cmat = mat.cycles

    split = layout.split()
    col = split.column()
    col.label(text="Surface:")
    col.prop(cmat, "sample_as_light", text="Multiple Importance")
    col.prop(cmat, "use_transparent_shadow")

    col = split.column()
    col.label(text="Volume:")
    sub = col.column()
    sub.active = use_cpu(context)
    sub.prop(cmat, "volume_sampling", text="")
    sub.prop(cmat, "volume_interpolation", text="")
    col.prop(cmat, "homogeneous_volume", text="Homogeneous")

    layout.separator()
    split = layout.split()

    col = split.column(align=True)
    col.label("Viewport Color:")
    col.prop(mat, "diffuse_color", text="")
    col.prop(mat, "alpha")

    col.separator()
    col.label("Viewport Alpha:")
    col.prop(mat.game_settings, "alpha_blend", text="")

    col = split.column(align=True)
    col.label("Viewport Specular:")
    col.prop(mat, "specular_color", text="")
    col.prop(mat, "specular_hardness", text="Hardness")

    col.separator()
    col.prop(mat, "pass_index")

Adding the code
row.prop(mat, "alpha")

results into an error code stating that "mat" is not defined which makes sense.
So when I then add add the mat definition after the def command
def draw(self, context):
    layout = self.layout

    obj = context.object
    mesh = obj.data
    mat = context.material
    cmat = mat.cycles

I get this error and I dont understand this and what cases this. I just copied the code.
location: :-1
Traceback (most recent call last):
  File "C:\Users\info\Desktop\untitled.blend\Claas_UI_2.py", line 98, in draw
AttributeError: 'Context' object has no attribute 'material'

The context contains the current state within blender, eg bpy.context.selected_objects is a list of the selected objects while bpy.context.active_object is the active object.
While you can have an active material selected, every object can have their own active material, so it is an object property not a global context property. So in your example you want to use -
obj = context.object
mesh = obj.data
mat = obj.active_material
cmat = mat.cycles

This worked perfect!


text:
how to draw name infront of Mesh data ID UI
layout.template_ID(obj, "data")

I assumed on could add , text="" inside the brackets but it seems not to work
layout.template_ID(obj, "data", text="Data Name")

I assume one could use row and lable commands drawing a text via label and the the template via the row command after it.
I am not sure if Blender does not allow what I try to do because also in the buttons menu there is no button text infron

So this is what I tried but the formatting result looks terrible.
    row = layout.row()
    row.label("Mesh Data")
    row.template_ID(obj, "data")
    row = layout.row()
    row.label("Object Name")
    row.template_ID(context.scene.objects, "active")

Alternatively I can also simply rebuild the main Blender UI elements and stretch them over the width of the panel like in the following image. This replicates also more a common visual look. But as you can see it is clean. The previous attempts were not vertically aligned along the left and right edge.

Maybe use an image editor to show what you'd like it to look like. It sounds like you want to use two columns the left column for names, the right column for the props.

or a row.split() see the UI cookbook.


text:
How can I render out Objects with Transparents but without Background?
I want to render out only the trail that I can composite it individually.
So when I render it out without a Background -> Transparent Background, then my Trail looks grey and is really hard to see.
I hope you can help me out it is really important for me to know how to fix it.

can you post a screenshot of your outliner?

Did you maybe select an output file format that does not support transparency, such as JPG?


text:
Why does my Python script "Onionize" my cone?
I have created the python script found at this link. The link also includes the associated Test.csv.
The purpose of my script is simply to create two cones, but somehow, for a reason I cannot figure out, the output of Blender (see image below) is to "Onionize" my cone; my cones look like strange pointy onions.
Why?!

Code:
    import bpy, csv

from bpy.props import IntProperty
from bpy.types import (MESH_OT_primitive_circle_add, MESH_OT_primitive_cylinder_add, MESH_OT_primitive_uv_sphere_add, MESH_OT_primitive_cone_add)
#MESH_OT_primitive_cone_add.vertices = IntProperty(name="Vertices", default=32)

for area in bpy.context.screen.areas: # iterate through areas in current screen
    if area.type == 'VIEW_3D':
        for space in area.spaces: # iterate through spaces in current VIEW_3D area
            if space.type == 'VIEW_3D': # check if space is a 3D view
                space.viewport_shade = 'RENDERED' # set the viewport shading to rendered

bpy.ops.script.python_file_run(filepath="C:\\Program Files\\Blender Foundation\\Blender\\2.79\\scripts\\presets\\units_length\\meters.py")
fp = "C:/Dropbox/Blender/Test.csv"
bpy.context.scene.render.engine = 'CYCLES'

def makeMaterial(name, diffuse, specular, alpha):
    mat = bpy.data.materials.new(name)
    mat.diffuse_color = diffuse
    mat.diffuse_shader = 'LAMBERT'
    mat.diffuse_intensity = 1.0
    mat.specular_color = specular
    mat.specular_shader = 'COOKTORR'
    mat.specular_intensity = 0.5
    mat.alpha = alpha
    mat.ambient = 1
    return mat

def setMaterial(ob, mat):
    me = ob.data
    me.materials.append(mat)

AQ2 = makeMaterial('AQ2', (0.329411764705882,0.505882352941176,0.611764705882353), (1,1,1), 1)
AQ4 = makeMaterial('AQ4', (0.611764706,0.478431373,0.329411764705882), (1,1,1), 1)

with open( fp ) as csvfile:
    rdr = csv.reader(csvfile, delimiter=',')
    for i, row in enumerate( rdr ):
        bpy.ops.mesh.primitive_cone_add(radius1 = float(row[3]), radius2=0, depth=float(row[3])*2, view_align=False, enter_editmode=False, location = ( float(row[0]),float(row[1]),float(row[2])), layers=(True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False))
        setMaterial(bpy.context.object, AQ4)
        active = bpy.context.active_object
        bpy.context.active_object.name = 'SAQ4'
        active.modifiers.new(name='mysubsurf', type='SUBSURF')
        active.modifiers["mysubsurf"].levels = 5
        bpy.ops.object.modifier_apply(apply_as='DATA', modifier="mysubsurf")

        bpy.ops.mesh.primitive_cone_add(radius1 = float(row[7]), radius2=0, depth=float(row[7])*2, view_align=False, enter_editmode=False, location = ( float(row[4]),float(row[5]),float(row[6])), layers=(True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False))
        setMaterial(bpy.context.object, AQ2)
        active = bpy.context.active_object
        bpy.context.active_object.name = 'SAQ2'
        active.modifiers.new(name='mysubsurf', type='SUBSURF')
        active.modifiers["mysubsurf"].levels = 5
        bpy.ops.object.modifier_apply(apply_as='DATA', modifier="mysubsurf")

    x = float(row[8])
    save_render = "C:/Dropbox/Blender/" + str("{:10.2f}".format(x)) + ".png"

    bpy.data.scenes["Scene"].render.filepath = save_render
    bpy.ops.render.render( write_still=True )

    # deselect all
    ##bpy.ops.object.select_all(action='DESELECT')
    # selection
    ##bpy.data.objects['SAQ2'].select = True
    # remove it
    ##bpy.ops.object.delete()
    # deselect all
    ##bpy.ops.object.select_all(action='DESELECT')
    # selection
    ##bpy.data.objects['SAQ4'].select = True
    # remove it
    ##bpy.ops.object.delete()

Probably this exact reason: https://blender.stackexchange.com/questions/118128/how-to-fix-ugly-lines-in-my-mesh/118139#118139 subdivision surface on tris

As commented above, the lines
active.modifiers.new(name='mysubsurf', type='SUBSURF')
active.modifiers["mysubsurf"].levels = 5
bpy.ops.object.modifier_apply(apply_as='DATA',modifier="mysubsurf")

in the code confirm that the problem is the interaction between subsurface modifier and tris in the mesh geometry. Remove or comment these lines and you will get beautiful cones.
The code can be used if the primitve added is based on quads.


text:
I can't open the settings of the completed operation

Firstly, when I tried to use the "spin" tool, my object was not duplicated as planned, but only rotated, and secondly, when I tried to open the settings of the last operation, it did not work (nothing simply appeared). Well, the display of the operation itself looks compressed, as in the screenshot


text:
How do I bake a Line Art modifier in BPY?
Is there a way to bake the LineArt Modifier of a Grease Pencil Object in Blender using bpy?

Hello, I believe you just have to apply the modifier https://blender.stackexchange.com/q/314434/86891


text:
How much do sub-surf impact real-time rendering or is there alternative solutions?
This is a Blender newbie speaking.
I wanted to make a game about growing flowers. My plan is to make the animation in Blender and import the animated mesh into unity.
I do have made a looking good base mesh for a section of stem + leaf. Though, the shading on some part of the mesh do not look satisfying enough, as the sharp geometric contour is still noticeable. I wanted to avoid this because a large part of the game is about looking at the flower growing from seeds.

I do tried to add a sub-surf modifier and the shading were great! Only that I noticed the vertices count ramped up by more than ten-fold (1131 -> 18009). How much will this impact the run-time rendering? If I wanted to avoid this, what potentially could I do?
Thank you all in advance for any of your comments.
Sincerely,
Anyu

You can render a test scene one time without a subdivision surface modifier and a second time with the modifier. There you have your difference. Of course it has an influence, but it's hard to give a general answer, it depends on your mesh, the levels of subdivision, the rest of the scene... and in Blender you can set different subdivision levels for viewport and render. And you can render with the modifier on the object. For Unity you have to apply the modifier so it becomes a real mesh. How much this effects the Unity performance, I have no idea. But this site is about Blender, not Unity.

Okay, thank you!

To be honest I think you are asking yourself the wrong question here. Instead of wondering the performance cost, you should wonder how to get the best looking result without having to waste performances on more subdivision. If you are interested in that, I invite you to [edit] your question to orient it to that purpose, and include closer screenshots in edit mode of your mesh, why not even share your file.


text:
Use only audio when mixing compositing and sequencer in post processing
I created a nice movie layout using only the Node editor. I added an mp3 audio file via the video sequence editor. Selected Both compositing and sequence in post processing under render properties and clicked the animation button and got a nice mp4 movie.
When I replace my mp3 file with a movie clip (containing both audio and video) in the video sequence editor and hide the movie by clicking the eye and set opacity to zero + moving the clip outside the start and end frame interval, I get an undesired result. The generated output movie does not contain any video, only audio.

Have you tried just deleting the movie strip you don't need?

That seems to solve it. A few days ago, I tried your solution and it did not work, because the associated audio track was automatically deleted. Now I tried it again and when I delete the video, the audio track remained.

You probably had both strips selected, with the movie strip active. It is not always very clear that a strip is selected (could be visually a bit more clear perhaps).

Instead of hiding the movie clip in such an laborious way, just select it and delete it. Make sure you have only the movie clip selected, and nothing else.


text:
Blender 2.69 Baking issue
I have spent a few days with this issue trying to solve an issue for a work project that needs to be ready in less than a week. I normally dont have a need to bake textures onto models however it is required for this project.
Basically I have followed every written and video tutorial I could find and tested them on a basic cube in blender, and every time I bake the texture to the cube it comes out wrong. Massive bleeding around the UV, the actual texture I created in GIMP is drastically shrunk, and is entirely on one face of the mesh.
And just a moment ago I decided to bake it again, without changing any settings and the texture magically rearranged itself to fit properly with some bleeding. I am very confused and need to know how to properly bake textures for real models for work.
Any help would be greatly appreciated.

I think what are calling "bleeding" is actually the Margin.

It looks like you have the hang of it. The problem the first time is likely the uv-mapping of the mesh you are baking from. Do you really want to do a "full render" bake? Normally you would do diffuse, normal or ambient occulusion.

Gandalf3 - Thanks, I'm not used to baking textures. Never needed to until now.

Gunslinger - I dont understand what you mean about the uv-mapping. Even though they look like different uv-maps, they are actually the same .png file. For some reason when I baked it the second time it baked it properly. And as far as "Full Render" goes, I have to use full render for the simulation software that the actual models will be imported to.

You must haven't chosen the UV map set that you really want to use. Just try deleting either of the two UV set, I'm sure you'll see what's happening.

@Leon Cheung, thanks for the idea. I just tried what you said and it didnt work. :( I get either a full red cube, which isnt what I want, or I get a red cube with a micro sized version of the UV texture.

In that case, please bring your "patient" up here via sites like www.pasteall.org, which would be straight forward to help you more.

@Leon Cheung http://www.pasteall.org/blend/26111 There be the sick one lol. I think I've either been starring at my computer too long and over looked something small, or I'm just way too tired.

@Leon Cheung Also, if blender by chance gives you a warning of possible missing plugins dont worry about it. The plugin is an exporter for a flight simulator called X-Plane. I'm having other issues that I will be calling them about tomorrow.(And in the "Bake" settings, I have to use "Full Render" for the XPlane export.)

If I bake directly with your file without any tweaking, it would fail, because the image on which you are baking is used by the object itself, which caused a circular reference, so you do need to create another image, or duplicate the current one (test.png in this case). However, if you actually mean the "bleeding" issue, as gandalf3 said, the Margin value setting in Bake panel is what you need.

@Leon Cheung Thank you for taking a look at the blend file. However I think I'm too tired at the moment to understand. Ill have to look at it again tomorrow. Also, I hate sounding like an absolute moron, especially since I am very familiar with blender, I just havent had a need to actually bake textures until this simulator project at work. But if its possible (I also hate sounding like I'm begging), would you be willing to look at a video of my terrible performance of attempting from scratch, while following a written tutorial and tell me where I went wrong?
I am way too tired for this haha

In a nut shell, my mind is a little weird. Ask me to design and animate something complex, no problem. Ask me to make something simple, and my brain dies. lol

Sure. let's check the video. Since the discussions here is over extended a bit, please try to earn at least 20 reputation around to continue this in chat room. PS: I need your confirmation here: What's the real problem now, bleeding or UV or something?

It is a little over extended. I can certainly try to reach 20 reputation. As for the confirmation, primarily the problem is UV/Baking. There is a secondary problem, however I will be calling the company that developed the software I am importing textured models into tomorrow. For now, I need to get some sleep for work tomorrow. The video has been uploaded to Youtube, and is being processed. Since I cannot give you a direct link yet, this is the youtube channel it will be viewable on in about an hour or so(hopefully). It will be the only video there. https://www.youtube.com/user/wraithofthemist

If you haven't already solved your problem by now, perhaps you could try it with out the large face overlapping the E?


text:
How to select two objects add a boolean modifier and enter name for object to be unioned
So currently when using the boolean modifier you have to set the type and then select the object manually.
I am curious how one could automate this like this:
select two objects
select Add Boolean Union button
the button will do this:
add boolean modifier to active object
set type to union
select other object as to be unioned to the active object
Ideally the object selection should be done via mouse selection.
First click is the tool object and last click is the active object to add the modifier to.

this addon may have it  : http://www.blendernation.com/2014/05/14/add-on-booltool/

Modifiers are stored in an object's modifier list and a new one can be added by calling obj.modifers.new(name, type). To adjust the modifier settings you can either collect the created modifier object returned by the new method or access it through the list.
import bpy

target_obj = bpy.data.objects['Cube']
cutter_obj = bpy.data.objects['Sphere']

bool_mod = target_obj.modifiers.new('cutter', 'BOOLEAN')

bool_mod.object = cutter_obj
bool_mod.operation = 'DIFFERENCE'

# or directly -
bpy.data.objects['Cube'].modifiers[0].object = bpy.data.objects['Sphere']

Wow this works so flawless. How can you define the cutter object via the mouse click similar to how you can select the active object via "target_obj = context.object"?

One way could be to have more than one object selected, use context.active_object as the object to get the modifiers and loop through context.selected_objects while skipping the one that == active_object and add a boolean modifier for each. You may also want to look at the booltool addon


text:
How to remove/apply all modifiers of one object in python
Lets assume you have 1 object with 4 modifiers added to it.
I am curious how one would approach the task to apply all or to delete all modifiers of a just selected object that has many modifiers already added.
The console reads out the modifier delete as
bpy.ops.object.modifier_remove(modifier="Box Right ")

So "Box Right " I might have to replace with something like active.object.modifier.name and then work each modifier off?
This would be very helpful when you want to generate a static mesh for animation or 3D printing.

related, very: http://blender.stackexchange.com/questions/7196/how-to-get-a-new-mesh-with-modifiers-applied-using-blender-python-api?rq=1

Ok let me try to figure this own. thank you!

A short way to apply and remove all modifiers on the active objects is bpy.ops.object.convert(target='MESH') this is the operator called when using Alt-C -> Mesh from curve

Modifier removal
To remove a modifier from an object.
obj below is a reference to an object either obtained via
obj = bpy.context.active_object
obj = bpy.context.object
# or
obj = bpy.data.objects[name]

If you want to remove a modifier it is done by name, not by type. You could have multiple array modifiers, but only want to remove
a specific one.
modifier_to_remove = obj.modifiers.get("Bevel")
obj.modifiers.remove(modifier_to_remove)

# or as a one-liner
obj.modifiers.remove(obj.modifiers.get("Bevel"))

# or remove all modifiers from an object
obj.modifiers.clear()

Modifier Apply
Using an operator
As sambler pointed out
# operates on all selected objects (not just the scene's _active_object_)
bpy.ops.object.convert(target='MESH')

lower level
If you want to apply all modifiers it's covered here: How to get a new mesh with modifiers applied using Blender Python API? - This involves using obj.to_mesh and there are a few things to consider, it:

generates a new mesh from your current obj (leaves current obj.data intact)
does not remove the modifiers automatically from the object. (unlike the Apply button on the Modifiers panel, or Convert to Mesh).

This snippet will:
"""
- make a reference to the current obj.data ( i call it old_mesh)
- make a new Mesh ( new_mesh) using the effect of the combined modifiers on `obj`
- remove all modifiers from `obj`
- assign the new Mesh to obj.data
- remove old_mesh from the blend
"""

in code:
import bpy

context = bpy.context
scene = context.scene
obj = context.object

# get a reference to the current obj.data
old_mesh = obj.data

# settings for to_mesh
apply_modifiers = True
settings = 'PREVIEW'
new_mesh = obj.to_mesh(scene, apply_modifiers, settings)

# object will still have modifiers, remove them
obj.modifiers.clear()

# assign the new mesh to obj.data
obj.data = new_mesh

# remove the old mesh from the .blend
bpy.data.meshes.remove(old_mesh)

modifiers.clear() is really great.  i used to remove modifiers sequentially, but if you have many modifiers it can cause the whole stack to update per removal.

Is there a way to make this work with the SURFACE_DEFORM mod? Also related to this, is there are way to bind a surface deform mod without  bpy.ops.object.surfacedeform_bind()?


text:
Why does Redo.Last command not work after executing a modeling command via Py script?
I noticed that when you write an operator lets say to extrude or crease an edge
and as the last step add the code for calling the F6 Redo.Last command, everything will be executed and work besides the F6 menu.
It seems that there is an issue calling the F6 from inside a script while calling it via pressing a button on a pie menu works:

pie.operator("screen.redo_last")

The idea or goal is to via script edge crease and then instantly call the redo.last command so you can via a better UI adjust the edge slide value.
#Set Edge Crease
class SetOrigin(bpy.types.Operator):
    bl_idname = "set.edgecrease"
    bl_label = "Set Edge Crease"
    bl_options = {'REGISTER'}

    def execute(self, context):
        scene = context.scene
        bpy.ops.transform.edge_crease(value=0)
        bpy.ops.screen.redo_last()
        return{'FINISHED'}

Any idea?

this doesn't fix the main problem, (turtles all the way down) but you need to use parentheses on direct operator calls bpy.ops.screen.redo_last()

I fixed the error but narrowed it down to that as it seems the screen.redo_last() works as a pie command but not as a bpy.ops inside a script.


text:
Python code for Edge Data Bevel and Crease Weight?
Anybody has an idea what the python code is to draw the edge data bevel and crease weight sliders?

It seems not to be part of "space_view3d.py"

not sure why this was downvoted, but this submenu is defined in C, not python -- (you can see this by rightclicking any of the sliders and trying to edit-source). I think you'll have to do a little bit of coding :)

Thats the impression I got as well. Is it possible to write a script that shows a slider and the value is uses as for edge crease or bevel weight?  I found the commands that adjust the edge data and the thing that might store the data?
bpy.types.MeshEdge
bpy.ops.transform.edge_bevelweight(value=0.366871)
bpy.ops.transform.edge_crease(value=-0.315626)

EDITED:
OK, apparently the previous answer was pretty worthless. Although there is a meshedge.crease property and a meshvertex.bevel_weight property, they do not influence modifiers at all, and their values do not change when changing the corresponding values in the properties panel.
However, there is a way to access these values through custom layers via BMESH. The addon below adds a panel that allows you to influence selected verts / edges or all verts / edges' crease and bevel weight properties.

It does have one weird bug though, which seems to be a bug in Blender, as seen in the GIF above. Even though this does indeed update the respective mesh properites, Blender does not update the display until you also change any value of a modifier on the active mesh.
EDITED 2:
Thanks to a comment from batFINGER, found a solution to the weird behavior mentioned and seen above: adding a bmesh.update_edit_mesh( meshData ) after updating the crease / bevel values. Updated code below accordingly.
To use this, download the code and save it as a python (.py) file on your computer, then install it as an addon (File --> User Preferences --> Add-ons --> Install From File).
The panel appears in Edit Mode only in the Tools tab, under "Crease and Bevel".
bl_info = {
    "name"       : "Crease and Bevel weight panel",
    "version"    : (0, 0, 1),
    "blender"    : (2, 77, 0),
    "category"   : "Tools",
    "location"   : "3D View > Toolbox",
    "description": "Shortcut UI panel for Mesh edge crease and vertex bevel weight properties"
}

import bpy, bmesh

class creaseAndBevelPanel(bpy.types.Panel):
    bl_idname      = "creaseAndBevelPanel"
    bl_label       = "Crease and Bevel"
    bl_space_type  = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category    = 'Tools'
    bl_context     = "mesh_edit"

    @classmethod
    def poll( self, context ):
        ''' Only show panel if there is an active mesh object '''
        return context.object and context.object.type == 'MESH'

    def draw( self, context ):
            layout = self.layout
            props  = context.scene.creaseAndBevelPG # Create reference to property group

            box = layout.box()                    # Draw a box
            col = box.column( align = True )      # Create a column
            col.prop( props, "whoToInfluence"  )  # Add properites to panel
            col.prop( props, "bevelWeight"     )
            col.prop( props, "edgeCrease"      )

class creaseAndBevelPG(bpy.types.PropertyGroup):
    ## Update functions
    def update_bevelWeight( self, context ):
        ''' Update function for bevelWeight property '''

        o  = bpy.context.object
        d  = o.data
        bm = bmesh.from_edit_mesh( d )

        bevelWeightLayer = bm.verts.layers.bevel_weight['BevelWeight']

        if self.whoToInfluence == 'Selected Elements':
            selectedVerts = [ v for v in bm.verts if v.select ]
            for v in selectedVerts: v[ bevelWeightLayer ] = self.bevelWeight
        else:
            for v in bm.verts: v[ bevelWeightLayer ] = self.bevelWeight

        bmesh.update_edit_mesh( d )

    def update_edgeCrease( self, context ):
        ''' Update function for edgeCrease property '''

        o  = bpy.context.object
        d  = o.data
        bm = bmesh.from_edit_mesh( d )

        creaseLayer = bm.edges.layers.crease['SubSurfCrease']

        if self.whoToInfluence == 'Selected Elements':
            selectedEdges = [ e for e in bm.edges if e.select ]
            for e in selectedEdges: e[ creaseLayer ] = self.edgeCrease
        else:
            for e in bm.edges: e[ creaseLayer ] = self.edgeCrease

        bmesh.update_edit_mesh( d )

    ## Properties
    items = [
        ('All', 'All', ''),
        ('Selected Elements', 'Selected Elements', '')
    ]

    whoToInfluence = bpy.props.EnumProperty( # Material distribution method
        description = "Influence all / selection",
        name        = "whoToInfluence",
        items       = items,
        default     = 'Selected Elements'
    )

    bevelWeight = bpy.props.FloatProperty(
        description = "Bevel Weight",
        name        = "bevelWeight",
        min         = 0.0,
        max         = 1.0,
        step        = 0.01,
        default     = 0,
        update      = update_bevelWeight
    )

    edgeCrease = bpy.props.FloatProperty(
        description = "Edge Crease",
        name        = "edgeCrease",
        min         = 0.0,
        max         = 1.0,
        step        = 0.01,
        default     = 0,
        update      = update_edgeCrease
    )

def register():
    bpy.utils.register_module(__name__)
    bpy.types.Scene.creaseAndBevelPG = bpy.props.PointerProperty( type = creaseAndBevelPG )

def unregister():
    bpy.utils.unregister_module(__name__)

Thank you - have to google how I could turn this into a UI.

I know this thread is very old. But what is the solution here?

@Tiles, in terms of how to implement this via a UI panel?

Yes :) :) :) :)

@Tiles, see updated answer.

Ah, the BMesh approach. Thanks for this example TLousky. Now i just need to understand it ^^ For the update part, maybe area.tag_redraw will lead to a solution here?

Tried all kinds of redraws and updates (context.scene.update(), object.modifiers.update() and the tag_redraw function), nothing really works. It's really weird since usually, when you move the 3D view the scene is redrawn and everything is updated, but in this case I found that only changing a modifier's property did the trick.

Too bad. Nevertheless thanks for your investigation and help :)

It does have one weird bug though, which seems to be a bug in Blender, <- @TLousky, just curious, shouldn't we report it as a bug then?

@Tiles, yeah, if it is truly a bug. I was hoping maybe some other guys here would comment on the matter to confirm or deny my suspicion before bothering the devs with another bug report.

Well. I can confirm the behaviour. And i don't know a solution neither. In worst case the devs would simply deny the report. Would you be so kind to report it? I fear my skills are too weak to explain the bug really in detail and indepth.

How about a bmesh.update_edit_mesh(d) at end of update method? quick test looks good for edge crease....

Awesome @batFINGER, works like a charm, will update answer.

You folks are awesome :)

Hm, i fear we have still an update problem. When i change the values in the original Transform panel, then the values in the addon does not update.

That's going to be a whole lot more tricky, since the panel is a way for you apply crease and bevel weight values on either all or the selected verts / edges. These values could be different for different mesh elements, which is why average values are shown in the props panel when more than one element is selected. Not impossible to do, but requires quite a lot more logics that's a bit beyond the scope of this particular problem (of accessing these values via a script or the UI).


text:
How to structure modal operator correctly with macro like step by step execution?
I struggle with understanding the modal operator concept. Below is a chain of commands I would like to step by step to execute, while during translate the following steps should wait till translate is done. So a modal operator structure is needed here.
        bpy.ops.object.select_all(action='DESELECT')
        bpy.ops.object.empty_add()
        bpy.ops.transform.translate('INVOKE_DEFAULT')
        bpy.ops.view3d.snap_cursor_to_selected()
        bpy.ops.object.delete()

This is the template I found and understand.
I select one object, execute the command which will then get the location and the modal takes over. But I failed to implement my commands into this structure. How can I make the modal aware of that I added the empty and jump into translate.
I understand the confirm and cancel being the states where I can execute the rest after transform or even undo the initial empty generation if need needed.
import bpy

class ModalOperator(bpy.types.Operator):
    bl_idname = "object.modal_operator"
    bl_label = "Simple Modal Operator"

    def __init__(self):
        print("Start")

    def __del__(self):
        print("End")

    def execute(self, context):
       # bpy.ops.object.empty_new()
        context.object.location.x = self.value / 1000.0
        return {'FINISHED'}

    def modal(self, context, event):
        if event.type == 'MOUSEMOVE':  # Apply
            self.value = event.mouse_x
            self.execute(context)
        elif event.type == 'LEFTMOUSE':  # Confirm
            bpy.ops.view3d.snap_cursor_to_selected()
           x bpy.ops.object.delete()
            return {'FINISHED'}
        elif event.type in {'RIGHTMOUSE', 'ESC'}:  # Cancel
            bpy.ops.object.delete(use_global=False)
            return {'CANCELLED'}

        return {'RUNNING_MODAL'}

    def invoke(self, context, event):
        self.init_loc_x = context.object.location.x
        self.value = event.mouse_x
        self.execute(context)

        context.window_manager.modal_handler_add(self)
        return {'RUNNING_MODAL'}

class ObjectData(bpy.types.Panel):
    bl_label = "Object + Mesh Data"
    bl_idname = "ObjectData"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'TOOLS'
    bl_category = "Modeling Toolbox"

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

        obj = context.object

        row = layout.row()
        self.layout.operator("object.modal_operator")

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

if __name__ == "__main__":
    register()

There is a new Approach which might help you out: Blender for Architecture and Engineering

related (snap target) http://blender.stackexchange.com/questions/1956/how-to-know-what-object-the-snap-function-is-targeting-in-python

Blender has no ability to move and snap the 3D cursor as an object. So the idea is to make an empty move it, allow the user while moving to snap to any object geometry vertext, and then releasing the mouse set the 3D cursor to the empty position and delete the empty.

Yes of course that is the only reason I try to figure this out. When you work with complex meshes and booleans you do not want to get into edit mode. The maker of Enhanced 3D Cursor stated that Blender would slow down with my models and his add-on. PivotPro uses macros and I was suggested to look into this as well, but fail to understand how to use it. http://blender.stackexchange.com/questions/44971/how-to-use-bpy-ops-macro-defining-macro-steps

OK. now I get it. It's sometimes easier to provide an answer when the final goal is known and explicitly stated too (not just inferred from the variable names). This changes the question imo.

Sorry for not explaining myself clear enough. I saw you edited my original text. I now changed it again to reflect better what I struggle with and posted in the new code I got to work sofar!

that's fine :)  i can't help but feel that you are trying to solve this problem with a workaround approach, rather than saying "i'm trying to snap the object origin while in object mode, this is the code i'm using - im not married to the code but would like a solution for the origin snapping"

Let us continue this discussion in chat.

Here is the code that does what I asked in my question.
Thank you Zeffi and Chebhou
import bpy
from bpy_extras import view3d_utils

class ModalOperator(bpy.types.Operator):
        bl_idname = "object.modal_operator"
        bl_label = "Simple Modal Operator"
        count = 0
        def __init__(self):
            print("Start")

        def __del__(self):
            print("End")

            # get the context arguments

        def modal(self, context, event):
            self.count += 1

            if self.count == 1:
                bpy.ops.transform.translate('INVOKE_DEFAULT')

            if event.type == 'LEFTMOUSE': # Confirm
                bpy.ops.view3d.snap_cursor_to_selected()
                bpy.ops.object.delete()
                return {'FINISHED'}

            elif event.type in {'RIGHTMOUSE', 'ESC'}: # Cancel
                bpy.ops.object.delete()
                return {'CANCELLED'}
            return {'RUNNING_MODAL'}

        def invoke(self, context, event):
            if context.space_data.type == 'VIEW_3D':

                self.scene = context.scene
                self.region = context.region
                self.rv3d = context.region_data
                self.mouse_co = event.mouse_region_x, event.mouse_region_y
                self.depth = view3d_utils.region_2d_to_vector_3d(self.region, self.rv3d, self.mouse_co)
                self.emp_co = view3d_utils.region_2d_to_location_3d(self.region, self.rv3d, self.mouse_co, self.depth)
                bpy.ops.object.select_all(action='DESELECT')
                bpy.ops.object.empty_add()
                context.object.location = self.emp_co

                context.window_manager.modal_handler_add(self)
                return {'RUNNING_MODAL'}
            else:
                self.report({'WARNING'}, "Active space must be a View3d")
                return {'CANCELLED'}

Your operator is not a modal operator and you are calling a modal operator inside it ,  SnapOriginObject will exit and leave transform.translate('INVOKE_DEFAULT') running behind ( it won't wait as you expect ) , you have to create a modal operator ( see the templates ) where you catch the mouse events ( movements, clicks, position ) to move the empty and delete it when you are done.

can a modal operator be inside the "def execute(self, context):" ?


text:
Order of buttons drawn not matching code order
As you can see in the image Diffuse Color and Alpha are drawn before the material selector. But in the code the material selector is before Diffuse Color and Alpha.
What is the reason for that?

    if obj and obj.active_material:
        mat = obj.active_material

        if mat:
            layout.template_ID(obj, "active_material", new="material.new")
            row.prop(mat, "diffuse_color")
            row.prop(mat, "alpha")
        else:
            row.label('no active_material')
    else:
        layout.template_ID(obj, "active_material", new="material.new")

I actually like the result because after I add the material the added material options are drawn below the object options.

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

    obj = context.active_object

    if obj and obj.active_material:
        mat = obj.active_material
        if mat:
            layout.template_ID(obj, "active_material", new="material.new")
            row = layout.row()
            row.prop(mat, "diffuse_color")
            row.prop(mat, "alpha")
        else:
            row = layout.row()
            row.label('no active_material')
    else:
        layout.template_ID(obj, "active_material", new="material.new")

Sometimes you have to be a bit more accurate about where a row should be generated. In your case the row is declared ahead of the template_ID, so any further additions to row will be added to that location.

The take-away here is that the line number of the UI elements like props and operators is less important than the line numbers on which the layout elements like row, col and box are first instanced. As with all good programming, variable names are important because they allow you to organize your thoughts.
While this is possible, it's asking for confusion:
def draw(self, context):
    layout = self.layout

    obj = context.object

    row1 = layout.row()
    row2 = layout.row()
    row3 = layout.row()

    # will display at the bottom
    row3.operator("mesh.primitive_cube_add")

    # will display in the middle
    row2.label(text="Active object is: " + obj.name)

    # will display on top
    row1.label(text="Hello world!", icon='WORLD_DATA')

The UI cookbook shows a worthwhile convention to follow, use extra identifiable postfixing for layout element names, row1, row2, row3 . etc. While reusing the variable row over and over again is handy, it tends to cause unnecessary confusion with more complex UI definitions.

Ah now I understand how it string things together. When I replace row with layout then the buttons will go after the material definition. Thanks.

yeah, there's quite a few ways to do this, and interesting ways to get confused :)

Getting confused lol constant state here ;)


text:
Why does defining a value make the script break when the value is not even used
The script works perfect
class ObjectShading(bpy.types.Panel):
bl_label = "Shading"
bl_idname = "ObjectShading"
bl_space_type = 'VIEW_3D'
bl_region_type = 'TOOLS'
bl_category = "Claas"

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

    obj = context.object
    mesh = obj.data

    row = layout.row()
    row.label(text="AutoEdgeBreak:")
    row = layout.row()
    row.prop(mesh, "use_auto_smooth", text="BreakEdge")
    row.active = mesh.use_auto_smooth and not mesh.has_custom_normals
    row.prop(mesh, "auto_smooth_angle", text="Angle")
    row = layout.row()
    row.label(text="ManualSmooth:")
    row = layout.row()
    row.operator("object.shade_smooth", text="Smooth", icon="SMOOTHCURVE")
    row.operator("object.shade_flat", text="Sharp", icon="LINCURVE")
    row = layout.row()
    row.prop(obj, "draw_type", text="Draw Type")
    row = layout.row()
    row.prop(obj, "show_wire", text="Wire")
    row.prop(obj, "show_transparent", text="Transparency")
    row.prop(obj, "show_x_ray", text="X-Ray")
    row = layout.row()
    #row.prop(mat, "alpha")
    split = layout.split()

But when I add the following value definition no buttons are drawn
def draw(self, context):
    layout = self.layout

    obj = context.object
    mesh = obj.data
    mat = context.material
    cmat = mat.cycles

What I try to do is to add an alpha value slider so I can set transparency for display and value in one area.
row.prop(mat, "alpha")

Yes, errors in the script's draw function will stop it from drawing beyond the line where the error happens (or it will stop drawing your panel entirely). The error you got is:
location: <unknown location>:-1
Traceback (most recent call last):
  File "/ui_panel.py", line ---, in draw
AttributeError: 'Context' object has no attribute 'material'

Fix this error and the panel will draw OK. It means context.material is the problem.
Get in the habit of starting Blender from Terminal during experimentation / development process. This will allow you to read the errors that occur when Blender doesn't explicitly tell you something's wrong.

Ok now I understand why I don't always see errors. Have to google how to start it from terminal under win10.

Using windows you can open a terminal window from Window -> Toggle System Console. See blender.org/manual/.../console_window.html --- but Blender on Linux and OSX don't have that feature.

OS X you open terminal and then drag blender into the window and hit enter.

sure. but windows is the only platform with the Window -> Toggle System Console in Blender. (just to be clear)


text:
Is there a max size for saving openEXR multilayer files?
I have a file that has many different render layers. I'm rendering at quite a high resolution, so the combined information I want to save is quite a lot. Blender gives an error when trying to save a OpenEXR Multilayer file. I tried saving a test file, and I was able to save one, so the only difference I can think of between when it works and when it comes up with an error is that that I am trying to save is too large.
If there is a max size, or a maximum number of render layers, what is it?
Thanks.

I can save a regular OpenEXR file, but then I can't use other render passes, like AO or normals.

Please include the error message. Your issue is most likely caused by the system running out of memory.

It simply says 'Error: Could not write image C:....filename.exr' It doesn't matter where I try to save the file either, it always tries to save it in a certain file directory (under my blendfiles folder)

@Benjimank Is there any more detailed info in the console/terminal?

I don't think there is a limit. In my experience EXR Multilayer Feature works really great in Blender. Make sure that:

you have file permissions to write on your drive,
it is not a compositor issue or
you are not running out of memory.

I once rendered an image which needs to be a 30K EXR Multilayer with all possible passes included, file size was about 12gb. Rendering and Saving as EXR works as expected, but finally the image resolution was to high for the current compositor (2.71) so I can't do the compositing in blender. That's why I suggest you to disable all post processing image operations for the rendering process.
For rendering EXRs with Cycles this answer is also helpful. In this post Brecht even mentioned that rendering EXRs is the only way to write and render the image at the same time. With that in mind it even makes sense to render as EXR for large filesize images.


text:
How to save transparent fire in blender
I'm trying to save a render of a fire flame in Blender I have followed the steps of this tutorial, but I'm having empty png's and tiff files, please help me solve this problem. I'm using Bleder 4.2.3 LTS on a MacOS Ventura my GPU is Intel hd 630 and AMD Radeon Pro 560
here are screenshots:

this is the view layer with the color-activated it shows the fire mask

this is the fire colors node setup with volume BSDF

this is the compositor node setup


text:
How would i create a hair material with a light streak effect on them?
im trying to make a light streak from a hair mesh, i tried faking it using a plane and some curves but it just does not look right. im trying to make a random light streak down the hair particle but what i got was a  lightshow.
here is what i got

and here is the effect i want to achieve

i want to try and make it in geometry node but im still not confident enough to use it.


text:
How to get a mesh to align evenly with imported stl so that you can use boolean to join them together
I'm new to blender and need to do some hard surface modelling to modify an imported stl. I'm trying to align this cube with one of the sides of the imported stl but cannot get it to become perfectly flat with the object. I've been using the grab tool and scale tool but cannot get the cube mesh to become even with the imported stl, some parts of it is even but others aren't. Could this be a rotational issue? Afterwards, I need to use boolean to join the cube to the surface but is there a way to align them perfectly first?

Can you share your Blender project file? Instructions for sharing.


text:
How to Show Colours
I'm very new to Blender.
I purchased a Rocket Launcher from Render Hub. M202 RL
It came with Blender 4.1 file. I can load it in but I don't have a clue how to show the Colours or Textures or Whatever they are called. It has the nodes set up and TGA files.

I would like to export it to DAZ, complete with colours showing, so it displays correctly in DAZ, if possible.

Have you tried File > External Data > Find Missing Files ... from the main menu? Navigate to the M202_Flash_main_textures folder (or subfolder). Blender will try to find the image textues there.


text:
Get "Object Color" property in Cycles
I need a way to get the Object Color in Cycles. I was thinking about using the attribute node, but I don't know what to write in the name entry.

Is there another way to get the color?
Please don't edit the title or the description; when I write Object Color, it's because that's the name of the property.
In Blender Render, I just have to check this box:

I don't want "Vertex Color" or "Viewport Color"; I need the Object Color attribute.

I'm asking to get the "Object Color" propierty inside a Cycles shader look at the pictures please. Why? Because in that way i can assign a Material to several objects and only change the "Object Color" to get anothe combo.

object color is a BI material option that isn't available in cycles. You should be able to access the objects color value through python while using cycles but not through a cycles material node. You may have some luck using a py driver.

I suggest you rearrange some in your workflow. Instead of using the same material depending on Object color (not available in cycles), use different materials in each object but put the common nodes in a group, shared between all objects. See http://blender.stackexchange.com/questions/3654/how-can-i-create-a-single-cycles-texture-with-a-different-image-for-each-object/3655#3655

@sambler I don't think this is possible with a driver, because of this issue.

Vertex Color:
Assuming that you mean Vertex colors, and that you want to get it in the node editor, then you would type the name of the vertex color layer into the attribute node:

From the wiki:

Retrieve attribute attached to the object or mesh. Currently UV maps and vertex color layers can be retrieved this way by their names, with layers and attributes planned to be added. Also internal attributes like P (position), N (normal), Ng (geometric normal) may be accessed this way, although there are more convenient nodes for this.

Note that if you have a UV layer with the same name it will be used instead.
Object Color:
For the Object Color property, the answer is no, this is not possible with the Attribute node currently.
You could try using a driver to get the color into a node tree, however I don't think it will do what you want it too. The driver can only access the object color of one object at a time, so you wouldn't be able to use a different color per object in one material.
As an alternative, you could specify the different colors in the node setup by using object pass indexes and the Object Info node:

Create an "equal to" nodegroup:

Then setup something like this:

If the object index is 1, the object will be green.
If the object index is 2, the object will be cyan.
If the object index is not 1 or 2, it will be red.
The object info node uses the Pass index of the object as the index. You can set the Pass index in Properties > Object > Relations:

You could write a python script to automatically set the colors, Pass index, and create the appropriate nodes for all the objects in your scene.
Here is a script (thanks to iKlsR and sambler for answering my questions here, here, and here) that will automatically setup the pass indexes and create an "Object Color" node group which you can add to your node setups:
import bpy

# Add "equal to" node group:
group = bpy.data.node_groups.new(type="ShaderNodeTree", name="Equal to")
group.inputs.new("NodeSocketFloat", "Value")
group.inputs.new("NodeSocketFloat", "Value")
input_node = group.nodes.new("NodeGroupInput")
input_node.location = (0, 0)

group.outputs.new("NodeSocketFloat", "Value")
output_node = group.nodes.new("NodeGroupOutput")
output_node.location = (600, 0)

# Add a greater than node
gtr_math_node = group.nodes.new(type='ShaderNodeMath')
gtr_math_node.operation = "GREATER_THAN"
gtr_math_node.name = "greater"
gtr_math_node.location = (200, 100)
group.links.new(input_node.outputs[0], gtr_math_node.inputs[0])
group.links.new(input_node.outputs[1], gtr_math_node.inputs[1])

# Add a less than node
lss_math_node = group.nodes.new(type='ShaderNodeMath')
lss_math_node.operation = "LESS_THAN"
lss_math_node.name = "less"
lss_math_node.location = (200,-100)
group.links.new(input_node.outputs[0], lss_math_node.inputs[0])
group.links.new(input_node.outputs[1], lss_math_node.inputs[1])

# Add an add node
add_math_node = group.nodes.new(type='ShaderNodeMath')
add_math_node.operation = "ADD"
add_math_node.name = "add"
add_math_node.use_clamp = True
add_math_node.location = (400, 0)

# connect nodes
group.links.new(gtr_math_node.outputs["Value"], add_math_node.inputs[0])
group.links.new(lss_math_node.outputs["Value"], add_math_node.inputs[1])
group.links.new(add_math_node.outputs["Value"], output_node.inputs[0])

# Create main "Object Color" node group
main_group = bpy.data.node_groups.new(type="ShaderNodeTree", name="Object Color")
main_group.outputs.new("NodeSocketColor", "Object Color")
output_node = main_group.nodes.new("NodeGroupOutput")
output_node.location = (600, 0)

#Add object info node:
ob_index = main_group.nodes.new(type="ShaderNodeObjectInfo")
ob_index.location = (-600,0)

index = 1
# Iterate through all objects in the current scene, set the path indexes and create nodes with the object color
for object in bpy.context.scene.objects:
    if object.type != 'CAMERA' and object.type != 'EMPTY' and object.type != 'LAMP':
        object.pass_index = index
        col = object.color
        if col != (1,1,1,1):

#            add frame node:
            frame = main_group.nodes.new(type="NodeFrame")
            frame.location = (-70, index*200)
            frame.label = object.name
            frame.use_custom_color = True
            frame.color = (0,.005,.133)

#            Add equalto node:
            group_node = main_group.nodes.new("ShaderNodeGroup")
            group_node.node_tree = group
            group_node.label = "Equal to"
            group_node.location = (-200, index*200)
            group_node.name = "eq_" + str(index)
            main_group.links.new(ob_index.outputs["Object Index"], group_node.inputs[0])
            group_node.inputs[1].default_value = index

#            Add mixRGB node:
            mix_node = main_group.nodes.new(type="ShaderNodeMixRGB")
            mix_node.location = (100, index*200)
            mix_node.name = "mix_" + str(index)
            main_group.links.new(group_node.outputs["Value"], mix_node.inputs["Fac"])
            mix_node.inputs["Color1"].default_value = col
            if index != 1:
                main_group.links.new(main_group.nodes["mix_" + str(index-1)].outputs["Color"], mix_node.inputs["Color2"])
            else:
                mix_node.inputs["Color2"].default_value = (1,1,1,1)

            index = index + 1
        else:
            print ("ob-color is white")
    else:
        print ("is camera or lamp")

main_group.links.new(mix_node.outputs["Color"], main_group.nodes["Group Output"].inputs["Object Color"])

# Optional: uncomment the following to add the node group to the active material automatically:
#tree = bpy.context.object.active_material.node_tree
#group_node = tree.nodes.new("ShaderNodeGroup")
#group_node.node_tree = main_group
#group_node.label = "Object Color"

Note that it sets the pass index for every object in the current scene that is not a Lamp, Camera, or an Empty. If you have pass indexes already set, this script will overwrite them.
Usage:
This is script can be run by pasting it into the Text editor and clicking Run Script. This will create the "Object Color" node group with all the nodes and colors set according to the actual Object Color property.
You can add this group to your setups by pressing ShiftA> Add > Node > Group > Object Color.
To change the colors, press Tab with the node group selected to edit it and change the colors of the Color1 slots on the mix nodes.
To update it for new objects etc. you will have to run the script again and create another node group.

No, i don't want vertex colors, i want "Object Color" that's the name, i'm be asking for this and people just tell me about viewpor color,  or shader color.

@HikaruAi Getting object color is not really possible atm, but there is a  workaround. See my updated answer.


text:
Node containing text?
Is it possible to add a node to the middle of, say, a material, that just contains plaintext information for people viewing the node tree?
I know that it's possible to add a tooltip to frames, which are nice for organizing, but screen real estate for what I'm working on requires that the text be wrapped into the node itself; basically so that I can reference it without having to pop over to another viewer or such, sort of the equivalent of adding comments in a programming language.

You can use a frame to achieve this. Frames are generally used to explain and group nodes/node layouts.

You could also try the Grease pencil (Ctrl+LMB on the node editor). It takes some skill with a mouse (Though I imagine this might actually work nicely with a tablet)

As of 2.74 you can display a text datablock in a frame node:

It's still quite limited, but at least it's somewhat possible now.

No such composite node exists (I am assuming you want it for that pane, but most of these are in Material and Texture too). Here are all the different types of composite nodes in Blender.

Types of Composite Nodes
This section is organized by type of nodes, which are grouped based on
similar functions:

Input - Adds something to the node map, such as an image or a value.
Output - Displays the result in progress as a small image.
Color - Manipulates the colors of an image.
Vector - Manipulate the intensities and reflections of an image
Filters - Process the image to enhance it, working on adjacent pixels.
Converters - Separate the image into its component video, or convert formats.
Mattes - Generating mattes to mask off areas of an image.
Distortion - Changing the shape of the image.
Groups - User-defined groups of nodes.

At most you can change the name of the label.

The no node exists thing seems to be the correct answer, unfortunately.


text:
Add marker to a strip
Is it possible to add a marker to a strip in the VSE? I don't want to add the marker to the timeline with m, but to the selected strip, e.g. to mark possible cut positions to choose from. Something like this:

No, video-editor strips don't have their own markers.

  One workaround for this is to cut the strip soft. Place the green time cursor where you might want to cut, then hit K. By selecting both ends of the cut, you can move the cut around, since both strips keep their original length under the hood.
  Until you delete or move one of the strips, the cut is not noticable. and you can always restor one of them to full length.

Not sure this is really great suggestion - in some cases it can be OK, but it will interfere with animation, effects and modifier stack.

It has been designed not to be a great answer. But if at least one blenderhead gets a useful idea out of it, it's worth mentioning it.

fine - but in that case the answer should note drawbacks with the proposed solution.

Oh, please don't get me wrong. I really do appreciate the second half of your first comment. And whenever I'm aware of drawbacks, I note them myself.


text:
How to get accumulated render time of animation
When rendering an animation in the render window on the top right you can see the render time of the last frame. But where can I see the sum of the render times of all frames?

There's an add-on called Render Time Estimation that will do that for you.
Full disclosure, I wrote that add-on.

Great! Why doesn't it ship by default with blender?

I've never pushed for its inclusion in trunk. I should probably clean it up a bit and do that.

Yes do that please. It's really usefull.

1 - Move cursor over a progress bar, it displays Estimated and Elapsed time. But it disappears after rendering.

2 - or you can check file info and calculate total (elapsed) time from "created" to " modified" time, if minutes are enough for you. Like here rendering took 4 min.

That file trick is really helpful!

I don’t think either answer addresses the question exactly - the poster wanted to know total render time already (not remaining), and for the whole animation, not for specific frames. I’ve written a plugin that gives you this exactly, which is free for personal use: https://blendermarket.com/products/total-render-time


text:
How can I ensure a minimal precision of 1cm in my project?
I'm working on a project for some architects. I have following requirement:

The maximal allowed error is 1cm.
Many people will work on that plan for some years. I think every Object/Vertex may be moved maximal 1000 times, so the maximal error per move shouldn't be above a 1/100th of mm.
The project is 15km big on each side.

Questions:

Should I take a special value for the world scale instead of the default 1BU = 1m to ensure that precision over the years?
Are object on the border (7,5km away from origin) more problematic because of the floating point value system ?
Blender stores vertex as 32bits float as far as I know. Is that per dimension (32bit x, 32bit y and 32bit z) or the total?

I think Blender can/does store data as 64bit float. Which pretty much eliminates any precision problem at the scale you are working on.  http://www.atmind.nl/blender/mystery_ot_blend.html

Campbell says 32bit here : http://blender.stackexchange.com/questions/3168/digits-of-precision-of-vertices-coordinates Who is right ? Edit : I can't find the 64bit float you speak about on that page. Which sentence is that?

In the link, it mentions 32/64bit pointers. Which I assumed meant the precision of all floats. If Campbell says it's 32bit only, I am inclined to believe him.

Based upon my experience, there are three things be required in the project you describe to ensure a minimal precision of 1 cm. First, Blender has a maximum order of magnitude of a dimension of 10,000 units, so for your 15 km project, you're going to want the project centered about the origin point so the minimum x, y, and z dimensions are a negative 7.500 km and the maximum x y and z dimensions are plus 7.500 km.
Next, it will be good practice to break the project down into multiple objects spread across multiple scenes. If there will be a checkpoint (guard shack) at the entrance located (to pull a location out of the air for the discussion) at 4.7 km in the positive x direction, and 5.9 miles in the positive y direction, make that guard shack as one or more independent object. As an independent object, you can track the dimensions of the guard shack / checkpoint to within 1 cm (actually smaller than that) more easily than tracking the four corners of the shack from the center point. Treating the guard shack separately also allows the guard shack to be constructed as multiple objects. This will be a necessity if at some point it is necessary or desirable to make some of the parts—sliding windows, or swinging doors, for example—movable. It is possible, of course, to collect all of the bits of the guard shack, and its accompanying devices (like entry gates) into a blender Group.
There is a precedent for making smaller groups of objects, not just within the main file, but moving some objects into other ~.blend files. Even if done on a full architectural plan, the architectural materials detailing the construction of the guard shack are going to e separate from the overall site plan. Putting some elements of the plan into other groups, or blend files is simply an extension of that already standard practice.
Third, Blender allows the movement of vertices (and groups of vertices) by changing values in the numeric boxes in the transform panel of the properties (N) shelf. If you change the location of a vertex (or a set of vertices) using these numeric values, you can help maximize the chances of the precision you want. There are two caveats to this. First the numbers displayed in the dimension boxes of the Transform depend a bit upon the width of the button. If the Properties shelf is too narrow to accommodate a ten digit number (with decimal point), it will truncate (or round) the number to fit. Second you might not get the precision for each set of corner vertices of the hypothetical guard shack referred to above if you choose to use global attributes. However, you can get the center of the guard shack to within a centimeter from the global center, and if you switch to local transformation orientation for the guard shack, you can certainly come within a one centimeter level of precision in the local object or group of objects.