Spring cleaning in python wrappers.

develop
Petr Mrázek 2011-03-18 06:17:43 +01:00
parent 001b8e059d
commit 737643a33f
71 changed files with 0 additions and 7341 deletions

@ -1,42 +0,0 @@
PROJECT (pydfhack)
FIND_PACKAGE(PythonLibs)
SET(PYTHON_MODULE_PREFIX "")
SET(PROJECT_LIBS ${PYTHON_LIBRARIES} dfhack )
IF(UNIX)
add_definitions(-DLINUX_BUILD)
add_definitions(-DUSE_CONFIG_H)
SET(CMAKE_CXX_FLAGS_DEBUG "-g -Wall")
SET(PYTHON_MODULE_SUFFIX ".so")
ENDIF(UNIX)
IF(WIN32)
#windows
SET(PYTHON_MODULE_SUFFIX ".pyd")
ENDIF(WIN32)
IF(PYTHONLIBS_FOUND)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
PYTHON_ADD_MODULE(pydfhack
DF_API.cpp
DF_Buildings.cpp
DF_Constructions.cpp
DF_CreatureManager.cpp
DF_GUI.cpp
DF_Maps.cpp
DF_Material.cpp
DF_Position.cpp
DF_Translate.cpp
DF_Vegetation.cpp
pydfhack.cpp
)
SET_TARGET_PROPERTIES(pydfhack PROPERTIES PREFIX "")
# fix suffix on windows
SET_TARGET_PROPERTIES(pydfhack PROPERTIES SUFFIX ${PYTHON_MODULE_SUFFIX})
TARGET_LINK_LIBRARIES(pydfhack ${PROJECT_LIBS})
ELSE(PYTHONLIBS_FOUND)
MESSAGE("UNABLE TO BUILD PYTHON BINDINGS!")
ENDIF(PYTHONLIBS_FOUND)

