There is a way to do what you want. I am not sure if this is optimal but it worked for me.
Starting Blender
You can not import bpy from outside of blender (see this related question). You can, however, start Blender and pass it the .blend file with your game and a python script to execute. From the command line start
<path-to-blender>/blender <path-to-blend-file>/my_game.blend --python <path-to-script>/my_script.py
Under Windows you have to use \
in the paths of course.
You can also execute this command from the follwing python script, if you want to create some data first:
import subprocess as sub
"""
create some data here and do other stuff like calling your Java application
"""
...
# execute Blender
command = r"<path-to-blender>/blender -b <path-to-blend-file>/my_game.blend --python <path-to-script>/my_script.py"
p = sub.Popen(command, stdout=sub.PIPE, stderr=sub.PIPE, shell=True)
output, errors = p.communicate()
if not output == "" :
print("\nOutput:\n\n" + output)
if not errors == "" :
print("\nErrors:\n\n" + errors)
You can find more informationon on subprocess
here.
Creating Objects
I would create the objects in a script passed to Blender, as I described above. You can also pass command line arguments to this script if necessary. Any command line argument passed after --
in the command line is treated as an argument for the script. The command line woud change to
<path-to-blender>/blender <path-to-blend-file>/my_game.blend --python <path-to-script>/my_script.py -- myArg1 myArg2 myArg3 ...
Inside of Blender you can get the arguments as follows:
import sys
if (("--" in sys.argv) == False) :
print("No arguments passed to the script.")
return
argsStartPos = sys.argv.index("--")
arg1 = sys.argv[argsStartPos + 1]
arg2 = sys.argv[argsStartPos + 2]
arg3 = sys.argv[argsStartPos + 3]
...
# process command line arguments, create trees or what ever
...
After object creation: Start the game
I think the easiest way to achieve what you want is to set up the collision detection and player controls in the .blend file you passed to Blender. Then you just have to start the game engine's standalone player. Just add these lines to the python script that creates your scene:
import bpy
...
# create scene and stuff
...
bpy.context.scene.render.engine = 'BLENDER_GAME'
bpy.ops.wm.blenderplayer_start()
Hiding Blender
To hide the Blender window, start Blender in background mode. Just pass -b
as command line argument. The full command should then be:
<path-to-blender>/blender -b <path-to-blend-file>/my_game.blend --python <path-to-script>/my_script.py -- myArg1 myArg2 myArg3 ...
Notice the -b
before the .blend file.
The standalone player will still be started with a visible window.
I hope this helps :)