cloning
link-mesh-array.py
link-mesh.py

mesh fabrication
staircase.py
triangle-donut.py
vertexAccumulator.py
randomSquareArray.py
meshFromBathymetry.py
cylinders-from-list-of-radii.py
binary-image-to-mesh.py
sphere-minecraft-schematic.py
spikify.py
add-to-mesh.py
mobius-strip.py
split-copy-mesh.py

fabricating other objects
create-text.py
text-from-file.py
create-camera.py
create-bezier.py
helix-bezier.py

material slots
cube-copy-blue.py
cube-turns-red.py
red-blue-per-object.py

animation and fcurves
csv-to-fcurve-loc-rot.py
csv-to-fcurve.py
pop-in-material.py
spike-wiggle-2.py
spike-wiggle.py
sweep-animate-size.py
animate-cycles-lamp-strength.py

incorporating python libraries
exec-text-library.py
exec-external-python.py
import-python.py

constraints
camera-track-object.py
text-track-camera.py

shape keys
explore-shape-keys.py
shape-key-fin.py
docking-tube.py

animating curve bevel
data-graph.py

drivers
scan-drivers.py
copy-drivers.py
driver-fin.py
driver-multi-chain.py

UV layers
barber-pole.py
expand-uv-to-fit.py
uv-from-geometry-cubic.py
flip-texture-v-coordinate.py

modifiers
hook-modifier-curve.py
rounded-prisms.py
make-tile.py
remove-action-modifiers.py

NLAs
explore-NLAs.py
spinning-frogs.py

video sequence editor (VSE)
create-vse-image-strips.py
slide-show.py
vse-strip-gap.py

images and textures
image-on-mesh.py
image-to-material-node.py
load-image-texture.py
texture-one-cube-face.py
condense-duplicate-images.py

analytic geometry
animate-random-spin.py
camera-cone-exp-2.py
camera-cone-exp.py
compute-circle-center.py
dihedral-angle-from-xy.py
extrude-edge-along-custom-axis.py
orientation-matrix.py
two-spheres.py
bezier-interpolate.py
rotate-to-match.py

node trees
change-diffuse-to-emission-node.py

etc
add-plane-from-selected-vertices.py
adjust-all-materials.py
all-nodes-cycles-materials.py
bit_shift.py
bone-orientation-demo.py
cannonball-packing.py
comb.py
convert-quaternion-keyframes-to-euler.py
copy-location-from-vertex-group.py
create-cycles-material.py
demonstrate-decomposition-instability.py
dump-point-cache.py
dump-screen-layout-info.py
expand-nla-strips.py
explore-edge-bevel-weight.py
find-action-users.py
find-green-rectangle.py
find-new-objects.py
fix-scene-layers.py
generate-makefile.py
link-external-data-blocks.py
list-referenced-files.py
material-readout.py
movie-card-stack.py
movies-on-faces.py
next-file-name.py
object-font-from-regular-font.py
operator-mesh-gridify.py
particle-animator.py
particle_loop.py
pose-match.py
pose-sequence-to-fbx.py
prepare-texture-bake.py
raining-physics.py
random-pebble-material.py
reverse-keyframes.py
scale-parallelogram.py
screenshot-sequence.py
select-objects-in-modifiers.py
select-vertices.py
shift-layers.py
snapshot-keyframes-as-mesh.py
sphere-project-texture.py
squish-mesh-axis.py
subdivide-fcurve.py
thicken-texture.py
transform-selected.py
voronoi-madness.py

__author__ = 'thoth'

import struct
import os.path

# http://blender.stackexchange.com/questions/15577/how-to-extract-convert-data-from-blender-cache-files-bphys-into-a-human-readabl