@ -1,884 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFAPI__
#define __DFAPI__
#include "Python.h"
#include <string>
#include "integers.h"
#include "DFTypes.h"
#include "DFContext.h"
#include "DF_Imports.cpp"
#include "DF_MemInfo.cpp"
#include "DF_Position.cpp"
#include "DF_Material.cpp"
#include "DF_CreatureManager.cpp"
#include "DF_Maps.cpp"
#include "DF_GUI.cpp"
#include "DF_Vegetation.cpp"
#include "DF_Translate.cpp"
#include "DF_Constructions.cpp"
using namespace std;
using namespace DFHack;
struct DF_API
{
PyObject_HEAD
PyObject* mem_info;
PyObject* position;
PyObject* material;
PyObject* creature;
PyObject* map;
PyObject* translate;
PyObject* construction;
PyObject* vegetation;
PyObject* gui;
PyObject* mem_info_type;
PyObject* position_type;
PyObject* material_type;
PyObject* creature_type;
PyObject* map_type;
PyObject* translate_type;
PyObject* construction_type;
PyObject* vegetation_type;
PyObject* gui_type;
DFHack::Context* api_Ptr;
};
// API type Allocation, Deallocation, and Initialization
static PyObject* DF_API_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DF_API* self;
self = (DF_API*)type->tp_alloc(type, 0);
if(self != NULL)
self->api_Ptr = NULL;
return (PyObject*)self;
}
static int DF_API_init(DF_API* self, PyObject* args, PyObject* kwds)
{
const char* memFileString = NULL;
if(self->api_Ptr == NULL)
{
self->mem_info = NULL;
self->position = NULL;
self->material = NULL;
self->creature = NULL;
self->map = NULL;
self->translate = NULL;
self->construction = NULL;
self->vegetation = NULL;
self->gui = NULL;
self->position_type = (PyObject*)&DF_Position_type;
self->map_type = (PyObject*)&DF_Map_type;
self->vegetation_type = (PyObject*)&DF_Vegetation_type;
self->gui_type = (PyObject*)&DF_GUI_type;
if(!PyArg_ParseTuple(args, "s", &memFileString))
return -1;
if(memFileString)
self->api_Ptr = new DFHack::Context(std::string(memFileString));
else
return -1;
}
return 0;
}
static void DF_API_dealloc(DF_API* self)
{
PySys_WriteStdout("API dealloc\n");
if(self != NULL)
{
PySys_WriteStdout("creature xdecref\n");
Py_XDECREF(self->creature);
PySys_WriteStdout("mem_info xdecref\n");
Py_XDECREF(self->mem_info);
PySys_WriteStdout("position xdecref\n");
Py_XDECREF(self->position);
PySys_WriteStdout("material xdecref\n");
Py_XDECREF(self->material);
PySys_WriteStdout("map xdecref\n");
Py_XDECREF(self->map);
PySys_WriteStdout("translate xdecref\n");
Py_XDECREF(self->translate);
PySys_WriteStdout("construction xdecref\n");
Py_XDECREF(self->construction);
PySys_WriteStdout("vegetation xdecref\n");
Py_XDECREF(self->vegetation);
PySys_WriteStdout("gui xdecref\n");
Py_XDECREF(self->gui);
if(self->api_Ptr != NULL)
{
PySys_WriteStdout("api_Ptr = 0x%x\n", self->api_Ptr);
delete self->api_Ptr;
PySys_WriteStdout("api_Ptr deleted\n");
self->api_Ptr = NULL;
}
self->ob_type->tp_free((PyObject*)self);
}
PySys_WriteStdout("API dealloc done\n");
}
// Accessors
static PyObject* DF_API_getIsAttached(DF_API* self, void* closure)
{
try
{
if(self->api_Ptr != NULL)
if(self->api_Ptr->isAttached())
Py_RETURN_TRUE;
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to read attached flag");
Py_RETURN_FALSE;
}
Py_RETURN_FALSE;
}
static PyObject* DF_API_getIsSuspended(DF_API* self, void* closure)
{
try
{
if(self->api_Ptr != NULL)
if(self->api_Ptr->isSuspended())
Py_RETURN_TRUE;
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to read suspension flag");
return NULL;
}
Py_RETURN_FALSE;
}
static PyObject* DF_API_getMemoryInfo(DF_API* self, void* closure)
{
if(self->mem_info != NULL)
return self->mem_info;
try
{
if(self->api_Ptr != NULL)
{
PyObject *apiarg;
apiarg = PyTuple_New(1);
PyTuple_SetItem(apiarg, 0, (PyObject*)self);
self->mem_info = PyObject_CallObject(self->mem_info_type, apiarg);
if(self->mem_info != NULL)
{
((DF_MemInfo*)(self->mem_info))->mem_Ptr = self->api_Ptr->getMemoryInfo();
if(((DF_MemInfo*)(self->mem_info))->mem_Ptr != NULL)
return self->mem_info;
}
}
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to read memory info");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject* DF_API_getPosition(DF_API* self, void* closure)
{
if(self->position != NULL)
return self->position;
try
{
if(self->api_Ptr != NULL)
{
PyObject *apiarg;
apiarg = PyTuple_New(1);
PyTuple_SetItem(apiarg, 0, (PyObject*)self);
self->position = PyObject_CallObject(self->position_type, apiarg);
if(self->position != NULL)
{
((DF_Position*)(self->position))->pos_Ptr = self->api_Ptr->getPosition();
if(((DF_Position*)(self->position))->pos_Ptr != NULL)
return self->position;
}
}
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to read position");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject* DF_API_getMaterial(DF_API* self, void* closure)
{
if(self->material != NULL)
return self->material;
try
{
if(self->api_Ptr != NULL)
{
PyObject *apiarg;
apiarg = PyTuple_New(1);
PyTuple_SetItem(apiarg, 0, (PyObject*)self);
self->material = PyObject_CallObject(self->material_type, apiarg);
if(self->material != NULL)
{
((DF_Material*)(self->material))->mat_Ptr = self->api_Ptr->getMaterials();
if(((DF_Material*)(self->material))->mat_Ptr != NULL)
return self->material;
}
}
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to read material");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject* DF_API_getCreature(DF_API* self, void* closure)
{
if(self->creature != NULL)
return self->creature;
try
{
if(self->api_Ptr != NULL)
{
PyObject *apiarg;
apiarg = PyTuple_New(1);
PyTuple_SetItem(apiarg, 0, (PyObject*)self);
self->creature = PyObject_CallObject(self->creature_type, apiarg);
if(self->creature != NULL)
{
((DF_CreatureManager*)(self->creature))->creature_Ptr = self->api_Ptr->getCreatures();
if(((DF_CreatureManager*)(self->creature))->creature_Ptr != NULL)
return self->creature;
}
}
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to read creature");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject* DF_API_getMap(DF_API* self, void* closure)
{
if(self->map != NULL)
return self->map;
try
{
if(self->api_Ptr != NULL)
{
PyObject *apiarg;
apiarg = PyTuple_New(1);
PyTuple_SetItem(apiarg, 0, (PyObject*)self);
self->map = PyObject_CallObject(self->map_type, apiarg);
if(self->map != NULL)
{
((DF_Map*)(self->map))->m_Ptr = self->api_Ptr->getMaps();
if(((DF_Map*)(self->map))->m_Ptr != NULL)
return self->map;
}
}
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to read map");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject* DF_API_getTranslation(DF_API* self, void* closure)
{
if(self->translate != NULL)
return self->translate;
try
{
if(self->api_Ptr != NULL)
{
PyObject *apiarg;
apiarg = PyTuple_New(1);
PyTuple_SetItem(apiarg, 0, (PyObject*)self);
self->translate = PyObject_CallObject(self->translate_type, apiarg);
if(self->translate != NULL)
{
((DF_Translate*)(self->translate))->tran_Ptr = self->api_Ptr->getTranslation();
if(((DF_Translate*)(self->translate))->tran_Ptr != NULL)
return self->translate;
}
}
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to read translation");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject* DF_API_getConstruction(DF_API* self, void* closure)
{
if(self->construction != NULL)
return self->construction;
try
{
if(self->api_Ptr != NULL)
{
PyObject *apiarg;
apiarg = PyTuple_New(1);
PyTuple_SetItem(apiarg, 0, (PyObject*)self);
self->construction = PyObject_CallObject(self->construction_type, apiarg);
if(self->construction != NULL)
{
((DF_Construction*)(self->construction))->c_Ptr = self->api_Ptr->getConstructions();
if(((DF_Construction*)(self->construction))->c_Ptr != NULL)
return self->construction;
}
}
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to read constructions");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject* DF_API_getVegetation(DF_API* self, void* closure)
{
if(self->vegetation != NULL)
return self->vegetation;
try
{
if(self->api_Ptr != NULL)
{
PyObject *apiarg;
apiarg = PyTuple_New(1);
PyTuple_SetItem(apiarg, 0, (PyObject*)self);
self->vegetation = PyObject_CallObject(self->vegetation_type, apiarg);
if(self->vegetation != NULL)
{
((DF_Vegetation*)(self->vegetation))->veg_Ptr = self->api_Ptr->getVegetation();
if(((DF_Vegetation*)(self->vegetation))->veg_Ptr != NULL)
return self->vegetation;
}
}
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to read vegetation");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject* DF_API_getGUI(DF_API* self, void* closure)
{
if(self->gui != NULL)
return self->gui;
try
{
if(self->api_Ptr != NULL)
{
PyObject *apiarg;
apiarg = PyTuple_New(1);
PyTuple_SetItem(apiarg, 0, (PyObject*)self);
self->gui = PyObject_CallObject(self->gui_type, apiarg);
if(self->gui != NULL)
{
((DF_GUI*)(self->gui))->g_Ptr = self->api_Ptr->getGui();
if(((DF_GUI*)(self->gui))->g_Ptr != NULL)
return self->gui;
}
}
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to read gui");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject* DF_API_getMemInfoType(DF_API* self, void* closure)
{
return self->mem_info_type;
}
static int DF_API_setMemInfoType(DF_API* self, PyObject* value)
{
if(PyType_Check(value) <= 0)
{
PySys_WriteStdout("failed type check");
PyErr_SetString(PyExc_TypeError, "value must be a type object");
return -1;
}
if(PyObject_IsSubclass(value, (PyObject*)&DF_MemInfo_type) <= 0)
{
PySys_WriteStdout("failed subclass check");
PyErr_SetString(PyExc_TypeError, "value must be descended from _pydfhack._MemInfo");
return -1;
}
self->mem_info_type = value;
return 0;
}
static PyObject* DF_API_getPositionType(DF_API* self, void* closure)
{
return self->position_type;
}
static int DF_API_setPositionType(DF_API* self, PyObject* value)
{
if(PyType_Check(value) <= 0)
{
PySys_WriteStdout("failed type check");
PyErr_SetString(PyExc_TypeError, "value must be a type object");
return -1;
}
if(PyObject_IsSubclass(value, (PyObject*)&DF_Position_type) <= 0)
{
PySys_WriteStdout("failed subclass check");
PyErr_SetString(PyExc_TypeError, "value must be descended from _pydfhack._PositionManager");
return -1;
}
self->position_type = value;
return 0;
}
static PyObject* DF_API_getMaterialType(DF_API* self, void* closure)
{
return self->material_type;
}
static int DF_API_setMaterialType(DF_API* self, PyObject* value)
{
if(PyType_Check(value) <= 0)
{
PySys_WriteStdout("failed type check");
PyErr_SetString(PyExc_TypeError, "value must be a type object");
return -1;
}
if(PyObject_IsSubclass(value, (PyObject*)&DF_Material_type) <= 0)
{
PySys_WriteStdout("failed subclass check");
PyErr_SetString(PyExc_TypeError, "value must be descended from pydfhack._MaterialManager");
return -1;
}
self->material_type = value;
return 0;
}
static PyObject* DF_API_getCreatureType(DF_API* self, void* closure)
{
return self->creature_type;
}
static int DF_API_setCreatureType(DF_API* self, PyObject* value)
{
if(PyType_Check(value) <= 0)
{
PySys_WriteStdout("failed type check");
PyErr_SetString(PyExc_TypeError, "value must be a type object");
return -1;
}
if(PyObject_IsSubclass(value, (PyObject*)&DF_CreatureManager_type) <= 0)
{
PySys_WriteStdout("failed subclass check");
PyErr_SetString(PyExc_TypeError, "value must be descended from pydfhack._CreatureManager");
return -1;
}
self->creature_type = value;
return 0;
}
static PyObject* DF_API_getMapType(DF_API* self, void* closure)
{
return self->map_type;
}
static int DF_API_setMapType(DF_API* self, PyObject* value)
{
if(PyType_Check(value) <= 0)
{
PySys_WriteStdout("failed type check");
PyErr_SetString(PyExc_TypeError, "value must be a type object");
return -1;
}
if(PyObject_IsSubclass(value, (PyObject*)&DF_Map_type) <= 0)
{
PySys_WriteStdout("failed subclass check");
PyErr_SetString(PyExc_TypeError, "value must be descended from pydfhack._MapManager");
return -1;
}
self->map_type = value;
return 0;
}
static PyObject* DF_API_getTranslateType(DF_API* self, void* closure)
{
return self->translate_type;
}
static int DF_API_setTranslateType(DF_API* self, PyObject* value)
{
if(PyType_Check(value) <= 0)
{
PySys_WriteStdout("failed type check");
PyErr_SetString(PyExc_TypeError, "value must be a type object");
return -1;
}
if(PyObject_IsSubclass(value, (PyObject*)&DF_Translate_type) <= 0)
{
PySys_WriteStdout("failed subclass check");
PyErr_SetString(PyExc_TypeError, "value must be descended from pydfhack._TranslateManager");
return -1;
}
self->translate_type = value;
return 0;
}
static PyObject* DF_API_getConstructionType(DF_API* self, void* closure)
{
return self->construction_type;
}
static int DF_API_setConstructionType(DF_API* self, PyObject* value)
{
if(PyType_Check(value) <= 0)
{
PySys_WriteStdout("failed type check");
PyErr_SetString(PyExc_TypeError, "value must be a type object");
return -1;
}
if(PyObject_IsSubclass(value, (PyObject*)&DF_Construction_type) <= 0)
{
PySys_WriteStdout("failed subclass check");
PyErr_SetString(PyExc_TypeError, "value must be descended from pydfhack._ConstructionManager");
return -1;
}
self->construction_type = value;
return 0;
}
static PyObject* DF_API_getVegetationType(DF_API* self, void* closure)
{
return self->vegetation_type;
}
static int DF_API_setVegetationType(DF_API* self, PyObject* value)
{
if(PyType_Check(value) <= 0)
{
PySys_WriteStdout("failed type check");
PyErr_SetString(PyExc_TypeError, "value must be a type object");
return -1;
}
if(PyObject_IsSubclass(value, (PyObject*)&DF_Vegetation_type) <= 0)
{
PySys_WriteStdout("failed subclass check");
PyErr_SetString(PyExc_TypeError, "value must be descended from pydfhack._VegetationManager");
return -1;
}
self->vegetation_type = value;
return 0;
}
static PyObject* DF_API_getGUIType(DF_API* self, void* closure)
{
return self->gui_type;
}
static int DF_API_setGUIType(DF_API* self, PyObject* value)
{
if(PyType_Check(value) <= 0)
{
PySys_WriteStdout("failed type check");
PyErr_SetString(PyExc_TypeError, "value must be a type object");
return -1;
}
if(PyObject_IsSubclass(value, (PyObject*)&DF_GUI_type) <= 0)
{
PySys_WriteStdout("failed subclass check");
PyErr_SetString(PyExc_TypeError, "value must be descended from pydfhack._GUIManager");
return -1;
}
self->gui_type = value;
return 0;
}
static PyGetSetDef DF_API_getterSetters[] =
{
{"is_attached", (getter)DF_API_getIsAttached, NULL, "is_attached", NULL},
{"is_suspended", (getter)DF_API_getIsSuspended, NULL, "is_suspended", NULL},
{"memory_info", (getter)DF_API_getMemoryInfo, NULL, "memory_info", NULL},
{"position", (getter)DF_API_getPosition, NULL, "position", NULL},
{"materials", (getter)DF_API_getMaterial, NULL, "materials", NULL},
{"creatures", (getter)DF_API_getCreature, NULL, "creatures", NULL},
{"maps", (getter)DF_API_getMap, NULL, "maps", NULL},
{"translation", (getter)DF_API_getTranslation, NULL, "translation", NULL},
{"constructions", (getter)DF_API_getConstruction, NULL, "constructions", NULL},
{"vegetation", (getter)DF_API_getVegetation, NULL, "vegetation", NULL},
{"gui", (getter)DF_API_getGUI, NULL, "gui", NULL},
{"_mem_info_mgr_type", (getter)DF_API_getMemInfoType, (setter)DF_API_setMemInfoType, "_mem_info_mgr_type", NULL},
{"_position_mgr_type", (getter)DF_API_getPositionType, (setter)DF_API_setPositionType, "_position_mgr_type", NULL},
{"_material_mgr_type", (getter)DF_API_getMaterialType, (setter)DF_API_setMaterialType, "_material_mgr_type", NULL},
{"_creature_mgr_type", (getter)DF_API_getCreatureType, (setter)DF_API_setCreatureType, "_creature_mgr_type", NULL},
{"_map_mgr_type", (getter)DF_API_getMapType, (setter)DF_API_setMapType, "_map_mgr_type", NULL},
{"_translate_mgr_type", (getter)DF_API_getTranslateType, (setter)DF_API_setTranslateType, "_translate_mgr_type", NULL},
{"_construction_mgr_type", (getter)DF_API_getConstructionType, (setter)DF_API_setConstructionType, "_construction_mgr_type", NULL},
{"_vegetation_mgr_type", (getter)DF_API_getVegetationType, (setter)DF_API_setVegetationType, "_vegetation_mgr_type", NULL},
{"_gui_mgr_type", (getter)DF_API_getGUIType, (setter)DF_API_setGUIType, "_gui_mgr_type", NULL},
{NULL} // Sentinel
};
// API type methods
static PyObject* DF_API_Attach(DF_API* self)
{
if(self->api_Ptr != NULL)
if(self->api_Ptr->Attach())
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
static PyObject* DF_API_Detach(DF_API* self)
{
if(self->api_Ptr != NULL)
if(self->api_Ptr->Detach())
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
static PyObject* DF_API_Suspend(DF_API* self)
{
try
{
if(self->api_Ptr != NULL)
if(self->api_Ptr->Suspend())
Py_RETURN_TRUE;
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to suspend");
return NULL;
}
Py_RETURN_FALSE;
}
static PyObject* DF_API_Resume(DF_API* self)
{
try
{
if(self->api_Ptr != NULL)
if(self->api_Ptr->Resume())
Py_RETURN_TRUE;
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to resume");
return NULL;
}
Py_RETURN_FALSE;
}
static PyObject* DF_API_AsyncSuspend(DF_API* self)
{
try
{
if(self->api_Ptr != NULL)
if(self->api_Ptr->AsyncSuspend())
Py_RETURN_TRUE;
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to asynchronously suspend");
return NULL;
}
Py_RETURN_FALSE;
}
static PyObject* DF_API_ForceResume(DF_API* self)
{
try
{
if(self->api_Ptr != NULL)
if(self->api_Ptr->ForceResume())
Py_RETURN_TRUE;
}
catch(...)
{
PyErr_SetString(PyExc_ValueError, "Error trying to force resume");
return NULL;
}
Py_RETURN_FALSE;
}
static PyMethodDef DF_API_methods[] =
{
{"Attach", (PyCFunction)DF_API_Attach, METH_NOARGS, "Attach to the DF process"},
{"Detach", (PyCFunction)DF_API_Detach, METH_NOARGS, "Detach from the DF process"},
{"Suspend", (PyCFunction)DF_API_Suspend, METH_NOARGS, "Suspend the DF process"},
{"Resume", (PyCFunction)DF_API_Resume, METH_NOARGS, "Resume the DF process"},
{"Async_Suspend", (PyCFunction)DF_API_AsyncSuspend, METH_NOARGS, "Asynchronously suspend the DF process"},
{"Force_Resume", (PyCFunction)DF_API_ForceResume, METH_NOARGS, "Force the DF process to resume"},
{NULL} // Sentinel
};
static PyTypeObject DF_API_type =
{
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pydfhack._API", /*tp_name*/
sizeof(DF_API), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)DF_API_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"pydfhack _API objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DF_API_methods, /* tp_methods */
0, /* tp_members */
DF_API_getterSetters, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DF_API_init, /* tp_init */
0, /* tp_alloc */
DF_API_new, /* tp_new */
};
#endif

@ -1,272 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFBUILDINGS__
#define __DFBUILDINGS__
#include "Python.h"
#include <map>
#include <string>
#include "DFIntegers.h"
using namespace std;
#include "DFTypes.h"
#include "modules/Buildings.h"
#include "DF_Helpers.cpp"
using namespace DFHack;
static PyObject* BuildBuilding(DFHack::t_building& building)
{
PyObject* t_dict;
PyObject* temp;
t_dict = PyDict_New();
temp = Py_BuildValue("(si)(si)(si)(sO)(s((ii)(ii)i))", \
"origin", building.origin, \
"vtable", building.vtable, \
"type", building.type, \
"material", BuildMatglossPair(building.material), \
"bounds", Py_BuildValue("(ii)(ii)i", building.x1, building.y1, building.x2, building.y2, building.z));
PyDict_MergeFromSeq2(t_dict, temp, 0);
return t_dict;
}
static DFHack::t_building ReverseBuildBuilding(PyObject* bDict)
{
PyObject* temp;
uint32_t x1, y1, x2, y2, z;
DFHack::t_building building;
building.origin = (uint32_t)PyInt_AsLong(PyDict_GetItemString(bDict, "origin"));
building.vtable = (uint32_t)PyInt_AsLong(PyDict_GetItemString(bDict, "vtable"));
building.material = ReverseBuildMatglossPair(PyDict_GetItemString(bDict, "material"));
building.type = (uint32_t)PyInt_AsLong(PyDict_GetItemString(bDict, "type"));
temp = PyDict_GetItemString(bDict, "bounds");
PyArg_ParseTuple(temp, "(ii)(ii)i", &x1, &y1, &x2, &y2, &z);
building.x1 = x1;
building.y1 = y1;
building.x2 = x2;
building.y2 = y2;
building.z = z;
return building;
}
struct DF_Building
{
PyObject_HEAD
DFHack::Buildings* b_Ptr;
};
static PyObject* DF_Building_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DF_Building* self;
self = (DF_Building*)type->tp_alloc(type, 0);
if(self != NULL)
self->b_Ptr = NULL;
return (PyObject*)self;
}
static int DF_Building_init(DF_Building* self, PyObject* args, PyObject* kwds)
{
return 0;
}
static void DF_Building_dealloc(DF_Building* self)
{
PySys_WriteStdout("building dealloc\n");
if(self != NULL)
{
PySys_WriteStdout("building not NULL\n");
if(self->b_Ptr != NULL)
{
PySys_WriteStdout("b_Ptr = 0x%x\n", self->b_Ptr);
delete self->b_Ptr;
PySys_WriteStdout("b_Ptr deleted\n");
self->b_Ptr = NULL;
}
self->ob_type->tp_free((PyObject*)self);
}
PySys_WriteStdout("building dealloc done\n");
}
// Type methods
static PyObject* DF_Building_Start(DF_Building* self, PyObject* args)
{
uint32_t numBuildings = 0;
if(self->b_Ptr != NULL)
{
if(self->b_Ptr->Start(numBuildings))
return PyInt_FromLong(numBuildings);
else
return PyInt_FromLong(-1);
}
Py_RETURN_NONE;
}
static PyObject* DF_Building_Finish(DF_Building* self, PyObject* args)
{
if(self->b_Ptr != NULL)
{
if(self->b_Ptr->Finish())
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Building_Read(DF_Building* self, PyObject* args)
{
uint32_t index = 0;
t_building building;
if(self->b_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "I", &index))
return NULL;
if(self->b_Ptr->Read(index, building))
return BuildBuilding(building);
}
Py_RETURN_NONE;
}
static PyObject* DF_Building_ReadCustomWorkshopTypes(DF_Building* self, PyObject* args)
{
PyObject* bDict;
std::map<uint32_t, string> bTypes;
std::map<uint32_t, string>::iterator bIter;
if(self->b_Ptr != NULL)
{
if(self->b_Ptr->ReadCustomWorkshopTypes(bTypes))
{
bDict = PyDict_New();
for(bIter = bTypes.begin(); bIter != bTypes.end(); bIter++)
{
PyObject* temp = Py_BuildValue("is", (*bIter).first, (*bIter).second.c_str());
PyDict_MergeFromSeq2(bDict, temp, 1);
}
return bDict;
}
}
Py_RETURN_NONE;
}
static PyObject* DF_Building_GetCustomWorkshopType(DF_Building* self, PyObject* args)
{
DFHack::t_building building;
if(self->b_Ptr != NULL)
{
building = ReverseBuildBuilding(args);
return PyInt_FromLong(self->b_Ptr->GetCustomWorkshopType(building));
}
Py_RETURN_NONE;
}
static PyMethodDef DF_Building_methods[] =
{
{"Start", (PyCFunction)DF_Building_Start, METH_NOARGS, ""},
{"Finish", (PyCFunction)DF_Building_Finish, METH_NOARGS, ""},
{"Read", (PyCFunction)DF_Building_Read, METH_VARARGS, ""},
{"Read_Custom_Workshop_Types", (PyCFunction)DF_Building_ReadCustomWorkshopTypes, METH_NOARGS, ""},
{"Get_Custom_Workshop_Type", (PyCFunction)DF_Building_GetCustomWorkshopType, METH_VARARGS, ""},
{NULL} // Sentinel
};
static PyTypeObject DF_Building_type =
{
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pydfhack.Building", /*tp_name*/
sizeof(DF_Building), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)DF_Building_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"pydfhack Building objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DF_Building_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DF_Building_init, /* tp_init */
0, /* tp_alloc */
DF_Building_new, /* tp_new */
};
#endif

@ -1,221 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFCONSTRUCTIONS__
#define __DFCONSTRUCTIONS__
#include "Python.h"
#include "integers.h"
#include "modules/Constructions.h"
#include "DF_Helpers.cpp"
using namespace DFHack;
static PyObject* BuildConstruction(DFHack::t_construction& construction)
{
PyObject* t_dict;
PyObject* temp;
t_dict = PyDict_New();
temp = PyTuple_Pack(3, construction.x, construction.y, construction.z);
DICTADD(t_dict, "position", temp);
temp = PyInt_FromLong(construction.form);
DICTADD(t_dict, "form", temp);
temp = PyInt_FromLong(construction.unk_8);
DICTADD(t_dict, "unk_8", temp);
temp = PyInt_FromLong(construction.mat_type);
DICTADD(t_dict, "mat_type", temp);
temp = PyInt_FromLong(construction.mat_idx);
DICTADD(t_dict, "mat_idx", temp);
temp = PyInt_FromLong(construction.unk3);
DICTADD(t_dict, "unk3", temp);
temp = PyInt_FromLong(construction.unk4);
DICTADD(t_dict, "unk4", temp);
temp = PyInt_FromLong(construction.unk5);
DICTADD(t_dict, "unk5", temp);
temp = PyInt_FromLong(construction.unk6);
DICTADD(t_dict, "unk6", temp);
temp = PyInt_FromLong(construction.origin);
DICTADD(t_dict, "origin", temp);
return t_dict;
}
struct DF_Construction
{
PyObject_HEAD
DFHack::Constructions* c_Ptr;
};
static PyObject* DF_Construction_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DF_Construction* self;
self = (DF_Construction*)type->tp_alloc(type, 0);
if(self != NULL)
self->c_Ptr = NULL;
return (PyObject*)self;
}
static int DF_Construction_init(DF_Construction* self, PyObject* args, PyObject* kwds)
{
return 0;
}
static void DF_Construction_dealloc(DF_Construction* self)
{
PySys_WriteStdout("construction dealloc\n");
if(self != NULL)
{
PySys_WriteStdout("construction not NULL\n");
if(self->c_Ptr != NULL)
{
PySys_WriteStdout("c_Ptr = 0x%x\n", self->c_Ptr);
delete self->c_Ptr;
PySys_WriteStdout("c_Ptr deleted\n");
self->c_Ptr = NULL;
}
self->ob_type->tp_free((PyObject*)self);
}
PySys_WriteStdout("construction dealloc done\n");
}
// Type methods
static PyObject* DF_Construction_Start(DF_Construction* self, PyObject* args)
{
uint32_t numConstructions = 0;
if(self->c_Ptr != NULL)
{
if(self->c_Ptr->Start(numConstructions))
return PyInt_FromLong(numConstructions);
else
return PyInt_FromLong(-1);
}
Py_RETURN_NONE;
}
static PyObject* DF_Construction_Finish(DF_Construction* self, PyObject* args)
{
if(self->c_Ptr != NULL)
{
if(self->c_Ptr->Finish())
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Construction_Read(DF_Construction* self, PyObject* args)
{
uint32_t index = 0;
t_construction construction;
if(self->c_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "I", &index))
return NULL;
if(self->c_Ptr->Read(index, construction))
return BuildConstruction(construction);
}
Py_RETURN_NONE;
}
static PyMethodDef DF_Construction_methods[] =
{
{"Start", (PyCFunction)DF_Construction_Start, METH_NOARGS, ""},
{"Finish", (PyCFunction)DF_Construction_Finish, METH_NOARGS, ""},
{"Read", (PyCFunction)DF_Construction_Read, METH_VARARGS, ""},
{NULL} // Sentinel
};
static PyTypeObject DF_Construction_type =
{
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pydfhack._ConstructionManager", /*tp_name*/
sizeof(DF_Construction), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)DF_Construction_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"pydfhack ConstructionManager object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DF_Construction_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DF_Construction_init, /* tp_init */
0, /* tp_alloc */
DF_Construction_new, /* tp_new */
};
#endif

@ -1,279 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFCREATURES__
#define __DFCREATURES__
#include <string>
#include <Python.h>
#include "stdio.h"
#include <vector>
#include "DFIntegers.h"
#include "DFTypes.h"
#include "modules/Materials.h"
#include "modules/Creatures.h"
#include "DF_CreatureType.cpp"
using namespace DFHack;
struct DF_CreatureManager
{
PyObject_HEAD
DFHack::Creatures* creature_Ptr;
};
// API type Allocation, Deallocation, and Initialization
static PyObject* DF_CreatureManager_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DF_CreatureManager* self;
self = (DF_CreatureManager*)type->tp_alloc(type, 0);
if(self != NULL)
self->creature_Ptr = NULL;
return (PyObject*)self;
}
static int DF_CreatureManager_init(DF_CreatureManager* self, PyObject* args, PyObject* kwds)
{
return 0;
}
static void DF_CreatureManager_dealloc(DF_CreatureManager* self)
{
PySys_WriteStdout("creature manager dealloc\n");
if(self != NULL)
{
PySys_WriteStdout("creature manager not NULL\n");
if(self->creature_Ptr != NULL)
{
PySys_WriteStdout("creature_Ptr = 0x%x\n", self->creature_Ptr);
delete self->creature_Ptr;
PySys_WriteStdout("creature_Ptr deleted\n");
self->creature_Ptr = NULL;
}
self->ob_type->tp_free((PyObject*)self);
}
PySys_WriteStdout("creature manager dealloc done\n");
}
// Type methods
static PyObject* DF_CreatureManager_Start(DF_CreatureManager* self, PyObject* args)
{
uint32_t numCreatures = 0;
if(self->creature_Ptr != NULL)
{
if(self->creature_Ptr->Start(numCreatures))
return PyInt_FromLong(numCreatures);
else
return PyInt_FromLong(-1);
}
Py_RETURN_NONE;
}
static PyObject* DF_CreatureManager_Finish(DF_CreatureManager* self, PyObject* args)
{
if(self->creature_Ptr != NULL)
{
if(self->creature_Ptr->Finish())
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_CreatureManager_ReadCreature(DF_CreatureManager* self, PyObject* args)
{
uint32_t index;
DFHack::t_creature furball;
if(self->creature_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "I", &index))
return NULL;
if(self->creature_Ptr->ReadCreature(index, furball))
{
return BuildCreature(furball);
}
else
{
Py_RETURN_FALSE;
}
}
Py_RETURN_NONE;
}
static PyObject* DF_CreatureManager_ReadCreatureInBox(DF_CreatureManager* self, PyObject* args)
{
int32_t index;
uint32_t x1, y1, z1, x2, y2, z2;
DFHack::t_creature furball;
if(self->creature_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "iIIIIII", &index, &x1, &y1, &z1, &x2, &y2, &z2))
return NULL;
if(self->creature_Ptr->ReadCreatureInBox(index, furball, x1, y1, z1, x2, y2, z2) >= 0)
return BuildCreature(furball);
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_CreatureManager_GetDwarfRaceIndex(DF_CreatureManager* self, PyObject* args)
{
if(self->creature_Ptr != NULL)
{
return PyInt_FromLong(self->creature_Ptr->GetDwarfRaceIndex());
}
Py_RETURN_NONE;
}
static PyObject* DF_CreatureManager_GetDwarfCivId(DF_CreatureManager* self, PyObject* args)
{
if(self->creature_Ptr != NULL)
{
return PyInt_FromLong(self->creature_Ptr->GetDwarfCivId());
}
Py_RETURN_NONE;
}
static PyObject* DF_CreatureManager_WriteLabors(DF_CreatureManager* self, PyObject* args)
{
int32_t index;
PyObject* laborList;
if(self->creature_Ptr != NULL)
{
uint8_t laborArray[NUM_CREATURE_LABORS];
if(!PyArg_ParseTuple(args, "iO", &index, &laborList))
return NULL;
if(!PyList_Check(laborList))
{
PyErr_SetString(PyExc_TypeError, "argument 2 must be a list");
return NULL;
}
if(PyList_Size(laborList) < NUM_CREATURE_LABORS)
{
char errBuff[50];
sprintf(errBuff, "list must contain at least %u entries", NUM_CREATURE_LABORS);
PyErr_SetString(PyExc_StandardError, errBuff);
return NULL;
}
for(int i = 0; i < NUM_CREATURE_LABORS; i++)
laborArray[i] = (uint8_t)PyInt_AsLong(PyList_GET_ITEM(laborList, i));
if(self->creature_Ptr->WriteLabors(index, laborArray))
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyMethodDef DF_CreatureManager_methods[] =
{
{"Start", (PyCFunction)DF_CreatureManager_Start, METH_NOARGS, ""},
{"Finish", (PyCFunction)DF_CreatureManager_Finish, METH_NOARGS, ""},
{"Read_Creature", (PyCFunction)DF_CreatureManager_ReadCreature, METH_VARARGS, ""},
{"Read_Creature_In_Box", (PyCFunction)DF_CreatureManager_ReadCreatureInBox, METH_VARARGS, ""},
{"Write_Labors", (PyCFunction)DF_CreatureManager_WriteLabors, METH_VARARGS, ""},
{"Get_Dwarf_Race_Index", (PyCFunction)DF_CreatureManager_GetDwarfRaceIndex, METH_NOARGS, ""},
{"Get_Dwarf_Civ_id", (PyCFunction)DF_CreatureManager_GetDwarfCivId, METH_NOARGS, ""},
{NULL} // Sentinel
};
static PyTypeObject DF_CreatureManager_type =
{
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pydfhack.CreatureManager", /*tp_name*/
sizeof(DF_CreatureManager), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)DF_CreatureManager_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"pydfhack CreatureManager objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DF_CreatureManager_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DF_CreatureManager_init, /* tp_init */
0, /* tp_alloc */
DF_CreatureManager_new, /* tp_new */
};
#endif

@ -1,258 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFCREATURETYPE__
#define __DFCREATURETYPE__
#include "Python.h"
#include "structmember.h"
//#include "DF_Imports.cpp"
#include "DF_Helpers.cpp"
#include "modules/Creatures.h"
using namespace DFHack;
struct DF_Creature_Base
{
PyObject_HEAD
// simple type stuff
uint32_t origin;
uint32_t race;
uint8_t profession;
uint16_t mood;
uint32_t happiness;
uint32_t c_id;
int32_t squad_leader_id;
uint8_t sex;
uint32_t pregnancy_timer;
uint32_t flags1, flags2;
PyObject* custom_profession;
// composites
PyObject* position;
PyObject *name, *artifact_name;
PyObject* current_job;
PyObject *strength, *agility, *toughness, *endurance, *recuperation, *disease_resistance;
PyObject* defaultSoul;
// lists
PyObject* labor_list;
};
// API type Allocation, Deallocation, and Initialization
static PyObject* DF_Creature_Base_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DF_Creature_Base* self;
self = (DF_Creature_Base*)type->tp_alloc(type, 0);
if(self != NULL)
{
self->origin = 0;
self->profession = 0;
self->mood = 0;
self->happiness = 0;
self->c_id = 0;
self->squad_leader_id = 0;
self->sex = 0;
self->pregnancy_timer = 0;
self->flags1 = 0;
self->flags2 = 0;
self->custom_profession = PyString_FromString("");
self->name = PyString_FromString("");
self->artifact_name = PyString_FromString("");
self->position = NULL;
self->strength = NULL;
self->agility = NULL;
self->toughness = NULL;
self->endurance = NULL;
self->recuperation = NULL;
self->disease_resistance = NULL;
self->defaultSoul = NULL;
self->labor_list = NULL;
}
return (PyObject*)self;
}
static int DF_Creature_Base_init(DF_Creature_Base* self, PyObject* args, PyObject* kwd)
{
return 0;
}
static void DF_Creature_Base_dealloc(DF_Creature_Base* self)
{
if(self != NULL)
{
Py_XDECREF(self->position);
Py_XDECREF(self->custom_profession);
Py_XDECREF(self->name);
Py_XDECREF(self->artifact_name);
Py_XDECREF(self->current_job);
Py_XDECREF(self->strength);
Py_XDECREF(self->agility);
Py_XDECREF(self->toughness);
Py_XDECREF(self->endurance);
Py_XDECREF(self->recuperation);
Py_XDECREF(self->disease_resistance);
Py_XDECREF(self->defaultSoul);
Py_XDECREF(self->labor_list);
self->ob_type->tp_free((PyObject*)self);
}
}
#pragma GCC diagnostic ignored "-Wwrite-strings"
static PyMemberDef DF_Creature_Base_members[] =
{
{"origin", T_UINT, offsetof(DF_Creature_Base, origin), 0, ""},
{"position", T_OBJECT_EX, offsetof(DF_Creature_Base, position), 0, ""},
{"_flags1", T_UINT, offsetof(DF_Creature_Base, flags1), 0, ""},
{"_flags2", T_UINT, offsetof(DF_Creature_Base, flags2), 0, ""},
{"race", T_UINT, offsetof(DF_Creature_Base, race), 0, ""},
{"name", T_OBJECT_EX, offsetof(DF_Creature_Base, name), 0, ""},
{"artifact_name", T_OBJECT_EX, offsetof(DF_Creature_Base, artifact_name), 0, ""},
{"profession", T_INT, offsetof(DF_Creature_Base, profession), 0, ""},
{"custom_profession", T_OBJECT_EX, offsetof(DF_Creature_Base, custom_profession), 0, ""},
{"happiness", T_SHORT, offsetof(DF_Creature_Base, happiness), 0, ""},
{"mood", T_SHORT, offsetof(DF_Creature_Base, mood), 0, ""},
{"squad_leader_id", T_INT, offsetof(DF_Creature_Base, squad_leader_id), 0, ""},
{"sex", T_UBYTE, offsetof(DF_Creature_Base, sex), 0, ""},
{"pregnancy_timer", T_UINT, offsetof(DF_Creature_Base, pregnancy_timer), 0, ""},
{NULL} //Sentinel
};
static PyGetSetDef DF_Creature_Base_getterSetters[] =
{
{NULL} //Sentinel
};
static PyMethodDef DF_Creature_Base_methods[] =
{
{NULL} //Sentinel
};
static PyTypeObject DF_Creature_Base_type =
{
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pydfhack.Creature_Base", /*tp_name*/
sizeof(DF_Creature_Base), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)DF_Creature_Base_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"pydfhack CreatureBase objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DF_Creature_Base_methods, /* tp_methods */
DF_Creature_Base_members, /* tp_members */
DF_Creature_Base_getterSetters, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DF_Creature_Base_init, /* tp_init */
0, /* tp_alloc */
DF_Creature_Base_new, /* tp_new */
};
static PyObject* BuildCreature(DFHack::t_creature& creature)
{
DF_Creature_Base* obj;
obj = (DF_Creature_Base*)PyObject_Call((PyObject*)&DF_Creature_Base_type, NULL, NULL);
if(obj != NULL)
{
obj->origin = creature.origin;
obj->position = Py_BuildValue("III", creature.x, creature.y, creature.z);
obj->profession = creature.profession;
obj->mood = creature.mood;
obj->happiness = creature.happiness;
obj->c_id = creature.id;
obj->race = creature.race;
obj->agility = BuildAttribute(creature.agility);
obj->strength = BuildAttribute(creature.strength);
obj->toughness = BuildAttribute(creature.toughness);
obj->endurance = BuildAttribute(creature.endurance);
obj->recuperation = BuildAttribute(creature.recuperation);
obj->disease_resistance = BuildAttribute(creature.disease_resistance);
obj->squad_leader_id = creature.squad_leader_id;
obj->sex = creature.sex;
obj->pregnancy_timer = creature.pregnancy_timer;
if(creature.custom_profession[0])
obj->custom_profession = PyString_FromString(creature.custom_profession);
obj->flags1 = creature.flags1.whole;
obj->flags2 = creature.flags2.whole;
obj->current_job = BuildJob(creature.current_job);
obj->name = BuildName(creature.name);
obj->artifact_name = BuildName(creature.artifact_name);
obj->labor_list = PyList_New(NUM_CREATURE_LABORS);
for(int i = 0; i < NUM_CREATURE_LABORS; i++)
PyList_SET_ITEM(obj->labor_list, i, PyInt_FromLong(creature.labors[i]));
return (PyObject*)obj;
}
Py_RETURN_NONE;
}
#endif

@ -1,209 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFGUI__
#define __DFGUI__
#include "Tranquility.h"
#pragma GCC diagnostic ignored "-Wwrite-strings"
#include "Python.h"
#include "integers.h"
#include "DFTypes.h"
#include "modules/Gui.h"
using namespace DFHack;
struct DF_GUI
{
PyObject_HEAD
DFHack::Gui* g_Ptr;
};
static PyObject* DF_GUI_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DF_GUI* self;
self = (DF_GUI*)type->tp_alloc(type, 0);
if(self != NULL)
self->g_Ptr = NULL;
return (PyObject*)self;
}
static int DF_GUI_init(DF_GUI* self, PyObject* args, PyObject* kwds)
{
return 0;
}
static void DF_GUI_dealloc(DF_GUI* self)
{
PySys_WriteStdout("gui dealloc\n");
if(self != NULL)
{
PySys_WriteStdout("gui not NULL\n");
if(self->g_Ptr != NULL)
{
PySys_WriteStdout("g_Ptr = 0x%x\n", self->g_Ptr);
delete self->g_Ptr;
PySys_WriteStdout("g_Ptr deleted\n");
self->g_Ptr = NULL;
}
self->ob_type->tp_free((PyObject*)self);
}
PySys_WriteStdout("gui dealloc done\n");
}
// Type methods
static PyObject* DF_GUI_Start(DF_GUI* self, PyObject* args)
{
if(self->g_Ptr != NULL)
{
if(self->g_Ptr->Start())
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_GUI_Finish(DF_GUI* self, PyObject* args)
{
if(self->g_Ptr != NULL)
{
if(self->g_Ptr->Finish())
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_GUI_ReadViewScreen(DF_GUI* self, PyObject* args)
{
DFHack::t_viewscreen viewscreen;
if(self->g_Ptr != NULL)
{
if(self->g_Ptr->ReadViewScreen(viewscreen))
return PyInt_FromLong(viewscreen.type);
}
Py_RETURN_NONE;
}
static PyMethodDef DF_GUI_methods[] =
{
{"Start", (PyCFunction)DF_GUI_Start, METH_NOARGS, ""},
{"Finish", (PyCFunction)DF_GUI_Finish, METH_NOARGS, ""},
{"Read_View_Screen", (PyCFunction)DF_GUI_ReadViewScreen, METH_NOARGS, ""},
{NULL} //Sentinel
};
// Getter/Setter
static PyObject* DF_GUI_getPauseState(DF_GUI* self, void* closure)
{
if(self->g_Ptr != NULL)
{
if(self->g_Ptr->ReadPauseState())
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_GUI_getMenuState(DF_GUI* self, void* closure)
{
if(self->g_Ptr != NULL)
{
return PyInt_FromLong(self->g_Ptr->ReadMenuState());
}
Py_RETURN_NONE;
}
static PyGetSetDef DF_GUI_getterSetters[] =
{
{"paused", (getter)DF_GUI_getPauseState, NULL, "paused", NULL},
{"menu_state", (getter)DF_GUI_getMenuState, NULL, "menu_state", NULL},
{NULL} // Sentinel
};
static PyTypeObject DF_GUI_type =
{
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pydfhack._GUIManager", /*tp_name*/
sizeof(DF_GUI), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)DF_GUI_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"pydfhack GUIManager object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DF_GUI_methods, /* tp_methods */
0, /* tp_members */
DF_GUI_getterSetters, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DF_GUI_init, /* tp_init */
0, /* tp_alloc */
DF_GUI_new, /* tp_new */
};
#endif

@ -1,369 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFHELPERS__
#define __DFHELPERS__
#include "Python.h"
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
using namespace std;
#include "DFTypes.h"
#include "DF_Imports.cpp"
using namespace DFHack;
#include "modules/Materials.h"
#include "modules/Creatures.h"
#define DICTADD(d, name, item) PyDict_SetItemString(d, name, item); Py_DECREF(item)
#define OBJSET(o, name, item) PyObject_SetAttrString(o, name, item); Py_DECREF(item)
static PyObject* BuildTileColor(uint16_t fore, uint16_t back, uint16_t bright)
{
PyObject *tObj, *args;
args = Py_BuildValue("iii", fore, back, bright);
tObj = PyObject_CallObject(TileColor_type, args);
Py_DECREF(args);
return tObj;
}
static PyObject* BuildPosition2D(uint16_t x, uint16_t y)
{
PyObject *posObj, *args;
args = Py_BuildValue("ii", x, y);
posObj = PyObject_CallObject(Position2D_type, args);
Py_DECREF(args);
return posObj;
}
static PyObject* BuildPosition3D(uint16_t x, uint16_t y, uint16_t z)
{
PyObject *posObj, *args;
args = Py_BuildValue("iii", x, y, z);
posObj = PyObject_CallObject(Position3D_type, args);
Py_DECREF(args);
return posObj;
}
static PyObject* BuildMatglossPair(DFHack::t_matglossPair& matgloss)
{
return Py_BuildValue("ii", matgloss.type, matgloss.index);
}
static DFHack::t_matglossPair ReverseBuildMatglossPair(PyObject* mObj)
{
DFHack::t_matglossPair mPair;
PyObject* temp;
temp = PyTuple_GetItem(mObj, 0);
mPair.type = (int16_t)PyInt_AsLong(temp);
Py_DECREF(temp);
temp = PyTuple_GetItem(mObj, 1);
mPair.index = (int32_t)PyInt_AsLong(temp);
Py_DECREF(temp);
return mPair;
}
static PyObject* BuildSkill(DFHack::t_skill& skill)
{
PyObject *args, *skillObj;
args = Py_BuildValue("III", skill.id, skill.experience, skill.rating);
skillObj = PyObject_CallObject(Skill_type, args);
Py_DECREF(args);
return skillObj;
}
static PyObject* BuildSkillList(DFHack::t_skill (&skills)[256], uint8_t numSkills)
{
PyObject* list = PyList_New(numSkills);
for(int i = 0; i < numSkills; i++)
PyList_SET_ITEM(list, i, BuildSkill(skills[i]));
return list;
}
static PyObject* BuildJob(DFHack::t_job& job)
{
return Py_BuildValue("Oi", PyBool_FromLong((int)job.active), job.jobId);
}
static PyObject* BuildAttribute(DFHack::t_attrib& at)
{
PyObject *args, *attrObj;
args = Py_BuildValue("IIIIIII", at.level, at.field_4, at.field_8, at.field_C, at.leveldiff, at.field_14, at.field_18);
attrObj = PyObject_CallObject(Attribute_type, args);
Py_DECREF(args);
return attrObj;
}
/*
static PyObject* BuildItemType(DFHack::t_itemType& item)
{
return Py_BuildValue("ss", item.id, item.name);
}
*/
static PyObject* BuildLike(DFHack::t_like& like)
{
PyObject* item;
item = Py_BuildValue("iii", like.type, like.itemClass, like.itemIndex);
return Py_BuildValue("OOO", item, BuildMatglossPair(like.material), PyBool_FromLong((int)like.active));
}
static PyObject* BuildNote(DFHack::t_note& note)
{
PyObject* noteObj;
PyObject *args, *position;
args = Py_BuildValue("III", note.x, note.y, note.z);
position = PyObject_CallObject(Position3D_type, args);
Py_DECREF(args);
args = Py_BuildValue("cIIsO", note.symbol, note.foreground, note.background, note.name, position);
noteObj = PyObject_CallObject(Note_type, args);
Py_DECREF(args);
return noteObj;
}
static int NAME_WORD_COUNT = 7;
static PyObject* BuildName(DFHack::t_name& name)
{
PyObject* nameObj;
PyObject *wordList, *speechList, *args;
wordList = PyList_New(NAME_WORD_COUNT);
speechList = PyList_New(NAME_WORD_COUNT);
for(int i = 0; i < NAME_WORD_COUNT; i++)
{
PyList_SET_ITEM(wordList, i, PyInt_FromLong(name.words[i]));
PyList_SET_ITEM(speechList, i, PyInt_FromLong(name.parts_of_speech[i]));
}
args = Py_BuildValue("ssiOOO", name.first_name, name.nickname, name.language, \
PyBool_FromLong((int)name.has_name), wordList, speechList);
nameObj = PyObject_CallObject(Name_type, args);
Py_DECREF(args);
return nameObj;
}
static DFHack::t_name ReverseBuildName(PyObject* nameObj)
{
PyObject *temp, *listTemp;
int boolTemp;
Py_ssize_t strLength;
char* strTemp;
DFHack::t_name name;
temp = PyObject_GetAttrString(nameObj, "language");
name.language = (uint32_t)PyInt_AsLong(temp);
temp = PyObject_GetAttrString(nameObj, "has_name");
boolTemp = (int)PyInt_AsLong(temp);
Py_DECREF(temp);
if(boolTemp != 0)
name.has_name = true;
else
name.has_name = false;
listTemp = PyObject_GetAttrString(nameObj, "words");
for(int i = 0; i < NAME_WORD_COUNT; i++)
name.words[i] = (uint32_t)PyInt_AsLong(PyList_GetItem(listTemp, i));
Py_DECREF(listTemp);
listTemp = PyObject_GetAttrString(nameObj, "parts_of_speech");
for(int i = 0; i < NAME_WORD_COUNT; i++)
name.parts_of_speech[i] = (uint16_t)PyInt_AsLong(PyList_GetItem(listTemp, i));
Py_DECREF(listTemp);
temp = PyObject_GetAttrString(nameObj, "first_name");
strLength = PyString_Size(temp);
strTemp = PyString_AsString(temp);
Py_DECREF(temp);
if(strLength > 128)
{
strncpy(name.first_name, strTemp, 127);
name.first_name[127] = '\0';
}
else
{
strncpy(name.first_name, strTemp, strLength);
name.first_name[strLength] = '\0';
}
temp = PyObject_GetAttrString(nameObj, "nickname");
strLength = PyString_Size(temp);
strTemp = PyString_AsString(temp);
Py_DECREF(temp);
if(strLength > 128)
{
strncpy(name.nickname, strTemp, 127);
name.nickname[127] = '\0';
}
else
{
strncpy(name.nickname, strTemp, strLength);
name.nickname[strLength] = '\0';
}
return name;
}
static PyObject* BuildSettlement(DFHack::t_settlement& settlement)
{
PyObject* setObj;
PyObject *world_pos, *local_pos, *args;
args = Py_BuildValue("ii", settlement.world_x, settlement.world_y);
world_pos = PyObject_CallObject(Position2D_type, args);
Py_DECREF(args);
args = Py_BuildValue("iiii", settlement.local_x1, settlement.local_y1, settlement.local_x2, settlement.local_y2);
local_pos = PyObject_CallObject(Rectangle_type, args);
Py_DECREF(args);
args = Py_BuildValue("iOOO", settlement.origin, BuildName(settlement.name), world_pos, local_pos);
setObj = PyObject_CallObject(Settlement_type, args);
Py_DECREF(args);
return setObj;
}
static PyObject* BuildSoul(DFHack::t_soul& soul)
{
PyObject *soulDict, *skillList, *temp, *emptyArgs;
PyObject* soulObj;
emptyArgs = Py_BuildValue("()");
soulDict = PyDict_New();
skillList = BuildSkillList(soul.skills, soul.numSkills);
DICTADD(soulDict, "skills", skillList);
temp = BuildAttribute(soul.analytical_ability);
DICTADD(soulDict, "analytical_ability", temp);
temp = BuildAttribute(soul.focus);
DICTADD(soulDict, "focus", temp);
temp = BuildAttribute(soul.willpower);
DICTADD(soulDict, "willpower", temp);
temp = BuildAttribute(soul.creativity);
DICTADD(soulDict, "creativity", temp);
temp = BuildAttribute(soul.intuition);
DICTADD(soulDict, "intuition", temp);
temp = BuildAttribute(soul.patience);
DICTADD(soulDict, "patience", temp);
temp = BuildAttribute(soul.memory);
DICTADD(soulDict, "memory", temp);
temp = BuildAttribute(soul.linguistic_ability);
DICTADD(soulDict, "linguistic_ability", temp);
temp = BuildAttribute(soul.spatial_sense);
DICTADD(soulDict, "spatial_sense", temp);
temp = BuildAttribute(soul.musicality);
DICTADD(soulDict, "musicality", temp);
temp = BuildAttribute(soul.kinesthetic_sense);
DICTADD(soulDict, "kinesthetic_sense", temp);
temp = BuildAttribute(soul.empathy);
DICTADD(soulDict, "empathy", temp);
temp = BuildAttribute(soul.social_awareness);
DICTADD(soulDict, "social_awareness", temp);
soulObj = PyObject_Call(Soul_type, emptyArgs, soulDict);
Py_DECREF(emptyArgs);
return soulObj;
}
#endif

@ -1,110 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFIMPORTS__
#define __DFIMPORTS__
#include "Python.h"
static PyObject* FlagsModule = NULL;
static PyObject* CreatureFlags1_type = NULL;
static PyObject* CreatureFlags2_type = NULL;
static PyObject* DesignationFlags_type = NULL;
static PyObject* OccupancyFlags_type = NULL;
static PyObject* ItemFlags_type = NULL;
static PyObject* BlockFlags_type = NULL;
static PyObject* TypesModule = NULL;
static PyObject* Note_type = NULL;
static PyObject* Construction_type = NULL;
static PyObject* Name_type = NULL;
static PyObject* MapBlock40d_type = NULL;
static PyObject* Vein_type = NULL;
static PyObject* FrozenLiquidVein_type = NULL;
static PyObject* SpatterVein_type = NULL;
static PyObject* Position2D_type = NULL;
static PyObject* Position3D_type = NULL;
static PyObject* Rectangle_type = NULL;
static PyObject* Settlement_type = NULL;
static PyObject* Attribute_type = NULL;
static PyObject* Skill_type = NULL;
static PyObject* Soul_type = NULL;
static PyObject* Tree_type = NULL;
static PyObject* CreatureCaste_type = NULL;
static PyObject* Matgloss_type = NULL;
static PyObject* DescriptorColor_type = NULL;
static PyObject* CreatureTypeEx_type = NULL;
static PyObject* TileColor_type = NULL;
static void DoImports()
{
if(FlagsModule == NULL)
{
FlagsModule = PyImport_ImportModule("pydfhack.pydfhackflags");
if (PyErr_Occurred())
{
PyErr_Print();
return ;
}
CreatureFlags1_type = PyObject_GetAttrString(FlagsModule, "CreatureFlags1");
CreatureFlags2_type = PyObject_GetAttrString(FlagsModule, "CreatureFlags2");
DesignationFlags_type = PyObject_GetAttrString(FlagsModule, "DesignationFlags");
OccupancyFlags_type = PyObject_GetAttrString(FlagsModule, "OccupancyFlags");
ItemFlags_type = PyObject_GetAttrString(FlagsModule, "ItemFlags");
BlockFlags_type = PyObject_GetAttrString(FlagsModule, "BlockFlags");
}
if(TypesModule == NULL)
{
TypesModule = PyImport_ImportModule("pydfhack.pydftypes");
if (PyErr_Occurred())
{
PyErr_Print();
return ;
}
Note_type = PyObject_GetAttrString(TypesModule, "Note");
Construction_type = PyObject_GetAttrString(TypesModule, "Construction");
Name_type = PyObject_GetAttrString(TypesModule, "Name");
MapBlock40d_type = PyObject_GetAttrString(TypesModule, "MapBlock40d");
Vein_type = PyObject_GetAttrString(TypesModule, "Vein");
FrozenLiquidVein_type = PyObject_GetAttrString(TypesModule, "FrozenLiquidVein");
SpatterVein_type = PyObject_GetAttrString(TypesModule, "SpatterVein");
Position2D_type = PyObject_GetAttrString(TypesModule, "Position2D");
Position3D_type = PyObject_GetAttrString(TypesModule, "Position3D");
Rectangle_type = PyObject_GetAttrString(TypesModule, "Rectangle");
Settlement_type = PyObject_GetAttrString(TypesModule, "Settlement");
Attribute_type = PyObject_GetAttrString(TypesModule, "Attribute");
Skill_type = PyObject_GetAttrString(TypesModule, "Skill");
Soul_type = PyObject_GetAttrString(TypesModule, "Soul");
Tree_type = PyObject_GetAttrString(TypesModule, "Tree");
CreatureCaste_type = PyObject_GetAttrString(TypesModule, "CreatureCaste");
Matgloss_type = PyObject_GetAttrString(TypesModule, "Matgloss");
DescriptorColor_type = PyObject_GetAttrString(TypesModule, "DescriptorColor");
CreatureTypeEx_type = PyObject_GetAttrString(TypesModule, "CreatureTypeEx");
TileColor_type = PyObject_GetAttrString(TypesModule, "TileColor");
}
}
#endif

@ -1,864 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFMAPS__
#define __DFMAPS__
#include "Tranquility.h"
#pragma GCC diagnostic ignored "-Wwrite-strings"
#include "Python.h"
#include <vector>
#include <string>
#include "integers.h"
using namespace std;
#include "DFTypes.h"
#include <map>
#include "modules/Maps.h"
#include "DF_Imports.cpp"
#include "DF_Helpers.cpp"
using namespace DFHack;
static PyObject* BuildVein(DFHack::t_vein& v)
{
PyObject* vObj;
PyObject* temp;
vObj = PyObject_Call(Vein_type, NULL, NULL);
temp = PyInt_FromLong(v.vtable);
OBJSET(vObj, "vtable", temp);
temp = PyInt_FromLong(v.type);
OBJSET(vObj, "type", temp);
temp = PyInt_FromLong(v.flags);
OBJSET(vObj, "flags", temp);
temp = PyInt_FromLong(v.address_of);
OBJSET(vObj, "address", temp);
temp = PyList_New(16);
for(int i = 0; i < 16; i++)
PyList_SET_ITEM(temp, i, PyInt_FromLong(v.assignment[i]));
OBJSET(vObj, "assignment", temp);
return vObj;
}
static PyObject* BuildFrozenLiquidVein(DFHack::t_frozenliquidvein& v)
{
PyObject* vObj;
PyObject *temp, *list;
vObj = PyObject_Call(FrozenLiquidVein_type, NULL, NULL);
temp = PyInt_FromLong(v.vtable);
OBJSET(vObj, "vtable", temp);
temp = PyInt_FromLong(v.address_of);
OBJSET(vObj, "address", temp);
list = PyList_New(16);
for(int i = 0; i < 16; i++)
{
temp = PyList_New(16);
for(int j = 0; j < 16; j++)
PyList_SET_ITEM(temp, j, PyInt_FromLong(v.tiles[i][j]));
PyList_SET_ITEM(list, i, temp);
}
OBJSET(vObj, "tiles", list);
return vObj;
}
static PyObject* BuildSpatterVein(DFHack::t_spattervein& v)
{
PyObject* vObj;
PyObject *temp, *list;
vObj = PyObject_Call(SpatterVein_type, NULL, NULL);
temp = PyInt_FromLong(v.vtable);
OBJSET(vObj, "vtable", temp);
temp = PyInt_FromLong(v.address_of);
OBJSET(vObj, "address", temp);
temp = PyInt_FromLong(v.mat1);
OBJSET(vObj, "mat1", temp);
temp = PyInt_FromLong(v.unk1);
OBJSET(vObj, "unk1", temp);
temp = PyInt_FromLong(v.mat2);
OBJSET(vObj, "mat2", temp);
temp = PyInt_FromLong(v.mat3);
OBJSET(vObj, "mat3", temp);
list = PyList_New(16);
for(int i = 0; i < 16; i++)
{
temp = PyList_New(16);
for(int j = 0; j < 16; j++)
PyList_SET_ITEM(temp, j, PyInt_FromLong(v.intensity[i][j]));
PyList_SET_ITEM(list, i, temp);
}
OBJSET(vObj, "intensity", list);
return vObj;
}
static PyObject* BuildVeinDict(std::vector<t_vein>& veins, std::vector<t_frozenliquidvein>& ices, std::vector<t_spattervein>& splatter)
{
PyObject* vDict;
PyObject* vList;
int veinSize;
vDict = PyDict_New();
veinSize = veins.size();
if(veinSize <= 0)
{
Py_INCREF(Py_None);
DICTADD(vDict, "veins", Py_None);
}
else
{
vList = PyList_New(veinSize);
for(int i = 0; i < veinSize; i++)
PyList_SET_ITEM(vList, i, BuildVein(veins[i]));
DICTADD(vDict, "veins", vList);
}
veinSize = ices.size();
if(veinSize <= 0)
{
Py_INCREF(Py_None);
DICTADD(vDict, "ices", Py_None);
}
else
{
vList = PyList_New(veinSize);
for(int i = 0; i < veinSize; i++)
PyList_SET_ITEM(vList, i, BuildFrozenLiquidVein(ices[i]));
DICTADD(vDict, "ices", vList);
}
veinSize = splatter.size();
if(veinSize <= 0)
{
Py_INCREF(Py_None);
DICTADD(vDict, "spatter", Py_None);
}
else
{
vList = PyList_New(veinSize);
for(int i = 0; i < veinSize; i++)
PyList_SET_ITEM(vList, i, BuildSpatterVein(splatter[i]));
DICTADD(vDict, "spatter", vList);
}
return vDict;
}
static PyObject* BuildTileTypes40d(DFHack::tiletypes40d& types)
{
PyObject *list, *temp;
list = PyList_New(16);
for(int i = 0; i < 16; i++)
{
temp = PyList_New(16);
for(int j = 0; j < 16; j++)
PyList_SET_ITEM(temp, j, PyInt_FromLong(types[i][j]));
PyList_SET_ITEM(list, i, temp);
}
return list;
}
static void ReverseBuildTileTypes40d(PyObject* list, DFHack::tiletypes40d t_types)
{
PyObject* innerList;
for(int i = 0; i < 16; i++)
{
innerList = PyList_GetItem(list, i);
for(int j = 0; j < 16; j++)
t_types[i][j] = (uint16_t)PyInt_AsLong(PyList_GetItem(innerList, j));
}
}
static PyObject* BuildOccupancies40d(DFHack::occupancies40d& occ)
{
PyObject *list, *temp, *args;
list = PyList_New(16);
for(int i = 0; i < 16; i++)
{
temp = PyList_New(16);
for(int j = 0; j < 16; j++)
{
args = Py_BuildValue("(I)", occ[i][j].whole);
PyList_SET_ITEM(temp, j, PyObject_Call(OccupancyFlags_type, args, NULL));
Py_DECREF(args);
}
PyList_SET_ITEM(list, i, temp);
}
return list;
}
static void ReverseBuildOccupancies40d(PyObject* list, DFHack::occupancies40d occ)
{
PyObject* innerList;
for(int i = 0; i < 16; i++)
{
innerList = PyList_GetItem(list, i);
for(int j = 0; j < 16; j++)
occ[i][j].whole = (uint32_t)PyInt_AsLong(PyList_GetItem(innerList, j));
}
}
static PyObject* BuildDesignations40d(DFHack::designations40d& des)
{
PyObject *list, *temp, *args;
list = PyList_New(16);
for(int i = 0; i < 16; i++)
{
temp = PyList_New(16);
for(int j = 0; j < 16; j++)
{
args = Py_BuildValue("(I)", des[i][j].whole);
PyList_SET_ITEM(temp, j, PyObject_Call(DesignationFlags_type, args, NULL));
Py_DECREF(args);
}
PyList_SET_ITEM(list, i, temp);
}
return list;
}
static void ReverseBuildDesignations40d(PyObject* list, DFHack::designations40d& des)
{
PyObject* innerList;
for(int i = 0; i < 16; i++)
{
innerList = PyList_GET_ITEM(list, i);
for(int j = 0; j < 16; j++)
des[i][j].whole = (uint32_t)PyInt_AS_LONG(PyList_GET_ITEM(innerList, j));
}
}
static PyObject* BuildBiomeIndices40d(DFHack::biome_indices40d& idx)
{
PyObject *list;
list = PyList_New(16);
for(int i = 0; i < 16; i++)
PyList_SET_ITEM(list, i, PyInt_FromLong(idx[i]));
return list;
}
static void ReverseBuildBiomeIndices40d(PyObject* list, DFHack::biome_indices40d bio)
{
for(int i = 0; i < 16; i++)
bio[i] = (uint8_t)PyInt_AsLong(PyList_GetItem(list, i));
}
static PyObject* BuildMapBlock40d(DFHack::mapblock40d& block)
{
PyObject *b_Obj;
PyObject *temp, *args;
b_Obj = PyObject_Call(MapBlock40d_type, NULL, NULL);
temp = BuildTileTypes40d(block.tiletypes);
OBJSET(b_Obj, "tiletypes", temp);
temp = BuildDesignations40d(block.designation);
OBJSET(b_Obj, "designation", temp);
temp = BuildOccupancies40d(block.occupancy);
OBJSET(b_Obj, "occupancy", temp);
temp = BuildBiomeIndices40d(block.biome_indices);
OBJSET(b_Obj, "biome_indices", temp);
temp = PyInt_FromLong(block.origin);
OBJSET(b_Obj, "origin", temp);
args = Py_BuildValue("(I)", block.blockflags.whole);
temp = PyObject_CallObject(BlockFlags_type, args);
temp = PyInt_FromLong(block.blockflags.whole);
OBJSET(b_Obj, "blockflags", temp);
return b_Obj;
}
struct DF_Map
{
PyObject_HEAD
DFHack::Maps* m_Ptr;
};
static PyObject* DF_Map_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DF_Map* self;
self = (DF_Map*)type->tp_alloc(type, 0);
if(self != NULL)
self->m_Ptr = NULL;
return (PyObject*)self;
}
static int DF_Map_init(DF_Map* self, PyObject* args, PyObject* kwds)
{
return 0;
}
static void DF_Map_dealloc(DF_Map* self)
{
PySys_WriteStdout("map dealloc\n");
if(self != NULL)
{
PySys_WriteStdout("map not NULL\n");
if(self->m_Ptr != NULL)
{
PySys_WriteStdout("m_Ptr = 0x%x\n", self->m_Ptr);
delete self->m_Ptr;
PySys_WriteStdout("m_Ptr deleted\n");
self->m_Ptr = NULL;
}
self->ob_type->tp_free((PyObject*)self);
}
PySys_WriteStdout("map dealloc done\n");
}
// Type methods
static PyObject* DF_Map_Start(DF_Map* self, PyObject* args)
{
if(self->m_Ptr != NULL)
{
if(self->m_Ptr->Start())
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_Finish(DF_Map* self, PyObject* args)
{
if(self->m_Ptr != NULL)
{
if(self->m_Ptr->Finish())
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_ReadGeology(DF_Map* self, PyObject* args)
{
PyObject *list, *temp;
int outerSize, innerSize;
if(self->m_Ptr != NULL)
{
std::vector< std::vector<uint16_t> > geoVec;
if(self->m_Ptr->ReadGeology(geoVec))
{
outerSize = geoVec.size();
list = PyList_New(outerSize);
for(int i = 0; i < outerSize; i++)
{
std::vector<uint16_t> innerVec = geoVec[i];
innerSize = innerVec.size();
temp = PyList_New(innerSize);
for(int j = 0; j < innerSize; j++)
PyList_SET_ITEM(temp, j, PyInt_FromLong(innerVec[i]));
PyList_SET_ITEM(list, i, temp);
}
return list;
}
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_IsValidBlock(DF_Map* self, PyObject* args)
{
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "III", &x, &y, &z))
return NULL;
if(self->m_Ptr->isValidBlock(x, y, z))
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_GetBlockPtr(DF_Map* self, PyObject* args)
{
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "III", &x, &y, &z))
return NULL;
return PyInt_FromLong(self->m_Ptr->getBlockPtr(x, y, z));
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_ReadBlock40d(DF_Map* self, PyObject* args)
{
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "III", &x, &y, &z))
return NULL;
mapblock40d mapblock;
if(self->m_Ptr->ReadBlock40d(x, y, z, &mapblock))
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_ReadTileTypes(DF_Map* self, PyObject* args)
{
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "III", &x, &y, &z))
return NULL;
tiletypes40d t_types;
if(self->m_Ptr->ReadTileTypes(x, y, z, &t_types))
return BuildTileTypes40d(t_types);
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_WriteTileTypes(DF_Map* self, PyObject* args)
{
PyObject* tileList;
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "IIIO", &x, &y, &z, &tileList))
return NULL;
tiletypes40d t_types;
ReverseBuildTileTypes40d(tileList, t_types);
if(self->m_Ptr->WriteTileTypes(x, y, z, &t_types))
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_ReadDesignations(DF_Map* self, PyObject* args)
{
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "III", &x, &y, &z))
return NULL;
DFHack::designations40d des;
if(self->m_Ptr->ReadDesignations(x, y, z, &des))
return BuildDesignations40d(des);
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_WriteDesignations(DF_Map* self, PyObject* args)
{
PyObject* desList;
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "IIIO", &x, &y, &z, &desList))
return NULL;
DFHack::designations40d writeDes;
ReverseBuildDesignations40d(desList, writeDes);
if(self->m_Ptr->WriteDesignations(x, y, z, &writeDes))
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_ReadOccupancy(DF_Map* self, PyObject* args)
{
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "III", &x, &y, &z))
return NULL;
occupancies40d occ;
if(self->m_Ptr->ReadOccupancy(x, y, z, &occ))
return BuildOccupancies40d(occ);
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_WriteOccupancy(DF_Map* self, PyObject* args)
{
PyObject* occList;
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "IIIO", &x, &y, &z, &occList))
return NULL;
occupancies40d occ;
ReverseBuildOccupancies40d(occList, occ);
if(self->m_Ptr->WriteOccupancy(x, y, z, &occ))
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_ReadDirtyBit(DF_Map* self, PyObject* args)
{
uint32_t x, y, z;
bool bit = false;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "III", &x, &y, &z))
return NULL;
self->m_Ptr->ReadDirtyBit(x, y, z, bit);
if(bit)
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_WriteDirtyBit(DF_Map* self, PyObject* args)
{
uint32_t x, y, z, b;
bool bit;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "IIIi", &x, &y, &z, &b))
return NULL;
if(b != 0)
bit = true;
else
bit = false;
if(self->m_Ptr->WriteDirtyBit(x, y, z, bit))
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_ReadBlockFlags(DF_Map* self, PyObject* args)
{
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "III", &x, &y, &z))
return NULL;
t_blockflags flags;
if(self->m_Ptr->ReadBlockFlags(x, y, z, flags))
return PyInt_FromLong(flags.whole);
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_WriteBlockFlags(DF_Map* self, PyObject* args)
{
uint32_t x, y, z, whole;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "IIII", &x, &y, &z, &whole))
return NULL;
t_blockflags blockFlags;
blockFlags.whole = whole;
if(self->m_Ptr->WriteBlockFlags(x, y, z, blockFlags))
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_ReadRegionOffsets(DF_Map* self, PyObject* args)
{
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "III", &x, &y, &z))
return NULL;
biome_indices40d biome;
if(self->m_Ptr->ReadRegionOffsets(x, y, z, &biome))
return BuildBiomeIndices40d(biome);
}
Py_RETURN_NONE;
}
static PyObject* DF_Map_ReadVeins(DF_Map* self, PyObject* args, PyObject* kwds)
{
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "III", &x, &y, &z))
return NULL;
std::vector<t_vein> veins;
std::vector<t_frozenliquidvein> ices;
std::vector<t_spattervein> splatter;
if(self->m_Ptr->ReadVeins(x, y, z, &veins, &ices, &splatter))
{
return BuildVeinDict(veins, ices, splatter);
}
}
Py_RETURN_NONE;
}
static PyMethodDef DF_Map_methods[] =
{
{"Start", (PyCFunction)DF_Map_Start, METH_NOARGS, ""},
{"Finish", (PyCFunction)DF_Map_Finish, METH_NOARGS, ""},
{"Read_Geology", (PyCFunction)DF_Map_ReadGeology, METH_NOARGS, ""},
{"Is_Valid_Block", (PyCFunction)DF_Map_IsValidBlock, METH_VARARGS, ""},
{"Read_Block_40d", (PyCFunction)DF_Map_ReadBlock40d, METH_VARARGS, ""},
{"Read_Tile_Types", (PyCFunction)DF_Map_ReadTileTypes, METH_VARARGS, ""},
{"Write_Tile_Types", (PyCFunction)DF_Map_WriteTileTypes, METH_VARARGS, ""},
{"Read_Designations", (PyCFunction)DF_Map_ReadDesignations, METH_VARARGS, ""},
{"Write_Designations", (PyCFunction)DF_Map_WriteDesignations, METH_VARARGS, ""},
{"Read_Occupancy", (PyCFunction)DF_Map_ReadOccupancy, METH_VARARGS, ""},
{"Write_Occupancy", (PyCFunction)DF_Map_WriteOccupancy, METH_VARARGS, ""},
{"Read_Dirty_Bit", (PyCFunction)DF_Map_ReadDirtyBit, METH_VARARGS, ""},
{"Write_Dirty_Bit", (PyCFunction)DF_Map_WriteDirtyBit, METH_VARARGS, ""},
{"Read_Block_Flags", (PyCFunction)DF_Map_ReadBlockFlags, METH_VARARGS, ""},
{"Write_Block_Flags", (PyCFunction)DF_Map_WriteBlockFlags, METH_VARARGS, ""},
{"Read_Region_Offsets", (PyCFunction)DF_Map_ReadRegionOffsets, METH_VARARGS, ""},
{NULL} //Sentinel
};
// Getter/Setter
static PyObject* DF_Map_getSize(DF_Map* self, void* closure)
{
uint32_t x, y, z;
if(self->m_Ptr != NULL)
{
self->m_Ptr->getSize(x, y, z);
return Py_BuildValue("III", x, y, z);
}
Py_RETURN_NONE;
}
static PyGetSetDef DF_Map_getterSetters[] =
{
{"size", (getter)DF_Map_getSize, NULL, "size", NULL},
{NULL} // Sentinel
};
static PyTypeObject DF_Map_type =
{
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pydfhack._MapManager", /*tp_name*/
sizeof(DF_Map), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)DF_Map_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"pydfhack MapManager object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DF_Map_methods, /* tp_methods */
0, /* tp_members */
DF_Map_getterSetters, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DF_Map_init, /* tp_init */
0, /* tp_alloc */
DF_Map_new, /* tp_new */
};
#endif

@ -1,413 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFMATERIAL__
#define __DFMATERIAL__
#include "Python.h"
#include <vector>
#include <string>
#include "DFIntegers.h"
using namespace std;
#include "DFTypes.h"
#include "modules/Materials.h"
#include "DF_Imports.cpp"
#include "DF_Helpers.cpp"
using namespace DFHack;
struct DF_Material
{
PyObject_HEAD
DFHack::Materials* mat_Ptr;
};
// Helpers
static PyObject* BuildMatgloss(t_matgloss& matgloss)
{
PyObject* matObj;
PyObject* args;
args = Py_BuildValue("siiis", matgloss.id, matgloss.fore, matgloss.back, matgloss.bright, matgloss.name);
matObj = PyObject_CallObject(Matgloss_type, args);
Py_DECREF(args);
return matObj;
}
static PyObject* BuildMatglossPlant(t_matglossPlant& matgloss)
{
PyObject* matDict;
matDict = PyDict_New();
if(matgloss.id[0])
PyDict_SetItemString(matDict, "id", PyString_FromString(matgloss.id));
else
PyDict_SetItemString(matDict, "id", PyString_FromString(""));
PyDict_SetItemString(matDict, "fore", PyInt_FromLong(matgloss.fore));
PyDict_SetItemString(matDict, "back", PyInt_FromLong(matgloss.back));
PyDict_SetItemString(matDict, "bright", PyInt_FromLong(matgloss.bright));
if(matgloss.name[0])
PyDict_SetItemString(matDict, "name", PyString_FromString(matgloss.name));
else
PyDict_SetItemString(matDict, "name", PyString_FromString(""));
if(matgloss.drink_name[0])
PyDict_SetItemString(matDict, "drink_name", PyString_FromString(matgloss.drink_name));
else
PyDict_SetItemString(matDict, "drink_name", PyString_FromString(""));
if(matgloss.food_name[0])
PyDict_SetItemString(matDict, "food_name", PyString_FromString(matgloss.food_name));
else
PyDict_SetItemString(matDict, "food_name", PyString_FromString(""));
if(matgloss.extract_name[0])
PyDict_SetItemString(matDict, "extract_name", PyString_FromString(matgloss.extract_name));
else
PyDict_SetItemString(matDict, "extract_name", PyString_FromString(""));
return matDict;
}
static PyObject* BuildMatglossList(std::vector<t_matgloss> & matVec)
{
PyObject* matList;
std::vector<t_matgloss>::iterator matIter;
matList = PyList_New(0);
for(matIter = matVec.begin(); matIter != matVec.end(); matIter++)
{
PyObject* matgloss = BuildMatgloss(*matIter);
PyList_Append(matList, matgloss);
Py_DECREF(matgloss);
}
return matList;
}
static PyObject* BuildDescriptorColor(t_descriptor_color& color)
{
PyObject* descObj;
PyObject* args;
args = Py_BuildValue("sfffs", color.id, color.r, color.v, color.b, color.name);
descObj = PyObject_CallObject(DescriptorColor_type, args);
Py_DECREF(args);
return descObj;
}
static PyObject* BuildDescriptorColorList(std::vector<t_descriptor_color>& colors)
{
PyObject* colorList;
std::vector<t_descriptor_color>::iterator colorIter;
colorList = PyList_New(0);
for(colorIter = colors.begin(); colorIter != colors.end(); colorIter++)
{
PyObject* color = BuildDescriptorColor(*colorIter);
PyList_Append(colorList, color);
Py_DECREF(colorList);
}
return colorList;
}
static PyObject* BuildCreatureCaste(t_creaturecaste& caste)
{
PyObject* casteObj;
PyObject* args;
args = Py_BuildValue("ssss", caste.rawname, caste.singular, caste.plural, caste.adjective);
casteObj = PyObject_CallObject(CreatureCaste_type, args);
Py_DECREF(args);
return casteObj;
}
static PyObject* BuildCreatureCasteList(std::vector<t_creaturecaste>& castes)
{
PyObject* casteList;
std::vector<t_creaturecaste>::iterator casteIter;
casteList = PyList_New(0);
for(casteIter = castes.begin(); casteIter != castes.end(); casteIter++)
{
PyObject* caste = BuildCreatureCaste(*casteIter);
PyList_Append(casteList, caste);
Py_DECREF(caste);
}
return casteList;
}
static PyObject* BuildCreatureTypeEx(t_creaturetype& creature)
{
PyObject* cObj;
PyObject* args;
args = Py_BuildValue("sOiO", creature.rawname, BuildCreatureCasteList(creature.castes), creature.tile_character, \
BuildTileColor(creature.tilecolor.fore, creature.tilecolor.back, creature.tilecolor.bright));
cObj = PyObject_CallObject(CreatureTypeEx_type, args);
Py_DECREF(args);
return cObj;
}
static PyObject* BuildCreatureTypeExList(std::vector<t_creaturetype>& creatures)
{
PyObject* creatureList;
std::vector<t_creaturetype>::iterator creatureIter;
creatureList = PyList_New(0);
for(creatureIter = creatures.begin(); creatureIter != creatures.end(); creatureIter++)
{
PyObject* creature = BuildCreatureTypeEx(*creatureIter);
PyList_Append(creatureList, creature);
Py_DECREF(creature);
}
return creatureList;
}
// API type Allocation, Deallocation, and Initialization
static PyObject* DF_Material_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DF_Material* self;
self = (DF_Material*)type->tp_alloc(type, 0);
if(self != NULL)
self->mat_Ptr = NULL;
return (PyObject*)self;
}
static int DF_Material_init(DF_Material* self, PyObject* args, PyObject* kwds)
{
return 0;
}
static void DF_Material_dealloc(DF_Material* self)
{
PySys_WriteStdout("material dealloc\n");
if(self != NULL)
{
PySys_WriteStdout("material not NULL\n");
if(self->mat_Ptr != NULL)
{
PySys_WriteStdout("mat_Ptr = 0x%x\n", self->mat_Ptr);
delete self->mat_Ptr;
PySys_WriteStdout("mat_Ptr deleted\n");
self->mat_Ptr = NULL;
}
self->ob_type->tp_free((PyObject*)self);
}
PySys_WriteStdout("material dealloc done\n");
}
// Type methods
static PyObject* DF_Material_ReadInorganicMaterials(DF_Material* self, PyObject* args)
{
if(self->mat_Ptr != NULL)
{
if(self->mat_Ptr->ReadInorganicMaterials())
{
return BuildMatglossList(self->mat_Ptr->inorganic);
}
}
Py_RETURN_NONE;
}
static PyObject* DF_Material_ReadOrganicMaterials(DF_Material* self, PyObject* args)
{
if(self->mat_Ptr != NULL)
{
if(self->mat_Ptr->ReadOrganicMaterials())
{
return BuildMatglossList(self->mat_Ptr->organic);
}
}
Py_RETURN_NONE;
}
static PyObject* DF_Material_ReadWoodMaterials(DF_Material* self, PyObject* args)
{
if(self->mat_Ptr != NULL)
{
if(self->mat_Ptr->ReadWoodMaterials())
{
return BuildMatglossList(self->mat_Ptr->tree);
}
}
Py_RETURN_NONE;
}
static PyObject* DF_Material_ReadPlantMaterials(DF_Material* self, PyObject* args)
{
if(self->mat_Ptr != NULL)
{
if(self->mat_Ptr->ReadPlantMaterials())
{
return BuildMatglossList(self->mat_Ptr->plant);
}
}
Py_RETURN_NONE;
}
static PyObject* DF_Material_ReadCreatureTypes(DF_Material* self, PyObject* args)
{
if(self->mat_Ptr != NULL)
{
if(self->mat_Ptr->ReadCreatureTypes())
{
return BuildMatglossList(self->mat_Ptr->race);
}
}
Py_RETURN_NONE;
}
static PyObject* DF_Material_ReadCreatureTypesEx(DF_Material* self, PyObject* args)
{
if(self->mat_Ptr != NULL)
{
if(self->mat_Ptr->ReadCreatureTypesEx())
{
return BuildCreatureTypeExList(self->mat_Ptr->raceEx);
}
}
Py_RETURN_NONE;
}
static PyObject* DF_Material_ReadDescriptorColors(DF_Material* self, PyObject* args)
{
if(self->mat_Ptr != NULL)
{
if(self->mat_Ptr->ReadDescriptorColors())
{
return BuildDescriptorColorList(self->mat_Ptr->color);
}
}
Py_RETURN_NONE;
}
static PyMethodDef DF_Material_methods[] =
{
{"Read_Inorganic_Materials", (PyCFunction)DF_Material_ReadInorganicMaterials, METH_NOARGS, ""},
{"Read_Organic_Materials", (PyCFunction)DF_Material_ReadOrganicMaterials, METH_NOARGS, ""},
{"Read_Wood_Materials", (PyCFunction)DF_Material_ReadWoodMaterials, METH_NOARGS, ""},
{"Read_Plant_Materials", (PyCFunction)DF_Material_ReadPlantMaterials, METH_NOARGS, ""},
{"Read_Creature_Types", (PyCFunction)DF_Material_ReadCreatureTypes, METH_NOARGS, ""},
{"Read_Creature_Types_Ex", (PyCFunction)DF_Material_ReadCreatureTypesEx, METH_NOARGS, ""},
{"Read_Descriptor_Colors", (PyCFunction)DF_Material_ReadDescriptorColors, METH_NOARGS, ""},
{NULL} //Sentinel
};
static PyTypeObject DF_Material_type =
{
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pydfhack.Material", /*tp_name*/
sizeof(DF_Material), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)DF_Material_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"pydfhack Material objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DF_Material_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DF_Material_init, /* tp_init */
0, /* tp_alloc */
DF_Material_new, /* tp_new */
};
#endif

@ -1,686 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DF_MEMINFO__
#define __DF_MEMINFO__
#include "DFPragma.h"
#pragma GCC diagnostic ignored "-Wwrite-strings"
#include "Python.h"
#include <string>
using namespace std;
#include "DFExport.h"
#include "DFIntegers.h"
#include "DFMemInfo.h"
using namespace DFHack;
struct DF_MemInfo
{
PyObject_HEAD
DFHack::memory_info* mem_Ptr;
};
// MemInfo type Allocation, Deallocation, and Initialization
static PyObject* DF_MemInfo_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DF_MemInfo* self;
self = (DF_MemInfo*)type->tp_alloc(type, 0);
if(self != NULL)
self->mem_Ptr = NULL;
return (PyObject*)self;
}
static int DF_MemInfo_init(DF_MemInfo* self, PyObject* args, PyObject* kwds)
{
return 0;
}
static void DF_MemInfo_dealloc(DF_MemInfo* self)
{
PySys_WriteStdout("mem_info dealloc\n");
if(self != NULL)
{
PySys_WriteStdout("mem_info not NULL\n");
if(self->mem_Ptr != NULL)
{
PySys_WriteStdout("mem_Ptr = 0x%x\n", self->mem_Ptr);
delete self->mem_Ptr;
PySys_WriteStdout("mem_Ptr deleted\n");
self->mem_Ptr = NULL;
}
self->ob_type->tp_free((PyObject*)self);
}
PySys_WriteStdout("mem_info dealloc done\n");
}
// Setters/Getters
static PyObject* DF_MemInfo_getBase(DF_MemInfo* self)
{
if(self->mem_Ptr != NULL)
{
return PyInt_FromLong(self->mem_Ptr->getBase());
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_setBase(DF_MemInfo* self, PyObject* args)
{
PyObject* arg = NULL;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "O", arg))
{
PyErr_SetString(PyExc_ValueError, "Bad argument list");
return NULL;
}
if(PyString_Check(arg))
self->mem_Ptr->setBase(std::string(PyString_AsString(arg)));
else if(PyInt_Check(arg))
self->mem_Ptr->setBase((uint32_t)PyInt_AsUnsignedLongMask(arg));
else
{
PyErr_SetString(PyExc_ValueError, "Argument must be string or integer");
return NULL;
}
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_getVersion(DF_MemInfo* self)
{
if(self->mem_Ptr != NULL)
{
return PyString_FromString(self->mem_Ptr->getVersion().c_str());
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_setVersion(DF_MemInfo* self, PyObject* args)
{
const char* v = NULL;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "s", &v))
return NULL;
self->mem_Ptr->setVersion(v);
}
Py_RETURN_NONE;
}
static PyGetSetDef DF_MemInfo_getterSetters[] =
{
{"base", (getter)DF_MemInfo_getBase, (setter)DF_MemInfo_setBase, "base", NULL},
{"version", (getter)DF_MemInfo_getVersion, (setter)DF_MemInfo_setVersion, "version", NULL},
{NULL} // Sentinel
};
// Member methods
static PyObject* DF_MemInfo_GetOffset(DF_MemInfo* self, PyObject* args)
{
const char* s = NULL;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "s", &s))
return NULL;
return PyInt_FromLong(self->mem_Ptr->getOffset(s));
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_SetOffset(DF_MemInfo* self, PyObject* args)
{
// const char* s = NULL;
// const char* n = NULL;
// int32_t i;
// PyObject* obj;
// if(self->mem_Ptr != NULL)
// {
// if(!PyArg_ParseTuple(args, "sO", &s, &obj))
// return NULL;
// if(PyString_Check(obj))
// {
// n = PyString_AsString(obj);
// self->mem_Ptr->setOffset(s, n);
// }
// else if(PyInt_Check(obj))
// {
// i = (int32_t)PyInt_AsLong(obj);
// self->mem_Ptr->setOffset(s, i);
// }
// }
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_GetAddress(DF_MemInfo* self, PyObject* args)
{
const char* s = NULL;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "s", &s))
return NULL;
return PyInt_FromLong(self->mem_Ptr->getAddress(s));
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_SetAddress(DF_MemInfo* self, PyObject* args)
{
// const char* s = NULL;
// const char* n = NULL;
// int32_t i;
// PyObject* obj;
// if(self->mem_Ptr != NULL)
// {
// if(!PyArg_ParseTuple(args, "sO", &s, &obj))
// return NULL;
// if(PyString_Check(obj))
// {
// n = PyString_AsString(obj);
// self->mem_Ptr->setAddress(s, n);
// }
// else if(PyInt_Check(obj))
// {
// i = (int32_t)PyInt_AsLong(obj);
// self->mem_Ptr->setAddress(s, i);
// }
// }
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_GetHexValue(DF_MemInfo* self, PyObject* args)
{
const char* s = NULL;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "s", &s))
return NULL;
return PyInt_FromLong(self->mem_Ptr->getHexValue(s));
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_SetHexValue(DF_MemInfo* self, PyObject* args)
{
// const char* s = NULL;
// const char* n = NULL;
// int32_t i;
// PyObject* obj;
// if(self->mem_Ptr != NULL)
// {
// if(!PyArg_ParseTuple(args, "sO", &s, &obj))
// return NULL;
// if(PyString_Check(obj))
// {
// n = PyString_AsString(obj);
// self->mem_Ptr->setHexValue(s, n);
// }
// else if(PyInt_Check(obj))
// {
// i = (int32_t)PyInt_AsLong(obj);
// self->mem_Ptr->setHexValue(s, i);
// }
// }
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_GetString(DF_MemInfo* self, PyObject* args)
{
const char* s = NULL;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "s", &s))
return NULL;
return PyString_FromString(self->mem_Ptr->getString(s).c_str());
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_SetString(DF_MemInfo* self, PyObject* args)
{
// const char* s = NULL;
// const char* n = NULL;
// if(self->mem_Ptr != NULL)
// {
// if(!PyArg_ParseTuple(args, "ss", &s, &n))
// return NULL;
// self->mem_Ptr->setString(s, n);
// }
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_GetProfession(DF_MemInfo* self, PyObject* args)
{
uint32_t s;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "I", &s))
return NULL;
return PyString_FromString(self->mem_Ptr->getProfession(s).c_str());
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_SetProfession(DF_MemInfo* self, PyObject* args)
{
const char* s = NULL;
const char* n = NULL;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "ss", &s, &n))
return NULL;
self->mem_Ptr->setProfession(s, n);
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_GetJob(DF_MemInfo* self, PyObject* args)
{
uint32_t s;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "I", &s))
return NULL;
return PyString_FromString(self->mem_Ptr->getJob(s).c_str());
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_SetJob(DF_MemInfo* self, PyObject* args)
{
const char* s = NULL;
const char* n = NULL;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "ss", &s, &n))
return NULL;
self->mem_Ptr->setJob(s, n);
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_GetSkill(DF_MemInfo* self, PyObject* args)
{
uint32_t s;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "I", &s))
return NULL;
return PyString_FromString(self->mem_Ptr->getSkill(s).c_str());
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_SetSkill(DF_MemInfo* self, PyObject* args)
{
const char* s = NULL;
const char* n = NULL;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "ss", &s, &n))
return NULL;
self->mem_Ptr->setSkill(s, n);
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_GetTrait(DF_MemInfo* self, PyObject* args)
{
uint32_t s, n;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "II", &s, &n))
return NULL;
return PyString_FromString(self->mem_Ptr->getTrait(s, n).c_str());
}
Py_RETURN_NONE;
}
// I have no idea what any of the strings are, so I can't really put meaningful names - doomchild
static PyObject* DF_MemInfo_SetTrait(DF_MemInfo* self, PyObject* args)
{
const char* a = NULL;
const char* b = NULL;
const char* c = NULL;
const char* d = NULL;
const char* e = NULL;
const char* f = NULL;
const char* g = NULL;
const char* h = NULL;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "ssssssss", &a, &b, &c, &d, &e, &f, &g, &h))
return NULL;
self->mem_Ptr->setTrait(a, b, c, d, e, f, g, h);
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_GetTraitName(DF_MemInfo* self, PyObject* args)
{
uint32_t s;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "I", &s))
return NULL;
return PyString_FromString(self->mem_Ptr->getTraitName(s).c_str());
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_GetLabor(DF_MemInfo* self, PyObject* args)
{
uint32_t s;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "i", &s))
return NULL;
return PyString_FromString(self->mem_Ptr->getLabor(s).c_str());
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_SetLabor(DF_MemInfo* self, PyObject* args)
{
const char* s = NULL;
const char* n = NULL;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "ss", &s, &n))
return NULL;
self->mem_Ptr->setLabor(s, n);
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_RebaseAddresses(DF_MemInfo* self, PyObject* args)
{
int32_t base;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "i", &base))
return NULL;
self->mem_Ptr->RebaseAddresses(base);
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_RebaseAll(DF_MemInfo* self, PyObject* args)
{
int32_t base;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "i", &base))
return NULL;
self->mem_Ptr->RebaseAll(base);
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_RebaseVTable(DF_MemInfo* self, PyObject* args)
{
int32_t offset;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "i", &offset))
return NULL;
self->mem_Ptr->RebaseVTable(offset);
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_ResolveObjectToClassID(DF_MemInfo* self, PyObject* args)
{
uint32_t address;
int32_t classID;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "I", &address))
return NULL;
if(self->mem_Ptr->resolveObjectToClassID(address, classID))
return PyInt_FromLong(classID);
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_ResolveClassNameToClassID(DF_MemInfo* self, PyObject* args)
{
// const char* name;
// int32_t classID;
// if(self->mem_Ptr != NULL)
// {
// if(!PyArg_ParseTuple(args, "s", &name))
// return NULL;
// if(self->mem_Ptr->resolveClassnameToClassID(name, classID))
// return PyInt_FromLong(classID);
// }
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_ResolveClassNameToVPtr(DF_MemInfo* self, PyObject* args)
{
const char* n;
uint32_t vPtr;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "s", &n))
return NULL;
std::string name(n);
if(self->mem_Ptr->resolveClassnameToVPtr(name, vPtr))
return PyInt_FromLong(vPtr);
}
Py_RETURN_NONE;
}
static PyObject* DF_MemInfo_ResolveClassIDToClassName(DF_MemInfo* self, PyObject* args)
{
int32_t id;
string name;
if(self->mem_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "i", &id))
return NULL;
if(self->mem_Ptr->resolveClassIDToClassname(id, name))
return PyString_FromString(name.c_str());
}
Py_RETURN_NONE;
}
static PyMethodDef DF_MemInfo_methods[] =
{
{"Rebase_Addresses", (PyCFunction)DF_MemInfo_RebaseAddresses, METH_VARARGS, ""},
{"Rebase_All", (PyCFunction)DF_MemInfo_RebaseAll, METH_VARARGS, ""},
{"Rebase_VTable", (PyCFunction)DF_MemInfo_RebaseVTable, METH_VARARGS, ""},
{"Get_Offset", (PyCFunction)DF_MemInfo_GetOffset, METH_VARARGS, ""},
{"Set_Offset", (PyCFunction)DF_MemInfo_SetOffset, METH_VARARGS, ""},
{"Get_Address", (PyCFunction)DF_MemInfo_GetAddress, METH_VARARGS, ""},
{"Set_Address", (PyCFunction)DF_MemInfo_SetAddress, METH_VARARGS, ""},
{"Get_HexValue", (PyCFunction)DF_MemInfo_GetHexValue, METH_VARARGS, ""},
{"Set_HexValue", (PyCFunction)DF_MemInfo_SetHexValue, METH_VARARGS, ""},
{"Get_String", (PyCFunction)DF_MemInfo_GetString, METH_VARARGS, ""},
{"Set_String", (PyCFunction)DF_MemInfo_SetString, METH_VARARGS, ""},
{"Get_Profession", (PyCFunction)DF_MemInfo_GetProfession, METH_VARARGS, ""},
{"Set_Profession", (PyCFunction)DF_MemInfo_SetProfession, METH_VARARGS, ""},
{"Get_Job", (PyCFunction)DF_MemInfo_GetJob, METH_VARARGS, ""},
{"Set_Job", (PyCFunction)DF_MemInfo_SetJob, METH_VARARGS, ""},
{"Get_Skill", (PyCFunction)DF_MemInfo_GetSkill, METH_VARARGS, ""},
{"Set_Skill", (PyCFunction)DF_MemInfo_SetSkill, METH_VARARGS, ""},
{"Get_Trait", (PyCFunction)DF_MemInfo_GetTrait, METH_VARARGS, ""},
{"Set_Trait", (PyCFunction)DF_MemInfo_SetTrait, METH_VARARGS, ""},
{"Get_Trait_Name", (PyCFunction)DF_MemInfo_GetTraitName, METH_VARARGS, ""},
{"Get_Labor", (PyCFunction)DF_MemInfo_GetLabor, METH_VARARGS, ""},
{"Set_Labor", (PyCFunction)DF_MemInfo_SetLabor, METH_VARARGS, ""},
{"Resolve_Object_To_Class_ID", (PyCFunction)DF_MemInfo_ResolveObjectToClassID, METH_VARARGS, ""},
{"Resolve_Classname_To_Class_ID", (PyCFunction)DF_MemInfo_ResolveClassNameToClassID, METH_VARARGS, ""},
{"Resolve_Classname_To_VPtr", (PyCFunction)DF_MemInfo_ResolveClassNameToVPtr, METH_VARARGS, ""},
{"Resolve_Class_ID_To_Classname", (PyCFunction)DF_MemInfo_ResolveClassIDToClassName, METH_VARARGS, ""},
{NULL} //Sentinel
};
static PyTypeObject DF_MemInfo_type =
{
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pydfhack.DF_MemInfo", /*tp_name*/
sizeof(DF_MemInfo), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)DF_MemInfo_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"pydfhack DF_MemInfo objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DF_MemInfo_methods, /* tp_methods */
0, /* tp_members */
DF_MemInfo_getterSetters, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DF_MemInfo_init, /* tp_init */
0, /* tp_alloc */
DF_MemInfo_new, /* tp_new */
};
#endif