class CacheRowReader:
    # BPHYS_DATA_* from DNA_object_force.h
    column_words = (1,3,3,4,3,1,3,5)
    column_formats = ("i", "fff", "fff", "ffff", "fff", "f", "fff", "fffff")

    def __init__(self, flavor, count, data_type_flags):
        self.count = count
        self.flavor = flavor
        self.data_type_flags = data_type_flags

        rec_len=0
        unpack_format = ""
        for i in range(len(CacheRowReader.column_words)):
            if 0 != (data_type_flags&(1<<i)):
                rec_len += 4 * CacheRowReader.column_words[i]
                unpack_format += CacheRowReader.column_formats[i]

        self.rec_len = rec_len
        self.unpack_format = unpack_format

    @classmethod
    def parse(cls, f):

        magic = f.read(8)
        if magic != b'BPHYSICS':
            raise Exception("not a blender physics cache")

        flavor = f.read(12)
        (flavor,count,data_type_flags) = struct.unpack("iii", flavor)

        #print( "%d\t%d\t%d"%(flavor,count,data_type_flags))

        return CacheRowReader(flavor, count, data_type_flags)

    def read_row(self, f):
        """
        :param f: a file opened with "rb" (binary) mode
        :return:
        """
        raw = f.read(self.rec_len)

        if raw is None or len(raw)==0:
            return None
        if len(raw) != self.rec_len:
            raise Exception("short read (%d<%d)"%( len(raw), self.rec_len))

        columns = struct.unpack(self.unpack_format, raw)

        rval = dict()
        cursor =0
        # a lot of these clauses are untested.  Feel free to leave me a comment on the stackexchange answer.
        if 0 != (self.data_type_flags&1):
            rval['index'] = columns[cursor]
            cursor +=1
        if 0 != self.data_type_flags&2:
            rval['location'] = columns[cursor:cursor+3]
            rval['smoke_low'] = rval['location']
            cursor +=3
        if 0 != self.data_type_flags&4:
            rval['velocity'] = columns[cursor:cursor+3]
            rval['smoke_high'] = rval['velocity']
            cursor +=3
        if 0 != self.data_type_flags&8:
            rval['dynamicpaint'] = rval['rotation'] = columns[cursor:cursor+4]
            cursor +=4
        if 0 != self.data_type_flags&0x10:
            rval['xconst'] = rval['avelocity'] = columns[cursor:cursor+3]
            cursor +=3
        if 0 != self.data_type_flags&0x20:
            rval['size'] = columns[cursor]
            cursor +=1
        if 0 != self.data_type_flags&0x40:
            rval['times'] = columns[cursor:cursor+3]
            cursor +=3
        if 0 != self.data_type_flags&0x80:
            rval['boids'] = columns[cursor:cursor+5]
            cursor +=5

        return rval

def dump_one_file(fname):
    f = open(fname, "rb")

    reader = CacheRowReader.parse(f)
    print("%d\t%d\t%d"%(reader.flavor, reader.count, reader.data_type_flags))

    while True:
        row = reader.read_row(f)
        if row is None:
            break
        print(row)


def dump_times_file(fname):

    f = open(fname, "rb")

    reader = CacheRowReader.parse(f)

    while True:
        row = reader.read_row(f)
        if row is None:
            break
        print(row)

def maybe_discard(scn, name):

    obj = bpy.data.objects.get(name)
    if obj is None:
        return

    obj.name = "discard"
    try:
        scn.objects.unlink(obj)
    except:
        pass


def curve_from_particle_track(scn, path_pattern):

    i=0

    tracks = []
    while True:

        fname = path_pattern%i
        #print(fname)

        if not os.path.isfile(fname):
            break

        f = open(fname, "rb")
        if f is None:
            break

        reader = CacheRowReader.parse(f)
        if 0 == (reader.data_type_flags &1):
            pass  # this is probably the first cache file with only time info, let's ignore it
        else:
            while True:
                row = reader.read_row(f)
                if row is None: break

                #print(row)
                idx = row['index']
                while len(tracks) <= idx:
                    tracks.append( [] )
                tracks[idx].append(row['location'])

        f.close()

        i+=1
        #print(i)

    #print (tracks)

    name = "tracks"
    curve = bpy.data.curves.new(name, 'CURVE')
    for i in range(len(tracks)):

        locations = tracks[i]
        if len(locations) < 1:
            continue

        spline = curve.splines.new('POLY')

        spline.points.add(len(locations) - len(spline.points))

        for j in range(len(locations)):
            #print(locations[j])
            spline.points[j].co[0:3] = locations[j]

    maybe_discard(scn, name)
    obj = bpy.data.objects.new(name, curve)

    scn.objects.link(obj)


if True:
    fname = "/home/thoth/art/ornaments-in-space/blendcache_ornaments-in-space/loop_000001_00.bphys"
    #fname = "/home/thoth/art/ornaments-in-space/blendcache_ornaments-in-space/loop_000000_00.bphys"
    #fname = "/home/thoth/art/ornaments-in-space/blendcache_ornaments-in-space/7061727469636C6520656D69747465722E303031_000000_00.bphys"
    dump_one_file(fname)
elif True:
    dump_one_file("/var/tmp/blendcache_particles/bacon_000000_00.bphys")
elif True:
    dump_one_file("/var/tmp/blendcache_particle/pants_000045_00.bphys")
elif False:
    dump_times_file("/var/tmp/blendcache_particle/pants_000000_00.bphys")
else:
    curve_from_particle_track(bpy.context.scene, "/var/tmp/blendcache_particle/pants_%06d_00.bphys")

Blender python API quick-start

Syntax highlighting by Pygments.