@ -1,203 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFPOSITION__
#define __DFPOSITION__
#pragma GCC diagnostic ignored "-Wwrite-strings"
#include "Python.h"
#include "integers.h"
#include "modules/Position.h"
using namespace DFHack;
struct DF_Position
{
PyObject_HEAD
DFHack::Position* pos_Ptr;
};
// API type Allocation, Deallocation, and Initialization
static PyObject* DF_Position_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DF_Position* self;
self = (DF_Position*)type->tp_alloc(type, 0);
if(self != NULL)
self->pos_Ptr = NULL;
return (PyObject*)self;
}
static int DF_Position_init(DF_Position* self, PyObject* args, PyObject* kwds)
{
return 0;
}
static void DF_Position_dealloc(DF_Position* self)
{
if(self != NULL)
{
if(self->pos_Ptr != NULL)
{
delete self->pos_Ptr;
self->pos_Ptr = NULL;
}
self->ob_type->tp_free((PyObject*)self);
}
}
// Getters/Setters
static PyObject* DF_Position_getViewCoords(DF_Position* self, void* closure)
{
int32_t x, y, z;
if(self->pos_Ptr != NULL)
{
if(self->pos_Ptr->getViewCoords(x, y, z))
return Py_BuildValue("iii", x, y, z);
}
Py_RETURN_NONE;
}
static PyObject* DF_Position_setViewCoords(DF_Position* self, PyObject* args)
{
int32_t x, y, z;
if(self->pos_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "iii", &x, &y, &z))
return NULL;
if(self->pos_Ptr->setViewCoords(x, y, z))
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Position_getCursorCoords(DF_Position* self, void* closure)
{
int32_t x, y, z;
if(self->pos_Ptr != NULL)
{
if(self->pos_Ptr->getCursorCoords(x, y, z))
return Py_BuildValue("iii", x, y, z);
}
Py_RETURN_NONE;
}
static PyObject* DF_Position_setCursorCoords(DF_Position* self, PyObject* args)
{
int32_t x, y, z;
if(self->pos_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "iii", &x, &y, &z))
return NULL;
if(self->pos_Ptr->setCursorCoords(x, y, z))
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Position_getWindowSize(DF_Position* self, void* closure)
{
int32_t x, y;
if(self->pos_Ptr != NULL)
{
if(self->pos_Ptr->getWindowSize(x, y))
return Py_BuildValue("ii", x, y);
}
Py_RETURN_NONE;
}
static PyGetSetDef DF_Position_getterSetters[] =
{
{"view_coords", (getter)DF_Position_getViewCoords, (setter)DF_Position_setViewCoords, "view_coords", NULL},
{"cursor_coords", (getter)DF_Position_getCursorCoords, (setter)DF_Position_setCursorCoords, "cursor_coords", NULL},
{"window_size", (getter)DF_Position_getWindowSize, NULL, "window_size", NULL},
{NULL} // Sentinel
};
static PyTypeObject DF_Position_type =
{
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pydfhack.Position", /*tp_name*/
sizeof(DF_Position), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)DF_Position_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"pydfhack Position objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
DF_Position_getterSetters, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DF_Position_init, /* tp_init */
0, /* tp_alloc */
DF_Position_new, /* tp_new */
};
#endif

@ -1,289 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFTRANSLATE__
#define __DFTRANSLATE__
#pragma GCC diagnostic ignored "-Wwrite-strings"
#include "Python.h"
#include <vector>
#include <string>
#include "integers.h"
using namespace std;
#include "DFTypes.h"
#include "modules/Translation.h"
#include "DF_Helpers.cpp"
using namespace DFHack;
struct DF_Translate
{
PyObject_HEAD
PyObject* dict;
DFHack::Translation* tran_Ptr;
};
// API type Allocation, Deallocation, and Initialization
static PyObject* DF_Translate_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DF_Translate* self;
self = (DF_Translate*)type->tp_alloc(type, 0);
if(self != NULL)
self->tran_Ptr = NULL;
return (PyObject*)self;
}
static int DF_Translate_init(DF_Translate* self, PyObject* args, PyObject* kwds)
{
return 0;
}
static void DF_Translate_dealloc(DF_Translate* self)
{
PySys_WriteStdout("translate dealloc\n");
if(self != NULL)
{
PySys_WriteStdout("translate not NULL\n");
if(self->tran_Ptr != NULL)
{
Py_XDECREF(self->dict);
PySys_WriteStdout("tran_Ptr = 0x%x\n", self->tran_Ptr);
delete self->tran_Ptr;
PySys_WriteStdout("tran_Ptr deleted\n");
self->tran_Ptr = NULL;
}
self->ob_type->tp_free((PyObject*)self);
}
PySys_WriteStdout("translate dealloc done\n");
}
// Type methods
static PyObject* DF_Translate_Start(DF_Translate* self, PyObject* args)
{
DFHack::Dicts* t_dicts;
std::vector<std::string> wordVec;
PyObject *list, *tempDict;
if(self->tran_Ptr != NULL)
{
if(self->tran_Ptr->Start())
{
Py_CLEAR(self->dict);
t_dicts = self->tran_Ptr->getDicts();
DFHack::DFDict & translations = t_dicts->translations;
DFHack::DFDict & foreign_languages = t_dicts->foreign_languages;
self->dict = PyDict_New();
tempDict = PyDict_New();
for(uint32_t i = 0; i < translations.size(); i++)
{
uint32_t size = translations[i].size();
uint32_t j = 0;
list = PyList_New(size);
for(; j < size; j++)
PyList_SET_ITEM(list, j, PyString_FromString(translations[i][j].c_str()));
PyObject* key = PyInt_FromLong(j);
PyDict_SetItem(tempDict, key, list);
Py_DECREF(key);
Py_DECREF(list);
}
PyDict_SetItemString(self->dict, "translations", tempDict);
Py_DECREF(tempDict);
tempDict = PyDict_New();
for(uint32_t i = 0; i < foreign_languages.size(); i++)
{
uint32_t size = foreign_languages[i].size();
uint32_t j = 0;
list = PyList_New(size);
for(; j < size; j++)
PyList_SET_ITEM(list, j, PyString_FromString(foreign_languages[i][j].c_str()));
PyObject* key = PyInt_FromLong(j);
PyDict_SetItem(tempDict, key, list);
Py_DECREF(key);
Py_DECREF(list);
}
PyDict_SetItemString(self->dict, "foreign_languages", tempDict);
Py_DECREF(tempDict);
Py_RETURN_TRUE;
}
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Translate_Finish(DF_Translate* self, PyObject* args)
{
if(self->tran_Ptr != NULL)
{
if(self->tran_Ptr->Finish())
{
if(self->dict != NULL)
PyDict_Clear(self->dict);
Py_CLEAR(self->dict);
Py_RETURN_TRUE;
}
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Translate_TranslateName(DF_Translate* self, PyObject* args)
{
PyObject *nameObj, *retString;
DFHack::t_name name;
int inEnglish = 1;
if(self->tran_Ptr != NULL)
{
if(PyArg_ParseTuple(args, "O|i", &nameObj, &inEnglish))
return NULL;
if(PyObject_IsInstance(nameObj, Name_type) != 1)
{
PyErr_SetString(PyExc_TypeError, "argument 1 must be a Name object");
return NULL;
}
name = ReverseBuildName(nameObj);
std::string nameStr = self->tran_Ptr->TranslateName(name, (bool)inEnglish);
retString = PyString_FromString(nameStr.c_str());
return retString;
}
Py_RETURN_NONE;
}
static PyMethodDef DF_Translate_methods[] =
{
{"Start", (PyCFunction)DF_Translate_Start, METH_NOARGS, ""},
{"Finish", (PyCFunction)DF_Translate_Finish, METH_NOARGS, ""},
{"Translate_Name", (PyCFunction)DF_Translate_TranslateName, METH_VARARGS, ""},
{NULL} //Sentinel
};
// Getters/Setters
static PyObject* DF_Translate_getDicts(DF_Translate* self, PyObject* args)
{
if(self->tran_Ptr != NULL)
{
if(self->dict != NULL)
return self->dict;
}
Py_RETURN_NONE;
}
static PyGetSetDef DF_Translate_getterSetters[] =
{
{"dictionaries", (getter)DF_Translate_getDicts, NULL, "dictionaries", NULL},
{NULL} // Sentinel
};
static PyTypeObject DF_Translate_type =
{
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pydfhack._TranslationManager", /*tp_name*/
sizeof(DF_Translate), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)DF_Translate_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"pydfhack TranslationManager object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DF_Translate_methods, /* tp_methods */
0, /* tp_members */
DF_Translate_getterSetters, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DF_Translate_init, /* tp_init */
0, /* tp_alloc */
DF_Translate_new, /* tp_new */
};
#endif

@ -1,195 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef __DFVEGETATION__
#define __DFVEGETATION__
#include "Python.h"
#include "DFIntegers.h"
#include "modules/Vegetation.h"
#include "DF_Helpers.cpp"
using namespace DFHack;
static PyObject* BuildTree(DFHack::t_tree& tree)
{
PyObject* t_Obj;
PyObject* args;
args = Py_BuildValue("iiOi", tree.type, tree.material, BuildPosition3D(tree.x, tree.y, tree.z), tree.address);
t_Obj = PyObject_CallObject(Tree_type, args);
Py_DECREF(args);
return t_Obj;
}
struct DF_Vegetation
{
PyObject_HEAD
DFHack::Vegetation* veg_Ptr;
};
static PyObject* DF_Vegetation_new(PyTypeObject* type, PyObject* args, PyObject* kwds)
{
DF_Vegetation* self;
self = (DF_Vegetation*)type->tp_alloc(type, 0);
if(self != NULL)
self->veg_Ptr = NULL;
return (PyObject*)self;
}
static int DF_Vegetation_init(DF_Vegetation* self, PyObject* args, PyObject* kwds)
{
return 0;
}
static void DF_Vegetation_dealloc(DF_Vegetation* self)
{
PySys_WriteStdout("vegetation dealloc\n");
if(self != NULL)
{
PySys_WriteStdout("vegetation not NULL\n");
if(self->veg_Ptr != NULL)
{
PySys_WriteStdout("veg_Ptr = 0x%x\n", self->veg_Ptr);
delete self->veg_Ptr;
PySys_WriteStdout("veg_Ptr deleted\n");
self->veg_Ptr = NULL;
}
self->ob_type->tp_free((PyObject*)self);
}
PySys_WriteStdout("vegetation dealloc done\n");
}
// Type methods
static PyObject* DF_Vegetation_Start(DF_Vegetation* self, PyObject* args)
{
uint32_t numTrees = 0;
if(self->veg_Ptr != NULL)
{
if(self->veg_Ptr->Start(numTrees))
return PyInt_FromLong(numTrees);
else
return PyInt_FromLong(-1);
}
Py_RETURN_NONE;
}
static PyObject* DF_Vegetation_Finish(DF_Vegetation* self, PyObject* args)
{
if(self->veg_Ptr != NULL)
{
if(self->veg_Ptr->Finish())
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
Py_RETURN_NONE;
}
static PyObject* DF_Vegetation_Read(DF_Vegetation* self, PyObject* args)
{
uint32_t index = 0;
t_tree tree;
if(self->veg_Ptr != NULL)
{
if(!PyArg_ParseTuple(args, "I", &index))
return NULL;
if(self->veg_Ptr->Read(index, tree))
return BuildTree(tree);
}
Py_RETURN_NONE;
}
static PyMethodDef DF_Vegetation_methods[] =
{
{"Start", (PyCFunction)DF_Vegetation_Start, METH_NOARGS, ""},
{"Finish", (PyCFunction)DF_Vegetation_Finish, METH_NOARGS, ""},
{"Read", (PyCFunction)DF_Vegetation_Read, METH_VARARGS, ""},
{NULL} // Sentinel
};
static PyTypeObject DF_Vegetation_type =
{
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pydfhack.Vegetation", /*tp_name*/
sizeof(DF_Vegetation), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)DF_Vegetation_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"pydfhack Vegetation objects", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DF_Vegetation_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DF_Vegetation_init, /* tp_init */
0, /* tp_alloc */
DF_Vegetation_new, /* tp_new */
};
#endif

@ -1,4 +0,0 @@
#!/bin/bash
python linsetup.py build_ext
cp build/lib.linux-i686-2.6/pydfhack.so .
rm -r build

@ -1,4 +0,0 @@
python setup.py build_ext
copy /Y .\build\lib.win32-2.6\pydfhack.pyd ..\..\output\pydfhack.pyd
rmdir /S /Q .\build
pause

@ -1,273 +0,0 @@
from ctypes import *
from pydftypes import *
int_ptr = POINTER(c_int)
uint_ptr = POINTER(c_uint)
libdfhack = cdll.libdfhack
libdfhack.API_Alloc.restype = c_void_p
libdfhack.API_Free.argtypes = [ c_void_p ]
libdfhack.API_getMemoryInfo.restype = c_void_p
libdfhack.API_getProcess.restype = c_void_p
libdfhack.API_getWindow.restype = c_void_p
libdfhack.API_getCreatures.restype = c_void_p
libdfhack.API_getMaps.restype = c_void_p
libdfhack.API_getGui.restype = c_void_p
libdfhack.API_getPosition.restype = c_void_p
libdfhack.API_getMaterials.restype = c_void_p
libdfhack.API_getTranslation.restype = c_void_p
libdfhack.API_getVegetation.restype = c_void_p
libdfhack.API_getBuildings.restype = c_void_p
libdfhack.API_getConstructions.restype = c_void_p
class API(object):
def __init__(self, memory_path):
self._api_ptr = libdfhack.API_Alloc(create_string_buffer(memory_path))
self._pos_obj = None
self._mat_obj = None
def __del__(self):
libdfhack.API_Free(self._api_ptr)
def attach(self):
return libdfhack.API_Attach(self._api_ptr) > 0
def detach(self):
return libdfhack.API_Detach(self._api_ptr) > 0
def suspend(self):
return libdfhack.API_Suspend(self._api_ptr) > 0
def resume(self):
return libdfhack.API_Resume(self._api_ptr) > 0
def force_resume(self):
return libdfhack.API_ForceResume(self._api_ptr) > 0
def async_suspend(self):
return libdfhack.API_AsyncSuspend(self._api_ptr) > 0
@property
def is_attached(self):
return libdfhack.API_isAttached(self._api_ptr) > 0
@property
def is_suspended(self):
return libdfhack.API_isSuspended(self._api_ptr) > 0
@property
def position(self):
if self._pos_obj is None:
ptr = libdfhack.API_getPosition(self._api_ptr)
if ptr is not None:
return Position(ptr)
else:
return None
else:
return self._pos_obj
@property
def materials(self):
if self._mat_obj is None:
ptr = libdfhack.API_getMaterials(self._api_ptr)
if ptr is not None:
return Materials(ptr)
else:
return None
else:
return self._mat_obj
class Position(object):
def __init__(self, ptr):
self._pos_ptr = ptr
self._vx, self._vy, self._vz = c_int(), c_int(), c_int()
self._cx, self._cy, self._cz = c_int(), c_int(), c_int()
self._ww, self._wh = c_int(), c_int()
def get_view_coords(self):
if libdfhack.Position_getViewCoords(self._pos_ptr, byref(self._vx), byref(self._vy), byref(self._vz)) > 0:
return (self._vx.value, self._vy.value, self._vz.value)
else:
return (-1, -1, -1)
def set_view_coords(self, v_coords):
self._vx.value, self._vy.value, self._vz.value = v_coords
libdfhack.Position_setViewCoords(self._pos_ptr, self._vx, self._vy, self._vz)
view_coords = property(get_view_coords, set_view_coords)
def get_cursor_coords(self):
if libdfhack.Position_getCursorCoords(self._pos_ptr, byref(self._cx), byref(self._cy), byref(self._cz)) > 0:
return (self._cx.value, self._cy.value, self._cz.value)
else:
return (-1, -1, -1)
def set_cursor_coords(self, c_coords):
self._cx.value, self._cy.value, self_cz.value = c_coords
libdfhack.Position_setCursorCoords(self._pos_ptr, self._cx, self._cy, self._cz)
cursor_coords = property(get_cursor_coords, set_cursor_coords)
@property
def window_size(self):
if libdfhack.Position_getWindowSize(self._pos_ptr, byref(self._ww), byref(self._wh)) > 0:
return (self._ww.value, self._wh.value)
else:
return (-1, -1)
libdfhack.Gui_ReadViewScreen.argtypes = [ c_void_p, c_void_p ]
class Gui(object):
def __init__(self, ptr):
self._gui_ptr = ptr
def start(self):
return libdfhack.Gui_Start(self._gui_ptr)
def finish(self):
return libdfhack.Gui_Finish(self._gui_ptr)
def read_pause_state(self):
return libdfhack.Gui_ReadPauseState(self._pos_ptr) > 0
def read_view_screen(self):
s = ViewScreen()
if libdfhack.Gui_ReadViewScreen(self._gui_ptr, byref(s)) > 0:
return s
else:
return None
arr_create_func = CFUNCTYPE(c_void_p, c_int)
get_arg_types = [ c_void_p, arr_create_func ]
libdfhack.Materials_getInorganic.argtypes = get_arg_types
libdfhack.Materials_getOrganic.argtypes = get_arg_types
libdfhack.Materials_getTree.argtypes = get_arg_types
libdfhack.Materials_getPlant.argtypes = get_arg_types
libdfhack.Materials_getRace.argtypes = get_arg_types
libdfhack.Materials_getRaceEx.argtypes = get_arg_types
libdfhack.Materials_getColor.argtypes = get_arg_types
libdfhack.Materials_getOther.argtypes = get_arg_types
class Materials(object):
def __init__(self, ptr):
self._mat_ptr = ptr
self.inorganic = None
self.organic = None
self.tree = None
self.plant = None
self.race = None
self.race_ex = None
self.color = None
self.other = None
def read_inorganic(self):
return libdfhack.Materials_ReadInorganicMaterials(self._mat_ptr)
def read_organic(self):
return libdfhack.Materials_ReadOrganicMaterials(self._mat_ptr)
def read_wood(self):
return libdfhack.Materials_ReadWoodMaterials(self._mat_ptr)
def read_plant(self):
return libdfhack.Materials_ReadPlantMaterials(self._mat_ptr)
def read_creature_types(self):
return libdfhack.Materials_ReadCreatureTypes(self._mat_ptr)
def read_creature_types_ex(self):
return libdfhack.Materials_ReadCreatureTypesEx(self._mat_ptr)
def read_descriptor_colors(self):
return libdfhack.Materials_ReadDescriptorColors(self._mat_ptr)
def read_others(self):
return libdfhack.Materials_ReadOthers(self._mat_ptr)
def read_all(self):
libdfhack.Materials_ReadAllMaterials(self._mat_ptr)
def get_description(self, material):
return libdfhack.Materials_getDescription(self._mat_ptr, byref(material))
def _allocate_matgloss_array(self, count):
arr_type = Matgloss * count
arr = arr_type()
ptr = c_void_p()
ptr = addressof(arr)
return (arr, ptr)
def update_inorganic_cache(self):
def update_callback(count):
allocated = self._allocate_matgloss_array(count)
self.inorganic = allocated[0]
return allocated[1]
callback = arr_create_func(update_callback)
return libdfhack.Materials_getInorganic(self._mat_ptr, callback)
def update_organic_cache(self):
def update_callback(count):
allocated = self._allocate_matgloss_array(count)
self.organic = allocated[0]
return allocated[1]
callback = arr_create_func(update_callback)
return libdfhack.Materials_getOrganic(self._mat_ptr, callback)
def update_tree_cache(self):
def update_callback(count):
allocated = self._allocate_matgloss_array(count)
self.tree = allocated[0]
return allocated[1]
callback = arr_create_func(update_callback)
return libdfhack.Materials_getTree(self._mat_ptr, callback)
def update_plant_cache(self):
def update_callback(count):
allocated = self._allocate_matgloss_array(count)
self.plant = allocated[0]
return allocated[1]
callback = arr_create_func(update_callback)
return libdfhack.Materials_getPlant(self._mat_ptr, callback)
def update_race_cache(self):
def update_callback(count):
allocated = self._allocate_matgloss_array(count)
self.race = allocated[0]
return allocated[1]
callback = arr_create_func(update_callback)
return libdfhack.Materials_getRace(self._mat_ptr, callback)

@ -1,43 +0,0 @@
import time
import math
import pydfapi
df = pydfapi.API("Memory.xml")
def test_attach():
if not df.Attach():
print "Unable to attach!"
return False
elif not df.Detach():
print "Unable to detach!"
return False
else:
return True
def suspend_test():
print "Testing suspend/resume"
df.Attach()
t1 = time.time()
for i in xrange(1000):
df.Suspend()
if i % 10 == 0:
print "%i%%" % (i / 10,)
df.Resume()
t2 = time.time()
df.Detach()
print "suspend tests done in %0.9f seconds" % (t2 - t1,)
if __name__ == "__main__":
if test_attach():
suspend_test()
print "Done. Press any key to continue"
raw_input()

@ -1,36 +0,0 @@
_splatter_dict = { 0 : "Rock",
1 : "Amber",
2 : "Coral",
3 : "Green Glass",
4 : "Clear Glass",
5 : "Crystal Glass",
6 : "Ice",
7 : "Coal",
8 : "Potash",
9 : "Ash",
10 : "Pearlash",
11 : "Lye",
12 : "Mud",
13 : "Vomit",
14 : "Salt",
15 : "Filth",
16 : "Frozen? Filth",
18 : "Grime",
0xF2 : "Very Specific Blood (references a named creature)" }
def get_splatter_type(mat1, mat2, creature_types):
from cStringIO import StringIO
if mat1 in _splatter_dict:
return _splatter_dict[mat1]
elif mat1 == 0x2A or mat1 == 0x2B:
splatter = StringIO()
if mat2 != -1:
splatter.write(creature_types[mat2]["id"] + " ")
splatter.write("Blood")
return splatter.getvalue()
else:
return "Unknown"

@ -1,22 +0,0 @@
import sys
import pydfapi
df = pydfapi.API("Memory.xml")
if not df.Attach():
print "Unable to attach!"
print "Press any key to continue"
raw_input()
sys.exit(1)
pos = df.position
print "view coords: %s" % (pos.view_coords,)
print "cursor coords: %s" % (pos.cursor_coords,)
print "window size: %s" % (pos.window_size,)
if not df.Detach():
print "Unable to detach!"
print "Done. Press any key to continue"
raw_input()

@ -1,8 +0,0 @@
import sys
from cStringIO import StringIO
import pydfapi
df = pydfapi.API("Memory.xml")
def print_settlement(settlement, english_words, foreign_words):
s = StringIO()

@ -1,38 +0,0 @@
import pydfapi
if __name__ == "__main__":
df = pydfapi.API("Memory.xml")
if not df.Attach():
print "Unable to attach!"
return False
print "Attached, DF should be suspended now"
raw_input()
df.Resume()
print "Resumed, DF should be running"
raw_input()
df.Suspend()
print "Suspended, DF should be suspended now"
raw_input()
df.Resume()
print "Resumed, testing ForceResume. Suspend using SysInternals Process Explorer"
raw_input()
df.Force_Resume()
print "ForceResumed. DF should be running."
raw_input()
if not df.Detach():
print "Can't detach from DF"
return False
print "Detached, DF should be running again"
raw_input()

@ -1,66 +0,0 @@
import sys
from cStringIO import StringIO
import pydfapi
df = pydfapi.API("Memory.xml")
if not df.Attach():
print "Unable to attach!\nPress any key to continue"
raw_input()
sys.exit(1)
pos = df.position
veg = df.vegetation
mat = df.materials
organics = mat.Read_Organic_Materials()
x, y, z = pos.cursor_coords
num_vegs = veg.Start()
if x == -30000:
print "----==== Trees ====----"
for i in xrange(num_vegs):
tree = veg.Read(i)
t_x, t_y, t_z = tree["position"]
print "%f/%f/%f, %f:%f" % (t_x, t_y, t_z, tree["type"], tree["material"])
else:
print "----==== Tree at %i/%i/%i" % (x, y, z)
for i in xrange(num_vegs):
tree = veg.Read(i)
t_x, t_y, t_z = tree["position"]
t_type = tree["address"]
if t_x == x and t_y == y and t_z == z:
s = StringIO()
s.write("%f:%f = " % (tree["type"], tree["material"]))
if t_type in (1, 3):
s.write("near-water ")
s.write("%i " % (organics[tree["material"]]["id"]),)
if t_type in (0, 1):
s.write("tree\n")
elif t_type in (2, 3):
s.write("shrub\n")
print s.getvalue()
print "Address: 0x%x" % (tree["address"],)
break
veg.Finish()
if not df.Detach():
print "Unable to detach!"
print "Done. Press any key to continue"
raw_input()

@ -1,284 +0,0 @@
#!python
"""Bootstrap setuptools installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from ez_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools, set a download
mirror, or use an alternate download directory, you can do so by supplying
the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools.
"""
import sys
DEFAULT_VERSION = "0.6c11"
DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
md5_data = {
'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
'setuptools-0.6c10-py2.3.egg': 'ce1e2ab5d3a0256456d9fc13800a7090',
'setuptools-0.6c10-py2.4.egg': '57d6d9d6e9b80772c59a53a8433a5dd4',
'setuptools-0.6c10-py2.5.egg': 'de46ac8b1c97c895572e5e8596aeb8c7',
'setuptools-0.6c10-py2.6.egg': '58ea40aef06da02ce641495523a0b7f5',
'setuptools-0.6c11-py2.3.egg': '2baeac6e13d414a9d28e7ba5b5a596de',
'setuptools-0.6c11-py2.4.egg': 'bd639f9b0eac4c42497034dec2ec0c2b',
'setuptools-0.6c11-py2.5.egg': '64c94f3bf7a72a13ec83e0b24f2749b2',
'setuptools-0.6c11-py2.6.egg': 'bfa92100bd772d5a213eedd356d64086',
'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03',
'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a',
'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6',
'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a',
}
import sys, os
try: from hashlib import md5
except ImportError: from md5 import md5
def _validate_md5(egg_name, data):
if egg_name in md5_data:
digest = md5(data).hexdigest()
if digest != md5_data[egg_name]:
print >>sys.stderr, (
"md5 validation of %s failed! (Possible download problem?)"
% egg_name
)
sys.exit(2)
return data
def use_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
download_delay=15
):
"""Automatically find/download setuptools and make it available on sys.path
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end with
a '/'). `to_dir` is the directory where setuptools will be downloaded, if
it is not already available. If `download_delay` is specified, it should
be the number of seconds that will be paused before initiating a download,
should one be required. If an older version of setuptools is installed,
this routine will print a message to ``sys.stderr`` and raise SystemExit in
an attempt to abort the calling script.
"""
was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
def do_download():
egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg)
import setuptools; setuptools.bootstrap_install_from = egg
try:
import pkg_resources
except ImportError:
return do_download()
try:
pkg_resources.require("setuptools>="+version); return
except pkg_resources.VersionConflict, e:
if was_imported:
print >>sys.stderr, (
"The required version of setuptools (>=%s) is not available, and\n"
"can't be installed while this script is running. Please install\n"
" a more recent version first, using 'easy_install -U setuptools'."
"\n\n(Currently using %r)"
) % (version, e.args[0])
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return do_download()
except pkg_resources.DistributionNotFound:
return do_download()
def download_setuptools(
version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
delay = 15
):
"""Download setuptools from a specified location and return its filename
`version` should be a valid setuptools version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download attempt.
"""
import urllib2, shutil
egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
url = download_base + egg_name
saveto = os.path.join(to_dir, egg_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
from distutils import log
if delay:
log.warn("""
---------------------------------------------------------------------------
This script requires setuptools version %s to run (even to display
help). I will attempt to download it for you (from
%s), but
you may need to enable firewall access for this script first.
I will start the download in %d seconds.
(Note: if this machine does not have network access, please obtain the file
%s
and place it in this directory before rerunning this script.)
---------------------------------------------------------------------------""",
version, download_base, delay, url
); from time import sleep; sleep(delay)
log.warn("Downloading %s", url)
src = urllib2.urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = _validate_md5(egg_name, src.read())
dst = open(saveto,"wb"); dst.write(data)
finally:
if src: src.close()
if dst: dst.close()
return os.path.realpath(saveto)
def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
try:
import setuptools
except ImportError:
egg = None
try:
egg = download_setuptools(version, delay=0)
sys.path.insert(0,egg)
from setuptools.command.easy_install import main
return main(list(argv)+[egg]) # we're done here
finally:
if egg and os.path.exists(egg):
os.unlink(egg)
else:
if setuptools.__version__ == '0.0.1':
print >>sys.stderr, (
"You have an obsolete version of setuptools installed. Please\n"
"remove it from your system entirely before rerunning this script."
)
sys.exit(2)
req = "setuptools>="+version
import pkg_resources
try:
pkg_resources.require(req)
except pkg_resources.VersionConflict:
try:
from setuptools.command.easy_install import main
except ImportError:
from easy_install import main
main(list(argv)+[download_setuptools(delay=0)])
sys.exit(0) # try to force an exit
else:
if argv:
from setuptools.command.easy_install import main
main(argv)
else:
print "Setuptools version",version,"or greater has been installed."
print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
def update_md5(filenames):
"""Update our built-in md5 registry"""
import re
for name in filenames:
base = os.path.basename(name)
f = open(name,'rb')
md5_data[base] = md5(f.read()).hexdigest()
f.close()
data = [" %r: %r,\n" % it for it in md5_data.items()]
data.sort()
repl = "".join(data)
import inspect
srcfile = inspect.getsourcefile(sys.modules[__name__])
f = open(srcfile, 'rb'); src = f.read(); f.close()
match = re.search("\nmd5_data = {\n([^}]+)}", src)
if not match:
print >>sys.stderr, "Internal error!"
sys.exit(2)
src = src[:match.start(1)] + repl + src[match.end(1):]
f = open(srcfile,'w')
f.write(src)
f.close()
if __name__=='__main__':
if len(sys.argv)>2 and sys.argv[1]=='--md5update':
update_md5(sys.argv[2:])
else:
main(sys.argv[1:])

@ -1,13 +0,0 @@
# -*- coding: utf-8 -*-
from distutils.core import setup, Extension
from os import path
e = Extension("pydfhack",
sources=["DF_API.cpp", "DF_Buildings.cpp", "DF_Constructions.cpp", "DF_CreatureManager.cpp", "DF_GUI.cpp", "DF_Maps.cpp", "DF_Material.cpp", "DF_Position.cpp", "DF_Translate.cpp", "DF_Vegetation.cpp", "pydfhack.cpp"],
include_dirs=["../", path.join("..", "include"), path.join("..","depends","md5"), path.join("..","depends","tinyxml")],
library_dirs=[path.join("..","..","output")],
extra_compile_args=["-DLINUX_BUILD", "-w"],
libraries=["dfhack"],
export_symbols=["initpydfhack", "ReadRaw", "WriteRaw"])
setup(name="PyDFHack", version="1.0", ext_modules=[e])

@ -1,135 +0,0 @@
/*
www.sourceforge.net/projects/dfhack
Copyright (c) 2009 Petr Mrázek (peterix), Kenneth Ferland (Impaler[WrG]), dorf, doomchild
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "Python.h"
#include "DF_Imports.cpp"
#include "DF_MemInfo.cpp"
#include "DF_Material.cpp"
#include "DF_CreatureType.cpp"
#include "DF_CreatureManager.cpp"
#include "DF_Translate.cpp"
#include "DF_Vegetation.cpp"
#include "DF_Buildings.cpp"
#include "DF_Constructions.cpp"
#include "DF_API.cpp"
#ifndef PyMODINIT_FUNC
#define PyMODINIT_FUNC void
#endif
extern "C"
{
void ReadRaw(DF_API* self, const uint32_t offset, const uint32_t size, uint8_t* target)
{
if(self != NULL && self->api_Ptr != NULL)
{
self->api_Ptr->ReadRaw(offset, size, target);
}
}
void WriteRaw(DF_API* self, const uint32_t offset, const uint32_t size, uint8_t* source)
{
if(self != NULL && self->api_Ptr != NULL)
{
self->api_Ptr->WriteRaw(offset, size, source);
}
}
};
static PyMethodDef module_methods[] =
{
{NULL} //Sentinel
};
PyMODINIT_FUNC init_pydfhack(void)
{
PyObject* module;
if(PyType_Ready(&DF_API_type) < 0)
return;
if(PyType_Ready(&DF_MemInfo_type) < 0)
return;
if(PyType_Ready(&DF_Position_type) < 0)
return;
if(PyType_Ready(&DF_Material_type) < 0)
return;
if(PyType_Ready(&DF_Creature_Base_type) < 0)
return;
if(PyType_Ready(&DF_CreatureManager_type) < 0)
return;
if(PyType_Ready(&DF_Translate_type) < 0)
return;
if(PyType_Ready(&DF_Vegetation_type) < 0)
return;
if(PyType_Ready(&DF_Building_type) < 0)
return;
if(PyType_Ready(&DF_Construction_type) < 0)
return;
if(PyType_Ready(&DF_Map_type) < 0)
return;
if(PyType_Ready(&DF_GUI_type) < 0)
return;
module = Py_InitModule3("_pydfhack", module_methods, "pydfhack extension module");
Py_INCREF(&DF_API_type);
Py_INCREF(&DF_MemInfo_type);
Py_INCREF(&DF_Position_type);
Py_INCREF(&DF_Material_type);
Py_INCREF(&DF_Creature_Base_type);
Py_INCREF(&DF_CreatureManager_type);
Py_INCREF(&DF_Translate_type);
Py_INCREF(&DF_Vegetation_type);
Py_INCREF(&DF_Building_type);
Py_INCREF(&DF_Construction_type);
Py_INCREF(&DF_Map_type);
Py_INCREF(&DF_GUI_type);
PyModule_AddObject(module, "_API", (PyObject*)&DF_API_type);
PyModule_AddObject(module, "_MemInfo", (PyObject*)&DF_MemInfo_type);
PyModule_AddObject(module, "_PositionManager", (PyObject*)&DF_Position_type);
PyModule_AddObject(module, "_MaterialsManager", (PyObject*)&DF_Material_type);
PyModule_AddObject(module, "_Creature_Base", (PyObject*)&DF_Creature_Base_type);
PyModule_AddObject(module, "_CreatureManager", (PyObject*)&DF_CreatureManager_type);
PyModule_AddObject(module, "_TranslationManager", (PyObject*)&DF_Translate_type);
PyModule_AddObject(module, "_VegetationManager", (PyObject*)&DF_Vegetation_type);
PyModule_AddObject(module, "_BuildingManager", (PyObject*)&DF_Building_type);
PyModule_AddObject(module, "_ConstructionManager", (PyObject*)&DF_Construction_type);
PyModule_AddObject(module, "_MapManager", (PyObject*)&DF_Map_type);
PyModule_AddObject(module, "_GUIManager", (PyObject*)&DF_GUI_type);
DoImports();
}

@ -1,139 +0,0 @@
# -*- coding: utf-8 -*-
"""
Module for high-level abstraction of tiles
"""
from collections import namedtuple
from .pydftypes import Rectangle
from .mixins import NoStart
from .decorators import suspend
class Point(object):
x = None
y = None
z = None
block = False
def __init__(self, x, y, z, block=False):
self.x = x
self.y = y
self.z = z
self.block = block
def get_block(self):
if not self.block:
return Point(self.x/16, self.y/16, self.z, True)
else:
return self
@property
def xyz(self):
return (self.x, self.y, self.z)
@property
def rect(self):
"""
Return block coords in form (x1, y1, x2, y2)
"""
block = self.get_block()
x1 = block.x * 16
y1 = block.y * 16
return Rectangle(x1, y1, x1+15, y1+15)
def __repr__(self):
b = ''
if self.block:
b = ', Block'
return "<Point(X:{0.x}, Y:{0.y}, Z:{0.z}{1})>".format(self, b)
class Block(NoStart):
"""
16x16 tiles block
"""
api = None
tiles = None
coords = None
x1 = None
y1 = None
def __init__(self, api, coords):
"""
api is instance of API, which is used for read/write operations
coords is Point object
"""
self.api = api
if not isinstance(coords, Point):
raise Exception(u"coords parameter should be Point")
coords = coords.get_block()
self.coords = coords
self.rect = self.coords.rect
self.reload()
@suspend
def reload(self):
tile_types = self.api.maps.Read_Tile_Types(point=self.coords)
tile_flags = self.api.maps.Read_Designations(point=self.coords)
if self.tiles:
for x in range(16):
for y in range(16):
self.tiles[x][y].update(ttype=tile_types[x][y], flags=tile_flags[x][y])
else:
self.tiles = []
for x in range(16):
row = []
for y in range(16):
row.append(Tile(self, tile_types[x][y], tile_flags[x][y], self.rect.x1 + x, self.rect.y1 + y, self.coords.z))
self.tiles.append(row)
@suspend
def save(self):
tile_types = map(lambda x:range(16), range(16))
tile_flags = map(lambda x:range(16), range(16))
for x in range(16):
for y in range(16):
tile_types[x][y] = self.tiles[x][y].ttype
tile_flags[x][y] = self.tiles[x][y].flags
self.api.maps.Write_Tile_Types(point=self.coords, tiles=tile_types)
# Designations are bugged
#self.api.maps.Write_Designations(point=self.coords, tiles=tile_flags)
def get_tile(self, x=0, y=0, z=0, point=None):
if point:
x, y, z = point.xyz
if z == self.coords.z and (self.rect.y1 <= y <= self.rect.y2) and (self.rect.x1 <= x <= self.rect.x2):
return self.tiles[x%16][y%16]
else:
raise Exception("This tile does not belong to this block")
def __repr__(self):
return "<Block(X:{2}-{4}, Y:{3}-{5}, Z:{1.z})>".format(self, self.coords, *self.coords.rect)
class Tile(object):
coords = None
block = None
ttype = None
temperature = None
flags = None
def __init__(self, block, ttype, flags, x=0, y=0, z=0, point=None):
self.ttype = ttype
self.flags = flags
if not point:
point = Point(x, y, z)
self.coords = point
self.block = block
def update(self, ttype, flags):
self.ttype = ttype
self.flags = flags
def reload(self):
self.block.reload()
def save(self):
self.block.save()
def __repr__(self):
return "<Tile({0.ttype} at {1.x}, {1.y}, {1.z})>".format(self, self.coords)

@ -1,18 +0,0 @@
# -*- coding: utf-8 -*-
"""
Python class for DF_Hack::Construction
"""
from ._pydfhack import _ConstructionManager
from .mixins import NeedsStart
from .decorators import suspend
class Construction(NeedsStart, _ConstructionManager):
api = None
cls = _ConstructionManager
def __init__(self, api, *args, **kwds):
self.cls.__init__(self, args, kwds)
self.api = api
@suspend
def Read(self, *args, **kw):
return self.cls.Read(self, *args, **kw)

@ -1,34 +0,0 @@
# -*- coding: utf-8 -*-
"""
Python class for DF_Hack::Creature
"""
from ._pydfhack import _CreatureManager
from .mixins import NeedsStart
from .decorators import suspend
class Creature(NeedsStart, _CreatureManager):
api = None
cls = _CreatureManager
def __init__(self, api, *args, **kwds):
self.cls.__init__(self, args, kwds)
self.api = api
@suspend
def Read_Creature(self, *args, **kw):
return self.cls.Read_Creature(self, *args, **kw)
@suspend
def Get_Dwarf_Race_Index(self, *args, **kw):
return self.cls.Get_Dwarf_Race_Index(self, *args, **kw)
@suspend
def Write_Labors(self, *args, **kw):
return self.cls.Write_Labors(self, *args, **kw)
@suspend
def Read_Creature_In_Box(self, *args, **kw):
return self.cls.Read_Creature_In_Box(self, *args, **kw)
@suspend
def Get_Dwarf_Civ_id(self, *args, **kw):
return self.cls.Get_Dwarf_Civ_id(self, *args, **kw)

@ -1,20 +0,0 @@
# -*- coding: utf-8 -*-
"""
Decorators for bound classes
"""
from decorator import decorator
@decorator
def suspend(func, self, *args, **kw):
"""
This decorator will try to suspend DF and start needed module before running func.
If DF was resumed when decorator was run, it will try to resume back after executing func
"""
susp = not self.api.is_attached or self.api.is_suspended
if self.prepare():
res = func(self, *args, **kw)
if not susp:
self.api.Resume()
return res
else:
raise Exception(u"Could not suspend/start")

@ -1,25 +0,0 @@
# -*- coding: utf-8 -*-
"""
Python class for DF_Hack::GUI
"""
from ._pydfhack import _GUIManager
class GUI(_GUIManager):
api = None
started = False
def __init__(self, api, *args, **kwds):
_GUIManager.__init__(self, args, kwds)
self.api = api
def prepare(self):
"""
Enforce Suspend/Start
"""
if self.api.prepare():
if not self.started:
self.started = self.Start()
return self.started
else:
return False

@ -1,116 +0,0 @@
# -*- coding: utf-8 -*-
"""
Python class for DF_Hack::Maps
"""
from ._pydfhack import _MapManager
from .mixins import NeedsStart
from .decorators import suspend
from .blocks import Block, Point
class Map(NeedsStart, _MapManager):
api = None
cls = _MapManager
def __init__(self, api, *args, **kwds):
self.cls.__init__(self, args, kwds)
self.api = api
@suspend
def get_size(self):
return self.size
@suspend
def Is_Valid_Block(self, x=0, y=0, z=0, point=None):
"""
Checks if coords are valid
"""
if point:
point = point.get_block()
x, y, z = point.xyz
return self.cls.Is_Valid_Block(self, x, y, z)
@suspend
def Read_Tile_Types(self, x=0, y=0, z=0, point=None):
"""
Returns 16x16 block in form of list of lists.
Should be called either by point or x,y,z coords. Coords are in block form.
"""
if point:
point = point.get_block()
x, y, z = point.xyz
return self.cls.Read_Tile_Types(self, x, y, z)
@suspend
def Write_Tile_Types(self, x=0, y=0, z=0, tiles=None, point=None):
if point:
point = point.get_block()
x, y, z = point.xyz
return self.cls.Write_Tile_Types(self, x, y, z, tiles)
@suspend
def Read_Designations(self, x=0, y=0, z=0, point=None):
"""
Returns 16x16 block in form of list of lists.
"""
if point:
point = point.get_block()
x, y, z = point.xyz
return self.cls.Read_Designations(self, x, y, z)
@suspend
def Write_Designations(self, x=0, y=0, z=0, tiles=None, point=None):
if point:
point = point.get_block()
x, y, z = point.xyz
return self.cls.Write_Designations(self, x, y, z, tiles)
@suspend
def Write_Occupancy(self, *args, **kw):
return self.cls.Write_Occupancy(self, *args, **kw)
@suspend
def Write_Dirty_Bit(self, *args, **kw):
return self.cls.Write_Dirty_Bit(self, *args, **kw)
@suspend
def Write_Block_Flags(self, *args, **kw):
return self.cls.Write_Block_Flags(self, *args, **kw)
@suspend
def Read_Region_Offsets(self, *args, **kw):
return self.cls.Read_Region_Offsets(self, *args, **kw)
@suspend
def Read_Dirty_Bit(self, *args, **kw):
return self.cls.Read_Dirty_Bit(self, *args, **kw)
@suspend
def Read_Occupancy(self, *args, **kw):
return self.cls.Read_Occupancy(self, *args, **kw)
@suspend
def Read_Block_Flags(self, *args, **kw):
return self.cls.Read_Block_Flags(self, *args, **kw)
@suspend
def Read_Geology(self, *args, **kw):
return self.cls.Read_Geology(self, *args, **kw)
@suspend
def Read_Block_40d(self, *args, **kw):
return self.cls.Read_Block_40d(self, *args, **kw)
@suspend
def get_block(self, point):
point = point.get_block()
block = Block(api=self.api, coords=point)
return block
@suspend
def get_tile(self, x=0, y=0, z=0, point=None):
if not point:
point = Point(x, y, z)
block = Block(api=self.api, coords=point.get_block())
return block.get_tile(point=point)

@ -1,42 +0,0 @@
# -*- coding: utf-8 -*-
"""
Python class for DF_Hack::Materials
"""
from ._pydfhack import _MaterialsManager
from .mixins import NoStart
from .decorators import suspend
class Materials(NoStart, _MaterialsManager):
api = None
cls = _MaterialsManager
def __init__(self, api, *args, **kwds):
cls.__init__(self, args, kwds)
self.api = api
@suspend
def Read_Wood_Materials(self, *args, **kw):
return self.cls.Read_Wood_Materials(self, *args, **kw)
@suspend
def Read_Plant_Materials(self, *args, **kw):
return self.cls.Read_Plant_Materials(self, *args, **kw)
@suspend
def Read_Inorganic_Materials(self, *args, **kw):
return self.cls.Read_Inorganic_Materials(self, *args, **kw)
@suspend
def Read_Descriptor_Colors(self, *args, **kw):
return self.cls.Read_Descriptor_Colors(self, *args, **kw)
@suspend
def Read_Creature_Types(self, *args, **kw):
return self.cls.Read_Creature_Types(self, *args, **kw)
@suspend
def Read_Organic_Materials(self, *args, **kw):
return self.cls.Read_Organic_Materials(self, *args, **kw)
@suspend
def Read_Creature_Types_Ex(self, *args, **kw):
return self.cls.Read_Creature_Types_Ex(self, *args, **kw)

@ -1,98 +0,0 @@
# -*- coding: utf-8 -*-
"""
Python class for DF_Hack::MemInfo
"""
from ._pydfhack import _MemInfo
from .mixins import NoStart
from .decorators import suspend
class MemInfo(NoStart, _MemInfo):
api = None
cls = _MemInfo
def __init__(self, api, *args, **kwds):
self.cls.__init__(self, args, kwds)
self.api = api
## Properties:
# version
# base
## No idea if these should work only on suspend. To check later.
def Rebase_All(self, *args, **kw):
return self.cls.Rebase_All(self, *args, **kw)
def Set_String(self, *args, **kw):
return self.cls.Set_String(self, *args, **kw)
def Resolve_Object_To_Class_ID(self, *args, **kw):
return self.cls.Resolve_Object_To_Class_ID(self, *args, **kw)
def Get_Trait(self, *args, **kw):
return self.cls.Get_Trait(self, *args, **kw)
def Get_Job(self, *args, **kw):
return self.cls.Get_Job(self, *args, **kw)
def Rebase_VTable(self, *args, **kw):
return self.cls.Rebase_VTable(self, *args, **kw)
def Get_String(self, *args, **kw):
return self.cls.Get_String(self, *args, **kw)
def Get_Trait_Name(self, *args, **kw):
return self.cls.Get_Trait_Name(self, *args, **kw)
def Set_Job(self, *args, **kw):
return self.cls.Set_Job(self, *args, **kw)
def Set_Offset(self, *args, **kw):
return self.cls.Set_Offset(self, *args, **kw)
def Rebase_Addresses(self, *args, **kw):
return self.cls.Rebase_Addresses(self, *args, **kw)
def Resolve_Classname_To_Class_ID(self, *args, **kw):
return self.cls.Resolve_Classname_To_Class_ID(self, *args, **kw)
def Set_Labor(self, *args, **kw):
return self.cls.Set_Labor(self, *args, **kw)
def Get_Skill(self, *args, **kw):
return self.cls.Get_Skill(self, *args, **kw)
def Set_Profession(self, *args, **kw):
return self.cls.Set_Profession(self, *args, **kw)
def Get_Profession(self, *args, **kw):
return self.cls.Get_Profession(self, *args, **kw)
def Get_Offset(self, *args, **kw):
return self.cls.Get_Offset(self, *args, **kw)
def Get_HexValue(self, *args, **kw):
return self.cls.Get_HexValue(self, *args, **kw)
def Set_Address(self, *args, **kw):
return self.cls.Set_Address(self, *args, **kw)
def Set_HexValue(self, *args, **kw):
return self.cls.Set_HexValue(self, *args, **kw)
def Get_Address(self, *args, **kw):
return self.cls.Get_Address(self, *args, **kw)
def Set_Trait(self, *args, **kw):
return self.cls.Set_Trait(self, *args, **kw)
def Resolve_Classname_To_VPtr(self, *args, **kw):
return self.cls.Resolve_Classname_To_VPtr(self, *args, **kw)
def Get_Labor(self, *args, **kw):
return self.cls.Get_Labor(self, *args, **kw)
def Set_Skill(self, *args, **kw):
return self.cls.Set_Skill(self, *args, **kw)
def Resolve_Class_ID_To_Classname(self, *args, **kw):
return self.cls.Resolve_Class_ID_To_Classname(self, *args, **kw)

@ -1,63 +0,0 @@
# -*- coding: utf-8 -*-
"""
Mix-ins for bound classes
"""
class NeedsStart(object):
"""
This mixin enforces Start/Finish routines
"""
started = False
def prepare(self):
"""
Enforce Suspend/Start
"""
if self.api.prepare():
if not self.started:
self.Start()
return self.started
else:
return False
def Start(self):
if self.started:
return True
if self.api.prepare():
self.started = self.cls.Start(self)
if self.started:
self.api.started.append(self)
return self.started
else:
return False
start = Start
def Finish(self):
if self.started:
self.cls.Finish(self)
self.started = False
if self in self.api.started:
self.api.started.remove(self)
finish = Finish
class NoStart(object):
"""
This mixin enforces Suspend, and disables Start/Finish
"""
def prepare(self):
"""
Enforce Suspend
"""
return self.api.prepare()
def Start(self):
raise Exception("{0.cls} does not need Start()".format(self))
start = Start
def Finish(self):
raise Exception("{0.cls} does not need Finish()".format(self))
finish = Finish

@ -1,42 +0,0 @@
# -*- coding: utf-8 -*-
"""
Python class for DF_Hack::Position
"""
from ._pydfhack import _PositionManager
from .blocks import Point, Block
from .mixins import NoStart
from .decorators import suspend
class Position(NoStart, _PositionManager):
api = None
cls = _PositionManager
def __init__(self, api, *args, **kwds):
self.cls.__init__(self, args, kwds)
self.api = api
@suspend
def get_cursor(self):
coords = self.cursor_coords
if coords:
return Point(*coords)
else:
return None
@suspend
def get_window_size(self):
wsize = self.window_size
return wsize
@suspend
def get_view_coords(self):
coords = self.view_coords
return Point(*coords)
@suspend
def get_cursor_tile(self):
point = self.get_cursor()
if point:
tile = self.api.maps.get_tile(point=point)
return tile
else:
return None

@ -1,71 +0,0 @@
import _pydfhack, os, copy
from .blocks import Point, Block
from .meminfo import MemInfo
from .position import Position
from .materials import Materials
from .creature import Creature
from .map import Map
from .translation import Translation
from .construction import Construction
from .vegetation import Vegetation
from .gui import GUI
class API(_pydfhack._API):
started = None
path = os.path.dirname(os.path.abspath(__file__))
datafile = os.path.join(path, "Memory.xml")
if not os.path.isfile(datafile):
raise ImportError, "Memory.xml not found."
# Rude hack to bypass xml location restrictions
datafile = "./" + "../"*20 + datafile
def prepare(self):
"""
Enforce Attach/Suspend behavior.
Return True if succeeded, else False
"""
r = True
if not self.is_attached:
r = self.Attach()
if r and not self.is_suspended:
r = self.Suspend()
return r
def __init__(self, *args, **kwds):
_pydfhack._API.__init__(self, API.datafile)
self._mem_info_mgr_type = MemInfo
self._position_mgr_type = Position
self._material_mgr_type = Materials
self._creature_mgr_type = Creature
self._map_mgr_type = Map
self._translate_mgr_type = Translation
self._construction_mgr_type = Construction
self._vegetation_mgr_type = Vegetation
self._gui_mgr_type = GUI
self.started = []
def Attach(self, *args, **kw):
print "API.Attach()"
return _pydfhack._API.Attach(self, *args, **kw)
def Detach(self, *args, **kw):
print "API.Detach()"
return _pydfhack._API.Detach(self, *args, **kw)
def Suspend(self, *args, **kw):
print "API.Suspend()"
return _pydfhack._API.Suspend(self, *args, **kw)
def Resume(self):
print "API.Resume()"
# Reference counting is fcked, so leave it alone for now
## Explicitly Finish() all started modules
#print self.started
#started = copy.copy(self.started)
#print started
#for m in started:
# print m
# m.Finish()
#self.started = []
return _pydfhack._API.Resume(self)

@ -1,213 +0,0 @@
# -*- coding: utf-8 -*-
from ctypes import Structure, Union, c_uint
class DesignationStruct(Structure):
_fields_ = [("flow_size", c_uint, 3),
("pile", c_uint, 1),
("dig", c_uint, 3),
("smooth", c_uint, 2),
("hidden", c_uint, 1),
("geolayer_index", c_uint, 4),
("light", c_uint, 1),
("subterranean", c_uint, 1),
("skyview", c_uint, 1),
("biome", c_uint, 4),
("liquid_type", c_uint, 1),
("water_table", c_uint, 1),
("rained", c_uint, 1),
("traffic", c_uint, 2),
("flow_forbid", c_uint, 1),
("liquid_static", c_uint, 1),
("feature_local", c_uint, 1),
("feature_global", c_uint, 1),
("liquid_character", c_uint, 2)]
class DesignationFlags(Union):
_fields_ = [("whole", c_uint, 32),
("bits", DesignationStruct)]
def __init__(self, initial = 0):
self.whole = initial
def __int__(self):
return self.whole
class OccupancyStruct(Structure):
_fields_ = [("building", c_uint, 3),
("unit", c_uint, 1),
("unit_grounded", c_uint, 1),
("item", c_uint, 1),
("splatter", c_uint, 26)]
class OccupancyFlags(Union):
_fields_ = [("whole", c_uint, 32),
("bits", OccupancyStruct)]
def __init__(self, initial = 0):
self.whole = initial
def __int__(self):
return self.whole
class CreatureStruct1(Structure):
_fields_ = [("move_state", c_uint, 1),
("dead", c_uint, 1),
("has_mood", c_uint, 1),
("had_mood", c_uint, 1),
("marauder", c_uint, 1),
("drowning", c_uint, 1),
("merchant", c_uint, 1),
("forest", c_uint, 1),
("left", c_uint, 1),
("rider", c_uint, 1),
("incoming", c_uint, 1),
("diplomat", c_uint, 1),
("zombie", c_uint, 1),
("skeleton", c_uint, 1),
("can_swap", c_uint, 1),
("on_ground", c_uint, 1),
("projectile", c_uint, 1),
("active_invader", c_uint, 1),
("hidden_in_ambush", c_uint, 1),
("invader_origin", c_uint, 1),
("coward", c_uint, 1),
("hidden_ambusher", c_uint, 1),
("invades", c_uint, 1),
("check_flows", c_uint, 1),
("ridden", c_uint, 1),
("caged", c_uint, 1),
("tame", c_uint, 1),
("chained", c_uint, 1),
("royal_guard", c_uint, 1),
("fortress_guard", c_uint, 1),
("suppress_wield", c_uint, 1),
("important_historical_figure", c_uint, 1)]
class CreatureFlags1(Union):
_fields_ = [("whole", c_uint, 32),
("bits", CreatureStruct1)]
def __init__(self, initial = 0):
self.whole = initial
def __int__(self):
return self.whole
class CreatureStruct2(Structure):
_fields_ = [("swimming", c_uint, 1),
("sparring", c_uint, 1),
("no_notify", c_uint, 1),
("unused", c_uint, 1),
("calculated_nerves", c_uint, 1),
("calculated_bodyparts", c_uint, 1),
("important_historical_figure", c_uint, 1),
("killed", c_uint, 1),
("cleanup_1", c_uint, 1),
("cleanup_2", c_uint, 1),
("cleanup_3", c_uint, 1),
("for_trade", c_uint, 1),
("trade_resolved", c_uint, 1),
("has_breaks", c_uint, 1),
("gutted", c_uint, 1),
("circulatory_spray", c_uint, 1),
("locked_in_for_trading", c_uint, 1),
("slaughter", c_uint, 1),
("underworld", c_uint, 1),
("resident", c_uint, 1),
("cleanup_4", c_uint, 1),
("calculated_insulation", c_uint, 1),
("visitor_uninvited", c_uint, 1),
("visitor", c_uint, 1),
("calculated_inventory", c_uint, 1),
("vision_good", c_uint, 1),
("vision_damaged", c_uint, 1),
("vision_missing", c_uint, 1),
("breathing_good", c_uint, 1),
("breathing_problem", c_uint, 1),
("roaming_wilderness_population_source", c_uint, 1),
("roaming_wilderness_population_source_not_a_map_feature", c_uint, 1)]
class CreatureFlags2(Union):
_fields_ = [("whole", c_uint, 32),
("bits", CreatureStruct2)]
def __init__(self, initial = 0):
self.whole = initial
def __int__(self):
return self.whole
class ItemStruct(Structure):
_fields_ = [("on_ground", c_uint, 1),
("in_job", c_uint, 1),
("in_inventory", c_uint, 1),
("u_ngrd1", c_uint, 1),
("in_workshop", c_uint, 1),
("u_ngrd2", c_uint, 1),
("u_ngrd3", c_uint, 1),
("rotten", c_uint, 1),
("unk1", c_uint, 1),
("u_ngrd4", c_uint, 1),
("unk2", c_uint, 1),
("u_ngrd5", c_uint, 1),
("unk3", c_uint, 1),
("u_ngrd6", c_uint, 1),
("narrow", c_uint, 1),
("u_ngrd7", c_uint, 1),
("worn", c_uint, 1),
("unk4", c_uint, 1),
("u_ngrd8", c_uint, 1),
("forbid", c_uint, 1),
("unk5", c_uint, 1),
("dump", c_uint, 1),
("on_fire", c_uint, 1),
("melt", c_uint, 1),
("hidden", c_uint, 1),
("u_ngrd9", c_uint, 1),
("unk6", c_uint, 1),
("unk7", c_uint, 1),
("unk8", c_uint, 1),
("unk9", c_uint, 1),
("unk10", c_uint, 1),
("unk11", c_uint, 1)]
class ItemFlags(Union):
_fields_ = [("whole", c_uint, 32),
("bits", ItemStruct)]
def __init__(self, initial = 0):
self.whole = initial
def __int__(self):
return self.whole
dig_types = { "no" : 0,
"default" : 1,
"ud_stair" : 2,
"channel" : 3,
"ramp" : 4,
"d_stair" : 5,
"u_stair" : 6,
"whatever" : 7 }
traffic_types = { "normal" : 0,
"low" : 1,
"high" : 2,
"restricted" : 3 }
class BlockFlagStruct(Structure):
_fields_ = [("designated", c_uint, 1),
("unk_1", c_uint, 1),
("liquid_1", c_uint, 1),
("liquid_2", c_uint, 1),
("unk_2", c_uint, 28)]
class BlockFlags(Union):
_fields_ = [("whole", c_uint, 32),
("bits", BlockFlagStruct)]
def __init__(self, inital = 0):
self.whole = initial
def __int__(self):
return self.whole

@ -1,50 +0,0 @@
from ctypes import *
from collections import namedtuple
Position2D = namedtuple("Position2D", "x, y")
Position3D = namedtuple("Position3D", "x, y, z")
Rectangle = namedtuple("Rectangle", "x1, y1, x2, y2")
Note = namedtuple("Note", "symbol, foreground, background, name, position")
Construction = namedtuple("Construction", "position, form, unk_8, mat_type, mat_idx, unk3, unk4, unk5, unk6, origin")
Vein = namedtuple("Vein", "vtable, type, flags, address, assignment")
FrozenLiquidVein = namedtuple("FrozenLiquidVein", "vtable, address, tiles")
SpatterVein = namedtuple("SpatterVein", "vtable, address, mat1, unk1, mat2, mat3, intensity")
Settlement = namedtuple("Settlement", "origin, name, world_pos, local_pos")
Attribute = namedtuple("Attribute", "level, field_4, field_8, field_C, leveldiff, field_14, field_18");
Skill = namedtuple("Skill", "id, experience, rating")
Tree = namedtuple("Tree", "type, material, position, address")
CreatureCaste = namedtuple("CreatureCaste", "rawname, singular, plural, adjective")
CreatureTypeEx = namedtuple("CreatureTypeEx", "rawname, castes, tile_character, tilecolor")
TileColor = namedtuple("TileColor", "fore, back, bright")
Name = namedtuple("Name", "first_name, nickname, language, has_name, words, parts_of_speech")
char_array = c_char * 128
class Soul(object):
def __init__(self, *args, **kwds):
if kwds:
for k, v in kwds.iteritems():
self.__dict__[k] = v
class MapBlock40d(object):
pass
class ViewScreen(Structure):
_fields_ = [("type", c_int)]
class Matgloss(Structure):
_fields_ = [("id", char_array),
("fore", c_byte),
("back", c_byte),
("bright", c_byte),
("name", char_array)]
class Descriptor_Color(Structure):
_fields_ = [("id", char_array),
("r", c_float),
("v", c_float),
("b", c_float),
("name", char_array)]
class MatglossOther(Structure):
_fields_ = [("rawname", char_array)]

@ -1,20 +0,0 @@
# -*- coding: utf-8 -*-
"""
Python class for DF_Hack::Translation
"""
from ._pydfhack import _TranslationManager
from .mixins import NeedsStart
from .decorators import suspend
class Translation(NeedsStart, _TranslationManager):
api = None
cls = _TranslationManager
def __init__(self, api, *args, **kwds):
self.cls.__init__(self, args, kwds)
self.api = api
def get_dictionaries(self):
return self.dictionaries
def Translate_Name(self, *args, **kw):
return self.cls.Translate_Name(self, *args, **kw)

@ -1,18 +0,0 @@
# -*- coding: utf-8 -*-
"""
Python class for DF_Hack::Vegetation
"""
from ._pydfhack import _VegetationManager
from .mixins import NeedsStart
from .decorators import suspend
class Vegetation(NeedsStart, _VegetationManager):
api = None
cls = _VegetationManager
def __init__(self, api, *args, **kwds):
self.cls.__init__(self, args, kwds)
self.api = api
@suspend
def Read(self, *args, **kw):
return self.cls.Read(self, *args, **kw)

@ -1,59 +0,0 @@
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from distutils.core import Extension
from os import path
import platform
if platform.system() == 'Windows':
# dfhack.lib location can differ, search for it
for libdir in ["..", path.join("..",".."), path.join("..", "..", "output"), path.join("..", "..", "output", "Release")]:
if path.isfile(path.join(libdir, "dfhack.lib")):
lib_dirs = libdir
libraries=["dfhack"]
break
if path.isfile(path.join(libdir, "libdfhack.dll")):
lib_dirs = libdir
libraries = ["libdfhack"]
break
else:
raise Exception("dfhack.lib is not found")
osspec = dict(library_dirs=[lib_dirs],
libraries=libraries)
elif platform.system() == 'Linux':
osspec = dict(extra_compile_args=["-DLINUX_BUILD", "-w"],
library_dirs=[path.join("..","..","output")],
libraries=["dfhack"])
e = Extension("pydfhack._pydfhack",
sources=["DF_API.cpp", "DF_Buildings.cpp", "DF_Constructions.cpp", "DF_CreatureManager.cpp",\
"DF_GUI.cpp", "DF_Maps.cpp", "DF_Material.cpp", "DF_Position.cpp", "DF_Translate.cpp",\
"DF_Vegetation.cpp", "pydfhack.cpp"],
include_dirs=["../", path.join("..", "include"), path.join("..","depends","md5"), path.join("..","depends","tinyxml")],
export_symbols=["init_pydfhack", "ReadRaw", "WriteRaw"],
**osspec)
for file in ["Memory.xml", path.join("..","..","output","Memory.xml")]:
if path.isfile(file):
datafile = file
break
else:
raise Exception("Memory.xml is not found.")
setup(
name="PyDFHack",
description="Python wrapper and bindings for DFHack library",
version="1.0",
packages=find_packages(exclude=['ez_setup']),
data_files=[('pydfhack', [datafile])],
include_package_data=True,
test_suite='nose.collector',
zip_safe=False,
ext_modules=[e],
)

@ -1,9 +0,0 @@
# -*- coding: utf-8 -*-
import pydfapi
print "Attempting to initialize pydfhack...",
DF = pydfapi.API()
Map = pydfapi.Map()
Vegetation = pydfapi.Vegetation()
GUI = pydfapi.GUI()
print "OK"

@ -1,38 +0,0 @@
#!/usr/bin/python
import sys
import pydfhack
DF = pydfhack.API("Memory.xml")
DF.Attach()
pos = DF.position
maps = DF.maps
refc = dict(pydfhack=pydfhack, API=pydfhack.API, DF=DF, pos=pos, maps=maps)
cursor = pos.get_cursor()
msize = maps.get_size()
block = None
tile = None
if cursor:
block = maps.get_block(point=cursor)
if block:
tile = block.get_tile(point=cursor)
DF.Resume()
locs = dict(pydfhack=pydfhack, API=pydfhack.API, DF=DF, pos=pos, maps=maps, msize=msize, cursor=cursor, block=block, tile=tile)
banner = """DFHack Shell\n\n"""\
"""\tpydfhack = {pydfhack}\n"""\
"""\tAPI = {API}\n"""\
"""\tDF = {DF}\n"""\
"""\tpos = {pos}\n"""\
"""\tmaps = {maps}\n"""\
"""\tmsize = {msize}\n"""\
"""\tcursor = {cursor}\n"""\
"""\tblock = {block}\n"""\
"""\ttile = {tile}\n""".format(**locs)
from IPython.Shell import IPShellEmbed
shell = IPShellEmbed()
shell.set_banner(shell.IP.BANNER + '\n\n' + banner)
shell(local_ns=locs, global_ns={})
DF.Detach()

@ -1,45 +0,0 @@
#!/usr/bin/python
import sys
import pydfhack
from pydfhack.blocks import Point
DF = pydfhack.API("Memory.xml")
DF.Attach()
pos = DF.position
maps = DF.maps
cursor = pos.get_cursor()
refc = dict(pydfhack=pydfhack, API=pydfhack.API, DF=DF, pos=pos, maps=maps)
msize = maps.get_size()
print msize
locs = dict(pydfhack=pydfhack, API=pydfhack.API, DF=DF, pos=pos, maps=maps, msize=msize, cursor=cursor)
for z in range(msize[2]):
trees = 0
saplings = 0
dead_saplings = 0
for x in range(msize[0]):
for y in range(msize[1]):
p = Point(x, y, z, True)
block = maps.get_block(point=p)
changed = False
if not block.tiles:
break
for tx in range(16):
for ty in range(16):
tile = block.tiles[tx][ty]
if tile.ttype == 24:
trees += 1
elif tile.ttype == 231:
saplings += 1
tile.ttype = 24
changed = True
elif tile.ttype == 392:
dead_saplings += 1
tile.ttype = 24
changed = True
if changed:
block.save()
print "Saved block {0}".format(block)
print "Z-Level {0}: Trees {1}, Saplings {2}, Dead saplings {3}".format(z, trees, saplings, dead_saplings)
DF.Resume()
DF.Detach()