code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
from test_core import *
from test_admin import *
| Python |
"""
Celery functions to be processed in a non-blocking distributed manner.
"""
import os
import re
import shutil
import time
from celery.contrib.abortable import AbortableTask
from celery.task import PeriodicTask
from datetime import datetime, timedelta
from django.conf import settings
from ocradmin.core import utils
from ocradmin.vendor import deepzoom
from ocradmin.projects.models import Project
class UnhandledCreateDzi(AbortableTask):
name = "_create.dzi"
def run(self, filepath, path, **kwargs):
"""
Create a DZI of the given file, as <path>/dzi/<basename>.
"""
logger = self.get_logger()
# find the deepzoom path
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
if not os.path.exists(path):
creator = deepzoom.ImageCreator(tile_size=512,
tile_overlap=2, tile_format="png",
image_quality=1, resize_filter="nearest")
logger.debug("Creating DZI path: %s", path)
creator.create(filepath, path)
return dict(out=utils.media_path_to_url(filepath),
dst=utils.media_path_to_url(path))
class UnhandledCreateDocDzi(AbortableTask):
name = "_create.docdzi"
def run(self, project_pk, pid, attr, **kwargs):
"""
Create a DZI of the given document, as <path>/dzi/<basename>.
"""
logger = self.get_logger()
project = Project.objects.get(pk=project_pk)
storage = project.get_storage()
doc = storage.get(pid)
path = storage.document_attr_dzi_path(doc, attr)
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
if not os.path.exists(path):
with storage.document_attr_content(doc, attr) as handle:
creator = deepzoom.ImageCreator(tile_size=512,
tile_overlap=2, tile_format="png",
image_quality=1, resize_filter="nearest")
logger.debug("Creating DZI path: %s", path)
creator.create(handle, path)
return dict(pid=pid, dst=utils.media_path_to_url(path))
class CleanupTempTask(PeriodicTask):
"""
Periodically cleanup images in the settings.MEDIA_ROOT/temp
directory. Currently they're swept if they're over 10 minutes
old.
"""
name = "cleanup.temp"
run_every = timedelta(seconds=600)
relative = True
ignore_result = True
def run(self, **kwargs):
"""
Clean the modia folder of any files that haven't
been accessed for X minutes.
"""
import glob
logger = self.get_logger()
tempdir = os.path.join(settings.MEDIA_ROOT,
settings.TEMP_PATH)
if not os.path.exists(tempdir):
return
for userdir in glob.glob("%s/*" % tempdir):
if not os.path.isdir(userdir):
continue
logger.debug("Checking dir: %s" % userdir)
fdirs = [d for d in sorted(os.listdir(userdir)) \
if re.match("\d{14}", d)]
if not fdirs:
continue
# keep the latest, then delete everything
# else not accessed in the last 10 mins
logger.info("Retaining: %s" % os.path.join(userdir, fdirs.pop()))
for fdir in fdirs:
# convert the dir last accessed time to a datetime
dtm = datetime(*time.localtime(
os.path.getmtime(os.path.join(userdir, fdir)))[0:6])
delta = datetime.now() - dtm
if delta.days < 1 and (delta.seconds / 60) <= 10:
logger.info("Retaining: %s" % os.path.join(userdir, fdir))
continue
logger.info("Cleanup directory: %s" % os.path.join(userdir, fdir))
try:
shutil.rmtree(os.path.join(userdir, fdir))
except StandardError, err:
logger.critical(
"Error during cleanup: %s" % err.message)
| Python |
"""
Basic OCR functions. Submit OCR tasks and retrieve the result.
"""
import os
import shutil
from django.core import serializers
from django.http import HttpResponse, HttpResponseRedirect, \
HttpResponseServerError, HttpResponseNotFound
from django.core.serializers.json import DjangoJSONEncoder
from django.shortcuts import render, render_to_response, get_object_or_404
from django.template import RequestContext
from ocradmin.documents import status as docstatus
from django.utils import simplejson as json
from django.views.decorators.csrf import csrf_exempt
from ocradmin.core import utils as ocrutils
from ocradmin.nodelib import utils as pluginutils
from ocradmin.core.decorators import saves_files, project_required
from ocradmin.ocrtasks.models import OcrTask
from ocradmin.presets.models import Preset
from ocradmin.core.decorators import project_required
class AppException(StandardError):
"""
Most generic app error.
"""
pass
def index(request):
"""
OCR index page.
"""
return HttpResponseRedirect("/presets/builder/")
def abort(request, task_id):
"""
Kill a running celery task.
"""
OcrTask.revoke_celery_task(task_id, kill=True)
out = dict(
task_id=task_id,
status="ABORT"
)
response = HttpResponse(mimetype="application/json")
json.dump(out, response, ensure_ascii=False)
return response
@csrf_exempt
@project_required
def update_ocr_task(request, pid):
"""
Re-save the params for a task and resubmit it,
redirecting to the transcript page.
"""
storage = request.project.get_storage()
doc = storage.get(pid)
# FIXME: This is fragile! It might not get the
# exact task that wrote the script! Need to find
# a more robust way of linking the two, like writing
# the task_id to the script metadata...
try:
task = OcrTask.objects.filter(page_name=doc.pid)\
.order_by("-updated_on")[0]
except IndexError:
return HttpResponseNotFound
script = request.POST.get("script")
ref = request.POST.get("ref", "/batch/show/%d/" % task.batch.pk)
json.loads(script)
task.args = (task.args[0], task.args[1], script)
task.save()
doc.ocr_status = docstatus.RUNNING
doc.save()
task.retry()
return HttpResponseRedirect(ref)
def task_config(request, task_pk):
"""
Get a task config as a set of key/value strings.
"""
task = get_object_or_404(OcrTask, pk=task_pk)
path, script, outdir = task.args
return HttpResponse(script, mimetype="application/json")
def result(request, task_id):
"""
Fetch the result for one Celery task id.
"""
async = OcrTask.get_celery_result(task_id)
out = dict(
task_id=async.task_id,
status=async.status,
results=async.result
)
response = HttpResponse(mimetype="application/json")
json.dump(out, response, ensure_ascii=False)
return response
def results(request, task_ids):
"""
Fetch the results of several Celery task ids.
"""
out = []
for task_id in task_ids.split(","):
async = OcrTask.get_celery_result(task_id)
out.append(dict(
result=_flatten_result(async.result),
task_id=task_id,
status=async.status,
))
response = HttpResponse(mimetype="application/json")
json.dump(out, response, ensure_ascii=False)
return response
def test(request):
"""
Dummy action for running JS unit tests. Probably needs to
be put somewhere else.
"""
return render_to_response("ocr/test.html", {})
def testlayout(request):
"""
Dummy action for running JS unit tests. Probably needs to
be put somewhere else.
"""
return render_to_response("ocr/testlayout.html", {})
def testparams(request):
"""
Dummy action for running JS unit tests. Probably needs to
be put somewhere else.
"""
return render_to_response("ocr/testparams.html", {})
def _flatten_result(result):
"""
Ensure we can serialize a celery result.
"""
if issubclass(type(result), Exception):
return result.message
else:
return result
| Python |
#!/usr/bin/python
"""
Cruddy script for binarizing files via the OCR web UI.
"""
import os
import sys
import tempfile
import subprocess as sp
import httplib2
import time
from optparse import OptionParser
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib
import urllib2
import simplejson
SITE = "http://ocr1.cerch.kcl.ac.uk"
LOGIN = "/accounts/login"
BINURL = "/ocr/binarize/"
RESURL = "/ocr/results/"
USERNAME = "cerch"
PASSWORD = "1want0cr"
cookie = tempfile.NamedTemporaryFile()
cookie.close()
class OcrAdmin(object):
def __init__(self, options):
self.opts = options
self.http = httplib2.Http()
self.authheaders = None
self.tokens = []
def login(self):
"""
Login and save the cookie
"""
body = {"username": USERNAME, "password": PASSWORD}
headers = {"Content-type": "application/x-www-form-urlencoded"}
response, content = self.http.request(
"%s%s" % (self.opts.host, LOGIN),
"POST", headers=headers, body=urllib.urlencode(body))
self.authheaders = {"Cookie": response["set-cookie"]}
def upload(self, files):
"""
Upload files to be binarized.
"""
if self.authheaders is None:
self.login()
# Register the streaming http handlers with urllib2
register_openers()
count = 1
for f in files:
self.tokens.append(self.upload_file(f, count))
count += 1
def upload_file(self, filename, count):
"""
Upload a file to the server.
"""
handle = open(filename, "rb")
params = {"image%s" % count: handle}
if self.opts.clean:
params["clean"] = self.opts.clean
datagen, headers = multipart_encode(
params)
headers.update(self.authheaders)
# Create the Request object
request = urllib2.Request("%s%s" % (self.opts.host, BINURL), datagen, headers)
# Actually do the request, and get the response
print "Uploading: %s" % filename
token = simplejson.load(urllib2.urlopen(request))[0]
token["file"] = filename
token["count"] = count
handle.close()
return token
def get_result(self, token):
"""
Get results for a job.
"""
url = "%s%s%s" % (self.opts.host, RESURL, token["task_id"])
data = {} #{"format": "png"}
#response, content = self.http.request(url, "GET",
# urllib.urlencode(data), headers=self.authheaders)
request = urllib2.Request(url,
urllib.urlencode(data), headers=self.authheaders)
#print request
response = urllib2.urlopen(request)
#print response.read()
content = response.read()
#print "CONTENT: " + content
outtoken = simplejson.loads(content)
#print outtoken
if outtoken["results"] is None:
return False
if not os.path.exists(self.opts.outdir):
os.makedirs(self.opts.outdir)
outfile = "%s/%04d.bin.png" % (self.opts.outdir, token["count"])
outurl = "%s%s" % (self.opts.host, outtoken["results"]["out"])
outreq = urllib2.Request(outurl,
urllib.urlencode(data), headers=self.authheaders)
outhandle = open(outfile, "wb")
outhandle.write(urllib2.urlopen(outreq).read())
outhandle.close()
print "Wrote: %s" % outfile
return True
def get_results(self):
"""
Poll for results.
"""
while True:
retries = []
while self.tokens:
token = self.tokens.pop(0)
if not self.get_result(token):
retries.append(token)
time.sleep(0.05)
if not retries:
break
self.tokens = retries
if __name__ == "__main__":
usage = "%prog [options] file1.png file2.png"
version = "%prog 1.00"
parser = OptionParser(usage=usage, version=version)
parser.add_option("--host", action="store", dest="host",
default=SITE, help="Site URL")
parser.add_option("-o", "--outdir", action="store", dest="outdir",
default="book", help="Output directory name")
parser.add_option("-c", "--clean", action="store", dest="clean",
default="StandardPreprocessing", help="Cleanup preset")
parser.add_option("-d", "--debug", action="store_true", dest="debug",
help="show debug information")
(options, args) = parser.parse_args()
ocr = OcrAdmin(options)
ocr.upload(args)
ocr.get_results()
| Python |
"""
Object representing a helper file for an OCR app.
"""
import datetime
from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User, related_name="ocrmodels")
derived_from = models.ForeignKey("self", null=True, blank=True, related_name="derivees")
tags = TagField()
name = models.CharField(max_length=100, unique=True)
description = models.TextField(blank=True)
created_on = models.DateField(editable=False)
updated_on = models.DateField(editable=False, null=True, blank=True)
public = models.BooleanField(default=True)
file = models.FileField(upload_to="models")
type = models.CharField(max_length=20,
choices=[("char", "Character"), ("lang", "Language")])
app = models.CharField(max_length=20,
choices=[("ocropus", "Ocropus"), ("tesseract", "Tesseract")])
def __unicode__(self):
"""
String representation.
"""
return self.name
def save(self):
if not self.id:
self.created_on = datetime.datetime.now()
else:
self.updated_on = datetime.datetime.now()
super(OcrModel, self).save()
def get_absolute_url(self):
"""URL to view an object detail"""
return "/ocrmodels/show/%i/" % self.id
def get_update_url(self):
"""url to update an object detail"""
return "/ocrmodels/edit/%i/" % self.id
def get_delete_url(self):
"""url to update an object detail"""
return "/ocrmodels/delete/%i/" % self.id
@classmethod
def get_list_url(cls):
"""URL to view the object list"""
return "/ocrmodels/list/"
@classmethod
def get_create_url(cls):
"""URL to create a new object"""
return "/ocrmodels/create/"
| Python |
import subprocess as sp
def get_ocropus_model_info(path):
"""
Get the info about an ocropus model/
"""
proc = sp.Popen(["ocropus", "cinfo", path], stdout=sp.PIPE)
return proc.stdout.read()
def get_tesseract_model_info(path):
"""
Get info about Tesseract models.
"""
return ""
| Python |
import os
import shutil
from django.conf import settings
from django.contrib.auth.models import User
from django.test import TestCase
from django.test.client import Client
from django.utils import simplejson
from ocradmin.core.tests import testutils
from ocradmin.ocrmodels.models import OcrModel
AJAX_HEADERS = {
"HTTP_X_REQUESTED_WITH": "XMLHttpRequest"
}
class OcrModelTest(TestCase):
fixtures = ["test_fixtures.json"]
def setUp(self):
"""
Setup OCR tests. Creates a test user.
"""
testutils.symlink_model_fixtures()
self.testuser = User.objects.create_user("test_user", "test@testing.com", "testpass")
self.client = Client()
self.client.login(username="test_user", password="testpass")
def tearDown(self):
"""
Cleanup a test.
"""
self.testuser.delete()
def test_ocrmodels_view(self):
"""
Test basic list view
"""
self.assertEqual(self.client.get("/ocrmodels/").status_code, 200)
def test_search(self):
"""
Test the search function that returns JSON data.
"""
r = self.client.get("/ocrmodels/search", dict(app="ocropus", type="char"))
self.assertEqual(r.status_code, 200)
self.assertEqual(r["Content-Type"], "application/json")
content = simplejson.loads(r.content)
self.assertEqual(len(content), 1)
def test_tag_filter(self):
"""
Test filtering by tag.
"""
r = self.client.get("/ocrmodels/list", {"tag": "test"})
self.assertEqual(r.status_code, 200)
def test_new_ajax_form(self):
"""
Test requesting a new upload form via Ajax works.
"""
r = self.client.get("/ocrmodels/create", {}, **AJAX_HEADERS)
self.assertEqual(r.status_code, 200)
# make sure there's a form in the results
self.assertTrue(r.content.find("<fieldset") != -1)
def test_create_model_ajax(self):
"""
Test creating a new model from an uploaded file.
"""
# we shouldn't have any ocrmodels in the DB yet. If
# successful it'll redirect back to the list.
before = OcrModel.objects.count()
r = self._create_test_model()
self.assertEqual(r.status_code, 302)
self.assertEqual(before + 1, OcrModel.objects.count())
def test_edit_model_view(self):
"""
Test viewing the edit for (no Ajax).
"""
r = self.client.get("/ocrmodels/edit/1/")
self.assertEqual(r.status_code, 200)
def test_edit_model_not_found(self):
"""
Test viewing the edit form for a non-existant item. Note:
horrible hardcoding of "high" primary key.
"""
r = self.client.get("/ocrmodels/edit/666/")
self.assertEqual(r.status_code, 404)
def test_update_model(self):
"""
Test the updating of the fixture model.
"""
r = self._update_test_model()
self.assertEqual(r.status_code, 302)
model = OcrModel.objects.get(pk=1)
self.assertEqual(model.description, "")
def _create_test_model(self):
"""
Insert a post test model view post
"""
modelpath = OcrModel.objects.all()[0].file.path
with open(modelpath) as tf:
r = self.client.post(
"/ocrmodels/create",
dict(
user=self.testuser.pk,
tags="test model",
name="Test Model",
description="Testing model creation",
public=True,
app="ocropus",
type="char",
file=tf,
),
)
return r
def _update_test_model(self):
"""
Update the fixture model.
"""
return self.client.post(
"/ocrmodels/edit/1/",
dict(
name="Test Update Model",
tags="test model update",
app="ocropus",
type="char",
description="",
public=False,
),
)
| Python |
from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from ocradmin.ocrmodels import views
urlpatterns = patterns('',
(r'^/?$', views.modellist),
(r'^list/?$', views.modellist),
(r'^show/(?P<pk>\d+)/$', views.modeldetail),
(r'^create/?$', login_required(views.modelcreate)),
(r'^edit/(?P<pk>\d+)/$', login_required(views.modeledit)),
(r'^delete/(?P<pk>\d+)/$', login_required(views.modeldelete)),
(r'^search$', views.search),
)
| Python |
"""
Create default app models. Models must be in the etc/defaultmodels directory
and be named thus: <app>_other_stuff_<type>.extension, where <app> is either
'ocropus' or 'tesseract' and <type> is either 'char' or 'lang'.
"""
import os
import sys
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from ocradmin.ocrmodels.models import OcrModel
from django.core.exceptions import ImproperlyConfigured
from django.core.files.base import File
MODELDIR = "etc/defaultmodels"
class Command(BaseCommand):
args = ""
help = "Creates the default model db entries for Ocropus & Tesseract"
def handle(self, *args, **options):
try:
adminuser = User.objects.get(is_superuser=True)
except User.DoesNotExist:
raise ImproperlyConfigured(
"An admin user must exist before default models can be added.")
for fname in os.listdir(MODELDIR):
if fname.startswith("."):
continue
basename = os.path.splitext(fname)[0]
nameparts = basename.split("_")
if not nameparts[0] in ("ocropus", "tesseract"):
continue
if not nameparts[-1] in ("char", "lang"):
continue
name = " ".join([p.title() for p in nameparts])
try:
exists = OcrModel.objects.get(name=name)
exists.delete()
except OcrModel.DoesNotExist:
pass
with open(os.path.join(MODELDIR, fname), "rb") as fh:
model = OcrModel(
name=name,
app=nameparts[0],
type=nameparts[-1],
public=True,
tags=" ".join(nameparts),
user=adminuser,
file=File(fh, fname)
)
model.save()
| Python |
from django import forms
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib import messages
from django.core import serializers
from django.db.models import Q
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.template import Template, Context
from django.template.loader import get_template
from tagging.models import TaggedItem
from ocradmin.ocrmodels import utils as ocrutils
from ocradmin.ocrmodels.models import OcrModel
from ocradmin.core import generic_views as gv
class OcrModelForm(forms.ModelForm):
"""
Base model form
"""
ALLOWED_FILE_TYPES = (
"application/octet-stream",
"application/x-gzip",
"application/x-compressed-tar")
def __init__(self, *args, **kwargs):
super(OcrModelForm, self).__init__(*args, **kwargs)
# change a widget attribute:
self.fields['description'].widget.attrs["rows"] = 2
self.fields['description'].widget.attrs["cols"] = 40
def clean_file(self):
"""
Validate allowed data types.
"""
data = self.cleaned_data["file"]
if not data.content_type in self.ALLOWED_FILE_TYPES:
raise forms.ValidationError(
"Bad file type: %s. Must be one of: %s" % (
data.content_type,
", ".join(self.ALLOWED_FILE_TYPES)))
return data
class Meta:
model = OcrModel
fields = ["name", "file", "description",
"public", "app", "type", "tags", "user"]
exclude = ["updated_on", "derived_from"]
widgets = dict(
user=forms.HiddenInput()
)
class OcrModelEditForm(OcrModelForm):
"""
Form for editing the few changable fields on an already
existing model.
"""
def __init__(self, *args, **kwargs):
super(OcrModelEditForm, self).__init__(*args, **kwargs)
class Meta:
model = OcrModel
fields = ["name", "description", "public", "tags", "app", "type"]
exclude = ["user", "updated_on", "derived_from"]
modellist = gv.GenericListView.as_view(
model=OcrModel,
page_name="OCR Models",
fields=["name", "description", "user", "created_on"],)
modelcreate = gv.GenericCreateView.as_view(
model=OcrModel,
enctype="multipart/form-data",
form_class=OcrModelForm,
page_name="New OCR Model",)
modeldetail = gv.GenericDetailView.as_view(
model=OcrModel,
page_name="OCR Model",
fields=["name", "description", "type", "app", "user", "public",
"file", "derived_from", "tags", "created_on",
"updated_on",])
modeledit = gv.GenericEditView.as_view(
model=OcrModel,
enctype="multipart/form-data",
form_class=OcrModelEditForm,
page_name="Edit OCR Model",)
modeldelete = gv.GenericDeleteView.as_view(
model=OcrModel,
page_name="Delete OCR Model",
success_url="/ocrmodels/list/",)
def model_query(user, order, **params):
"""
Query the model set.
"""
tag = params.get("tag")
try:
del params["tag"]
except KeyError:
pass
query = Q(public=True) | (Q(public=False) & Q(user=user))
for key, val in params.items():
ld = {key: val}
query = query & Q(**ld)
# if there's a tag present search by tagged item
if tag:
return TaggedItem.objects.get_by_model(
OcrModel.objects.filter(query),
tag).order_by(*order)
else:
return OcrModel.objects.filter(query).order_by(*order)
@login_required
def search(request):
"""
Search specific model types.
"""
qd = {}
for key, val in request.GET.items():
if key in ("app", "type"):
qd[str(key)] = str(val)
mods = model_query(request.user, ["name", "created_on"],
tag=request.GET.get("tag"), **qd)
return HttpResponse(serializers.serialize("json", mods),
mimetype="application/json")
| Python |
from django.conf import settings
from django.test.simple import DjangoTestSuiteRunner
USAGE = """\
Custom test runner to allow testing of celery delayed tasks.
"""
class CeleryTestSuiteRunner(DjangoTestSuiteRunner):
def run_tests(self, test_labels, *args, **kwargs):
"""Django test runner allowing testing of celery delayed tasks.
All tasks are run locally, not in a worker.
"""
settings.CELERY_ALWAYS_EAGER = True
return super(CeleryTestSuiteRunner, self).run_tests(test_labels,
*args, **kwargs)
| Python |
"""
Object representing an OCR project, used to group files, batches,
and presets.
"""
import datetime
from django.db import models
from django.contrib.auth.models import User
from tagging import fields as taggingfields
import autoslug
from ocradmin.core import utils as ocrutils
from ocradmin.storage import registry
class Project(models.Model):
"""
OCR Project model.
"""
name = models.CharField(max_length=255, unique=True)
slug = autoslug.AutoSlugField(populate_from="name", unique=True)
description = models.TextField(blank=True)
tags = taggingfields.TagField()
storage_backend = models.CharField(max_length=255,
choices=[(k, k) for k in registry.stores.keys()])
created_on = models.DateTimeField(editable=False)
updated_on = models.DateTimeField(blank=True, null=True, editable=False)
def __unicode__(self):
"""
String representation.
"""
return self.name
def storage_config_dict(self):
"""Return a dictionary of storage config values."""
return dict([(c.name, c.value) \
for c in self.storage_config_values.all()])
def get_storage(self):
backend = registry.stores[self.storage_backend]
return backend(**self.storage_config_dict())
def save(self):
if not self.id:
self.created_on = datetime.datetime.now()
else:
self.updated_on = datetime.datetime.now()
super(Project, self).save()
def get_absolute_url(self):
"""URL to view an object detail"""
return "/projects/show/%i/" % self.id
def get_update_url(self):
"""url to update an object detail"""
return "/projects/edit/%i/" % self.id
def get_delete_url(self):
"""url to update an object detail"""
return "/projects/delete/%i/" % self.id
@classmethod
def get_list_url(cls):
"""URL to view the object list"""
return "/projects/list/"
@classmethod
def get_create_url(cls):
"""URL to create a new object"""
return "/projects/create/"
class ProjectStorageConfig(models.Model):
"""Project storage config values."""
project = models.ForeignKey(Project, related_name="storage_config_values")
name = models.CharField(max_length=255)
value = models.CharField(max_length=255)
def __unicode__(self):
"""
String representation.
"""
return u"<%s='%s'>" % (self.name, self.value)
| Python |
import os
import shutil
from django.conf import settings
from django.contrib.auth.models import User
from django.test import TestCase
from django.test.client import Client
from django.utils import simplejson
from ocradmin.projects.models import Project
AJAX_HEADERS = {
"HTTP_X_REQUESTED_WITH": "XMLHttpRequest"
}
class ProjectsTest(TestCase):
fixtures = ["test_fixtures.json"]
def setUp(self):
"""
Setup OCR tests. Creates a test user.
"""
self.testuser = User.objects.create_user("test_user", "test@testing.com", "testpass")
self.client = Client()
self.client.login(username="test_user", password="testpass")
def tearDown(self):
"""
Cleanup a test.
"""
self.testuser.delete()
def test_projects_view(self):
"""
Test basic list view
"""
self.assertEqual(self.client.get("/projects/").status_code, 200)
def test_tag_filter(self):
"""
Test filtering by tag.
"""
r = self.client.get("/projects/list", {"tag": "test"})
self.assertEqual(r.status_code, 200)
def test_new_ajax_form(self):
"""
Test requesting a new upload form via Ajax works.
"""
r = self.client.get("/projects/create/", {}, **AJAX_HEADERS)
self.assertEqual(r.status_code, 200)
# make sure there's a form in the results
self.assertTrue(r.content.find("<fieldset") != -1)
def test_create_project_ajax(self):
"""
Test creating a new project from an uploaded file.
"""
# we shouldn't have any projects in the DB yet. If
# successful it'll redirect back to the list.
before = Project.objects.count()
r = self._create_test_project()
self.assertEqual(r.status_code, 302)
self.assertEqual(before + 1, Project.objects.count())
def test_edit_project_view(self):
"""
Test viewing the edit for (no Ajax).
"""
r = self.client.get("/projects/edit/1/")
self.assertEqual(r.status_code, 200)
def test_edit_project_not_found(self):
"""
Test viewing the edit form for a non-existant item.
"""
r = self.client.get("/projects/edit/666666/")
self.assertEqual(r.status_code, 404)
def test_update_project(self):
"""
Test the updating of the fixture project.
"""
r = self._update_test_project()
self.assertEqual(r.status_code, 302)
project = Project.objects.get(pk=1)
self.assertEqual(project.description, "")
def test_confirm_delete(self):
"""
Test checking if the user wants to delete a project.
"""
r = self._create_test_project()
project = Project.objects.get(pk=1)
r = self.client.get("/projects/delete/1/")
self.assertEqual(r.status_code, 200)
def test_delete_project(self):
"""
Test actually deleting a project.
"""
r = self._create_test_project()
before = Project.objects.count()
r = self.client.post("/projects/delete/1/")
self.assertEqual(r.status_code, 302)
after = Project.objects.count()
self.assertEqual(before, after + 1)
def _create_test_project(self):
"""
Insert a post test project view post
"""
return self.client.post(
"/projects/create", {
"0-name" : "Yet ANother test",
"0-description" : "",
"0-storage_backend" : "FedoraStorage",
"0-tags" : "",
"1-root" : "localhost:8080/fedora",
"1-image_name" : "IMG",
"1-password" : "fedora",
"1-namespace" : "yet-another-test",
"1-transcript_name" : "TRANSCRIPT",
"1-username" : "fedoraAdmin",
"hash_0" : "89075382b10c271f10c479251fa68c057242ba40",
"wizard_step" : "1",
}
)
def _update_test_project(self):
"""
Update the fixture project.
"""
return self.client.post(
"/projects/edit/1/",
dict(
name="Test Update Project",
tags="test project update",
storage_backend="FileSystemStorage",
description="",
),
)
| Python |
"""
URLConf for OCR projects.
"""
from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from ocradmin.projects import views
urlpatterns = patterns('',
(r'^/?$', login_required(views.projectlist)),
(r'^list/?$', login_required(views.projectlist)),
(r'^create/?$', views.ProjectWizard(
[views.ProjectForm, views.DummyStorageForm])),
(r'^show/(?P<pk>\d+)/?$', login_required(views.projectdetail)),
(r'^edit/(?P<pk>\d+)/?$', login_required(views.projectedit)),
(r'^delete/(?P<pk>\d+)/?$', login_required(views.projectdelete)),
(r'^open/?$', login_required(views.projectlist)),
(r'^close/?$', login_required(views.close)),
(r'^load/(?P<project_pk>\d+)/$', login_required(views.load)),
)
| Python |
"""
Celery functions to be processed in a non-blocking distributed manner.
"""
| Python |
"""
Project-related view functions.
"""
import os
from datetime import datetime
from django import forms
from django.conf import settings
from django.contrib.formtools.wizard import FormWizard
from django.contrib import messages
from django.core import serializers
from django.template.defaultfilters import slugify
from django.db import transaction
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.template.defaultfilters import slugify
from tagging.models import TaggedItem
from ocradmin.core import utils as ocrutils
from ocradmin.ocrtasks.models import OcrTask
from ocradmin.batch.models import Batch
from ocradmin.projects.models import Project
from ocradmin.core import generic_views as gv
from fedora.adaptor import fcobject
from ordereddict import OrderedDict
PER_PAGE = 10
from ocradmin import storage
class ExportForm(forms.Form):
"""
Fedora Export form.
"""
username = forms.CharField(max_length=50)
password = forms.CharField(max_length=255,
widget=forms.PasswordInput(render_value=False))
repository_url = forms.CharField(max_length=255)
namespace = forms.CharField(max_length=255)
class DublinCoreForm(forms.Form):
"""
Dublin Core Metadata form.
"""
title = forms.CharField(max_length=255)
creator = forms.CharField(max_length=255)
subject = forms.CharField(max_length=255)
description = forms.CharField(max_length=255, required=False)
publisher = forms.CharField(max_length=255, required=False)
contributors = forms.CharField(max_length=255, required=False)
date = forms.DateField(required=False)
type = forms.CharField(max_length=255, required=False)
format = forms.CharField(max_length=255, required=False)
identifier = forms.CharField(max_length=255, required=False)
source = forms.CharField(max_length=255, required=False)
language = forms.CharField(max_length=255, required=False)
relation = forms.CharField(max_length=255, required=False)
coverage = forms.CharField(max_length=255, required=False)
right = forms.CharField(max_length=255, required=False)
class ProjectForm(forms.ModelForm):
"""New project form."""
def __init__(self, *args, **kwargs):
super(forms.ModelForm, self).__init__(*args, **kwargs)
# change a widget attribute:
self.fields['description'].widget.attrs["rows"] = 2
self.fields['description'].widget.attrs["cols"] = 40
class Meta:
model = Project
exclude = ["slug", "created_on", "storage_config_values",]
widgets = dict(
user=forms.HiddenInput(),
)
class DummyStorageForm(forms.Form):
"""Placeholder for dynamically-generated storage
config form."""
class ProjectWizard(FormWizard):
"""Wizard for project creation."""
def __init__(self, *args, **kwargs):
super(ProjectWizard, self).__init__(*args, **kwargs)
self.initial = {
0: {"storage_backend": "FedoraStorage"},
}
def process_step(self, request, form, step):
"""Dynamically configure the storage config form
given the storage backend specified in the first
wizard page."""
if step == 0:
backend = storage.get_backend(
form.cleaned_data["storage_backend"])
self.form_list[1] = backend.configform
self.initial[1] = backend.defaults
self.initial[1]["namespace"] = slugify(form.cleaned_data["name"])
return super(ProjectWizard, self).process_step(request, form, step)
def render_template(self, request, form, previous_fields, step, context=None):
self.extra_context.update(
model=Project,
page_name="New OCR Project: Step %d of %d" % (
step + 1, self.num_steps()
),
success_url="/projects/list/",
)
return super(ProjectWizard, self).render_template(request, form, previous_fields, step, context)
def get_template(self, step):
"""Get project wizard template."""
return "projects/create%d.html" % step
def done(self, request, form_list):
"""Save all form values and redirect to load page."""
project = form_list[0].instance
project.save()
for field, value in form_list[1].cleaned_data.iteritems():
project.storage_config_values.create(name=field, value=value)
return HttpResponseRedirect("/projects/load/%s/" % project.pk)
projectlist = gv.GenericListView.as_view(
model=Project,
page_name="OCR Projects",
fields=["name", "description", "user", "created_on"],)
projectcreate = gv.GenericCreateView.as_view(
model=Project,
form_class=ProjectForm,
page_name="New OCR Project",
success_url="/projects/load/%(id)s/",)
projectdetail = gv.GenericDetailView.as_view(
model=Project,
page_name="OCR Project",
fields=["name", "description", "user", "tags", "created_on",
"updated_on",])
projectedit = gv.GenericEditView.as_view(
model=Project,
form_class=ProjectForm,
page_name="Edit OCR Project",
success_url="/projects/load/%(id)s/",)
projectdelete = gv.GenericDeleteView.as_view(
model=Project,
page_name="Delete OCR Project",
success_url="/projects/list/",)
def project_query(user, order, **params):
"""
Query the model set.
"""
tag = params.get("tag")
try:
del params["tag"]
except KeyError:
pass
query = Q()
for key, val in params.items():
if key.find("__") == -1 and \
not key in Project._meta.get_all_field_names():
continue
ldata = {key: val}
query = query & Q(**ldata)
# if there's a tag present search by tagged item
if tag:
return TaggedItem.objects.get_by_model(
Project.objects.filter(query),
tag).order_by(*order)
else:
return Project.objects.filter(query).order_by(*order)
def load(request, project_pk):
"""
Open a project (load it in the session).
"""
project = get_object_or_404(Project, pk=project_pk)
request.session["project"] = project
return HttpResponseRedirect("/documents/list/")
def close(request):
"""
Close the current project.
"""
try:
del request.session["project"]
except KeyError:
pass
return HttpResponseRedirect("/ocr/")
| Python |
"""
Utils for document storage.
"""
import json
from . import base
class DocumentEncoder(json.JSONEncoder):
"""
Encoder for JSONifying documents.
"""
def default(self, doc):
"""Flatten node for JSON encoding."""
if issubclass(doc.__class__, base.BaseDocument):
return dict(
label=doc.label,
pid=doc.pid,
ocr_status=doc.ocr_status
)
return super(DocumentEncoder, self).default(doc)
| Python |
"""
Fedora storage backend.
"""
import io
import re
import urllib
from django import forms
from django.conf import settings
import eulfedora
import hashlib
from cStringIO import StringIO
from eulfedora.server import Repository
from eulfedora.models import DigitalObject, FileDatastream
from . import base
class ConfigForm(base.BaseConfigForm):
root = forms.CharField(max_length=255)
username = forms.CharField(max_length=255)
password = forms.CharField(max_length=255, widget=forms.PasswordInput)
image_name = forms.CharField(max_length=255)
transcript_name = forms.CharField(max_length=255)
class FedoraDocument(base.BaseDocument):
"""Fedora document class."""
def __init__(self, digiobj, *args, **kwargs):
self._doc = digiobj
super(FedoraDocument, self).__init__(self._doc.pid, *args, **kwargs)
@property
def pid(self):
return self._doc.pid
class FedoraStorage(base.BaseStorage):
"""Fedora Commons repository storage."""
configform = ConfigForm
defaults = dict(
root=getattr(settings, "FEDORA_ROOT", ""),
username=getattr(settings, "FEDORA_USER", ""),
password=getattr(settings, "FEDORA_PASS", ""),
namespace=getattr(settings, "FEDORA_PIDSPACE", ""),
image_name=getattr(settings, "FEDORA_IMAGE_NAME", ""),
transcript_name=getattr(settings, "FEDORA_TRANSCRIPT_NAME", "")
)
def __init__(self, *args, **kwargs):
super(FedoraStorage, self).__init__(*args, **kwargs)
self.namespace = kwargs["namespace"]
self.image_name = kwargs["image_name"]
self.thumbnail_name = "THUMBNAIL"
self.binary_name = "BINARY"
self.script_name = "OCR_SCRIPT"
self.transcript_name = kwargs["transcript_name"]
self.repo = Repository(
root=kwargs["root"], username=kwargs["username"],
password=kwargs["password"])
self.model = type("Document", (DigitalObject,), {
"default_pidspace": kwargs["namespace"],
"FILE_CONTENT_MODEL": "info:fedora/genrepo:File-1.0",
"CONTENT_MODELS": ["info:fedora/genrepo:File-1.0"],
"image": FileDatastream(self.image_name, "Document image", defaults={
'versionable': True,
}),
"binary": FileDatastream(self.binary_name, "Document image binary", defaults={
'versionable': True,
}),
"thumbnail": FileDatastream(self.thumbnail_name, "Document image thumbnail", defaults={
'versionable': True,
}),
"script": FileDatastream(self.script_name, "OCR Script", defaults={
"versionable": True,
}),
"transcript": FileDatastream(self.transcript_name, "Document transcript", defaults={
"versionable": True,
}),
"meta": FileDatastream("meta", "Document metadata", defaults={
"versionable": False,
}),
})
def read_metadata(self, doc):
meta = doc._doc.meta.content
if hasattr(meta, "read"):
meta = meta.read()
if not meta:
return {}
return dict([v.strip().split("=") for v in \
meta.split("\n") if re.match("^\w+=[^=]+$", v.strip())])
def write_metadata(self, doc, **kwargs):
meta = self.read_metadata(doc)
meta.update(kwargs)
metacontent = [u"%s=%s" % (k, v) for k, v in meta.iteritems()]
doc._doc.meta.content = "\n".join(metacontent)
def attr_uri(self, doc, attr):
"""URI for image datastream."""
return "%sobjects/%s/datastreams/%s/content" % (
self.repo.fedora_root,
urllib.quote(doc.pid),
getattr(self, "%s_name" % attr)
)
def document_label(self, doc):
"""Get the document label."""
return doc._doc.label
def document_attr_empty(self, doc, attr):
"""Check if document attr is empty."""
return getattr(doc._doc, attr).info.size == 0
def document_attr_label(self, doc, attr):
"""Get label for an image type attribute."""
return getattr(doc._doc, attr).label
def document_attr_mimetype(self, doc, attr):
"""Get mimetype for an image type attribute."""
return getattr(doc._doc, attr).mimetype
def document_attr_content_handle(self, doc, attr):
"""Get content for an image type attribute."""
handle = getattr(doc._doc, attr).content
return StringIO() if handle is None else handle
def document_metadata(self, doc):
"""Get document metadata. This currently
just exposes the DC stream attributes."""
return self.read_metadata(doc)
def _set_document_ds_content(self, doc, dsattr, content):
docattr = getattr(doc._doc, dsattr)
#checksum = hashlib.md5(content.read()).hexdigest()
#content.seek(0)
#docattr.checksum = checksum
#docattr.checksum_type = "MD5"
docattr.content = content
def set_document_attr_content(self, doc, attr, content):
"""Set image content."""
self._set_document_ds_content(doc, attr, content)
def set_document_attr_mimetype(self, doc, attr, mimetype):
"""Set image mimetype."""
getattr(doc._doc, attr).mimetype = mimetype
def set_document_attr_label(self, doc, attr, label):
"""Set image label."""
getattr(doc._doc, attr).label = label
def set_document_label(self, doc, label):
"""Set document label."""
doc._doc.label = label
def set_document_metadata(self, doc, **kwargs):
"""Set arbitrary document metadata."""
self.write_metadata(doc, kwargs)
def save_document(self, doc):
"""Save document."""
doc._doc.save()
def create_document(self, label):
"""Get a new document object"""
dobj = self.repo.get_object(type=self.model)
dobj.label = label
dobj.meta.label = "Document Metadata"
dobj.meta.mimetype = "text/plain"
doc = FedoraDocument(dobj, self)
return doc
def get(self, pid):
"""Get an object by id."""
doc = self.repo.get_object(pid, type=self.model)
if doc:
return FedoraDocument(doc, self)
def delete(self, doc, msg=None):
"""Delete an object."""
self.repo.purge_object(doc.pid, log_message=msg)
def list(self, namespace=None):
"""List documents in the repository."""
ns = namespace if namespace is not None else self.namespace
return [FedoraDocument(d, self) \
for d in self.repo.find_objects("%s:*" % ns, type=self.model)]
def list_pids(self, namespace=None):
"""List of pids. This unforunately involves calling
list(), so it not a quicker alternative."""
return [doc.pid for doc in self.list()]
| Python |
"""
Storage backend base class.
"""
import os
import re
import io
import textwrap
from contextlib import contextmanager
from django import forms
from django.conf import settings
from . import registry
from PIL import Image
from cStringIO import StringIO
class BaseConfigForm(forms.Form):
"""Base class for config form values."""
namespace = forms.CharField(max_length=255)
class StorageType(type):
"""Storage metaclass. Registers each storage
backend on initialisation."""
def __new__(cls, name, bases, attrs):
new = super(StorageType, cls).__new__
store_module = attrs.get("__module__") or "__main__"
# Abstract class: abstract attribute should not be inherited.
if attrs.pop("abstract", None) or not attrs.get("autoregister", True):
return new(cls, name, bases, attrs)
# Automatically generate missing/empty name, description, arity.
autoname = False
if not attrs.get("name"):
attrs["name"] = name
autoname = True
store_name = attrs["name"]
if store_name not in registry.stores:
storecls = new(cls, name, bases, attrs)
if attrs.get("description") is None:
doc = attrs.get("__doc__") or ""
storecls.description = textwrap.dedent(doc).strip()
registry.stores.register(storecls)
return registry.stores[store_name]
def __repr__(cls):
return "<class Storage %s>" % cls.name
class BaseStorage(object):
"""Base class for document storage backends."""
__metaclass__ = StorageType
abstract = True
configform = BaseConfigForm
defaults = {}
def __init__(self, *args, **kwargs):
self.namespace = kwargs["namespace"]
def document_attr_dzi_path(self, doc, attr):
return "%s/dzi/%s/%s/%s.dzi" % (
settings.MEDIA_ROOT,
self.namespace,
doc.pid, attr)
def attr_uri(self, doc):
"""URI for image datastream."""
raise NotImplementedError
def document_label(self, doc):
"""Get the document label."""
raise NotImplementedError
def document_attr_empty(self, doc, attr):
"""Check if an attr is missing or empty."""
raise NotImplementedError
def document_attr_label(self, doc, attr):
"""Get the document image label."""
raise NotImplementedError
def document_attr_mimetype(self, doc, attr):
"""Get the document image mimetype."""
raise NotImplementedError
def document_attr_content_handle(self, doc, attr):
"""Get document image content. Currently
EULFedora doesn't support a streaming content
API so we have to load it into an in memory
buffer."""
raise NotImplementedError
@contextmanager
def document_attr_content(self, doc, attr):
"""Get the document image content as a stream."""
handle = self.document_attr_content_handle(doc, attr)
try:
yield handle
finally:
handle.close()
def read_metadata(self, doc):
"""Get a dictionary of document metadata."""
raise NotImplementedError
def write_metadata(self, doc, **kwargs):
"""Get a dictionary of document metadata."""
raise NotImplementedError
def merge_metadata(self, doc, **kwargs):
meta = self.read_metadata(doc)
meta.update(kwargs)
self.write_metadata(doc, **meta)
def delete_metadata(self, *args):
meta = self.read_metadata(doc)
newmeta = dict([(k, v) for k, v in meta.iteritems() \
if k not in args])
self.write_metadata(doc, **newmeta)
def set_document_attr_content(self, doc, attr, content):
"""Set image content."""
raise NotImplementedError
def set_document_attr_mimetype(self, doc, attr, mimetype):
"""Set image mimetype."""
raise NotImplementedError
def set_document_attr_label(self, doc, attr, label):
"""Set image label."""
raise NotImplementedError
def set_document_label(self, doc, label):
"""Set document label."""
raise NotImplementedError
def save_document(self, doc):
"""Save document."""
raise NotImplementedError
def create_document(self, label):
"""Get a new document object"""
raise NotImplementedError
def get(self, id):
"""Get an object by id."""
raise NotImplementedError
def delete(self, pid, msg=None):
"""Delete an object."""
raise NotImplementedError
def list(self, namespace=None):
"""List documents in the repository."""
raise NotImplementedError
def list_pids(self):
"""List of pids."""
raise NotImplementedError
def next(self, pid):
"""Get next pid to this one"""
plist = self.list_pids()
idx = plist.index(pid)
if len(plist) == idx + 1:
return None
return plist[idx + 1]
def prev(self, pid):
"""Get previous pid to this one."""
plist = self.list_pids()
idx = plist.index(pid)
if idx == 0:
return None
return plist[idx - 1]
@classmethod
def pid_index(cls, namespace, pid):
"""Get the numerical index of a pid."""
match = re.match("^" + namespace + ":(\d+)$", pid)
if match:
return int(match.groups()[0])
@classmethod
def sort_pidlist(cls, namespace, pidlist):
"""Sort a pid list numerically."""
def sfunc(a, b):
return cls.pid_index(namespace, a) - cls.pid_index(namespace, b)
return sorted(pidlist, sfunc)
class BaseDocumentType(type):
"""Metaclass to generate accessors for document
image attributes. At present, an OCR document
has three image members (image, binary, thumbnail)
which each have three accessible properties (label,
content, and mimetype.) These are all accessed via
the backend storage `document_attr_<attr>`
methods."""
def __new__(cls, name, bases, attrs):
new = super(BaseDocumentType, cls).__new__
if attrs.pop("abstract", None):
return new(cls, name, bases, attrs)
doccls = new(cls, name, bases, attrs)
for obj in ["image", "thumbnail", "binary", "transcript", "script"]:
for attr in ["label", "mimetype", "content"]:
generate_image_attr_accessors(doccls, obj, attr)
return doccls
def generate_image_attr_accessors(cls, objattr, attr):
def getter(self):
meth = getattr(self._storage, "document_attr_%s" % attr)
return meth(self, objattr)
getter.__doc__ = "Get %s %s" % (objattr, attr)
getter.__name__ = "get_%s_%s" % (objattr, attr)
setattr(cls, getter.__name__, getter)
def setter(self, value):
meth = getattr(self._storage, "set_document_attr_%s" % attr)
meth(self, objattr, value)
setter.__doc__ = "Set %s %s" % (objattr, attr)
setter.__name__ = "set_%s_%s" % (objattr, attr)
setattr(cls, setter.__name__, setter)
setattr(cls, "%s_%s" % (objattr, attr), property(getter, setter))
def checker(self):
meth = getattr(self._storage, "document_attr_empty")
return meth(self, objattr)
checker.__doc__ = "Check if %s is empty" % objattr
checker.__name__ = "%s_empty" % objattr
setattr(cls, checker.__name__, checker)
setattr(cls, "%s_empty" % objattr, property(checker))
class BaseDocument(object):
"""Document model abstract class. Just provides
a thin object abstraction object each storage backend."""
__metaclass__ = BaseDocumentType
abstract = True
def __init__(self, pid, storage):
"""Initialise the Document with an image path/handle."""
self._pid = pid
self._storage = storage
self._deleted = False
self._metacache = None
def __repr__(self):
return "<Document: %s>" % self.label
def __unicode__(self):
"""Unicode representation."""
return self.label
@property
def pid(self):
return self._pid
def save(self):
"""Save objects, settings dates if necessary
and writing all cached datastreams to storage."""
self._storage.save_document(self)
def process_thumbnail(self, pil):
"""Process thumbnail, padding to a constant size"""
size = settings.THUMBNAIL_SIZE
pil.thumbnail(settings.THUMBNAIL_SIZE, Image.ANTIALIAS)
back = Image.new("RGBA", settings.THUMBNAIL_SIZE)
back.paste((255,255,255,0), (0, 0, size[0], size[1]))
back.paste(pil, ((size[0] - pil.size[0]) / 2, (size[1] - pil.size[1]) / 2))
return back
def make_thumbnail(self):
"""Create a thumbnail of the main image."""
with self.image_content as handle:
im = Image.open(handle)
thumb = self.process_thumbnail(im)
# FIXME: This is NOT elegant...
try:
stream = StringIO()
thumb.save(stream, "PNG")
self.thumbnail_mimetype = "image/png"
self.thumbnail_label = "%s.thumb.png" % os.path.splitext(
self.image_label)[0]
self.thumbnail_content = stream
self.save()
finally:
stream.close()
@property
def transcript_url(self):
return "/documents/edit/%s/" % self.pid
@property
def image_uri(self):
return self._storage.attr_uri(self, "image")
@property
def thumbnail_uri(self):
return self._storage.attr_uri(self, "thumbnail")
@property
def ocr_status(self):
return self.get_metadata("ocr_status")
@property
def label(self):
return self._storage.document_label(self)
@property
def metadata(self):
if self._metacache is not None:
return self._metacache
self._metacache = self._storage.read_metadata(self)
return self._metacache
@ocr_status.setter
def ocr_status(self, status):
self.set_metadata(ocr_status=status)
def get_metadata(self, attr=None):
meta = self.metadata
if attr:
return meta.get(attr)
return meta
def set_metadata(self, **kwargs):
"""Set a key/pair value."""
self._metacache = None
self._storage.merge_metadata(self, **kwargs)
def delete_metadata(self, *args):
"""Delete metadata keys."""
self._metacache = None
self._storage.delete_metadata(self, *args)
def delete(self):
"""Delete this object."""
self._storage.delete(self)
self._deleted = True
| Python |
"""
Filesystem storage module.
"""
import os
import io
import re
import shutil
from cStringIO import StringIO
from django import forms
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from ocradmin.core.utils import media_path_to_url
from PIL import Image
from . import base, exceptions
class ConfigForm(base.BaseConfigForm):
"""File system storage config."""
class Document(base.BaseDocument):
"""File system document."""
def make_thumbnail(self):
"""Create a thumbnail of the main image."""
with self.image_content as handle:
im = Image.open(handle)
thumb = self.process_thumbnail(im)
# FIXME: This is NOT elegant...
with io.open(os.path.join(
self._storage.document_path(self), self._storage.thumbnail_name), "wb") as h:
thumb.save(h, "PNG")
self.thumbnail_label = "%s.thumb.png" % os.path.splitext(self.image_label)[0]
self.thumbnail_mimetype = "image/png"
self.save()
# README: This is a very naive and inefficient file-based repository.
# Currently nothing is cached and all attribute updates are written
# immediately.
class FileSystemStorage(base.BaseStorage):
"""Filesystem storage backend. A document is represented
as a directory of datastreams, i.e:
<project-name>:1/
IMG
THUMBNAIL
TRANSCRIPT
meta.txt
"""
configform = ConfigForm
image_name = "IMG"
binary_name = "BINARY"
thumbnail_name = "THUMBNAIL"
transcript_name = "TRANSCRIPT"
script_name = "OCR_SCRIPT"
meta_name = "meta.txt"
def _checkconfigured(self):
docroot = getattr(settings, "DOCUMENT_ROOT", "")
if not os.path.exists(docroot) and os.path.isdir(docroot):
raise ImproperlyConfigured("Document root does not exist."
" Make sure 'DOCUMENT_ROOT' is set in django.settings and"
" that it is a writable directory.")
if not os.access(docroot, os.W_OK):
raise ImproperlyConfigured("Document root does not appear to be writable."
" Make sure 'DOCUMENT_ROOT' is set in django.settings and"
" that it is a writable directory.")
def __init__(self, *args, **kwargs):
self.namespace = kwargs["namespace"]
self._checkconfigured()
@property
def namespace_root(self):
docroot = getattr(settings, "DOCUMENT_ROOT", "")
return os.path.join(docroot, self.namespace)
def document_path(self, doc):
return os.path.join(self.namespace_root, doc.pid)
def get_next_pid(self):
"""Get the next filesystem pid. FIXME: This is not
re-entrance or thread-safe (but then not much else is!)"""
if not os.path.exists(self.namespace_root):
return "%s:1" % self.namespace
pidnums = []
for item in os.listdir(self.namespace_root):
if os.path.isdir(os.path.join(self.namespace_root, item)):
pidindex = self.pid_index(self.namespace, item)
if pidindex is not None:
pidnums.append(pidindex)
if not len(pidnums):
return "%s:1" % self.namespace
return "%s:%d" % (self.namespace, max(sorted(pidnums)) + 1)
def read_metadata(self, doc):
metapath = os.path.join(self.document_path(doc), self.meta_name)
if not os.path.exists(metapath):
return {}
with io.open(metapath, "r") as metahandle:
return dict([v.strip().split("=") for v in \
metahandle.readlines() if re.match("^\w+=[^=]+$", v.strip())])
def write_metadata(self, doc, **kwargs):
metapath = os.path.join(self.document_path(doc), self.meta_name)
with io.open(metapath, "w") as metahandle:
for k, v in kwargs.iteritems():
metahandle.write(u"%s=%s\n" % (k, v))
def create_document(self, label):
"""Get a new document object"""
pid = self.get_next_pid()
# better that this fails than try to handle it
os.makedirs(os.path.join(self.namespace_root, pid))
doc = Document(pid, self)
self.merge_metadata(doc, label=label)
return doc
def save_document(self, doc):
"""Save document contents."""
pass
def attr_uri(self, doc, attr):
"""URI for image datastream."""
return media_path_to_url(
os.path.join(self.document_path(doc), getattr(self, "%s_name" % attr)))
def document_label(self, doc):
"""Get the document label."""
return self.read_metadata(doc).get("label", "")
def document_attr_empty(self, doc, attr):
"""Check if document attr is empty."""
path = os.path.join(
self.document_path(doc), getattr(self, "%s_name" % attr))
return not os.path.exists(path) or os.stat(path)[6] == 0
def document_attr_label(self, doc, attr):
"""Get the document image label."""
return self.read_metadata(doc).get("%s_label" % attr, "")
def document_attr_mimetype(self, doc, attr):
"""Get the document image mimetype."""
return self.read_metadata(doc).get("%s_mimetype" % attr, "")
def document_attr_content_handle(self, doc, attr):
"""Get a handle to a document attribute's content. This
should be closed when finished, or used via the context
manager method `document_attr_content`."""
imgpath = os.path.join(
self.document_path(doc), getattr(self, "%s_name" % attr))
if os.path.exists(imgpath):
return io.open(imgpath, "rb")
return StringIO("")
def set_document_attr_content(self, doc, attr, content):
"""Set image content."""
imgpath = os.path.join(self.document_path(doc), getattr(self, "%s_name" % attr))
with io.open(imgpath, "wb") as imghandle:
if content is None:
imghandle.truncate()
elif isinstance(content, basestring):
imghandle.write(content)
else:
imghandle.write(content.read())
def set_document_attr_mimetype(self, doc, attr, mimetype):
"""Set image mimetype."""
self.merge_metadata(doc, **{"%s_mimetype" % attr: mimetype})
def set_document_attr_label(self, doc, attr, label):
"""Set image label."""
self.merge_metadata(doc, **{"%s_label" % attr: label})
def set_document_label(self, doc, label):
"""Set document label."""
self.merge_metadata(doc, label=label)
def get(self, pid):
"""Get an object by id."""
if os.path.exists(os.path.join(self.namespace_root, pid)):
return Document(pid, self)
def delete(self, doc, msg=None):
"""Delete an object."""
# TODO: Make more robust
shutil.rmtree(self.document_path(doc))
# if we're deleting the last object
# also delete the namespace root.
# Just try this and ignore the error
try:
os.rmdir(self.namespace_root)
except OSError:
pass
def list(self, namespace=None):
"""List documents in the repository."""
if not os.path.exists(self.namespace_root):
return []
return [Document(pid, self) for pid in self.list_pids()]
def list_pids(self, namespace=None):
if not os.path.exists(self.namespace_root):
return []
return self.sort_pidlist(self.namespace,
[p for p in os.listdir(self.namespace_root) \
if os.path.isdir(os.path.join(self.namespace_root, p)) and \
not self.pid_index(self.namespace, p) is None])
def next(self, pid):
"""Get next pid to this one"""
plist = self.list_pids()
idx = plist.index(pid)
if len(plist) == idx + 1:
return None
return plist[idx + 1]
def prev(self, pid):
"""Get previous pid to this one."""
plist = self.list_pids()
idx = plist.index(pid)
if idx == 0:
return None
return plist[idx - 1]
| Python |
"""
Storage backend exceptions.
"""
class AmbiguousDatastreamError(StandardError):
pass
class DatastreamNotFoundError(StandardError):
pass
| Python |
"""
Storage module. Abstracts various document-storage backends.
"""
from __future__ import absolute_import
from . import registry, fedora, file_system, mongodb
def get_backend(name):
return registry.stores[name]
| Python |
"""
Registry for storage backends.
This class was adapted from the Celery Project's task registry.
"""
import inspect
class NotRegistered(KeyError):
pass
class StorageRegistry(dict):
NotRegistered = NotRegistered
def register(self, store):
"""Register a store class in the store registry."""
self[store.name] = inspect.isclass(store) and store or store.__class__
def unregister(self, name):
"""Unregister store by name."""
try:
# Might be a store class
name = name.name
except AttributeError:
pass
self.pop(name)
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
raise self.NotRegistered(key)
def pop(self, key, *args):
try:
return dict.pop(self, key, *args)
except KeyError:
raise self.NotRegistered(key)
stores = StorageRegistry()
| Python |
"""
Mongodb storage backend.
"""
from django import forms
from pymongo import Connection
import gridfs
from . import base
class ConfigForm(base.BaseConfigForm):
"""Mongodb config form."""
class MongoDbStorage(base.BaseStorage):
"""Mongodb storage backend."""
| Python |
from django.db import models
from ocradmin.projects.models import Project
from ocradmin import storage
from django.conf import settings
#class DocumentBase(object):
# """Document model abstract class. Each storage
# backend implements its own version of this."""
# def __init__(self, label):
# """Initialise the Document with an image path/handle."""
# self._label = label
#
# @property
# def label(self):
# raise NotImplementedError
#
# def __unicode__(self):
# """Unicode representation."""
# return self.label
#
# def save(self):
# """Save objects, settings dates if necessary
# and writing all cached datastreams to storage."""
# raise NotImplementedError
#
# def set_image_content(self, content):
# """Set image content."""
# raise NotImplementedError
#
# def set_image_mimetype(self, mimetype):
# """Set image mimetype."""
# raise NotImplementedError
#
# def set_image_label(self, label):
# """Set image label."""
# raise NotImplementedError
#
# def set_label(self, label):
# """Set document label."""
# raise NotImplementedError
#
# def set_metadata(self, attr, value):
# """Set arbitrary document metadata."""
# raise NotImplementedError
| Python |
# OCR Batch utils
import os
import re
import subprocess as sp
class Aspell(object):
"""
Aspell Wrapper.
"""
suggestre = re.compile("& (?P<word>\S+) (?P<numsuggestions>\d+) \d+: (?P<suggestions>.+)")
nomatchre = re.compile("# (?P<word>\S+) \d+")
def __init__(self):
"""
Initialise an Aspell object.
"""
pass
def spellcheck(self, data):
"""
Spellcheck some data.
"""
pipe = self._get_aspell_pipe("-a -d en")
head = pipe.stdout.readline()
if head.find("International Ispell") == -1:
raise AssertionError("Unexpected Ispell output: " + head)
# switch to terse mode
pipe.stdin.write('!\n')
# write the data
pipe.stdin.write(data.encode('utf8') + "\n")
stdout, stderr = pipe.communicate()
out = {}
for line in stdout.split("\n"):
if line.startswith("&"):
m = self.suggestre.match(line)
captures = m.groupdict()
captures["suggestions"] = m.group("suggestions").split(", ")
out[m.group("word")] = captures
elif line.startswith("#"):
n = self.nomatchre.match(line)
captures = n.groupdict()
captures["numsuggestions"] = "0"
out[n.group("word")] = captures
return out
def dump_dicts(self):
"""
Show available dictionaries.
"""
pipe = self._get_aspell_pipe("dump dicts")
dicts = pipe.communicate()[0]
return dicts.split("\n")
def _get_aspell_pipe(self, options):
"""
Open an aspell command.
"""
return sp.Popen(["aspell %s" % options], shell=True,
stdout=sp.PIPE, stdin=sp.PIPE, close_fds=True)
if __name__=="__main__":
a = Aspell()
print a.spellcheck("This is some\nlins to check")
| Python |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| Python |
"""
URLConf for OCR documents.
"""
from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from ocradmin.documents import views
urlpatterns = patterns('',
(r'^/?$', login_required(views.doclist)),
(r'^list/?$', login_required(views.doclist)),
(r'^create/?$', login_required(views.create)),
(r'^create_ajax/?$', login_required(views.create_ajax)),
(r'^batch/?$', login_required(views.quick_batch)),
(r'^show/(?P<pid>[^/]+)/?$', login_required(views.detail)),
(r'^edit/?$', login_required(views.editor)),
(r'^edit/(?P<pid>[^/]+)/?$', login_required(views.editor)),
(r'^transcript/(?P<pid>[^/]+)/?$', login_required(views.transcript)),
(r'^binary/(?P<pid>[^/]+)/?$', login_required(views.binary)),
(r'^status/(?P<pid>[^/]+)/?$', login_required(views.status)),
(r'^show_small/(?P<pid>[^/]+)/?$', login_required(views.show_small)),
(r'^delete/(?P<pid>[^/]+)/?$', login_required(views.delete)),
(r'^delete_multiple/?$', login_required(views.delete_multiple)),
(r'^spellcheck/?$', login_required(views.spellcheck)),
)
| Python |
"""
Flags indicating document status
"""
PRETTY_STATUS = {
"initial" : "Initial",
"error" : "Error",
"uncorrected": "Uncorrected",
"part_corrected": "Part Corrected",
"complete" : "Complete",
}
RUNNING = "running"
ERROR = "error"
INITIAL = "initial"
UNCORRECTED = "uncorrected"
PART_CORRECTED = "part_corrected"
COMPLETE = "complete"
| Python |
"""
Views for handling documents and document storage.
"""
import json
from django import forms
from django.db import transaction
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, \
HttpResponseServerError, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from ocradmin import storage
from ocradmin.storage.utils import DocumentEncoder
from ocradmin.documents import status as docstatus
from ocradmin.documents.utils import Aspell
from ocradmin.core.decorators import project_required
from ocradmin.presets.models import Preset, Profile
from ocradmin.ocrtasks.models import OcrTask
from ocradmin.batch.models import Batch
from ocradmin.batch.views import dispatch_batch
from BeautifulSoup import BeautifulSoup
from cStringIO import StringIO
class DocumentForm(forms.Form):
"""New document form."""
file = forms.FileField()
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
@project_required
def doclist(request):
"""List documents."""
project = request.project
storage = project.get_storage()
template = "documents/list.html" if not request.is_ajax() \
else "documents/includes/document_list.html"
profiles = Profile.objects.filter(name="Batch OCR")
presets = Preset.objects.filter(profile__isnull=False).order_by("name")
newform = DocumentForm()
if profiles:
presets = profiles[0].presets.order_by("name").all()
context = dict(
project=project,
storage=storage,
objects=storage.list(),
presets=presets,
newform=newform,
pfields=["tags", "description", "created_on", "storage_backend"],
sfields=project.storage_config_dict().keys()
)
return render(request, template, context)
@project_required
def quick_batch(request):
"""Quickly dispatch a batch job."""
preset = get_object_or_404(Preset, pk=request.POST.get("preset", 0))
pids = request.POST.getlist("pid")
assert len(pids), "No pids submitted"
batchname = "%s - Batch %d" % (request.project.name,
request.project.batches.count() + 1)
batch = Batch(
name=batchname,
user=request.user,
project=request.project,
description="",
script=preset.data,
tags="",
task_type="run.batchitem"
)
batch.save()
with transaction.commit_on_success():
dispatch_batch(batch, pids)
if request.is_ajax():
return HttpResponse(json.dumps({"pk":batch.pk}),
mimetype="application/json")
return HttpResponseRedirect("/batch/show/%s/" % batch.pk)
@project_required
def editor(request, pid=None):
"""Edit document transcript."""
context = {}
if pid is not None:
storage = request.project.get_storage()
doc = storage.get(pid)
context = dict(
next=storage.next(pid),
prev=storage.prev(pid),
doc=doc)
if not request.is_ajax():
template = "documents/editor.html"
return render(request, template, context)
# if it's an Ajax request, write the document text to the
# response
response = HttpResponse(mimetype="application/json")
json.dump(context, response, cls=DocumentEncoder)
return response
@project_required
def transcript(request, pid):
"""Get/set the transcript for a document."""
doc = request.project.get_storage().get(pid)
if not request.method == "POST":
response = HttpResponse(mimetype=doc.transcript_mimetype)
with doc.transcript_content as handle:
response.write(handle.read())
return response
# FIXME: This method of saving the data could potentially throw away
# metadata from the OCR source. Ultimately we need to merge it
# into the old HOCR document, rather than creating a new one
data = request.POST.get("data")
if not data:
return HttpResponseServerError("No data passed to 'save' function.")
with doc.transcript_content as handle:
soup = BeautifulSoup(handle)
soup.find("div", {"class": "ocr_page"}).replaceWith(data)
doc.transcript_content = str(soup)
doc.save()
return HttpResponse(json.dumps({"ok": True}), mimetype="application/json")
@project_required
def binary(request, pid):
"""
Trigger a re-binarization of the image for viewing purposes.
"""
taskname = "create.docdzi"
doc = request.project.get_storage().get(pid)
if not request.is_ajax():
response = HttpResponse(mimetype=doc.binary_mimetype)
with doc.binary_content as handle:
response.write(handle.read())
return response
if doc.binary_empty:
return HttpResponseNotFound
async = OcrTask.run_celery_task(taskname, (request.project.pk, pid, "binary"),
untracked=True,
queue="interactive", asyncronous=request.POST.get("async", False))
out = dict(task_id=async.task_id, status=async.status,
results=async.result)
return HttpResponse(json.dumps(out), mimetype="application/json")
@project_required
def create(request):
"""Create a new document."""
store = request.session["project"].get_storage()
if not request.method == "POST":
form = DocumentForm()
return render(request, "documents/create.html", dict(
form=form, page_name="%s: Add document" % store.name)
)
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
if not form.cleaned_data["label"]:
form.cleaned_data["label"] = request.FILES["file"].name
doc = store.create_document(form.cleaned_data["label"])
doc.image_content = request.FILES["file"]
doc.image_mimetype = request.FILES["file"].content_type
doc.image_label = request.FILES["file"].name
doc.set_metadata(
title=form.cleaned_data["label"],
ocr_status=docstatus.INITIAL)
doc.make_thumbnail()
doc.save()
# TODO: Make async
#doc.save()
return HttpResponseRedirect("/documents/list")
@project_required
def show_small(request, pid, doc=None):
"""Render a document's details."""
if doc is None:
storage = request.project.get_storage()
doc = storage.get(pid)
template = "documents/includes/document.html"
return render(request, template, dict(object=doc))
@csrf_exempt
@project_required
def create_ajax(request):
"""Create new documents with an Ajax POST."""
if request.method == "POST" and request.GET.get("inlinefile"):
storage = request.project.get_storage()
filename = request.GET.get("inlinefile")
doc = storage.create_document(filename)
try:
doc.image_content = StringIO(request.raw_post_data)
doc.image_mimetype = request.META.get("HTTP_X_FILE_TYPE")
doc.image_label = filename
doc.set_metadata(title=filename, ocr_status=docstatus.INITIAL)
doc.make_thumbnail()
doc.save()
except Exception, err:
logger.exception(err)
if request.is_ajax():
return show_small(request, doc.pid, doc)
return HttpRedirect("/documents/list/")
@project_required
def spellcheck(request):
"""
Spellcheck some POST data.
"""
jsondata = request.POST.get("data")
print "Spellcheck data: %s" % jsondata
if not jsondata:
return HttpResponseServerError(
"No data passed to 'spellcheck' function.")
data = json.loads(jsondata)
aspell = Aspell()
response = HttpResponse(mimetype="application/json")
json.dump(aspell.spellcheck(data), response, ensure_ascii=False)
return response
@project_required
def status(request, pid):
"""Set document status."""
doc = request.project.get_storage().get(pid)
if request.method == "POST":
stat = request.POST.get("status", docstatus.INITIAL)
print "Setting status of %s to %s" % (pid, stat)
doc.set_metadata(ocr_status=stat)
doc.save()
if request.is_ajax():
return HttpResponse(json.dumps({"status":doc.ocr_status}),
mimetype="application/json")
return HttpResponse(doc.ocr_status, mimetype="text/plain")
@project_required
def detail(request, pid):
storage = request.project.get_storage()
doc = storage.get(pid)
return render(request, "document/details.html", dict(object=doc))
@project_required
def delete(request, pid):
storage = request.project.get_storage()
doc = storage.get(pid)
return render(request, "document/delete.html", dict(object=doc))
@project_required
def delete_multiple(request):
# fixme, figure out how to do the post
# properly
if request.method == "POST":
pids = request.GET.getlist("pid");
storage = request.project.get_storage()
print "Deleting %s" % pids
[storage.get(pid).delete() for pid in pids]
if request.is_ajax():
return HttpResponse(json.dumps({"ok": True}),
mimetype="application/json")
return render(request, "document/delete.html", dict(object=doc))
| Python |
from UserDict import DictMixin
class OrderedDict(dict, DictMixin):
def __init__(self, *args, **kwds):
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__end
except AttributeError:
self.clear()
self.update(*args, **kwds)
def clear(self):
self.__end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.__map = {} # key --> [key, prev, next]
dict.clear(self)
def __setitem__(self, key, value):
if key not in self:
end = self.__end
curr = end[1]
curr[2] = end[1] = self.__map[key] = [key, curr, end]
dict.__setitem__(self, key, value)
def __delitem__(self, key):
dict.__delitem__(self, key)
key, prev, next = self.__map.pop(key)
prev[2] = next
next[1] = prev
def __iter__(self):
end = self.__end
curr = end[2]
while curr is not end:
yield curr[0]
curr = curr[2]
def __reversed__(self):
end = self.__end
curr = end[1]
while curr is not end:
yield curr[0]
curr = curr[1]
def popitem(self, last=True):
if not self:
raise KeyError('dictionary is empty')
if last:
key = reversed(self).next()
else:
key = iter(self).next()
value = self.pop(key)
return key, value
def __reduce__(self):
items = [[k, self[k]] for k in self]
tmp = self.__map, self.__end
del self.__map, self.__end
inst_dict = vars(self).copy()
self.__map, self.__end = tmp
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def keys(self):
return list(self)
setdefault = DictMixin.setdefault
update = DictMixin.update
pop = DictMixin.pop
values = DictMixin.values
items = DictMixin.items
iterkeys = DictMixin.iterkeys
itervalues = DictMixin.itervalues
iteritems = DictMixin.iteritems
def __repr__(self):
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
def copy(self):
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
d = cls()
for key in iterable:
d[key] = value
return d
def __eq__(self, other):
if isinstance(other, OrderedDict):
return len(self)==len(other) and self.items() == other.items()
return dict.__eq__(self, other)
def __ne__(self, other):
return not self == other
| Python |
# fedora adaptor
import re
from fcrepo.http.restapi import FCRepoRestAPI
from xml.dom import minidom
import fcobject
DEFAULTS = {
"repository_url": 'http://optiplex:8080/fedora',
"username": 'fedoraAdmin',
"password": 'fedora',
"realm": 'any',
"namespace": 'fedora'
}
NS = "{http://www.fedora.info/definitions/1/0/types/}"
DCNS = "{http://purl.org/dc/elements/1.1/}"
RESPONSEMAP = {
}
def add_ns(tag):
return "%s%s" % (NS, tag)
def strip_ns(tag, ns=None):
if ns is None:
ns = NS
return tag.replace(ns, "", 1)
class FedoraException(Exception):
pass
class FedoraAdaptorException(Exception):
pass
| Python |
# Fedora Commons Datastream Object
import utils
reload(utils)
import fcbase
reload(fcbase)
from datetime import datetime
from xml.dom import minidom
import urllib
class FedoraDatastream(fcbase.FedoraBase):
"""
Fedora Datastream.
"""
NAMESPACE = None
# Map attribute names from XML to Object
ATTRMAP = {
"dsid" : "dsid",
"mimeType" : "mimetype",
"dcmDate" : "dc_modification_date",
}
PROFMAP = {
"dsID" : "dsid",
"dsLabel" : "label",
"dsMIME" : "mimetype",
"dsInfoType" : "info_type",
"dsChecksum" : "checksum",
"dsChecksumType" : "checksum_type",
"dsCreateDate" : "creation_date",
"dsState" : "state",
"dsControlGroup" : "control_group",
"dsVersionable" : "versionable",
"dsSize" : "size",
"dsFormatURI" : "format_uri",
"dsLocation" : "location",
"dsLocationType" : "location_type",
"dsVersionID" : "version_id",
}
ATTRIBUTES = [
"label",
"creation_date",
"mimetype",
"info_type",
"checksum",
"checksum_type",
"format_uri",
"location",
"location_type",
"version_id",
"versionable",
"state",
"size",
]
def __init__(self, *args, **kwargs):
fcbase.FedoraBase.__init__(self, *args, **kwargs)
self._loaded = False
self._saved = True
self._temp_content = None
self.pid = kwargs.get("pid")
self.dsid = kwargs.get("dsid")
self.label = kwargs.get("dsid")
@classmethod
def new(cls, pid, dsid):
"""
Instantiate a brand-new Datastream ready to be saved.
"""
ds = cls(pid=pid, dsid=dsid)
ds._saved = False
return ds
@classmethod
def load_from_xml(cls, pid, xmlnode):
"""
Load an existing Datastream from XML content.
"""
ds = cls(pid)
ds.set_attributes_from_xml(xmlnode)
return ds
def set_content(self, content):
"""
Set arbitary content attribute. This could be an XML string,
or anything that implements the file I/O interface.
"""
self._temp_content = content
self._saved = False
return self
def set_attributes_from_xml(self, xmlnode):
"""
Load from listDatastreams XML.
"""
if xmlnode.nodeName == "datastream":
for i in range(0, xmlnode.attributes.length):
attrname = xmlnode.attributes.item(i).nodeName
value = xmlnode.attributes.item(i).nodeValue
try:
value = datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
except ValueError:
pass
self.__dict__[self.normalise_attrname(attrname)] = value
elif xmlnode.nodeName == "datastreamProfile":
self.dsid = xmlnode.getAttribute("dsID")
self.set_attributes_from_profile_xml(xmlnode)
return self
def set_attribute(self, name, value):
cattr = self.__dict__.get(name)
if (not cattr) or (cattr != value):
self.__dict__[name] = value
self._saved = False
return self
def delete(self):
"""
Run purgeDatastream on the given dsid
"""
self._response = self._handler.purgeDatastream(
self.pid,
self.dsid
)
self._deleted = self._response.getStatus() == "204"
return self._deleted
def save(self):
"""
Save/modify an object.
"""
if self._saved:
return self.save_modified()
else:
return self.save_new()
def save_modified(self):
"""
Save changes to an object.
"""
self._response = self._handler.modifyDatastream(
self.pid,
self.dsid,
dsLabel=self.label,
controlGroup="M",
mimeType=urllib.quote(self.mimetype),
contentLength=self.size,
content=self._temp_content
)
print self._response.getBody().getContent()
print self._response.getStatus()
return self._response.getStatus() == "201"
def save_new(self):
"""
Save a new the datastream.
"""
self._response = self._handler.addDatastream(
self.pid,
self.dsid,
dsLabel=self.label,
controlGroup="M",
mimeType=urllib.quote(self.mimetype),
contentLength=self.size,
content=self._temp_content
)
print self._response.getBody().getContent()
print self._response.getStatus()
self._temp_content = None
self._saved = self._response.getStatus() == "201"
return self._saved
def is_saved(self):
"""
Return whether the object is newly initialised or loaded from the repository.
"""
return self._saved
def content(self):
"""
Return the datastream dissemintation for the object
"""
self._response = self._handler.getDatastreamDissemination(self.pid, self.dsid, download="true")
if not self._response != "200":
raise utils.FedoraAdaptorException("Datastream '%s' for object with pid '%s' not found" % (self.dsid, self.pid))
return self._response.getBody().getContent()
def _lazy_load_profile(self):
"""
Parse profile XML to attributes.
"""
if self._loaded:
return
response = self._handler.getDatastream(self.pid, self.dsid, format="xml")
doc = minidom.parseString(response.getBody().getContent())
self.set_attributes_from_profile_xml(doc.documentElement)
self._loaded = True
def __repr__(self):
return "<%s %s: %s>" % (self.__class__.__name__, self.dsid, self.mimetype)
| Python |
# Run some tests on the fcobject classes
import fcobject
import unittest
class TestFedoraObject(fcobject.FedoraObject):
NAMESPACE = "test-python-wrapper-object"
class TestFedoraObjectRunner(unittest.TestCase):
def setUp(self):
self.fco = TestFedoraObject()
self.fco.save()
def testCreation(self):
self.assertEqual(self.fco.is_saved(), True)
self.assertTrue(self.fco.pid.startswith(TestFedoraObject.NAMESPACE))
def testQuery(self):
querystr = "pid~%s" % self.fco.pid
results = TestFedoraObject.query(query=querystr)
self.assertEqual(len(results), 1)
def testUnsuccessfulQuery(self):
querystr = "pid~ILLEGAL_PID"
results = TestFedoraObject.query(query=querystr)
self.assertEqual(len(results), 0)
def testLazyLoad(self):
# check there's no existing creation_date attribute
self.assertEqual(None, self.fco.__dict__.get("creation_date"))
cdate = self.fco.creation_date
cdatecmp = TestFedoraObject.find(self.fco.pid).creation_date
self.assertEqual(cdate.__class__.__name__, "datetime")
self.assertEqual(cdate, cdatecmp)
def testListDatastreams(self):
# by default we should only have two datastreams: the DC and RELS-EXT
dslist = self.fco.datastreams()
self.assertEqual(len(dslist), 2)
self.assertEqual(dslist[0].dsid, "DC")
self.assertEqual(dslist[1].dsid, "RELS-EXT")
def testAddDeleteDatastream(self):
testdsid = "TEST_DS1"
ds = self.fco.new_datastream(testdsid, label="Test Datastream",
content="<some_xml></some_xml>", content_type="text/xml")
ds.save()
self.assertTrue(ds.is_saved())
# test listing
dslist = self.fco.datastreams()
self.assertEqual(len(dslist), 3)
self.assertEqual(dslist[2].dsid, testdsid)
# now delete it again
ds.delete()
self.testListDatastreams()
def testFindDatastream(self):
ds = self.fco.datastream("DC")
self.assertEqual(ds.dsid, "DC")
def testSetDublincoreDict(self):
newlabel = "Brand New Label"
dcd = self.fco.dublincore()
dcd["label"] = newlabel
self.fco.set_dublincore(dcd)
# re-get the dict and check it's still the same
dcd = self.fco.dublincore()
self.assertEqual(dcd["label"], newlabel)
def tearDown(self):
self.fco.delete()
if __name__ == '__main__':
unittest.main()
| Python |
# Fedora Commons Base Object
import re
import urllib2
from datetime import datetime
from utils import FedoraException
from utils import DEFAULTS
from xml.dom import minidom
from fcrepo.http.restapi import FCRepoRestAPI
def denormalise_query_args(argdict):
"""
Map Python types to REST query strings.
"""
args = {}
for arg, val in argdict.iteritems():
if arg.startswith("_"):
continue
if isinstance(val, bool):
args[arg] = str(val).lower()
else:
args[arg] = str(val)
return args
class FedoraBase(object):
"""
Fedora Commons Base Object. This contains the connection
settings and underlying query methods.
"""
NAMESPACE = "fcobject"
ATTRMAP = {}
PROFMAP = {}
ATTRIBUTES = []
_handler = FCRepoRestAPI(**DEFAULTS)
def __init__(self, *args, **kwargs):
"""
Initialise a base object.
"""
self._params = {}
self._params.update(DEFAULTS)
self._params.update([(k, v) for k, v in kwargs.iteritems() \
if DEFAULTS.get(k)])
self._handler = FCRepoRestAPI(**self._params)
def errors(self):
"""
Return the most likely helpful string from the response.
"""
out = "Unknown error"
if self.__dict__.get("_response"):
out = self._response.getBody().getContent()
return out
def set_attribute(self, attrname, value):
raise NotImplementedError
def set_attributes_from_xml(self, xmlnode):
raise NotImplementedError
def set_attributes_from_profile_xml(self, xmlnode):
"""
Load from the profile XML data.
"""
for ele in xmlnode.getElementsByTagName("*"):
try:
value = ele.childNodes[0].nodeValue
except IndexError:
value = ""
try:
if re.match("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", value):
value = value[:-5]
# FIXME: Correct for timezone/daylight savings?
value = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S")
except ValueError:
pass
self.__dict__[self.normalise_profile_attrname(ele.nodeName)] = value
return self
def _lazy_load_profile(self):
raise NotImplementedError
def to_xml(self):
raise NotImplementedError
def to_foxml(self):
raise NotImplementedError
def from_xml(self):
raise NotImplementedError
def __getattr__(self, attrname):
"""
Lazy load attributes if necessary.
"""
if self.__dict__.get(attrname):
return self.__dict__.get(attrname)
if self.__dict__.get("pid") and attrname in self.ATTRIBUTES:
self._lazy_load_profile()
return self.__dict__.get(attrname)
raise AttributeError("%s object has no attribute '%s'" % ("FedoraObject", attrname))
def set_attributes_from_profile_xml(self, xmlnode):
"""
Load from the profile XML data.
"""
for ele in xmlnode.getElementsByTagName("*"):
try:
value = ele.childNodes[0].nodeValue
except IndexError:
value = ""
try:
if value and re.match("\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z", value.encode()):
value = value[:-5]
# FIXME: Correct for timezone/daylight savings?
value = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S")
except ValueError, e:
print e.message
pass
self.__dict__[self.normalise_profile_attrname(ele.nodeName)] = value
return self
def _lazy_load_profile(self):
raise NotImplementedError
@classmethod
def query(self, *args, **kwargs):
"""
Query the Fedora Repository and return a list of
matching objects.
"""
# make sure we request a pid, and quote certain params
kwargs["pid"] = True
if kwargs.get("query"):
kwargs["query"] = urllib2.quote(kwargs["query"])
if kwargs.get("terms"):
kwargs["terms"] = urllib2.quote(kwargs["terms"])
self._response = self._handler.findObjects(**denormalise_query_args(kwargs))
if self._response.getStatus().startswith("40"):
return []
return self.object_list_from_query_xml(self._response.getBody().getContent())
@classmethod
def find(cls, pid):
"""
Find an object with the given pid.
"""
response = cls._handler.getObjectProfile(pid=pid, format="xml")
response.getBody().getContent()
doc = minidom.parseString(response.getBody().getContent())
f = cls(pid)
f.set_attributes_from_profile_xml(doc.documentElement)
return f
@classmethod
def object_list_from_query_xml(cls, responsexml):
objects = []
rdoc = minidom.parseString(responsexml)
for item in rdoc.documentElement.getElementsByTagName("objectFields"):
pid = item.getElementsByTagName("pid")[0].childNodes[0].nodeValue
f = cls(pid)
f.set_attributes_from_xml(item)
objects.append(f)
return objects
@classmethod
def get_next_pid(cls, **kwargs):
if not kwargs.get("format"):
kwargs["format"] = "xml"
response = cls._handler.getNextPID(**kwargs)
pidlist = minidom.parseString(response.getBody().getContent()).documentElement
return pidlist.getElementsByTagName("pid")[0].childNodes[0].nodeValue
@classmethod
def normalise_attrname(cls, name):
return cls.ATTRMAP.get(name, name).encode()
@classmethod
def denormalise_attrname(cls, name):
inv_map = dict((v,k) for k, v in cls.ATTRMAP.items())
return inv_map.get(name, name)
@classmethod
def normalise_profile_attrname(cls, name):
return cls.PROFMAP.get(name, name).encode()
@classmethod
def denormalise_profile_attrname(cls, name):
inv_map = dict((v,k) for k, v in cls.PROFMAP.items())
return inv_map.get(name, name)
| Python |
# Risearch Module
import httplib2
import urllib
class RiSearch(object):
"""
Wrapper class for executing ItQL queries.
"""
def __init__(self, url):
self._url = url
def query(self, querystr):
"""
Execute a risearch query.
"""
data = {
"distinct" : "on",
"format": "Sparql",
"lang": "itql",
"limit": "",
"type": "tuples",
"query" : querystr,
}
headers = {
"Content-Type": "application/x-www-form-urlencoded",
}
import httplib2
http = httplib2.Http()
resphead, respdata = http.request(
self._url,
"POST",
urllib.urlencode(data),
headers,
)
if resphead["status"] != "200":
raise Exception("risearch failed with status %s: %s" % (resphead["status"], respdata))
return respdata
| Python |
# Fedora Commons Object
import re
import utils
from ordereddict import OrderedDict
import fcbase
reload(fcbase)
import fcdatastream
reload(fcdatastream)
import risearch
reload(risearch)
from datetime import datetime
from xml.dom import minidom
import urllib
def query_args(argdict):
args = {}
for arg, val in argdict.iteritems():
if arg.startswith("_"):
continue
if isinstance(val, bool):
args[arg] = str(val).lower()
else:
args[arg] = str(val)
return args
class FedoraObject(fcbase.FedoraBase):
"""
Fedora Object.
"""
NAMESPACE = "fedora-object"
DSIDBASE = "DS"
CONTENT_MODEL = "fedora-system:ContentModel-3.0"
# Map attribute names from XML to Object
ATTRMAP = {
"ownerId" : "owner_id",
"cDate" : "creation_date",
"mDate" : "modification_date",
"dcmDate" : "dc_modification_date",
}
PROFMAP = {
"objLabel": "label",
"objOwnerId" : "owner_id",
"objCreateDate" : "creation_date",
"objLastModDate" : "modification_date",
}
ATTRIBUTES = [
"label",
"title",
"creation_date",
"modification_date",
"owner_id",
]
DUBLINCORE = [
"title",
"creator",
"subject",
"description",
"publisher",
"contributers",
"date",
"type",
"format",
"identifier",
"source",
"language",
"relation",
"coverage",
"rights",
]
def __init__(self, *args, **kwargs):
fcbase.FedoraBase.__init__(self, *args, **kwargs)
self._loaded = False
self._deleted = False
pid = kwargs.get("pid")
if pid:
self.pid = pid
self._saved = True
else:
self.pid = None
self._saved = False
def save(self):
"""
Ingest or update the object in the
repository.
"""
if not self.pid:
self.pid = self.get_next_pid(namespace=self.NAMESPACE)
# FIXME: Using the actual objects pid here doesn't seem to work
# so we add it to the FOXML and use "new" instead.
foxml = self.to_foxml()
print foxml
self._response = self._handler.ingest(pid="new", content=foxml)
print "PARAMS: %s" % self._params
print "RESPONSE: %s" % self._response.getBody().getContent()
self._saved = self._response.getStatus() == "201"
return self._saved
else:
# update the object
pass
def is_saved(self):
"""
Return whether the object is newly initialised or loaded from the repository.
"""
return self._saved
def delete(self, msg=""):
"""
Purge an object from the repository.
"""
self._response = self._handler.purgeObject(pid=self.pid, logMessage=msg)
self._deleted = self._response.getStatus() == "204"
return self._deleted
def set_attribute(self, name, value):
cattr = self.__dict__.get(name)
if (not cattr) or (cattr != value):
self.__dict__[name] = value
self._saved = False
return self
def set_attributes_from_xml(self, xmlnode):
"""
Load from query XML data.
"""
for ele in xmlnode.getElementsByTagName("*"):
if ele.nodeName == "pid":
continue
if not ele.childNodes:
continue
value = ele.childNodes[0].nodeValue
try:
value = datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
except ValueError:
pass
self.__dict__[self.normalise_attrname(ele.nodeName)] = value
return self
def _lazy_load_profile(self):
"""
Parse profile XML to attributes.
"""
if self._loaded:
return
response = self._handler.getObjectProfile(pid=self.pid, format="xml")
doc = minidom.parseString(response.getBody().getContent())
self.set_attributes_from_profile_xml(doc.documentElement)
self._loaded = True
def to_xml(self):
"""
Flatten to an XML string.
"""
attrs = {}
for attr, value in self.__dict__.iteritems():
if attr.startswith("_"):
continue
if isinstance(value, datetime):
attrs[self.normalise_attrname(attr)] = value.strftime("%F %T")
else:
attrs[self.normalise_attrname(attr)] = str(value)
raise NotImplementedError
def to_foxml(self):
"""
Flatten to a Fedora Object XML string.
"""
# there seems to be a problem with ingesting with a set pid. As a workaround
# set the pid in the FOXML and hope that works
pid = self.__dict__.get("pid")
if not pid:
pid = self.get_next_pid()
doc = minidom.Document()
root = doc.createElement("foxml:digitalObject")
doc.appendChild(root)
root.setAttribute("VERSION", "1.1")
root.setAttribute("PID", pid)
root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
root.setAttribute("xmlns:foxml", "info:fedora/fedora-system:def/foxml#")
root.setAttribute("xsi:schemaLocation", "info:fedora/fedora-system:def/foxml# http://www.fedora.info/definitions/1/0/foxml1-1.xsd")
objprops = doc.createElement("foxml:objectProperties")
root.appendChild(objprops)
stateprop = doc.createElement("foxml:property")
stateprop.setAttribute("NAME", "info:fedora/fedora-system:def/model#state")
stateprop.setAttribute("VALUE", "A")
labelprop = doc.createElement("foxml:property")
labelprop.setAttribute("NAME", "info:fedora/fedora-system:def/model#label")
labelprop.setAttribute("VALUE", self.__dict__.get("label", ""))
ownerprop = doc.createElement("foxml:property")
ownerprop.setAttribute("NAME", "info:fedora/fedora-system:def/model#ownerId")
ownerprop.setAttribute("VALUE", self.__dict__.get("creator", ""))
for p in [stateprop, labelprop, ownerprop]:
objprops.appendChild(p)
dcstream = doc.createElement("foxml:datastream")
root.appendChild(dcstream)
dcstream.setAttribute("ID", "DC")
dcstream.setAttribute("STATE", "A")
dcstream.setAttribute("CONTROL_GROUP", "X")
dcstreamver = doc.createElement("foxml:datastreamVersion")
dcstream.appendChild(dcstreamver)
dcstreamver.setAttribute("ID", "DC.0")
dcstreamver.setAttribute("MIMETYPE", "text/xml")
dcstreamver.setAttribute("LABEL", "Default Dublin Core Record")
dcxml = doc.createElement("foxml:xmlContent")
dcstreamver.appendChild(dcxml)
dcroot = doc.createElement("oai_dc:dc")
dcxml.appendChild(dcroot)
dcroot.setAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/")
dcroot.setAttribute("xmlns:oai_dc", "http://www.openarchives.org/OAI/2.0/oai_dc/")
for attr in ["date", "title", "creator", "description"]:
dcattr = doc.createElement("dc:%s" % attr)
dcroot.appendChild(dcattr)
dcattr.appendChild(doc.createTextNode(str(self.__dict__.get(attr, ""))))
relsextstream = doc.createElement("foxml:datastream")
root.appendChild(relsextstream)
relsextstream.setAttribute("ID", "RELS-EXT")
relsextstream.setAttribute("STATE", "A")
relsextstream.setAttribute("CONTROL_GROUP", "X")
relsextstream.setAttribute("VERSIONABLE", "true")
relsextstreamver = doc.createElement("foxml:datastreamVersion")
relsextstream.appendChild(relsextstreamver)
relsextstreamver.setAttribute("ID", "RELS-EXT.0")
relsextstreamver.setAttribute("MIMETYPE", "application/rdf+xml")
relsextstreamver.setAttribute("LABEL", "RDF")
# <rdf:RDF
# xmlns:fedora-model="info:fedora/fedora-system:def/model#"
# xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
rdfxml = doc.createElement("foxml:xmlContent")
relsextstreamver.appendChild(rdfxml)
rdfroot = doc.createElement("rdf:RDF")
rdfxml.appendChild(rdfroot)
rdfroot.setAttribute("xmlns:fedora-model", "info:fedora/fedora-system:def/model#")
rdfroot.setAttribute("xmlns:rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
rdfdesc = doc.createElement("rdf:Description")
rdfroot.appendChild(rdfdesc)
rdfdesc.setAttribute("rdf:about", "info:fedora/%s" % pid)
rdfmodel = doc.createElement("fedora-model:hasModel")
rdfdesc.appendChild(rdfmodel)
rdfmodel.setAttribute("rdf:resource", "info:fedora/%s" % self.CONTENT_MODEL)
return doc.toxml()
def from_foxml(self, foxml):
"""
Load object from a Fedora Object XML string.
"""
doc = minidom.parseString(foxml)
root = doc.documentElement
@classmethod
def from_xml(cls, xml, **kwargs):
fo = cls(**kwargs)
for subele in xml.getchildren():
fo.__dict__[utils.strip_ns(subele.tag)] = subele.text
return fo
def datastream(self, dsid):
self._response = self._handler.getDatastream(self.pid, dsid, format="xml")
if self._response.getStatus() != "200":
raise utils.FedoraException("Datastream '%s' for object with pid '%s' not found" % (dsid, self.pid))
rdoc = minidom.parseString(self._response.getBody().getContent())
return fcdatastream.FedoraDatastream.load_from_xml(self.pid, rdoc.documentElement)
def datastreams(self):
self._response = self._handler.listDatastreams(self.pid, format="xml")
rdoc = minidom.parseString(self._response.getBody().getContent())
ds = []
for item in rdoc.getElementsByTagName("datastream"):
d = fcdatastream.FedoraDatastream.load_from_xml(self.pid, item)
ds.append(d)
return ds
def delete_datastream(self, dsid):
"""
Run purgeDatastream on the given dsid
"""
self._response = self._handler.purgeDatastream(
self.pid,
dsid
)
return self._response.getStatus() == "204"
def add_datastream(self, *args, **kwargs):
"""
Add a new datastream to the object.
"""
print "Calling FedoraObject add_datastream"
ds = self.new_datastream(*args, **kwargs)
return ds.save()
def new_datastream(self, dsid, label=None, content=None, content_type=None, content_length=None):
"""
Return a new datastream for this object.
"""
ds = fcdatastream.FedoraDatastream.new(self.pid, dsid)
ds.set_attribute("label", label)
ds.set_attribute("mimetype", content_type)
ds.set_attribute("size", content_length)
ds.set_content(content)
return ds
# def add_relationship(self, relobject, reldesc):
# """
# Set a relationship to another object in this object's RELS-EXT.
# """
#
# rels = self.relationships()
# for rel in rels:
# desc, pid = rel
# if relobject.pid == pid and reldesc == desc:
# return self
# rels.append((reldesc, relobject.pid))
# return self.set_relationships(rels)
# def related_by(self, desctype):
# rels = self.relationships()
# relpids = []
# for desc, pid in rels:
# if desctype == desc:
# relpids.append(pid)
# querystr =
def find_related_by(self, reldesc):
"""
Query relationships with risearch.
TODO: Turn this into a reuseable module.
"""
query = "select $object from <#ri> where $object <fedora-rels-ext:%s> <info:fedora/%s>" % (
reldesc,
self.pid
)
ri = risearch.RiSearch("http://localhost:8080/fedora/risearch")
response = ri.query(query)
# parse the response into a set of results
objects = []
rdoc = minidom.parseString(response)
for result in rdoc.documentElement.getElementsByTagName("object"):
pid = result.getAttribute("uri").replace("info:fedora/", "", 1)
objects.append(FedoraObject(pid))
return objects
def relationships(self):
"""
Get list of RELS-EXT data. Each item is a tuple containing
the relationship description and the related object pid.
"""
self._response = self._handler.getDatastreamDissemination(self.pid, "RELS-EXT", format="xml")
# return an empty dict if nothing was found
if self._response.getStatus() == "404":
return []
rdoc = minidom.parseString(self._response.getBody().getContent())
rels = []
for ele in rdoc.documentElement.getElementsByTagName("rdf:Description"):
# skip descriptions for other subjects
subject = ele.getAttribute("rdf:about")
if not subject.endswith(self.pid):
continue
for relele in ele.getElementsByTagName("*"):
desc = relele.nodeName.replace("rel:", "", 1)
pid = relele.getAttribute("rdf:resource").replace("info:fedora/", "", 1)
rels.append((desc, pid))
return rels
def set_relationships(self, rels):
"""
Set RELS-EXT relationships.
"""
# determine the rdf content from the rels tuples
rdfxml = self._relations_rdf(rels)
self._response = self._handler.getDatastreamDissemination(self.pid, "RELS-EXT", format="xml")
if self._response.getStatus() == "404":
ds = self.new_datastream("RELS-EXT", content_type="application/rdf+xml", content=rdfxml)
if not ds.save():
return False
self._response = self._handler.modifyDatastream(self.pid, "RELS-EXT", content=rdfxml)
return self._response.getStatus() == "201"
def set_relationship(self, reldesc, relto):
"""
Set a single RELS-EXT relationship.
"""
rels = self.relationships()
for desc, subject in rels:
if desc == reldesc and subject == relto.pid:
return True
rels.append((reldesc, relto.pid))
return self.set_relationships(rels)
def dublincore(self):
self._response = self._handler.getDatastreamDissemination(self.pid, "DC", format="xml")
rdoc = minidom.parseString(self._response.getBody().getContent())
dc = OrderedDict([(a,"") for a in self.DUBLINCORE])
for ele in rdoc.documentElement.getElementsByTagName("*"):
try:
value = ele.childNodes[0].nodeValue
except IndexError:
value = ""
dc[ele.nodeName.replace("dc:", "", 1) ] = value
return dc
def set_dublincore(self, dc):
self._response = self._handler.getDatastreamDissemination(self.pid, "DC", format="xml")
print self._response.getBody().getContent()
dcdoc = minidom.parseString(self._response.getBody().getContent())
root = dcdoc.documentElement
root.childNodes = []
for key, value in dc.iteritems():
n = dcdoc.createElement("dc:%s" % key)
n.appendChild(dcdoc.createTextNode(value))
root.appendChild(n)
self._response = self._handler.modifyDatastream(self.pid, "DC", content=dcdoc.toxml())
return self._response.getStatus() == "201"
def next_dsid(self):
# if we've not been given an id, get the next logical one
dsnums = []
newdsid = self.DSIDBASE + "1"
for ds in self.datastreams():
dsidmatch = re.match("^%s(\d+)$" % self.DSIDBASE, ds.dsid)
if dsidmatch:
dsnums.append(int(dsidmatch.groups()[0]))
if dsnums:
maxdsid = sorted(dsnums)[-1]
newdsid = "%s%d" % (self.DSIDBASE, maxdsid + 1)
return newdsid
def _relations_rdf(self, rels):
"""
Get RDF from a list of relationship -> subject tuples.
"""
doc = minidom.Document()
rdfroot = doc.createElement("rdf:RDF")
doc.appendChild(rdfroot)
rdfroot.setAttribute("xmlns:fedora-model", "info:fedora/fedora-system:def/model#")
rdfroot.setAttribute("xmlns:rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
rdfroot.setAttribute("xmlns:fedora-rels-ext", "info:fedora/fedora-system:def/relations-external#")
rdfdesc = doc.createElement("rdf:Description")
rdfroot.appendChild(rdfdesc)
rdfdesc.setAttribute("rdf:about", "info:fedora/%s" % self.pid)
# make sure the content model is always set
if not "fedora-model:hasModel" in [rel[0] for rel in rels]:
rels.append(("fedora-model:hasModel", "info:fedora/%s" % self.CONTENT_MODEL))
for desc, subject in rels:
dnode = doc.createElement(desc)
dnode.setAttribute("rdf:resource", "info:fedora/%s" % subject)
rdfdesc.appendChild(dnode)
return doc.toxml()
def __eq__(self, other):
return self.pid == other.pid
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self.__dict__.get("pid"))
| Python |
# Fedora Commons Handler Object
from utils import FedoraException
| Python |
import fcobject
reload(fcobject)
import utils
reload(utils)
import xml.etree.cElementTree as elementtree
from cStringIO import StringIO
def query_args(argdict):
args = {}
for arg, val in argdict.iteritems():
if arg.startswith("_"):
continue
if isinstance(val, bool):
args[arg] = str(val).lower()
else:
args[arg] = str(val)
return args
class FedoraAdaptor(object):
def __init__(self, *args, **kwargs):
self._params = {}
self._params.update(utils.DEFAULTS)
self._handler = utils.FCRepoRestAPI(**self._params)
def query(self, *args, **kwargs):
objects = []
response = self._handler.findObjects(**query_args(kwargs))
parsetree = elementtree.parse(StringIO(response.getBody().getContent()))
for results in parsetree.getroot().findall(utils.add_ns("resultList")):
for ele in results.findall(utils.add_ns("objectFields")):
objects.append(fcobject.FedoraObject.from_xml(ele, **self._params))
return objects
def new_object(self, *args, **kwargs):
response = self._handler.getNextPID(**query_args(kwargs))
parsetree = elementtree.parse(StringIO(response.getBody().getContent()))
try:
nextpid = parsetree.findall("pid")[0].text
return fcobject.FedoraObject.from_pid(self._handler, nextpid)
except IndexError, e:
raise utils.FedoraException("Unable to retrieve next pid for object. Last response body: %s" %
response.getBody().getContent())
def __getattr__(self, attrname):
try:
return self.__dict__[attrname]
except KeyError:
return getattr(self._handler, attrname)
| Python |
""" Python implmentation of the REST API for the Fedora Repository. It is
framework independent in that all it requires is an HTTP module with
a FCRepoRequestFactory class and a FCRepoPesponse class.
The imported FCRepoFactory needs to provide only a constructor and
four methods :
GET : takes a sinlge argument, the method URI
PUT : takes two arguments, the method URI and content
POST : takes two arguments, the method URI and content
DELETE : takes a sinlge argument, the method URI
The FCRepoFactory constructor must take at least four arguments :
repository_url = base URL of the Fedora Repository instance, for
example 'http://localhost:8080/fedora'
username = name of a user that is authorized to execute methods
of the REST API
password = password the the authorized user
realm = authorization realm
"""
from exceptions import NotImplementedError
from types import StringTypes
from fcrepo.http.RequestFactory import FCRepoRequestFactory
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
class FCRepoRestAPI:
METHOD_PARAMS = { }
RETURN_STATUS = { }
FORMAT_AS_XML = [ ]
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def __init__(self, repository_url='http://localhost:8080/fedora',
username='fedoraAdmin', password='fedora',
realm='any', namespace='fedora'):
self.repository_url= repository_url
self.username = username
self.password = password
self.auth_realm = realm
self.namespace = namespace
def guessMimeType(self, content):
# make a very simplistic guess at strings
if type(content) in StringTypes:
if content.rfind('</html>') > 0:
return 'text/html'
elif content.rfind('</xhtml>') > 0:
return 'text/xhtml'
else:
less = content.count('<')
more = content.count('>')
if less == more:
return 'text/xml'
else:
return 'text/plain'
# don't even attempt to figure out all possible Mime Types
return 'unknown'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getRequestFactory(self):
return FCRepoRequestFactory(self.repository_url, self.username,
self.password, self.auth_realm)
def paramsAsURI(self, method_name, params, ignore=()):
valid_params = self.METHOD_PARAMS[method_name]
uri = ''
for name in params:
if name in valid_params and name not in ignore:
if uri: uri += '&'
uri += name + '=' + self.urlSafeString(params[name])
if method_name in self.FORMAT_AS_XML and 'format' not in params:
if uri: uri += '&'
uri += 'format=xml'
return uri
def urlSafeString(self, text):
return text.replace(' ','%20')
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def describeRepository(self, **kwargs):
raise NotImplementedError
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def addDatastream(self, pid, dsID, **kwargs):
uri = '/objects/' + pid + '/datastreams/' + dsID
param_uri = self.paramsAsURI('addDatastream', kwargs,
ignore=('content',))
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
content = kwargs.get('content', None)
mime_type = kwargs.get('mimeType',None)
content_length = kwargs.get('contentLength', None)
if mime_type is None:
mime_type = self.guessMimeType(content)
return repo.POST(uri, content, mime_type, content_length=content_length)
METHOD_PARAMS['addDatastream'] = ( 'controlGroup', 'dsLocation', 'altIDs'
, 'dsLabel', 'versionable', 'dsState'
, 'formatURI', 'checksumType', 'checksum'
, 'mimeType', 'logMessage'
)
RETURN_STATUS['addDatastream'] = '201'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def addRelationship(self, **kwargs):
raise NotImplementedError
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def compareDatastreamChecksum(self, **kwargs):
raise NotImplementedError
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def export(self, pid, **kwargs):
uri = '/objects/' + pid + '/export'
param_uri = self.paramsAsURI('export', kwargs)
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
return repo.GET(uri)
METHOD_PARAMS['export'] = ('format', 'context', 'encoding')
RETURN_STATUS['export'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def findObjects(self, **kwargs):
uri = '/objects?'
if 'query' in kwargs:
uri += 'query=' + kwargs['query']
elif 'terms' in kwargs:
uri += 'terms=' + kwargs['terms']
else:
uri += 'terms=*'
if 'resultFormat' in kwargs:
uri += '&resultFormat=' + kwargs['resultFormat']
else:
uri += '&resultFormat=xml'
param_uri = self.paramsAsURI('findObjects', kwargs,
ignore=('terms','query','resultFormat'))
if len(param_uri) < 2:
param_uri = 'pid=true&label=true'
uri += '&' + param_uri
#
repo = self.getRequestFactory()
return repo.GET(uri)
METHOD_PARAMS['findObjects'] = ( 'terms', 'query', 'maxResults'
, 'resultFormat', 'pid', 'label', 'state'
, 'ownerid', 'cDate' 'mDate', 'dcnDate'
, 'title', 'creator', 'subject'
, 'description', 'publisher', 'contributor'
, 'date', 'type', 'format', 'identifier'
, 'source', 'language', 'relation'
, 'coverage', 'rights'
)
RETURN_STATUS['findObjects'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getDatastream(self, pid, dsID, **kwargs):
uri = '/objects/' + pid + '/datastreams/' + dsID
param_uri = self.paramsAsURI('getDatastream', kwargs)
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
return repo.GET(uri)
FORMAT_AS_XML.append('getDatastream')
METHOD_PARAMS['getDatastream'] = ('format', 'asOfDateTime')
RETURN_STATUS['getDatastream'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getDatastreamHistory(self, **kwargs):
raise NotImplementedError
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getDatastreamDissemination(self, pid, dsID, **kwargs):
uri = '/objects/' + pid + '/datastreams/' + dsID + '/content'
param_uri = self.paramsAsURI('getDatastreamDissemination', kwargs)
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
return repo.GET(uri)
METHOD_PARAMS['getDatastreamDissemination'] = ('asOfDateTime',)
RETURN_STATUS['getDatastreamDissemination'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getDatastreams(self, **kwargs):
raise NotImplementedError
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getDissemination(self, **kwargs):
raise NotImplementedError
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getNextPID(self, **kwargs):
uri = '/objects/nextPID'
param_uri = self.paramsAsURI('getNextPID', kwargs)
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
return repo.POST(uri)
FORMAT_AS_XML.append('getNextPID')
METHOD_PARAMS['getNextPID'] = ('numPIDs', 'namespace', 'format')
RETURN_STATUS['getNextPID'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getObjectHistory(self, pid, **kwargs):
uri = '/objects/' + pid + '/versions'
param_uri = self.paramsAsURI('getObjectHistory', kwargs)
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
return repo.GET(uri)
FORMAT_AS_XML.append('getObjectHistory')
METHOD_PARAMS['getObjectHistory'] = ('format',)
RETURN_STATUS['getObjectHistory'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getObjectProfile(self, **kwargs):
if 'pid' not in kwargs:
return None
uri = '/objects/' + kwargs["pid"]
param_uri = self.paramsAsURI('getObjectProfile', kwargs)
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
return repo.GET(uri)
FORMAT_AS_XML.append('getObjectProfile')
METHOD_PARAMS['getObjectProfile'] = ('asOfDateTime','format',)
RETURN_STATUS['getObjectProfile'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getObjectXML(self, pid, **kwargs):
uri = '/objects/' + pid + '/objectXML'
repo = self.getRequestFactory()
return repo.GET(uri)
METHOD_PARAMS['getObjectXML'] = ()
RETURN_STATUS['getObjectXML'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getRelationships(self, **kwargs):
raise NotImplementedError
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def ingest(self, pid='new', **kwargs):
uri = '/objects/' + pid
param_uri = self.paramsAsURI('ingest', kwargs,
ignore=('pid', 'content'))
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
content = kwargs.get('content', None)
return repo.POST(uri, content, 'text/xml')
METHOD_PARAMS['ingest'] = ( 'label', 'format', 'encoding', 'namespace'
, 'ownerId', 'logMessage', 'ignoreMime'
, 'content'
)
RETURN_STATUS['ingest'] = '201'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def listDatastreams(self, pid, **kwargs):
uri = '/objects/' + pid + '/datastreams'
param_uri = self.paramsAsURI('listDatastreams', kwargs)
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
return repo.GET(uri)
FORMAT_AS_XML.append('listDatastreams')
METHOD_PARAMS['listDatastreams'] = ('format', 'asOfDateTime')
RETURN_STATUS['listDatastreams'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def listMethods(self, pid, **kwargs):
uri = '/objects/' + pid + '/methods'
param_uri = self.paramsAsURI('listMethods', kwargs)
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
return repo.GET(uri)
FORMAT_AS_XML.append('listMethods')
METHOD_PARAMS['listMethods'] = ('format', 'asOfDateTime')
RETURN_STATUS['listMethods'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def modifyDatastream(self, pid, dsID, **kwargs):
uri = '/objects/' + pid+ '/datastreams/' + dsID
param_uri = self.paramsAsURI('modifyDatastream', kwargs,
ignore=('content',))
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
content = kwargs.get('content', None)
content_length = kwargs.get('contentLength', None)
mimetype = kwargs.get('mimeType',None)
if mimetype is None:
mimetype = self.guessMimeType(content)
return repo.POST(uri, content, mimetype)
METHOD_PARAMS['modifyDatastream'] = ( 'dsLocation', 'altIDs', 'dsLabel'
, 'versionable', 'dsState', 'formatURI'
, 'checksumType', 'checksum'
, 'mimeType', 'logMessage', 'force'
, 'ignoreContent', 'content'
)
RETURN_STATUS['modifyDatastream'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def modifyObject(self, pid, **kwargs):
uri = '/objects/' + pid
param_uri = self.paramsAsURI('modifyObject', kwargs)
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
return repo.PUT(uri)
METHOD_PARAMS['modifyObject'] = ('label', 'ownerId', 'state', 'logMessage')
RETURN_STATUS['modifyObject'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def purgeDatastream(self, pid, dsID, **kwargs):
uri = '/objects/' + pid + '/datastreams/' + dsID
param_uri = self.paramsAsURI('purgeDatastream', kwargs)
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
return repo.DELETE(uri)
METHOD_PARAMS['purgeDatastream'] = ( 'startDT', 'endDT', 'logMessage'
, 'force'
)
RETURN_STATUS['purgeDatastream'] = '204'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def purgeObject(self, pid, **kwargs):
uri = '/objects/' + pid
param_uri = self.paramsAsURI('purgeObject', kwargs)
if param_uri:
uri += '?' + param_uri
#
repo = self.getRequestFactory()
return repo.DELETE(uri)
METHOD_PARAMS['purgeObject'] = ( 'logMessage', 'force')
RETURN_STATUS['purgeObject'] = '204'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def purgeRelationship(self, **kwargs):
raise NotImplementedError
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def resumeFindObjects(self, **kwargs):
uri = '/objects?'
if 'query' in kwargs:
uri += 'query=' + kwargs['query']
elif 'terms' in kwargs:
uri += 'terms=' + kwargs['terms']
else:
uri += 'terms=*'
if 'resultFormat' in kwargs:
uri += '&resultFormat=' + kwargs['resultFormat']
else:
uri += '&resultFormat=xml'
param_uri = self.paramsAsURI('findObjects', kwargs,
ignore=('terms','query','resultFormat'))
if len(param_uri) < 2:
param_uri = 'pid=true&label=true'
uri += '&' + param_uri
#
repo = self.getRequestFactory()
return repo.GET(uri)
METHOD_PARAMS['resumeFindObjects'] = ( 'sessionToken', 'terms', 'query'
, 'maxResults', 'resultFormat', 'pid'
, 'label', 'state', 'ownerid', 'cDate'
, 'mDate', 'dcnDate', 'title'
, 'creator', 'subject', 'description'
, 'publisher', 'contributor', 'date'
, 'type', 'format', 'identifier'
, 'source', 'language', 'relation'
, 'coverage', 'rights'
)
RETURN_STATUS['resumeFindObjects'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def setDatastreamState(self, pid, dsID, **kwargs):
uri = '/objects/' + pid + '/datastreams/' + dsID
state = kwargs.get('dsState', 'A')
if len(state) < 1:
state = state[0]
uri += '?dsState=' + state
#
repo = self.getRequestFactory()
return repo.PUT(uri)
METHOD_PARAMS['setDatastreamState'] = ('dsState',)
RETURN_STATUS['setDatastreamState'] = '200'
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def setDatastreamVersionable(self, pid, dsID, **kwargs):
uri = '/objects/' + pid + '/datastreams/' + dsID
versionable = kwargs.get('versionable', 'true')
if type(versionable) == type(True):
if versionable:
versionable = 'true'
else:
versionable = 'false'
uri += '?versionable=' + versionable
#
repo = self.getRequestFactory()
return repo.PUT(uri)
METHOD_PARAMS['setDatastreamVersionable'] = ('versionable',)
RETURN_STATUS['setDatastreamVersionable'] = '200'
| Python |
""" Base implementation of FCRepoRequestFactory interface.
"""
from fcrepo.http.interfaces import I_FCRepoRequestFactory
from fcrepo.http.interfaces import I_FCRepoResponse
from fcrepo.http.interfaces import I_FCRepoResponseBody
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
class B_FCRepoResponseBody(I_FCRepoResponseBody):
""" Abstract base implementation of I_FCRepoResponseBody interface.
"""
def __init__(self, raw_data, mime_type):
self._raw_data = raw_data
self._mime_type = mime_type
def getMimeType(self):
return self._mime_type
def getRawData(self):
return self._raw_data
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
class B_FCRepoResponse(I_FCRepoResponse):
""" Abstract base implementation of I_FCRepoResponse interface.
"""
def getFooter(self, name, default=''):
return self.getFooters().get(name, default)
def getHeader(self, name, default=''):
return self.getHeaders().get(name, default)
def getRequest(self):
request = self.getRequestMethod() + ' ' + self.getRequestURI()
return request
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
class B_FCRepoRequestFactory(I_FCRepoRequestFactory):
""" Abstract base implementation of I_FCRepoRequestFactory interface.
"""
def __init__(self, repository_url, username='fedoraAdmin',
password='fedora', realm='any'):
self.initRepository(repository_url)
self.setAuthUser(username)
self.setAuthPassword(password)
self.setAuthRealm(realm)
self._last_request = ''
def initRepository(self, url):
slash_slash = url.find('://')
self.protocol = url[:slash_slash]
remainder = url[slash_slash+3:]
colon = remainder.find(':')
self.setDomain(remainder[:colon])
remainder = remainder[colon+1:]
slash = remainder.find('/')
self.setPort(remainder[:slash])
remainder = remainder[slash+1:]
slash = remainder.find('/')
if slash > -1:
self.setContext(remainder[:slash])
else:
self.setContext(remainder)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getAuthPassword(self):
return self.auth_pwd
def getAuthRealm(self):
return self.auth_realm
def getAuthUser(self):
return self.auth_user
def getContext(self):
return self.context
def getDomain(self):
return self.domain
def getLastRequest(self):
return self._last_request
def getPort(self):
return str(self.port)
def getProtocol(self):
return self.protocol
def getRepositoryURL(self):
url = self.protocol + '://' + self.domain + ':' + str(self.port)
url += '/' + self.context
return url
def getRequestURL(self, request_uri):
url = self.getRepositoryURL()
if not request_uri.startswith('/'):
url += '/'
url += request_uri
return url
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def setAuthPassword(self, password):
self.auth_pwd = password
def setAuthRealm(self, realm):
self.auth_realm = realm
def setAuthUser(self, username):
self.auth_user = username
def setContext(self, context):
if context.startswith('/'):
context = context[1:]
if context.endswith('/'):
context = context[:-1]
self.context = context
def setDomain(self, url):
slash_slash = url.find('://')
if slash_slash > -1:
domain = url[slash_slash+3:]
colon = domain.find(':')
if colon > -1:
self.domain = domain[:colon]
else:
self.domain = url
def setPort(self, port):
self.port = int(port)
def setProtocol(self, protocol):
if '://' in protocol:
slash_slash = url.find('://')
protocol = protocol[:slash_slash-1]
self.protocol = protocol
| Python |
""" Interfaces for FCRepoRequestFactory, FCRepoResponse and FCRepoResponseBody.
"""
from exceptions import NotImplementedError
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
class I_FCRepoResponseBody:
def __init__(self, raw_content, mime_type):
""" Constructor takes tow arguments :
raw_content = raw body content (Base64 encoded).
mime_type = MimeTyoe of the body content.
"""
raise NotImplementedError
def getContent(self):
""" Returns the reponse body properly formatted for the MimeType.
"""
raise NotImplementedError
def getMimeType(self):
""" Returns the MimeType of the body content.
"""
raise NotImplementedError
def getRawData(self):
""" Returns the raw response body (Base64 encoded).
"""
raise NotImplementedError
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
class I_FCRepoResponse:
def __init__(self):
# init method args are implementation-dependent
pass
def getBody(self):
""" Provides accces to body content enclosed in the response
"""
raise NotImplementedError
def getFooter(self, name, default):
""" Returns value of a response footer parameter. Takes two arguments:
name = name of the parameter
default = default value to be returned when parameter is NOT
in the footer.
"""
raise NotImplementedError
def getFooters(self):
""" Returns all response footer parameters as a Python dictionary.
"""
raise NotImplementedError
def getHeader(self, name, default):
""" Returns value of a response header parameter. Takes two arguments:
name = name of the parameter
default = default value to be returned when parameter is NOT
in the header.
"""
raise NotImplementedError
def getHeaders(self):
""" Returns all response header parameters as a Python dictionary.
"""
raise NotImplementedError
def getStatus(self):
""" Returns the HTTP status code returned for the request.
"""
raise NotImplementedError
def getRequestMethod(self):
""" Returns the name of the HTTP method used for the request.
"""
raise NotImplementedError
def getRequestURI(self):
""" Returns the complete escaped URI used for the request.
"""
raise NotImplementedError
def getRequest(self):
""" Returns the reguest method and the complete escaped request
URI as a single string.
"""
raise NotImplementedError
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
class I_FCRepoRequestFactory:
def __init__(self, repository_url, username, password, realm='any'):
""" Requires at least four arguments:
repository_url = the base URL for the Fedora Repository
including the protocol, domain, port,
and context.
username = name of a user that is authorized to perform
requests using the Fedora REST API.
password = password for the authorized user.
realm = authorization realm, must ak=llow the string 'any' to
designate that authentication is valid for anty realm.
"""
raise NotImplementedError
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def DELETE(self, request_uri):
""" Submits a DELETE request for the requested URI.
Takes a single argument:
request_uri = the query portion of the DELETE request
i.e. the URL for the request without the protocol,
domain, port and context of the Fedora Repository.
Returns results of the request as a FCRepoResponse object.
"""
raise NotImplementedError
def GET(self, request_uri):
""" Submits a GET request for the requested URI
Takes a single argument:
request_uri = the query portion of the DELETE request
i.e. the URL for the request without the protocol,
domain, port and context of the Fedora Repository.
"""
raise NotImplementedError
def POST(self, request_uri, content=None, chunked=False):
""" Submits a POST request for the requested URI
Takes a three arguments:
request_uri = the query portion of the DELETE request
i.e. the URL for the request without the protocol,
domain, port and context of the Fedora Repository.
content = contet to be include in POST request (if any)
chunked = boolean indiciating whether contant is to be provided
in chunks.
"""
raise NotImplementedError
def PUT(self, request_uri, content=None, chunked=False):
""" Submits a PUT request for the requested URI
Takes a three arguments:
request_uri = the query portion of the DELETE request
i.e. the URL for the request without the protocol,
domain, port and context of the Fedora Repository.
content = contet to be include in POST request (if any)
chunked = boolean indiciating whether contant is to be provided
in chunks.
"""
raise NotImplementedError
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getAuthPassword(self):
""" Returns current value of password to be used for authenticating
access to the Fedora Repository (as set in the constructor or by
the setAuthPassword method).
"""
raise NotImplementedError
def getAuthRealm(self):
""" Returns current value of realm to be used for authenticating
access to the Fedora Repository (as set in the constructor or by
the setAuthRealm method).
"""
raise NotImplementedError
def getAuthUser(self):
""" Returns current value of the username to be used for
authenticating access to the Fedora Repository (as set in the
constructor or by the setAuthUser method).
"""
raise NotImplementedError
def getContext(self):
""" Returns current value of the context to be used for accesssing
the Fedora Repository (as initialized by the constructor or
set by the setContext method).
"""
raise NotImplementedError
def getDomain(self):
""" Returns current value of the internat domain to be used for
accesssing the Fedora Repository (as initialized by the constructor
or set by the setDomain method).
"""
raise NotImplementedError
def getPort(self):
""" Returns current value of the port to be used for accesssing
the Fedora Repository (as initialized by the constructor or set
by the setPort method).
"""
raise NotImplementedError
def getProtocol(self):
""" Returns current value of the HTTP protocol to be used for
accesssing the Fedora Repository (as initialized by the constructor
or set by the setProtocol method).
"""
raise NotImplementedError
def getRepositoryURL(self):
""" Returns current value of the root URL to be used for accesssing
the Fedora Repository. It is constructed from the current values
of the HTTP protocol, repository domain name, port number and
repository context.
"""
raise NotImplementedError
def getLastRequest(self):
""" Returns a string representing the last HTTP Request that was
submitted by the factory. It will include the HTTP method and the
URL submitted. PUT and POST request strings will NOT include the
content submitted with the request.
"""
raise NotImplementedError
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def setAuthPassword(self, password):
""" Changes the value of the password to be used for authenticating
access to the Fedora Repository.
"""
raise NotImplementedError
def setAuthRealm(self, realm):
""" Changes the value of the realm to be used for authenticating
access to the Fedora Repository.
"""
raise NotImplementedError
def setAuthUser(self, username):
""" Changes the name of the user to be used for authenticating
access to the Fedora Repository.
"""
raise NotImplementedError
def setContext(self, context):
""" Changes the value of the context to be used for accessing
the Fedora Repository.
"""
raise NotImplementedError
def setDomain(self, url):
""" Changes the value of the domain to be used for accesssing
the Fedora Repository.
"""
raise NotImplementedError
def setPort(self, port):
""" Changes the value of the port used to be used for accesssing
the Fedora Repository.
"""
raise NotImplementedError
def setProtocol(self, protocol):
""" Changes the value of the HTTP protocol to be used for accesssing
the Fedora Repository.
"""
raise NotImplementedError
| Python |
#
| Python |
""" Pure Python Implementation of FCRepoRequestFactory and FCRepoResponse
"""
import base64
from types import StringTypes
from httplib2 import Http
from fcrepo.http.base import B_FCRepoRequestFactory
from fcrepo.http.base import B_FCRepoResponse
from fcrepo.http.base import B_FCRepoResponseBody
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
class ResponseBody(B_FCRepoResponseBody):
def getContent(self):
if 'text' in self._mime_type:
return unicode(base64.b64decode(self._raw_data), 'utf-8')
else:
return self._raw_data
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
class FCRepoResponse(B_FCRepoResponse):
def __init__(self, repository, http_method, request_uri, response, body):
self._repository = repository
self._http_method = http_method
self._request_uri = request_uri
self._status = response['status']
#
self._headers = {}
for name, value in response.items():
self._headers[name] = value
self._footers = {}
#
mime_type = self._headers.get('Content-Type','unknown')
self._body = ResponseBody(body, mime_type)
def getBody(self):
return self._body
def getFooter(self, name, default=None):
return self._footers.get(name, default)
def getFooters(self):
return self._footers
def getHeader(self, name, default=None):
return self._headers.get(name, default)
def getHeaders(self):
return self._headers
def getStatus(self):
return self._status
def getRequestMethod(self):
return self._http_method
def getRequestURI(self):
return self._request_uri
def getRepository(self):
return self._repository
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
class FCRepoRequestFactory(B_FCRepoRequestFactory):
def DELETE(self, request_uri):
return self.submit('DELETE', request_uri)
def GET(self, request_uri):
return self.submit('GET', request_uri)
def POST(self, request_uri, content=None, content_type='unknown',
content_length=None, chunked=False):
return self.submit('POST', request_uri, content, content_type, content_length, chunked)
def PUT(self, request_uri, content=None, content_type='unknown',
content_length=None, chunked=False):
return self.submit('PUT', request_uri, content, content_type, content_length, chunked)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def submit(self, method, request_uri, content=None, content_type=None,
content_length=None, chunked=False):
headers = { 'Connection' : 'Keep-Alive'
, 'Keep-Alive' : '300'
}
repository = self.getRepositoryURL()
url = self.getRequestURL(request_uri)
#
http = Http()
#http.add_credentials(self.auth_user, self.auth_pwd, self.domain)
auth = base64.encodestring("%s:%s" % (self.auth_user, self.auth_pwd))
headers['Authorization'] = 'Basic ' + auth
if content is None:
self._last_request = '%s ' % method + url
response, body = http.request(url, method, headers=headers)
else:
self._last_request = '%s (%s) ' % (method, content_type) + url
headers['Content-Type'] = content_type
if content_length:
headers['Content-Length'] = str(content_length)
response, body = http.request(url, method, body=content,
headers=headers)
response = FCRepoResponse(repository, method, request_uri,
response, body)
return response
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def getAuthScope(self):
return (self.domain, self.port, self.auth_realm)
def getCredentials(self):
return (self.auth_user, self.auth_pwd)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def setAuthRealm(self, realm):
self.auth_realm = realm
| Python |
#
| Python |
"""
Interface to interacting with OCR preset profiles.
"""
from django import forms
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from ocradmin.core import generic_views as gv
from ocradmin.presets.models import Preset, Profile
class ProfileForm(forms.ModelForm):
"""
Base profile form
"""
def __init__(self, *args, **kwargs):
super(ProfileForm, self).__init__(*args, **kwargs)
# change a widget attribute:
self.fields['description'].widget.attrs["rows"] = 2
self.fields['description'].widget.attrs["cols"] = 40
class Meta:
model = Profile
fields = ["name", "tags", "description", "data"]
exclude = ["created_on", "updated_on"]
profilelist = gv.GenericListView.as_view(
model=Profile,
page_name="OCR Profiles",
fields=["name", "description", "created_on"],)
profilecreate = gv.GenericCreateView.as_view(
model=Profile,
form_class=ProfileForm,
page_name="New OCR Profile",)
profiledetail = gv.GenericDetailView.as_view(
model=Profile,
page_name="OCR Profile",
fields=["name", "description", "tags", "created_on",
"updated_on",])
profileedit = gv.GenericEditView.as_view(
model=Profile,
form_class=ProfileForm,
page_name="Edit OCR Profile",)
profiledelete = gv.GenericDeleteView.as_view(
model=Profile,
page_name="Delete OCR Profile",
success_url="/profiles/list/",)
| Python |
"""
Model to store script data.
"""
import json
import datetime
from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
import autoslug
from nodetree import script
class JsonTextField(models.TextField):
def to_python(self, value):
return value
def validate(self, value, *args, **kwargs):
super(models.TextField, self).validate(value, *args, **kwargs)
try:
json.loads(value)
except ValueError:
raise models.exceptions.ValidationError("Data must be valid JSON")
class Preset(models.Model):
user = models.ForeignKey(User, related_name="presets")
tags = tagging.fields.TagField()
name = models.CharField(max_length=100, unique=True)
slug = autoslug.AutoSlugField(populate_from="name", unique=True)
description = models.TextField(blank=True)
public = models.BooleanField(default=True)
created_on = models.DateField(editable=False)
updated_on = models.DateField(editable=False, null=True, blank=True)
data = JsonTextField()
profile = models.ForeignKey("Profile", related_name="presets",
null=True, blank=True)
def __unicode__(self):
"""
String representation.
"""
return self.name
def save(self):
if not self.id:
self.created_on = datetime.datetime.now()
else:
self.updated_on = datetime.datetime.now()
super(Preset, self).save()
def get_absolute_url(self):
"""URL to view an object detail"""
return "/presets/show/%s/" % self.slug
def get_update_url(self):
"""url to update an object detail"""
return "/presets/edit/%s/" % self.slug
def get_delete_url(self):
"""url to update an object detail"""
return "/presets/delete/%s/" % self.slug
@classmethod
def get_list_url(cls):
"""URL to view the object list"""
return "/presets/list/"
@classmethod
def get_create_url(cls):
"""URL to create a new object"""
return "/presets/create/"
TEST_PROFILE = {
"must_exist" : [
{
"attr": "stage",
"value": "recognize",
"unique": False,
},
{
"attr": "stage",
"value": "input",
"unique": True,
},
],
}
class Profile(models.Model):
"""Preset profile. This defines a class of
presets to which the information in the preset
must conform."""
name = models.CharField(max_length=255)
slug = autoslug.AutoSlugField(populate_from="name", unique=True)
tags = tagging.fields.TagField()
description = models.TextField(blank=True)
created_on = models.DateField(editable=False)
updated_on = models.DateField(editable=False, null=True, blank=True)
data = JsonTextField()
def __unicode__(self):
"""
String representation.
"""
return self.name
def save(self):
if not self.id:
self.created_on = datetime.datetime.now()
else:
self.updated_on = datetime.datetime.now()
super(Profile, self).save()
def validate_preset(self, data):
this = json.loads(self.data)
tree = script.Script(data)
errors = []
for name, preds in this.iteritems():
for pred in preds:
perrors = self.validate_predicate(name, pred, tree)
if perrors:
errors.extend(perrors)
return errors
def validate_predicate(self, name, pred, tree):
errors = []
if name == "must_exist":
attr = pred.get("attr")
value = pred.get("value")
unique = pred.get("unique")
nodes = tree.get_nodes_by_attr(attr, value)
if not nodes:
errors.append("A node with attr '%s'='%s' must exist" % (attr, value))
elif len(nodes) > 1:
errors.append("Node with attr '%s'='%s' must be unique" % (attr, value))
return errors
def get_absolute_url(self):
"""URL to view an object detail"""
return "/profiles/show/%s/" % self.slug
def get_update_url(self):
"""url to update an object detail"""
return "/profiles/edit/%s/" % self.slug
def get_delete_url(self):
"""url to update an object detail"""
return "/profiles/delete/%s/" % self.slug
@classmethod
def get_list_url(cls):
"""URL to view the object list"""
return "/profiles/list/"
@classmethod
def get_create_url(cls):
"""URL to create a new object"""
return "/profiles/create/"
| Python |
"""
URLConf for OCR presets.
"""
from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from ocradmin.presets import views
urlpatterns = patterns('',
(r'^builder/?$', login_required(views.builder)),
(r'^builder/(?P<pid>[^/]+)/?$', login_required(views.builder_doc_edit)),
(r'^clear_cache/?$', login_required(views.clear_cache)),
(r'^clear_node_cache/?$', views.clear_node_cache),
(r'^create/?$', login_required(views.presetcreate)),
(r'^createjson/?$', login_required(views.createjson)),
(r'^data/(?P<slug>[-\w]+)/?$', views.data),
(r'^delete/(?P<slug>[-\w]+)/?$', login_required(views.presetdelete)),
(r'^download/(?P<slug>[-\w]+)/?$', views.download),
(r'^edit/(?P<slug>[-\w]+)/?$', login_required(views.presetedit)),
(r'^fetch/?$', views.fetch),
(r'^layout_graph/?$', views.layout_graph),
(r'^list/?$', views.presetlist),
(r'^query/?$', views.query_nodes),
(r'^run/?$', views.run_preset),
(r'^show/(?P<slug>[-\w]+)/?$', views.presetdetail),
(r'^update_data/(?P<slug>[-\w]+)/?$', views.update_data),
(r'^upload/?$', login_required(views.upload_file)),
(r'^(?P<slug>[-\w]+)/?$', views.presetdetail),
)
| Python |
"""
Import a script file or files into the database.
"""
import os
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from ocradmin.presets.models import Preset
from django.core.exceptions import ImproperlyConfigured
from django.utils import simplejson as json
class Command(BaseCommand):
args = "<scriptfile1> ... <scriptfileN>"
help = "Import JSON scripts into the presets database"
option_list = BaseCommand.option_list + (
make_option(
"-d",
"--description",
action="store",
type="string",
dest="description",
default="",
help="Description for the given preset"),
make_option(
"-n",
"--name",
action="store",
type="string",
dest="name",
help="Name of the preset. If not given, inferred from the file name"),
make_option(
"-t",
"--tags",
action="store",
type="string",
dest="tags",
default="",
help="Comma separated list of tags"),
)
def handle(self, *args, **options):
try:
adminuser = User.objects.get(is_superuser=True)
except User.DoesNotExist:
raise ImproperlyConfigured(
"An admin user must exist before presets can be imported.")
if not args:
raise CommandError("Scripts to import must be given as arguments.")
for f in args:
if not os.path.exists(f):
raise CommandError("Script file does not exist: %s" % f)
name = options.get("name")
if name is None:
name = os.path.splitext(os.path.basename(f))[0].capitalize()
if name.strip() == "":
raise CommandError("Script must have a valid name")
tags = " ".join([t.strip() for t in options.get("tags", "").split(",")])
description = options.get("description")
with open(f) as fh:
data = fh.read()
try:
script = json.loads(data)
meta = script.get("__meta")
if meta is not None:
name = meta.get("name", name)
description = meta.get("description", options.get("description"))
tags = meta.get("tags", tags)
except json.JSONDecodeError, err:
raise CommandError("Invalid script: JSON data could not be decoded.")
p = Preset(
name=name,
user=adminuser,
tags=tags,
description=description,
data=data,
)
p.save()
self.stdout.write("Successfully import preset: %s\n" % name)
| Python |
from presets_testmaker import *
from test_scripts import *
from test_builder import *
| Python |
#coding: utf-8
import os
import glob
from django.test import TestCase
from django.test import Client
from django import template
from django.db.models import get_model
from django.contrib.auth.models import User
from ocradmin.core.tests import testutils
from nodetree import script, node
class Testmaker(TestCase):
fixtures = [
"presets/fixtures/profile_fixtures.json",
"presets/fixtures/test_fixtures.json"
]
def setUp(self):
"""
Setup OCR tests. Creates a test user.
"""
testutils.symlink_model_fixtures()
self.testuser = User.objects.create_user("AnonymousUser", "test@testing.com", "testpass")
self.client = Client()
self.client.login(username="test_user", password="testpass")
def test_presetsbuilder_131016874872(self):
r = self.client.get('/presets/builder/', {})
self.assertEqual(r.status_code, 302)
def test_staticcssformscss_131016875011(self):
r = self.client.get('/static/css/forms.css', {})
self.assertEqual(r.status_code, 200)
def test_staticcsscleancss_131016875012(self):
r = self.client.get('/static/css/clean.css', {})
self.assertEqual(r.status_code, 200)
def test_staticcssnodetreecss_131016875013(self):
r = self.client.get('/static/css/nodetree.css', {})
self.assertEqual(r.status_code, 200)
def test_staticjsuploadersajaxjs_131016875014(self):
r = self.client.get('/static/js/ocr_js/ajax_uploader.js', {})
self.assertEqual(r.status_code, 200)
def test_staticjspresetsbuilderjs_131016875015(self):
r = self.client.get('/static/js/presets/builder.js', {})
self.assertEqual(r.status_code, 200)
def test_staticjspreset_managerjs_131016875015(self):
r = self.client.get('/static/js/preset_manager.js', {})
self.assertEqual(r.status_code, 200)
def test_staticcssimage_viewercss_131016875018(self):
r = self.client.get('/static/css/image_viewer.css', {})
self.assertEqual(r.status_code, 200)
def test_presetsquery_131016875081(self):
r = self.client.get('/presets/query/', {})
self.assertEqual(r.status_code, 200)
def test_presetslist_131016875553(self):
r = self.client.get('/presets/list/', {})
self.assertEqual(r.status_code, 200)
self.assertEqual(unicode(r.context["media"]), u"""screen""")
self.assertEqual(unicode(r.context["preset_list"]), u"""[<Preset: CuneiformBasic>, <Preset: Evaluation Test>, <Preset: OcropusBasic>, <Preset: SegmentTest>, <Preset: SwitchTest>, <Preset: TesseractBasic>]""")
self.assertEqual(unicode(r.context["fields"]), u"""['name', 'description', 'profile', 'user', 'created_on']""")
self.assertEqual(unicode(r.context["object_list"]), u"""[<Preset: CuneiformBasic>, <Preset: Evaluation Test>, <Preset: OcropusBasic>, <Preset: SegmentTest>, <Preset: SwitchTest>, <Preset: TesseractBasic>]""")
self.assertEqual(unicode(r.context["LANGUAGES"]), u"""(('ar', 'Arabic'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('bn', 'Bengali'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('el', 'Greek'), ('en', 'English'), ('en-gb', 'British English'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy-nl', 'Frisian'), ('ga', 'Irish'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hu', 'Hungarian'), ('id', 'Indonesian'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('nl', 'Dutch'), ('no', 'Norwegian'), ('nb', 'Norwegian Bokmal'), ('nn', 'Norwegian Nynorsk'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-cn', 'Simplified Chinese'), ('zh-tw', 'Traditional Chinese'))""")
self.assertEqual(unicode(r.context["page_obj"]), u"""<Page 1 of 1>""")
self.assertEqual(unicode(r.context["page_name"]), u"""OCR Presets""")
self.assertEqual(unicode(r.context["user"]), u"""AnonymousUser""")
self.assertEqual(unicode(r.context["model"]), u"""<class 'presets.models.Preset'>""")
self.assertEqual(unicode(r.context["is_paginated"]), u"""False""")
self.assertEqual(unicode(r.context["order"]), u"""name""")
self.assertEqual(unicode(r.context["LANGUAGE_BIDI"]), u"""False""")
self.assertEqual(unicode(r.context["MEDIA_URL"]), u"""/media/""")
def test_staticcssgenericcss_13101687559(self):
r = self.client.get('/static/css/generic.css', {})
self.assertEqual(r.status_code, 200)
def test_presetsshowcuneiformbasic_131016875901(self):
r = self.client.get('/presets/show/cuneiformbasic/', {})
self.assertEqual(r.status_code, 200)
self.assertEqual(unicode(r.context["media"]), u"""screen""")
self.assertEqual(unicode(r.context["fields"]), u"""['name', 'description', 'user', 'public', 'profile', 'tags', 'created_on', 'updated_on']""")
self.assertEqual(unicode(r.context["object"]), u"""CuneiformBasic""")
self.assertEqual(unicode(r.context["LANGUAGES"]), u"""(('ar', 'Arabic'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('bn', 'Bengali'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('el', 'Greek'), ('en', 'English'), ('en-gb', 'British English'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy-nl', 'Frisian'), ('ga', 'Irish'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hu', 'Hungarian'), ('id', 'Indonesian'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('nl', 'Dutch'), ('no', 'Norwegian'), ('nb', 'Norwegian Bokmal'), ('nn', 'Norwegian Nynorsk'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-cn', 'Simplified Chinese'), ('zh-tw', 'Traditional Chinese'))""")
self.assertEqual(unicode(r.context["preset"]), u"""CuneiformBasic""")
self.assertEqual(unicode(r.context["page_name"]), u"""OCR Preset""")
self.assertEqual(unicode(r.context["user"]), u"""AnonymousUser""")
self.assertEqual(unicode(r.context["LANGUAGE_BIDI"]), u"""False""")
self.assertEqual(unicode(r.context["MEDIA_URL"]), u"""/media/""")
def test_presetseditcuneiformbasic_131016876156(self):
r = self.client.get('/presets/edit/cuneiformbasic/', {})
self.assertEqual(r.status_code, 302)
def test_presetsshowcuneiformbasic_131016877426(self):
r = self.client.get('/presets/show/cuneiformbasic/', {})
self.assertEqual(r.status_code, 200)
self.assertEqual(unicode(r.context["media"]), u"""screen""")
self.assertEqual(unicode(r.context["fields"]), u"""['name', 'description', 'user', 'public', 'profile', 'tags', 'created_on', 'updated_on']""")
self.assertEqual(unicode(r.context["object"]), u"""CuneiformBasic""")
self.assertEqual(unicode(r.context["LANGUAGES"]), u"""(('ar', 'Arabic'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('bn', 'Bengali'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('el', 'Greek'), ('en', 'English'), ('en-gb', 'British English'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy-nl', 'Frisian'), ('ga', 'Irish'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hu', 'Hungarian'), ('id', 'Indonesian'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('nl', 'Dutch'), ('no', 'Norwegian'), ('nb', 'Norwegian Bokmal'), ('nn', 'Norwegian Nynorsk'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-cn', 'Simplified Chinese'), ('zh-tw', 'Traditional Chinese'))""")
self.assertEqual(unicode(r.context["preset"]), u"""CuneiformBasic""")
self.assertEqual(unicode(r.context["page_name"]), u"""OCR Preset""")
self.assertEqual(unicode(r.context["user"]), u"""AnonymousUser""")
self.assertEqual(unicode(r.context["LANGUAGE_BIDI"]), u"""False""")
self.assertEqual(unicode(r.context["MEDIA_URL"]), u"""/media/""")
def test_presetsdeletecuneiformbasic_13101687797(self):
r = self.client.get('/presets/delete/cuneiformbasic/', {})
self.assertEqual(r.status_code, 302)
def test_presetsshowcuneiformbasic_131016878162(self):
r = self.client.get('/presets/show/cuneiformbasic/', {})
self.assertEqual(r.status_code, 200)
self.assertEqual(unicode(r.context["media"]), u"""screen""")
self.assertEqual(unicode(r.context["fields"]), u"""['name', 'description', 'user', 'public', 'profile', 'tags', 'created_on', 'updated_on']""")
self.assertEqual(unicode(r.context["object"]), u"""CuneiformBasic""")
self.assertEqual(unicode(r.context["LANGUAGES"]), u"""(('ar', 'Arabic'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('bn', 'Bengali'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('el', 'Greek'), ('en', 'English'), ('en-gb', 'British English'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy-nl', 'Frisian'), ('ga', 'Irish'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hu', 'Hungarian'), ('id', 'Indonesian'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('nl', 'Dutch'), ('no', 'Norwegian'), ('nb', 'Norwegian Bokmal'), ('nn', 'Norwegian Nynorsk'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-cn', 'Simplified Chinese'), ('zh-tw', 'Traditional Chinese'))""")
self.assertEqual(unicode(r.context["preset"]), u"""CuneiformBasic""")
self.assertEqual(unicode(r.context["page_name"]), u"""OCR Preset""")
self.assertEqual(unicode(r.context["user"]), u"""AnonymousUser""")
self.assertEqual(unicode(r.context["LANGUAGE_BIDI"]), u"""False""")
self.assertEqual(unicode(r.context["MEDIA_URL"]), u"""/media/""")
def test_presetslist_13101687835(self):
r = self.client.get('/presets/list/', {})
self.assertEqual(r.status_code, 200)
self.assertEqual(unicode(r.context["media"]), u"""screen""")
self.assertEqual(unicode(r.context["preset_list"]), u"""[<Preset: CuneiformBasic>, <Preset: Evaluation Test>, <Preset: OcropusBasic>, <Preset: SegmentTest>, <Preset: SwitchTest>, <Preset: TesseractBasic>]""")
self.assertEqual(unicode(r.context["fields"]), u"""['name', 'description', 'profile', 'user', 'created_on']""")
self.assertEqual(unicode(r.context["object_list"]), u"""[<Preset: CuneiformBasic>, <Preset: Evaluation Test>, <Preset: OcropusBasic>, <Preset: SegmentTest>, <Preset: SwitchTest>, <Preset: TesseractBasic>]""")
self.assertEqual(unicode(r.context["LANGUAGES"]), u"""(('ar', 'Arabic'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('bn', 'Bengali'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('el', 'Greek'), ('en', 'English'), ('en-gb', 'British English'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy-nl', 'Frisian'), ('ga', 'Irish'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hu', 'Hungarian'), ('id', 'Indonesian'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('nl', 'Dutch'), ('no', 'Norwegian'), ('nb', 'Norwegian Bokmal'), ('nn', 'Norwegian Nynorsk'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-cn', 'Simplified Chinese'), ('zh-tw', 'Traditional Chinese'))""")
self.assertEqual(unicode(r.context["page_obj"]), u"""<Page 1 of 1>""")
self.assertEqual(unicode(r.context["page_name"]), u"""OCR Presets""")
self.assertEqual(unicode(r.context["user"]), u"""AnonymousUser""")
self.assertEqual(unicode(r.context["model"]), u"""<class 'presets.models.Preset'>""")
self.assertEqual(unicode(r.context["is_paginated"]), u"""False""")
self.assertEqual(unicode(r.context["order"]), u"""name""")
self.assertEqual(unicode(r.context["LANGUAGE_BIDI"]), u"""False""")
self.assertEqual(unicode(r.context["MEDIA_URL"]), u"""/media/""")
def test_presetsshowcuneiformbasic_131016879459(self):
r = self.client.get('/presets/show/cuneiformbasic/', {})
self.assertEqual(r.status_code, 200)
self.assertEqual(unicode(r.context["media"]), u"""screen""")
self.assertEqual(unicode(r.context["fields"]), u"""['name', 'description', 'user', 'public', 'profile', 'tags', 'created_on', 'updated_on']""")
self.assertEqual(unicode(r.context["object"]), u"""CuneiformBasic""")
self.assertEqual(unicode(r.context["LANGUAGES"]), u"""(('ar', 'Arabic'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('bn', 'Bengali'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('el', 'Greek'), ('en', 'English'), ('en-gb', 'British English'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy-nl', 'Frisian'), ('ga', 'Irish'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hu', 'Hungarian'), ('id', 'Indonesian'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('nl', 'Dutch'), ('no', 'Norwegian'), ('nb', 'Norwegian Bokmal'), ('nn', 'Norwegian Nynorsk'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-cn', 'Simplified Chinese'), ('zh-tw', 'Traditional Chinese'))""")
self.assertEqual(unicode(r.context["preset"]), u"""CuneiformBasic""")
self.assertEqual(unicode(r.context["page_name"]), u"""OCR Preset""")
self.assertEqual(unicode(r.context["user"]), u"""AnonymousUser""")
self.assertEqual(unicode(r.context["LANGUAGE_BIDI"]), u"""False""")
self.assertEqual(unicode(r.context["MEDIA_URL"]), u"""/media/""")
def test_presetslist_131016879738(self):
r = self.client.get('/presets/list/', {})
self.assertEqual(r.status_code, 200)
self.assertEqual(unicode(r.context["media"]), u"""screen""")
self.assertEqual(unicode(r.context["preset_list"]), u"""[<Preset: CuneiformBasic>, <Preset: Evaluation Test>, <Preset: OcropusBasic>, <Preset: SegmentTest>, <Preset: SwitchTest>, <Preset: TesseractBasic>]""")
self.assertEqual(unicode(r.context["fields"]), u"""['name', 'description', 'profile', 'user', 'created_on']""")
self.assertEqual(unicode(r.context["object_list"]), u"""[<Preset: CuneiformBasic>, <Preset: Evaluation Test>, <Preset: OcropusBasic>, <Preset: SegmentTest>, <Preset: SwitchTest>, <Preset: TesseractBasic>]""")
self.assertEqual(unicode(r.context["LANGUAGES"]), u"""(('ar', 'Arabic'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('bn', 'Bengali'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('el', 'Greek'), ('en', 'English'), ('en-gb', 'British English'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy-nl', 'Frisian'), ('ga', 'Irish'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hu', 'Hungarian'), ('id', 'Indonesian'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('nl', 'Dutch'), ('no', 'Norwegian'), ('nb', 'Norwegian Bokmal'), ('nn', 'Norwegian Nynorsk'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-cn', 'Simplified Chinese'), ('zh-tw', 'Traditional Chinese'))""")
self.assertEqual(unicode(r.context["page_obj"]), u"""<Page 1 of 1>""")
self.assertEqual(unicode(r.context["page_name"]), u"""OCR Presets""")
self.assertEqual(unicode(r.context["user"]), u"""AnonymousUser""")
self.assertEqual(unicode(r.context["model"]), u"""<class 'presets.models.Preset'>""")
self.assertEqual(unicode(r.context["is_paginated"]), u"""False""")
self.assertEqual(unicode(r.context["order"]), u"""name""")
self.assertEqual(unicode(r.context["LANGUAGE_BIDI"]), u"""False""")
self.assertEqual(unicode(r.context["MEDIA_URL"]), u"""/media/""")
def test_presetsbuilder_13101688024(self):
r = self.client.get('/presets/builder/', {})
self.assertEqual(r.status_code, 302)
def test_presetsquery_131016880277(self):
r = self.client.get('/presets/query/', {})
self.assertEqual(r.status_code, 200)
def test_staticcsscustom_themeimagesui_icons_454545_256x240png_13101688043(self):
r = self.client.get('/static/css/custom-theme/images/ui-icons_454545_256x240.png', {})
self.assertEqual(r.status_code, 200)
def test_presetslist_131016880551(self):
r = self.client.get('/presets/list/', {'format': 'json', })
self.assertEqual(r.status_code, 200)
def test_staticcsscustom_themeimagesui_bg_flat_0_aaaaaa_40x100png_13101688056(self):
r = self.client.get('/static/css/custom-theme/images/ui-bg_flat_0_aaaaaa_40x100.png', {})
self.assertEqual(r.status_code, 200)
def test_presetsdatacuneiformbasic_131016880844(self):
r = self.client.get('/presets/data/cuneiformbasic', {'format': 'json', })
self.assertEqual(r.status_code, 200)
| Python |
"""
Run plugin tasks on the Celery queue
"""
import os
import glob
from datetime import datetime, timedelta
from celery.contrib.abortable import AbortableTask
from celery.task import PeriodicTask
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
from django.utils import simplejson as json
from django.contrib.auth.models import User
from ocradmin.core import utils
from ocradmin.ocrtasks.decorators import register_handlers
from ocradmin.nodelib import cache, types, nodes
from ocradmin.nodelib import utils as pluginutils
from nodetree import node, script, exceptions
import numpy
class UnhandledRunScriptTask(AbortableTask):
"""
Convert an image of text into some JSON. This is done using
the OcropusWrapper (and it's proxy, TessWrapper) in util.py.
"""
name = "_run.script"
max_retries = None
def run(self, evalnode, nodelist, writepath, cachedir):
"""
Runs the convert action.
"""
logger = self.get_logger()
cacheclass = pluginutils.get_dzi_cacher(settings)
cacher = cacheclass(
path=os.path.join(settings.MEDIA_ROOT, settings.TEMP_PATH),
key=cachedir, logger=logger)
logger.debug("Using cacher: %s, Bases %s", cacher, cacheclass.__bases__)
try:
tree = script.Script(nodelist,
nodekwargs=dict(logger=logger, cacher=cacher))
term = tree.get_node(evalnode)
if term is None:
term = tree.get_terminals()[0]
result = term.eval()
except exceptions.NodeError, err:
logger.error("Node Error (%s): %s", err.node, err.message)
return dict(type="error", node=err.node.label, error=err.message)
return self.handle_output(term, cacher, result)
def handle_output(self, term, cacher, result):
# special case for switches
if term.__class__.__name__ == "Switch":
return self.handle_output(term.first_active(), cacher, result)
outpath = cacher.get_path(term.first_active())
outname = term.first_active().get_file_name()
outdzi = utils.media_path_to_url(
os.path.join(outpath, "%s.dzi" % os.path.splitext(outname)[0]))
indzi = None
if term.arity > 0 and term.input(0):
inpath = cacher.get_path(term.input(0).first_active())
inname = term.input(0).first_active().get_file_name()
indzi = utils.media_path_to_url(
os.path.join(inpath, "%s.dzi" % os.path.splitext(inname)[0]))
if term.outtype == numpy.ndarray:
out = dict(type="image", output=outdzi)
if indzi is not None:
out["input"] = indzi
return out
elif term.outtype == dict:
result.update(type="pseg", input=indzi)
return result
elif term.outtype == types.HocrString:
return dict(type="hocr", data=result)
elif issubclass(term.outtype, basestring):
return dict(type="text", data=result)
@register_handlers
class RunScriptTask(UnhandledRunScriptTask):
name = "run.script"
class PruneCacheTask(PeriodicTask):
"""
Periodically prune a user's cache directory by deleting
node cache's (oldest first) till the dir is under
NODETREE_USER_MAX_CACHE size.
"""
name = "cleanup.cache"
run_every = timedelta(seconds=600)
relative = True
ignore_result = True
def run(self, **kwargs):
"""
Clean the modia folder of any files that haven't
been accessed for X minutes.
"""
logger = self.get_logger()
cacheclass = pluginutils.get_dzi_cacher(settings)
for user in User.objects.all():
cachedir = "cache_%s" % user.username
cacher = cacheclass(
path=os.path.join(settings.MEDIA_ROOT, settings.TEMP_PATH),
key=cachedir, logger=logger)
logger.debug("Using cacher: %s, Bases %s", cacher, cacheclass.__bases__)
| Python |
"""
Interface to interacting with OCR presets.
"""
import os
import glob
import json
from django import forms
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.core.exceptions import ValidationError
from django.views.decorators.csrf import csrf_exempt
from ocradmin.core import generic_views as gv
from ocradmin.core.decorators import project_required, saves_files
from ocradmin.ocrtasks.models import OcrTask
from ocradmin.nodelib import graph, cache
from ocradmin.nodelib import utils as pluginutils
from ocradmin.presets.models import Preset, Profile
from nodetree import script, node, registry
from nodetree import utils as nodeutils
from ocradmin.nodelib import nodes
class PresetForm(forms.ModelForm):
"""
Base preset form
"""
def __init__(self, *args, **kwargs):
super(PresetForm, self).__init__(*args, **kwargs)
# change a widget attribute:
self.fields['description'].widget.attrs["rows"] = 2
self.fields['description'].widget.attrs["cols"] = 40
def clean(self):
cleaned_data = self.cleaned_data
try:
data = json.loads(self.cleaned_data["data"])
except ValueError:
msg = u"Preset data must be valid JSON"
self._errors["data"] = self.error_class([msg])
del cleaned_data["data"]
profile = self.cleaned_data["profile"]
if profile is not None:
errors = profile.validate_preset(data)
if errors:
self._errors["profile"] = self.error_class(errors)
del cleaned_data["profile"]
return cleaned_data
class Meta:
model = Preset
fields = ["name", "tags", "description", "public", "profile", "user", "data"]
exclude = ["created_on", "updated_on"]
widgets = dict(
user=forms.HiddenInput()
)
presetlist = gv.GenericListView.as_view(
model=Preset,
page_name="OCR Presets",
fields=["name", "description", "profile", "user", "created_on"],)
presetcreate = gv.GenericCreateView.as_view(
model=Preset,
form_class=PresetForm,
page_name="New OCR Preset",)
presetdetail = gv.GenericDetailView.as_view(
model=Preset,
page_name="OCR Preset",
fields=["name", "description", "user", "public", "profile", "tags", "created_on",
"updated_on",])
presetedit = gv.GenericEditView.as_view(
model=Preset,
form_class=PresetForm,
page_name="Edit OCR Preset",)
presetdelete = gv.GenericDeleteView.as_view(
model=Preset,
page_name="Delete OCR Preset",
success_url="/presets/list/",)
def createjson(request):
"""Create a preset and return JSON data"""
form = PresetForm(request.POST)
if not form.is_valid():
return HttpResponse(json.dumps(
dict(description="Invalid preset", errors=form.errors)),
mimetype="application/json")
form.save()
return HttpResponse(json.dumps(form.instance.slug),
status=201, mimetype="application/json")
def data(request, slug):
"""Return the data for a given preset in JSON format"""
preset = get_object_or_404(Preset, slug=slug)
return HttpResponse(preset.data, mimetype="application/json")
def update_data(request, slug):
"""Update script data for a given script."""
preset = get_object_or_404(Preset, slug=slug)
scriptdata = request.POST.get("data", "")
if preset.profile:
errors = {}
try:
data = json.loads(scriptdata)
except ValueError:
errors["data"] = [u"Preset data must be valid JSON"]
else:
proferrors = preset.profile.validate_preset(data)
if proferrors:
errors["profile"] = proferrors
if errors:
return HttpResponse(json.dumps(
dict(description="Invalid preset", errors=errors)),
mimetype="application/json")
preset.data = scriptdata
preset.save()
return HttpResponse(preset.data, status=201, mimetype="application/json")
@csrf_exempt
def download(request, slug):
"""Return the data for a preset as an attachment"""
preset = get_object_or_404(Preset, slug=slug)
response = HttpResponse(preset.data, mimetype="application/json")
response['Content-Disposition'] = "attachment; filename=%s.json" % slug
return response
@csrf_exempt
def fetch(request):
"""Hacky method of forcing downloading of an in-progress script via JS"""
slug = request.POST.get("name", "untitled")
script = request.POST.get("script")
response = HttpResponse(script, mimetype="application/json")
response['Content-Disposition'] = "attachment; filename=%s.json" % slug
return response
@saves_files
def builder(request, doc=None, scriptdata=None):
"""
Show the preset builder.
"""
context = dict(
form=PresetForm(initial=dict(user=request.user)),
presets=Preset.objects.order_by("name"),
profiles=Preset.objects.order_by("name"),
doc=doc,
scriptdata=scriptdata,
ref=request.GET.get("ref", "/documents/list")
)
return render(request, "presets/builder.html", context)
@project_required
def builder_doc_edit(request, pid):
"""Show the preset builder for a specific document script."""
doc = request.project.get_storage().get(pid)
# FIXME: another not-optimal situation, this is super dodgy
with doc.script_content as handle:
data = "".join(handle.readlines())
return builder(request, doc=doc, scriptdata=data)
def query_nodes(request):
"""
Query plugin info. This returns a list
of available OCR engines and an URL that
can be queries when one of them is selected.
"""
stages = request.GET.getlist("stage")
nodes = registry.nodes.get_by_attr("stage", *stages)
return HttpResponse(
json.dumps(nodes, cls=nodeutils.NodeEncoder),
mimetype="application/json")
@saves_files
def run_preset(request):
"""
Execute a script (sent as JSON).
"""
evalnode = request.POST.get("node", "")
jsondata = request.POST.get("script")
nodes = json.loads(jsondata)
tree = script.Script(nodes)
errors = tree.validate()
if errors:
return HttpResponse(json.dumps(dict(
status="VALIDATION",
errors=errors,
)), mimetype="application/json")
term = tree.get_node(evalnode)
if term is None:
terms = tree.get_terminals()
if not terms:
return HttpResponse(json.dumps(dict(
status="NOSCRIPT",
)), mimetype="application/json")
term = terms[0]
async = OcrTask.run_celery_task("run.script", (evalnode, nodes,
request.output_path, _cache_name(request)),
untracked=True, asyncronous=True, queue="interactive")
out = dict(
node=evalnode,
task_id=async.task_id,
status=async.status,
results=async.result
)
response = HttpResponse(mimetype="application/json")
json.dump(out, response, ensure_ascii=False)
return response
@csrf_exempt
@saves_files
def upload_file(request):
"""
Upload a temp file.
"""
fpath = os.path.join(request.output_path,
request.GET.get("inlinefile"))
if not os.path.exists(request.output_path):
os.makedirs(request.output_path, 0777)
tmpfile = file(fpath, "wb")
tmpfile.write(request.raw_post_data)
tmpfile.close()
return HttpResponse(json.dumps(dict(
file=os.path.relpath(fpath),
)), mimetype="application/json")
def layout_graph(request):
"""
Get GraphViz positions for nodes in a list.
"""
jsonscript = request.POST.get("script")
try:
aspect = float(request.POST.get("aspect"))
except TypeError:
aspect = None
nodes = json.loads(jsonscript)
return HttpResponse(
json.dumps(graph.get_node_positions(nodes, aspect)),
mimetype="application/json")
def _cache_name(request):
"""
Name for a preset cache.
"""
return "cache_%s" % request.user.username
def clear_cache(request):
"""
Clear a preset data cache.
"""
cacheclass = pluginutils.get_dzi_cacher(settings)
cacher = cacheclass(
path=os.path.join(settings.MEDIA_ROOT, settings.TEMP_PATH),
key=_cache_name(request))
cacher.clear()
return HttpResponse(json.dumps({"ok": True}),
mimetype="application/json")
def clear_node_cache(request):
"""
Clear the preset cache for a single node.
"""
evalnode = request.POST.get("node")
jsondata = request.POST.get("script")
nodes = json.loads(jsondata)
tree = script.Script(nodes)
node = tree.get_node(evalnode)
cacheclass = pluginutils.get_dzi_cacher(settings)
cacher = cacheclass(
path=os.path.join(settings.MEDIA_ROOT, settings.TEMP_PATH),
key=_cache_name(request))
cacher.clear_cache(node)
return HttpResponse(json.dumps({"ok": True}),
mimetype="application/json")
| Python |
"""
URLConf for OCR profiles.
"""
from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from ocradmin.presets import profileviews as views
urlpatterns = patterns('',
(r'^create/?$', login_required(views.profilecreate)),
(r'^delete/(?P<slug>[-\w]+)/?$', login_required(views.profiledelete)),
(r'^edit/(?P<slug>[-\w]+)/?$', login_required(views.profileedit)),
(r'^list/?$', views.profilelist),
(r'^show/(?P<slug>[-\w]+)/?$', views.profiledetail),
(r'^(?P<slug>[-\w]+)/?$', views.profiledetail),
)
| Python |
#!/usr/bin/python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Python |
"""
Virtualenv bootstrap script, borrowed from:
http://www.caktusgroup.com/blog/2010/04/22/basic-django-deployment-with-virtualenv-fabric-pip-and-rsync/
"""
import os
import subprocess
if "VIRTUAL_ENV" not in os.environ:
sys.stderr.write("$VIRTUAL_ENV not found.\n\n")
parser.print_usage()
sys.exit(-1)
virtualenv = os.environ["VIRTUAL_ENV"]
file_path = os.path.dirname(__file__)
subprocess.call(["pip", "install", "-E", virtualenv, "--requirement",
os.path.join(file_path, "requirements/apps.txt")])
| Python |
#!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.6c5"
DEFAULT_URL = "http://cheeseshop.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.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',
}
import sys, os
def _validate_md5(egg_name, data):
if egg_name in md5_data:
from md5 import md5
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.
"""
try:
import setuptools
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)
except ImportError:
egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg)
import setuptools; setuptools.bootstrap_install_from = egg
import pkg_resources
try:
pkg_resources.require("setuptools>="+version)
except pkg_resources.VersionConflict, e:
# XXX could we install in a subprocess here?
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.\n\n(Currently using %r)"
) % (version, e.args[0])
sys.exit(2)
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':
# tell the user to uninstall obsolete version
use_setuptools(version)
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
from md5 import md5
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:])
| Python |
#!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.6c5"
DEFAULT_URL = "http://cheeseshop.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.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',
}
import sys, os
def _validate_md5(egg_name, data):
if egg_name in md5_data:
from md5 import md5
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.
"""
try:
import setuptools
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)
except ImportError:
egg = download_setuptools(version, download_base, to_dir, download_delay)
sys.path.insert(0, egg)
import setuptools; setuptools.bootstrap_install_from = egg
import pkg_resources
try:
pkg_resources.require("setuptools>="+version)
except pkg_resources.VersionConflict, e:
# XXX could we install in a subprocess here?
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.\n\n(Currently using %r)"
) % (version, e.args[0])
sys.exit(2)
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':
# tell the user to uninstall obsolete version
use_setuptools(version)
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
from md5 import md5
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:])
| Python |
# -*- coding: utf-8 -*-
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
setup(
name='Ferlons',
version="0.0.1",
description=u"Controle de Ferias",
author="Claudio Torcato",
author_email="claudiotorcato@gmail.com",
url="http://claudiotorcato.wordpress.com",
install_requires=["Pylons>=0.9.6","SQLAlchemy>=0.3.8"],
packages=find_packages(),
include_package_data=True,
test_suite = 'nose.collector',
package_data={'ferlons': ['i18n/*/LC_MESSAGES/*.mo']},
entry_points="""
[paste.app_factory]
main=ferlons:make_app
[paste.app_install]
main=pylons.util:PylonsInstaller
""",
)
| Python |
# -*- coding: utf-8 -*-
from tw import forms
from tw.api import WidgetsList
from tw.forms.validators import UnicodeString, Email, Int
forms.FormField.engine_name = "mako"
class UsuarioToscaForm(forms.TableForm):
class fields(WidgetsList):
id = forms.HiddenField(default=0)
matricula = forms.TextField(label_text = u'Matrícula', validator = UnicodeString(not_empty=True))
cpf = forms.TextField(label_text = 'CPF', validator = UnicodeString(not_empty=True))
nome = forms.TextField(validator = UnicodeString(not_empty=True))
senha = forms.HiddenField(label_text=u'Senha')#, validator = formencode.validators.UnicodeString(not_empty=True))
data_admissao = forms.CalendarDatePicker(label_text = u'Data de Admissão', date_format='%d/%m/%Y',calendar_lang='pt', button_text="Escolha")
tipo = forms.SingleSelectField(validator = Int, options=[(1,u'Funcionário'),(2,u'Gerente')])
usuario_form = UsuarioToscaForm("usuario_form")
| Python |
"""SQLAlchemy Metadata and Session object"""
from sqlalchemy import MetaData
__all__ = ['engine', 'metadata', 'Session']
# SQLAlchemy database engine. Updated by model.init_model().
engine = None
# SQLAlchemy session manager. Updated by model.init_model().
Session = None
# Global metadata. If you have multiple databases with overlapping table
# names, you'll need a metadata for each database.
metadata = MetaData()
| Python |
from pylons import config
from ferlons.model import meta
from sqlalchemy import Column, MetaData, Table, Integer,Unicode,DateTime
from sqlalchemy.orm import mapper, relation
from sqlalchemy import orm
def init_model(engine):
sm = orm.sessionmaker(autoflush=True, autocommit=False, bind=engine)
meta.engine = engine
meta.Session = orm.scoped_session(sm)
meta.metadata.bind = engine
usuario_table = Table('usuario', meta.metadata,
Column('id', Integer, primary_key=True),
Column('matricula', Unicode(20), nullable=False),
Column('cpf', Unicode(20)),
Column('nome', Unicode(100)),
Column('senha', Unicode(20)),
Column('data_admissao', DateTime()),
Column('tipo', Integer)
)
class Usuario(object):
def __str__(self):
return self.matricula
mapper(Usuario, usuario_table)
| Python |
# -*- coding: utf-8 -*-
"""Pylons application test package
When the test runner finds and executes tests within this directory,
this file will be loaded to setup the test environment.
It registers the root directory of the project in sys.path and
pkg_resources, in case the project hasn't been installed with
setuptools. It also initializes the application via websetup (paster
setup-app) with the project's test.ini configuration file.
"""
import os
import sys
from unittest import TestCase
import pkg_resources
import paste.fixture
import paste.script.appinstall
from paste.deploy import loadapp
from paste.deploy import appconfig
from ferlons.config.environment import load_environment
from routes import url_for
import logging
log = logging.getLogger(__name__)
__all__ = ['url_for', 'TestController']
here_dir = os.path.dirname(os.path.abspath(__file__))
conf_dir = os.path.dirname(os.path.dirname(here_dir))
sys.path.insert(0, conf_dir)
pkg_resources.working_set.add_entry(conf_dir)
pkg_resources.require('Paste')
pkg_resources.require('PasteScript')
test_file = os.path.join(conf_dir, 'test.ini')
## don't run setup-app
# cmd = paste.script.appinstall.SetupCommand('setup-app')
# cmd.run([test_file])
conf = appconfig('config:' + test_file)
load_environment(conf.global_conf, conf.local_conf)
from ferlons import model
from ferlons.model import meta
from fixture import SQLAlchemyFixture
from fixture.style import NamedDataStyle
dbfixture = SQLAlchemyFixture(
env=model,
engine=meta.engine,
style=NamedDataStyle()
)
def setup():
meta.metadata.create_all(bind=meta.engine)
def teardown():
meta.metadata.drop_all(bind=meta.engine)
try:
os.unlink('test.db')
except:
pass
class TestController(TestCase):
def __init__(self, *args, **kwargs):
wsgiapp = loadapp('config:test.ini', relative_to=conf_dir)
self.app = paste.fixture.TestApp(wsgiapp)
self.app.extra_environ['REMOTE_ADDR'] = '127.0.0.1' # Hack needed for testing things like AuthKit
TestCase.__init__(self, *args, **kwargs)
def setUp(self):
meta.Session.remove() # clear any stragglers from last test
def tearDown(self):
pass
| Python |
"""Setup the artigos application"""
import logging
from paste.deploy import appconfig
from pylons import config
from ferlons.config.environment import load_environment
log = logging.getLogger(__name__)
def setup_config(command, filename, section, vars):
"""Place any commands to setup artigos here"""
conf = appconfig('config:' + filename)
load_environment(conf.global_conf, conf.local_conf)
| Python |
"""
ferlons
This file loads the finished app from ferlons.config.middleware.
"""
from ferlons.config.middleware import make_app
| Python |
from ferlons.lib.base import *
from pylons.controllers.util import abort
class TemplateController(BaseController):
def view(self, url):
"""
This is the last place which is tried during a request to try to find a
file to serve. It could be used for example to display a template::
def view(self, url):
return render_response(url)
Or, if you're using Myghty and would like to catch the component not
found error which will occur when the template doesn't exist; you
can use the following version which will provide a 404 if the template
doesn't exist::
import myghty.exception
def view(self, url):
try:
return render_response('/'+url)
except myghty.exception.ComponentNotFound:
return Response(code=404)
The default is just to abort the request with a 404 File not found
status message.
"""
abort(404)
| Python |
import os.path
from paste.urlparser import StaticURLParser
from pylons.middleware import error_document_template, media_path
from ferlons.lib.base import *
class ErrorController(BaseController):
"""Generates error documents as and when they are required.
The ErrorDocuments middleware forwards to ErrorController when error
related status codes are returned from the application.
This behaviour can be altered by changing the parameters to the
ErrorDocuments middleware in your config/middleware.py file.
"""
def document(self):
"""Render the error document"""
page = error_document_template % \
dict(prefix=request.environ.get('SCRIPT_NAME', ''),
code=request.params.get('code', ''),
message=request.params.get('message', ''))
return page
def img(self, id):
"""Serve Pylons' stock images"""
return self._serve_file(os.path.join(media_path, 'img', id))
def style(self, id):
"""Serve Pylons' stock stylesheets"""
return self._serve_file(os.path.join(media_path, 'style', id))
def _serve_file(self, root, path):
"""Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
"""
static = StaticURLParser(root)
request.environ['PATH_INFO'] = '/%s' % path
return static(request.environ, self.start_response)
| Python |
# -*- coding: utf-8 -*-
from ferlons.lib.base import *
from tw.forms.datagrid import DataGrid
from tw.mods.pylonshf import validate
from ferlons.model import meta, Usuario
from ferlons.model import form
import time
from datetime import datetime
#from webhelpers.pagination import paginate
def link_edicao(usuario):
return '<a href="/usuario/edit/%d">%s</a>' % (usuario.id, usuario.nome)
def link_remover(usuario):
return '<a href="/usuario/delete/%d">X</a>' % (usuario.id, )
colunas_usuarios = [('Nome',link_edicao),('Matricula','matricula'),('Remover',link_remover)]
class UsuarioController(BaseController):
def __before__(self):
c.data_hoje = datetime.now().strftime('%d-%m-%Y')
def index(self):
c.usuarios = meta.Session.query(Usuario).all()
#c.usuarios_paginator, c.usuarios_set = paginate(model.Usuario,page=1)
c.grid_usuarios = DataGrid(fields = colunas_usuarios,engine_name = 'mako')
return render('/usuario-list.html')
def edit(self,id):
usuario = meta.Session.query(Usuario).get(id)
if not usuario:
usuario = Usuario()
usuario.id = 0
usuario.data_admissao = datetime.now()
c.form = form.usuario_form
c.value = usuario
return render('/usuario-edit.html')
@validate(form.UsuarioToscaForm(), error_handler="edit")
def save(self,id):
if id != 0:
usuario = meta.Session.query(Usuario).get(id)
if not usuario:
usuario = Usuario()
usuario.matricula = request.params['matricula']
usuario.cpf = request.params['cpf']
usuario.nome = request.params['nome']
usuario.senha = request.params['senha']
data = datetime(*(time.strptime(request.params['data_admissao'], '%d/%m/%Y')[0:6]))
usuario.data_admissao = data
usuario.tipo = request.params['tipo']
meta.Session.save_or_update(usuario)
meta.Session.commit()
redirect_to(action = 'index',id=None)
def delete(self,id):
usuario = meta.Session.query(Usuario).get(id)
meta.Session.delete(usuario)
meta.Session.commit()
redirect_to(action='index',id=None)
| Python |
"""Routes configuration
The more specific and detailed routes should be defined first so they may take
precedent over the more generic routes. For more information refer to the
routes manual at http://routes.groovie.org/docs/
"""
from pylons import config
from routes import Mapper
def make_map():
"""Create, configure and return the routes Mapper"""
map = Mapper(directory=config['pylons.paths']['controllers'],
always_scan=config['debug'])
# The ErrorController route (handles 404/500 error pages); it should likely
# stay at the top, ensuring it can always be resolved
map.connect('error/:action/:id', controller='error')
# CUSTOM ROUTES HERE
map.connect('',controller='usuario', action='index')
map.connect(':controller/:action/:id')
map.connect('*url', controller='template', action='view')
return map
| Python |
#
| Python |
"""Pylons middleware initialization"""
from beaker.middleware import CacheMiddleware, SessionMiddleware
from paste.cascade import Cascade
from paste.registry import RegistryManager
from paste.urlparser import StaticURLParser
from paste.deploy.converters import asbool
from pylons import config
from pylons.middleware import ErrorHandler, StatusCodeRedirect
from pylons.wsgiapp import PylonsApp
from routes.middleware import RoutesMiddleware
from ferlons.config.environment import load_environment
from tw.api import make_middleware
def make_app(global_conf, full_stack=True, **app_conf):
"""Create a Pylons WSGI application and return it
``global_conf``
The inherited configuration for this application. Normally from
the [DEFAULT] section of the Paste ini file.
``full_stack``
Whether or not this application provides a full WSGI stack (by
default, meaning it handles its own exceptions and errors).
Disable full_stack when this application is "managed" by
another WSGI middleware.
``app_conf``
The application's local configuration. Normally specified in
the [app:<name>] section of the Paste ini file (where <name>
defaults to main).
"""
# Configure the Pylons environment
load_environment(global_conf, app_conf)
# The Pylons WSGI app
app = PylonsApp()
# CUSTOM MIDDLEWARE HERE (filtered by the error handling middlewares)
# Routing/Session/Cache Middleware
app = RoutesMiddleware(app, config['routes.map'])
app = SessionMiddleware(app, config)
app = CacheMiddleware(app, config)
app = make_middleware(app, {
'toscawidgets.framework' : 'pylons',
'toscawidgets.framework.default_view' : 'mako'
})
#from paste.translogger import TransLogger
#app = TransLogger(app)
if asbool(full_stack):
# Handle Python exceptions
app = ErrorHandler(app, global_conf, **config['pylons.errorware'])
# Display error documents for 401, 403, 404 status codes (and
# 500 when debug is disabled)
if asbool(config['debug']):
app = StatusCodeRedirect(app)
else:
app = StatusCodeRedirect(app, [400, 401, 403, 404, 500])
# Establish the Registry for this application
app = RegistryManager(app)
# Static files (If running in production, and Apache or another web
# server is handling this static content, remove the following 3 lines)
static_app = StaticURLParser(config['pylons.paths']['static_files'])
app = Cascade([static_app, app])
return app
| Python |
"""Pylons environment configuration"""
import os
from pylons import config
import webhelpers
from ferlons.config.routing import make_map
import ferlons.lib.app_globals as app_globals
import ferlons.lib.helpers
from sqlalchemy import engine_from_config
from ferlons.model import init_model
def load_environment(global_conf, app_conf):
"""Configure the Pylons environment via the pylons.config object"""
# Pylons paths
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
paths = dict(root=root,
controllers=os.path.join(root, 'controllers'),
static_files=os.path.join(root, 'public'),
templates=[os.path.join(root, 'templates')])
# Initialize config with the basic options
config.init_app(global_conf, app_conf, package='ferlons',
template_engine='mako', paths=paths)
config['pylons.g'] = app_globals.Globals()
config['pylons.h'] = ferlons.lib.helpers
config['routes.map'] = make_map()
# Customize templating options via this variable
tmpl_options = config['buffet.template_options']
# The following template options are passed to your template engines
#tmpl_options['mako.log_errors'] = True
tmpl_options['mako.input_encoding'] = 'utf-8'
tmpl_options['mako.output_encoding'] = 'utf-8'
#print(tmpl_options)
engine = engine_from_config(config, 'sqlalchemy.')
init_model(engine)
| Python |
"""
Helper functions
All names available in this module will be available under the Pylons h object.
"""
from webhelpers import *
from pylons.controllers.util import log
from pylons.i18n import get_lang, set_lang
from webhelpers.html.tags import *
from routes import url_for
from pylons.controllers.util import redirect_to
| Python |
# -*- coding: utf-8 -*-
from pylons import Response, c, g, cache, request, session
from pylons.controllers import WSGIController
from pylons.decorators import jsonify, validate
from pylons.templating import render, render_response
from pylons.i18n import N_, _, ungettext
from ferlons.model import meta
from ferlons.model import form
import ferlons.lib.helpers as h
#from webhelpers.rails import *
from routes import url_for
from pylons.controllers.util import abort, redirect_to, etag_cache
class BaseController(WSGIController):
def __call__(self, environ, start_response):
try:
return WSGIController.__call__(self, environ, start_response)
finally:
meta.Session.remove()
# Include the '_' function in the public names
__all__ = [__name for __name in locals().keys() if not __name.startswith('_') \
or __name == '_']
| Python |
"""The application's Globals object"""
from pylons import config
class Globals(object):
"""Globals acts as a container for objects available throughout the life of
the application.
"""
def __init__(self):
"""One instance of Globals is created during application initialization
and is available during requests via the 'g' variable.
"""
pass
| Python |
#!BPY
"""
Name: 'OGRE Scene'
Blender: 244
Group: 'Export'
Tooltip: 'Exports the current scene to OGRE'
"""
__author__ = ['Michael Reimpell']
__version__ = '0.0.0'
__url__ = ['OGRE website, http://www.ogre3d.org',
'OGRE forum, http://www.ogre3d.org/phpBB2/']
__bpydoc__ = "Please see the external documentation that comes with the script."
# Copyright (C) 2005 Michel Reimpell
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# epydoc doc format
__docformat__ = "javadoc en"
######
# imports
######
import sys
try:
import Blender
except ImportError:
sys.exit("Please run this script from within Blender!\nSee the script's manual for more information.")
import os, math
######
# namespaces
######
from Blender import Draw
from Blender import Mathutils
from Blender import Registry
from Blender.BGL import *
######
# Classes
######
class Action:
"""Action interface.
Actions encapsulate user requests.
"""
def __init__(self):
"""Constructor.
"""
return
def execute(self):
"""Executes the action.
"""
return
class QuitAction(Action):
"""Quits the windowing system.
"""
def execute(self):
Blender.Draw.Exit()
return
class Model:
"""Model interface.
"""
def __init__(self):
self.viewList = []
return
def addView(self, view):
self.viewList.append(view)
return
def removeView(self, view):
if view in self.viewList:
self.viewList.remove(view)
return
# protected
def _notify(self):
"""Notify views.
"""
for view in self.viewList:
view.update()
return
class View:
"""View interface.
"""
def __init__(self):
return
def update(self):
return
class Widget:
"""Widget interface.
@cvar INFINITY Infinity value for size hints.
"""
INFINITY = 2147483647
def __init__(self):
"""Constructor.
"""
return
def draw(self, screenRectangle):
"""Draws the widget into an area of the screen.
@param screenRectangle Area of the screen to draw into.
The screenRectangle is a list of the integers
<code>[xl, yl, xu, yu]</code>, where (xl,yl) is
the lower left corner of the area and (xu, yu) is
the upper right corner of the area.
"""
return
def eventFilter(self, event, value):
"""Called from event callback function.
@see Blender.Draw.Register
"""
return
def addButtons(self, parent):
"""Registers widget buttons at the parent.
@param parent Parent widget or screen.
"""
return
def removeButtons(self, parent):
"""Removes widget buttons from parent.
@param parent Parent widget or screen.
"""
return
def getMaximumSize(self):
"""Returns the maximum size of this widget.
@return List of integers <code>[width, height]</code>.
"""
return [Widget.INFINITY, Widget.INFINITY]
def getMinimumSize(self):
"""Returns the minimum size of this widget.
@return List of integers <code>[width, height]</code>.
"""
return [0, 0]
def getPreferredSize(self):
"""Returns the preferred size of this widget.
@return List of integers <code>[width, height]</code>.
"""
return [0, 0]
class VerticalLayout(Widget):
"""Widget that manages vertically stacked child widgets.
"""
def __init__(self):
"""Constructor.
"""
# widgetDict key: name, value: Widget
self.widgetDict = {}
# displayList list of widget names in the order to draw them
self.displayList = []
# parent to register buttons to.
self.parent = None
return
def addWidget(self, widget, name):
"""Adds a child widget to this layout.
The child widget is appended below all other widgets.
@param widget Widget to add.
@param name Unique name for the widget.
"""
self.widgetDict[name] = widget
if name not in self.displayList:
self.displayList.append(name)
# register to known parent
if self.parent:
widget.addButtons(self.parent)
return
def removeWidget(self, name):
"""Removes a child widget from this layout.
@param name Name of the widget to remove.
@see addWidget
"""
if self.widgetDict.has_key(name):
if self.parent:
self.widgetDict[name].removeButtons(self.parent)
del self.widgetDict[name]
del self.displayList[self.displayList.index(name)]
return
def addButtons(self, parent):
self.parent = parent
for widget in self.widgetDict.values():
widget.addButtons(self.parent)
return
def removeButtons(self, parent):
for widget in self.widgetDict.values():
widget.removeButtons(self.parent)
return
def draw(self, screenRectangle):
# split height for the child widgets
minimumSize = self.getMinimumSize()
height = screenRectangle[3]- screenRectangle[1]
additionalHeight = height - minimumSize[1]
stretchWidgetList = []
extraHeight = 0
# get widgets with unlimited preferred height
if (additionalHeight > 0):
stretchWidgetList = [name for (name, w) in self.widgetDict.items() if w.getPreferredSize()[1] >= Widget.INFINITY]
if (len(stretchWidgetList) > 0):
# give equal extra height to widgets with unlimited preferred height
extraHeight = additionalHeight / len(stretchWidgetList)
# draw widgets with minimum or minimum plus extra size
y = screenRectangle[3]
dy = 0
for name in self.displayList:
widget = self.widgetDict[name]
dy = widget.getMinimumSize()[1]
if (name in stretchWidgetList):
dy += extraHeight
widget.draw([screenRectangle[0], y-dy, screenRectangle[2], y])
y -= dy
return
def eventFilter(self, event, value):
for widget in self.widgetDict.values():
widget.eventFilter(event, value)
return
def getMaximumSize(self):
size = [0, 0]
for widget in self.widgetDict.values():
if (size[0] < widget.getMaximumSize()[0]):
size[0] = widget.getMaximumSize()[0]
size[1] += widget.getMaximumSize()[1]
return size
def getMinimumSize(self):
size = [0, 0]
for widget in self.widgetDict.values():
if (size[0] < widget.getMinimumSize()[0]):
size[0] = widget.getMinimumSize()[0]
size[1] += widget.getMinimumSize()[1]
return size
def getPreferredSize(self):
size = [0, 0]
for widget in self.widgetDict.values():
if (size[0] < widget.getPreferredSize()[0]):
size[0] = widget.getPreferredSize()[0]
size[1] += widget.getPreferredSize()[1]
return size
class HorizontalLayout(Widget):
"""Widget that manages horizontally stacked child widgets.
"""
def __init__(self):
"""Constructor.
"""
# widgetDict key: name, value: Widget
self.widgetDict = {}
# displayList list of widget names in the order to draw them
self.displayList = []
# parent to register buttons to.
self.parent = None
return
def addWidget(self, widget, name):
"""Adds a child widget to this layout.
The child widget is appended below all other widgets.
@param widget Widget to add.
@param name Unique name for the widget.
"""
self.widgetDict[name] = widget
if name not in self.displayList:
self.displayList.append(name)
if self.parent:
widget.addButtons(self.parent)
return
def removeWidget(self, name):
"""Removes a child widget from this layout.
@param name Name of the widget to remove.
@see addWidget
"""
if self.widgetDict.has_key(name):
if self.parent:
self.widgetDict[name].removeButtons(self.parent)
del self.widgetDict[name]
del self.displayList[self.displayList.index(name)]
return
def addButtons(self, parent):
self.parent = parent
for widget in self.widgetDict.values():
widget.addButtons(self.parent)
return
def removeButtons(self, parent):
for widget in self.widgetDict.values():
widget.removeButtons(self.parent)
return
def draw(self, screenRectangle):
# split height for the child widgets
minimumSize = self.getMinimumSize()
width = screenRectangle[2]- screenRectangle[0]
additionalWidth = width - minimumSize[0]
stretchWidgetList = []
extraWidth = 0
# get widgets with unlimited preferred height
if (additionalWidth > 0):
stretchWidgetList = [name for (name, w) in self.widgetDict.items() if w.getPreferredSize()[0] >= Widget.INFINITY]
if (len(stretchWidgetList) > 0):
# give equal extra height to widgets with unlimited preferred height
extraWidth = additionalWidth / len(stretchWidgetList)
# draw widgets with minimum or minimum plus extra size
x = screenRectangle[0]
dx = 0
for name in self.displayList:
widget = self.widgetDict[name]
dx = widget.getMinimumSize()[0]
if (name in stretchWidgetList):
dx += extraWidth
widget.draw([x, screenRectangle[1], x+dx, screenRectangle[3]])
x += dx
return
def eventFilter(self, event, value):
for widget in self.widgetDict.values():
widget.eventFilter(event, value)
return
def getMaximumSize(self):
size = [0, 0]
for widget in self.widgetDict.values():
size[0] += widget.getMaximumSize()[0]
if (size[1] < widget.getMaximumSize()[1]):
size[1] = widget.getMaximumSize()[1]
return size
def getMinimumSize(self):
size = [0, 0]
for widget in self.widgetDict.values():
size[0] += widget.getMinimumSize()[0]
if (size[1] < widget.getMinimumSize()[1]):
size[1] = widget.getMinimumSize()[1]
return size
def getPreferredSize(self):
size = [0, 0]
for widget in self.widgetDict.values():
size[0] += widget.getPreferredSize()[0]
if (size[1] < widget.getPreferredSize()[1]):
size[1] = widget.getPreferredSize()[1]
return size
class HorizontalRatioLayout(Widget):
"""Widget that manages horizontally stacked child widgets.
The drawing area is distributed among the childs with a given ratio.
"""
def __init__(self):
# widgetDict key: name, value: [Widget, ratio]
self.widgetDict = {}
# displayList list of widget names in the order to draw them
self.displayList = []
# parent to register buttons to.
self.parent = None
return
def addWidget(self, ratio, widget, name):
"""Adds a child widget to this layout.
The child widget is appended right to all other widgets.
The ratios must sum up to one.
@param ratio Ratio of screen width to occupy with this widget.
@param widget Widget to add.
@param name Unique name for the widget.
"""
self.widgetDict[name] = [widget, ratio]
if name not in self.displayList:
self.displayList.append(name)
if self.parent:
widget.addButtons(self.parent)
return
def removeWidget(self, name):
"""Removes a child widget from this layout.
@param name Name of the widget to remove.
@see addWidget
"""
if self.widgetDict.has_key(name):
if self.parent:
self.widgetDict[name].removeButtons(self.parent)
del self.widgetDict[name]
del self.displayList[self.displayList.index(name)]
return
def addButtons(self, parent):
self.parent = parent
for widget in self.widgetDict.values():
widget[0].addButtons(self.parent)
return
def removeButtons(self, parent):
for widget in self.widgetDict.values():
widget[0].removeButtons(self.parent)
return
def draw(self, screenRectangle):
# split height for the child widgets
minimumSize = self.getMinimumSize()
width = screenRectangle[2] - screenRectangle[0]
ratioSum = 0
x = screenRectangle[0]
dx = 0
for name in self.displayList:
[widget, ratio] = self.widgetDict[name]
ratioSum += ratio
if ratio >= 1:
dx = screenRectangle[2] - x + 1
else:
dx = int(ratio*width)
widget.draw([x, screenRectangle[1], x+dx-1, screenRectangle[3]])
x += dx
return
def eventFilter(self, event, value):
for [widget, ratio] in self.widgetDict.values():
widget.eventFilter(event, value)
return
def getMaximumSize(self):
size = [0, 0]
for [widget, ratio] in self.widgetDict.values():
size[0] += widget.getMaximumSize()[0]
if (size[1] < widget.getMaximumSize()[1]):
size[1] = widget.getMaximumSize()[1]
return size
def getMinimumSize(self):
size = [0, 0]
for [widget, ratio] in self.widgetDict.values():
size[0] += widget.getMinimumSize()[0]
if (size[1] < widget.getMinimumSize()[1]):
size[1] = widget.getMinimumSize()[1]
return size
def getPreferredSize(self):
size = [Widget.INFINITY, 0]
for [widget, ratio] in self.widgetDict.values():
if (size[1] < widget.getPreferredSize()[1]):
size[1] = widget.getPreferredSize()[1]
return size
class Spacer(Widget):
"""Occupies blank space on the screen.
"""
def __init__(self, minimumSize, maximumSize=None, preferredSize=None):
"""Constructor.
If maximum or preferred size is not given, the minimum size will be used instead.
"""
self.minimumSize = minimumSize
if maximumSize:
self.maximumSize = maximumSize
else:
self.maximumSize = minimumSize
if preferredSize:
self.preferredSize = preferredSize
else:
self.preferredSize = minimumSize
def getMaximumSize(self):
return self.maximumSize
def getMinimumSize(self):
return self.minimumSize
def getPreferredSize(self):
return self.preferredSize
class Decorator(Widget):
"""Decorates a child widget.
"""
def __init__(self, childWidget):
self.childWidget = childWidget
return
def draw(self, screenRectangle):
self.childWidget.draw(screenRectangle)
return
def eventFilter(self, event, value):
self.childWidget.eventFilter(event, value)
return
def addButtons(self, parent):
self.childWidget.addButtons(parent)
return
def removeButtons(self, parent):
self.childWidget.removeButtons(parent)
return
class Border(Decorator):
"""Border around widgets.
"""
def __init__(self, childWidget, borderSize=10):
"""Constructor.
@param childWidget Widget to decorate.
@param borderSize Size of the border.
"""
Decorator.__init__(self, childWidget)
self.borderSize = borderSize
return
def draw(self, screenRectangle):
rect = screenRectangle[:]
rect[0] += self.borderSize
rect[1] += self.borderSize
rect[2] -= self.borderSize
rect[3] -= self.borderSize
self.childWidget.draw(rect)
return
def getMaximumSize(self):
size = self.childWidget.getMaximumSize()[:]
size[0] += 2*self.borderSize
size[1] += 2*self.borderSize
return size
def getMinimumSize(self):
size = self.childWidget.getMinimumSize()[:]
size[0] += 2*self.borderSize
size[1] += 2*self.borderSize
return size
def getPreferredSize(self):
size = self.childWidget.getPreferredSize()[:]
size[0] += 2*self.borderSize
size[1] += 2*self.borderSize
return size
class Box(Decorator):
"""Provides a border with an optional titel for a child widget.
"""
def __init__(self, childWidget, title=None):
"""Constructor.
@param childWidget Widget to decorate.
@param title Optional frame title.
"""
Decorator.__init__(self, childWidget)
self.title = title
return
def draw(self, screenRectangle):
rect = screenRectangle[:]
if self.title:
# border and title
rect[0] += 3
rect[1] += 3
rect[2] -= 3
rect[3] -= 13
# title
titleWidth = Blender.Draw.GetStringWidth(self.title)
theme = Blender.Window.Theme.Get()[0]
glColor4ub(*theme.get('text').text)
glRasterPos2i(rect[0]+4, rect[3])
Blender.Draw.Text(self.title)
# border
glColor3f(0.0, 0.0, 0.0)
glBegin(GL_LINE_STRIP)
glVertex2i(rect[0]+6+titleWidth, rect[3]+5)
glVertex2i(rect[2], rect[3]+5)
glVertex2i(rect[2], rect[1])
glVertex2i(rect[0], rect[1])
glVertex2i(rect[0], rect[3]+5)
glVertex2i(rect[0]+3, rect[3]+5)
glEnd()
rect[0] += 3
rect[1] += 3
rect[2] -= 3
rect[3] -= 3
else:
# border only
glColor3f(0.0, 0.0, 0.0)
glBegin(GL_LINE_STRIP)
rect[0] += 3
rect[1] += 3
rect[2] -= 3
rect[3] -= 3
glVertex2i(rect[0], rect[1])
glVertex2i(rect[0], rect[3])
glVertex2i(rect[2], rect[3])
glVertex2i(rect[2], rect[1])
glVertex2i(rect[0], rect[1])
glEnd()
rect[0] += 3
rect[1] += 3
rect[2] -= 3
rect[3] -= 3
self.childWidget.draw(rect)
return
def getMaximumSize(self):
size = self.childWidget.getMaximumSize()[:]
size[0] += 12
size[1] += 12
if size[0] < self.getMinimumSize()[0]:
size[0] = self.getMinimumSize()[0]
return size
def getMinimumSize(self):
size = self.childWidget.getMinimumSize()[:]
# basic border size
size[0] += 12
size[1] += 12
# add title size
if self.title:
size[1] += 11
if (size[0] < (Blender.Draw.GetStringWidth(self.title)+16)):
size[0] = (Blender.Draw.GetStringWidth(self.title)+16)
return size
def getPreferredSize(self):
size = self.childWidget.getPreferredSize()[:]
size[0] += 12
size[1] += 12
if size[0] < self.getMinimumSize()[0]:
size[0] = self.getMinimumSize()[0]
return size
class WidgetList(Widget):
"""Displays a list of vertically stacked widgets using a scrollbar if necessary.
"""
def __init__(self):
"""Constructor.
"""
# widgetDict key: name, value: Widget
self.widgetDict = {}
# displayList list of widget names in the order to draw them
self.displayList = []
# visible child widgets
self.visibleList = []
# parent to register buttons to.
self.parent = None
# scrollbar
self.scrollbar = VerticalScrollbar(0, 0, 0)
return
def addWidget(self, widget, name):
"""Adds a child widget to this layout.
The child widget is appended below all other widgets.
@param widget Widget to add.
@param name Unique name for the widget.
"""
self.widgetDict[name] = widget
if name not in self.displayList:
self.displayList.append(name)
# register to known parent
if self.parent:
widget.addButtons(self.parent)
return
def removeWidget(self, name):
"""Removes a child widget from this layout.
@param name Name of the widget to remove.
@see addWidget
"""
if self.widgetDict.has_key(name):
if self.parent:
self.widgetDict[name].removeButtons(self.parent)
del self.widgetDict[name]
del self.displayList[self.displayList.index(name)]
return
def addButtons(self, parent):
self.parent = parent
for widget in self.widgetDict.values():
widget.addButtons(self.parent)
self.scrollbar.addButtons(self.parent)
return
def removeButtons(self, parent):
for widget in self.widgetDict.values():
widget.removeButtons(self.parent)
self.scrollbar.removeButtons(self.parent)
return
def draw(self, screenRectangle):
# draw a border
rect = screenRectangle[:]
glColor3f(0.0, 0.0, 0.0)
glBegin(GL_LINE_STRIP)
glVertex2i(rect[0], rect[3])
glVertex2i(rect[2], rect[3])
glVertex2i(rect[2], rect[1])
glVertex2i(rect[0], rect[1])
glVertex2i(rect[0], rect[3])
glVertex2i(rect[0], rect[3])
glEnd()
rect[0] += 1
rect[1] += 1
rect[2] -= 1
rect[3] -= 1
# calculate nFirstLines form screenRectangle and set scrollbar accordingly
firstLine = self.scrollbar.getCurrentValue()
# get list backwards until height is fully used
nLines = len(self.displayList)
height = rect[3] - rect[1]
iLine = -1
while ((iLine >= -nLines) and (height > 0)):
height -= self.widgetDict[self.displayList[iLine]].getMinimumSize()[1]
if height >= 0:
iLine -= 1
# nLines + iLine + 1 = nFirstLines - 1
if (firstLine > (nLines + iLine + 1)):
firstLine = nLines + iLine + 1
self.scrollbar.currentValue = firstLine
self.scrollbar.maximumValue = nLines + iLine + 1
self.scrollbar.draw([rect[2]-20, rect[1], rect[2], rect[3]])
# widgets
self.visibleList = []
height = rect[3] - rect[1]
iLine = firstLine
y = rect[3]
while ((iLine < nLines) and (height > 0)):
widget = self.widgetDict[self.displayList[iLine]]
dy = widget.getMinimumSize()[1]
height -= dy
if (height > 0):
widget.draw([rect[0], y - dy, rect[2]-21, y])
self.visibleList.append(widget)
y -= dy
iLine += 1
return
def eventFilter(self, event, value):
for widget in self.visibleList:
widget.eventFilter(event, value)
self.scrollbar.eventFilter(event, value)
return
def getMinimumSize(self):
# max minimumSize()[0] + scrollbar and minimumSize[1] of childs
size = [0, 0]
for widget in self.widgetDict.values():
widgetSize = widget.getMinimumSize()
if size[0] < widgetSize[0]:
size[0] = widgetSize[0]
if size[1] < widgetSize[1]:
size[1] = widgetSize[1]
# scrollbar
scrollbarSize = self.scrollbar.getMinimumSize()
size[0] += scrollbarSize[0]
if size[1] < scrollbarSize[1]:
size[1] = scrollbarSize[1]
return size
def getMaximumSize(self):
# max maximumSize()[0] and sum maximumSize()[1] of childs
return [0, 0]
def getPreferredSize(self):
# self.minimumSize()[0] and Widget.INFINITY for height
minimumSize = self.getMinimumSize()
return [minimumSize[0], Widget.INFINITY]
class Label(Widget):
"""Displays a text string.
"""
def __init__(self, string, fontSize='normal', fontColor=None):
"""Constructor.
@param string Text string to display.
@param fontSize Size of the font used for display:
<code>'normal'</code>, <code>'small'</code> or <code>'tiny'</code>.
@param fontColor List of font color values.
"""
self.string = string
self.fontSize = fontSize
self.fontColor = fontColor
return
def draw(self, screenRectangle):
if self.fontColor:
if (len(self.fontColor) == 3):
glColor3f(*self.fontColor)
else:
glColor4f(*self.fontColor)
else:
# theme font color
theme = Blender.Window.Theme.Get()[0]
glColor4ub(*theme.get('text').text)
glRasterPos2i(screenRectangle[0], screenRectangle[1]+3)
Blender.Draw.Text(self.string, self.fontSize)
return
def getMinimumSize(self):
return [Blender.Draw.GetStringWidth(self.string, self.fontSize), 11]
class Button(Widget):
"""Push button.
"""
def __init__(self, action, name, size, tooltip=None):
"""Constructor.
@param action Action to execute when the button is pushed.
@param name Button name.
@param size Minimum size of the button, <code>[width, height]</code>.
@param tooltip Tooltip to display for the button.
"""
self.action = action
# Button event number
self.event = None
self.name = name
self.size = size
self.preferredSize = size
self.tooltip = tooltip
return
def draw(self, rect):
if self.tooltip:
Blender.Draw.PushButton(self.name, self.event, rect[0], rect[1], rect[2]-rect[0], rect[3]-rect[1]-1, self.tooltip)
else:
Blender.Draw.PushButton(self.name, self.event, rect[0], rect[1], rect[2]-rect[0], rect[3]-rect[1]-1)
return
def addButtons(self, parent):
self.event = parent.addButtonAction(self.action)
return
def getMinimumSize(self):
return self.size
def getPreferredSize(self):
return self.preferredSize
class QuitButton(Button):
def eventFilter(self, event, value):
if (value != 0):
# pressed
if (event == Draw.ESCKEY):
self.action.execute()
if (event == Draw.QKEY):
self.action.execute()
return
class CheckBox(Widget):
"""Two state toggle button.
To provide two way communication between the CheckBox and its parent widget
you can use the following setup:
<pre>
Parent CheckBox OnChangeAction
|--------------------->T Action(self)
|------->T | CheckBox(OnChangeAction, ...)
| |------------>| OnChangeAction.execute()
|<-------+-------------| Parent.checkBoxChanged()
|------->| | CheckBox.isChecked()
</pre>
"""
def __init__(self, onChangeAction, checked, name, size, tooltip=None):
# check status
self.checked = checked
self.action = CheckBox.CheckAction(self, onChangeAction)
self.name = name
self.size = size
self.tooltip = tooltip
self.event = None
return
def toggle(self):
self.checked = 1 - self.checked
Blender.Draw.Redraw(1)
return
def isChecked(self):
return self.checked
def draw(self, rect):
if self.tooltip:
Blender.Draw.Toggle(self.name, self.event, rect[0], rect[1], rect[2]-rect[0]-1, rect[3]-rect[1]-1, self.isChecked(), self.tooltip)
else:
Blender.Draw.Toggle(self.name, self.event, rect[0], rect[1], rect[2]-rect[0]-1, rect[3]-rect[1]-1, self.isChecked())
return
def addButtons(self, parent):
self.event = parent.addButtonAction(self.action)
return
def getMinimumSize(self):
return self.size
class CheckAction(Action):
def __init__(self, checkBox, action):
self.checkBox = checkBox
self.action = action
return
def execute(self):
self.checkBox.toggle()
self.action.execute()
return
class StringButton(Button):
def __init__(self, string, action, name, size, tooltip=None):
"""Constructor.
@param string Initial string
@param action Action to execute when the button is pushed.
@param name Button name.
@param size Minimum size of the button, <code>[width, height]</code>.
@param tooltip Tooltip to display for the button.
"""
self.string = Blender.Draw.Create(string)
Button.__init__(self, action, name, size, tooltip)
return
def getString(self):
"""Returns current string.
"""
return self.string.val
def draw(self, rect):
if self.tooltip:
self.string = Blender.Draw.String(self.name, self.event, rect[0], rect[1], rect[2]-rect[0], rect[3]-rect[1]-1, self.string.val, 255, self.tooltip)
else:
self.string = Blender.Draw.String(self.name, self.event, rect[0], rect[1], rect[2]-rect[0], rect[3]-rect[1]-1, self.string.val, 255)
return
class BoundedValueModel(Model):
def __init__(self, minimum=0, maximum=0, initial=0):
Model.__init__(self)
self.minimum = minimum
self.maximum = maximum
self.value = None
self.setValue(initial)
return
def getMinimum(self):
return self.minimum
def getMaximum(self):
return self.maximum
def getValue(self):
return self.value
def setValue(self, value):
if (value != self.value):
if value < self.minimum:
self.value = self.minimum
elif value > self.maximum:
self.value = self.maximum
else:
self.value = value
self._notify()
return
class NumberView(Widget, View):
def __init__(self, name, model, minSize, prefSize=None, maxSize=None, tooltip=None):
"""Constructor.
@param model BoundedValueModel.
"""
Widget.__init__(self)
View.__init__(self)
self.model = model
self.model.addView(self)
self.numberButton = Blender.Draw.Create(self.model.getValue())
self.title = name
self.tooltip = tooltip
self.minSize = minSize
self.maxSize = maxSize or minSize
self.prefSize = prefSize or minSize
self.event = None
return
def addButtons(self, parent):
self.event = parent.addButtonAction(NumberView.SetAction(self))
return
def draw(self, rect):
if self.tooltip:
self.numberButton = Blender.Draw.Number(self.title, self.event, \
rect[0], rect[1], rect[2]-rect[0]-1, rect[3]-rect[1]-1, \
self.model.getValue(), self.model.getMinimum(), self.model.getMaximum(), self.tooltip)
else:
self.numberButton = Blender.Draw.Number(self.title, self.event, \
rect[0], rect[1], rect[2]-rect[0]-1, rect[3]-rect[1]-1, \
self.model.getValue(), self.model.getMinimum(), self.model.getMaximum())
return
def update(self):
Blender.Draw.Redraw(1)
return
def getMaximumSize(self):
return self.maxSize
def getMinimumSize(self):
return self.minSize
def getPreferredSize(self):
return self.prefSize
class SetAction(Action):
def __init__(self, view):
self.view = view
return
def execute(self):
self.view.model.setValue(self.view.numberButton.val)
return
class VerticalScrollbar(Widget):
"""Scrollbar.
"""
def __init__(self, initial, minimum, maximum):
"""Constructor.
@param initial Initial value.
@param minimum Minimum value.
@param maximum Maximum value.
"""
self.currentValue = initial
self.minimumValue = minimum
self.maximumValue = maximum
# private
self.buttonUpEvent = None
self.buttonDownEvent = None
self.guiRect = [0,0,0,0]
self.positionRect = [0,0,0,0]
self.markerRect = [0,0,0,0]
self.mousePressed = 0
self.mouseFocusX = 0
self.mouseFocusY = 0
self.markerFocusY = 0
self.mousePositionY = 0
return
def getCurrentValue(self):
"""Returns current marker position.
"""
return self.currentValue
def up(self, steps=1):
"""Move scrollbar up.
"""
if (steps > 0):
if ((self.currentValue - steps) > self.minimumValue):
self.currentValue -= steps
else:
self.currentValue = self.minimumValue
return
def down(self, steps=1):
"""Move scrollbar down.
"""
if (steps > 0):
if ((self.currentValue + steps) < self.maximumValue):
self.currentValue += steps
else:
self.currentValue = self.maximumValue
return
def draw(self, screenRectangle):
"""draw scrollbar
"""
# get size of the GUI window to translate MOUSEX and MOUSEY events
guiRectBuffer = Blender.BGL.Buffer(GL_FLOAT, 4)
Blender.BGL.glGetFloatv(Blender.BGL.GL_SCISSOR_BOX, guiRectBuffer)
self.guiRect = [int(guiRectBuffer.list[0]), int(guiRectBuffer.list[1]), \
int(guiRectBuffer.list[2]), int(guiRectBuffer.list[3])]
# relative position
x = screenRectangle[0]
y = screenRectangle[1]
width = screenRectangle[2] - x
height = screenRectangle[3] - y
self.positionRect = screenRectangle
# check minimal size:
# 2 square buttons,4 pixel borders and 1 pixel inside for inner and marker rectangles
#if ((height > (2*(width+5))) and (width > 2*5)):
# keep track of remaining area
remainRect = self.positionRect[:]
# draw square buttons
Blender.Draw.Button("/\\", self.buttonUpEvent, x, y + (height-width), width, width, "scroll up")
remainRect[3] -= width + 2
Blender.Draw.Button("\\/", self.buttonDownEvent, x, y, width, width, "scroll down")
remainRect[1] += width + 1
# draw inner rectangle
Blender.BGL.glColor3f(0.13,0.13,0.13) # dark grey
Blender.BGL.glRectf(remainRect[0], remainRect[1], remainRect[2], remainRect[3])
remainRect[0] += 1
remainRect[3] -= 1
Blender.BGL.glColor3f(0.78,0.78,0.78) # light grey
Blender.BGL.glRectf(remainRect[0], remainRect[1], remainRect[2], remainRect[3])
remainRect[1] += 1
remainRect[2] -= 1
Blender.BGL.glColor3f(0.48,0.48,0.48) # grey
Blender.BGL.glRectf(remainRect[0], remainRect[1], remainRect[2], remainRect[3])
# draw marker rectangle
# calculate marker rectangle
innerHeight = remainRect[3]-remainRect[1]
markerHeight = innerHeight/(self.maximumValue-self.minimumValue+1.0)
# markerRect
self.markerRect[0] = remainRect[0]
self.markerRect[1] = remainRect[1] + (self.maximumValue - self.currentValue)*markerHeight
self.markerRect[2] = remainRect[2]
self.markerRect[3] = self.markerRect[1] + markerHeight
# clip markerRect to innerRect (catch all missed by one errors)
if self.markerRect[1] > remainRect[3]:
self.markerRect[1] = remainRect[3]
if self.markerRect[3] > remainRect[3]:
self.markerRect[3] = remainRect[3]
# draw markerRect
remainRect = self.markerRect
Blender.BGL.glColor3f(0.78,0.78,0.78) # light grey
Blender.BGL.glRectf(remainRect[0], remainRect[1], remainRect[2], remainRect[3])
remainRect[0] += 1
remainRect[3] -= 1
Blender.BGL.glColor3f(0.13,0.13,0.13) # dark grey
Blender.BGL.glRectf(remainRect[0], remainRect[1], remainRect[2], remainRect[3])
remainRect[1] += 1
remainRect[2] -= 1
# check if marker has foucs
if (self.mouseFocusX and self.mouseFocusY and (self.mousePositionY > self.markerRect[1]) and (self.mousePositionY < self.markerRect[3])):
Blender.BGL.glColor3f(0.64,0.64,0.64) # marker focus grey
else:
Blender.BGL.glColor3f(0.60,0.60,0.60) # marker grey
Blender.BGL.glRectf(remainRect[0], remainRect[1], remainRect[2], remainRect[3])
return
def eventFilter(self, event, value):
"""event filter for keyboard and mouse input events
call it inside the registered event function
"""
if (value != 0):
# Buttons
if (event == Blender.Draw.PAGEUPKEY):
self.up(3)
Blender.Draw.Redraw(1)
elif (event == Blender.Draw.PAGEDOWNKEY):
self.down(3)
Blender.Draw.Redraw(1)
elif (event == Blender.Draw.UPARROWKEY):
self.up(1)
Blender.Draw.Redraw(1)
elif (event == Blender.Draw.DOWNARROWKEY):
self.down(1)
Blender.Draw.Redraw(1)
# Mouse
elif (event == Blender.Draw.MOUSEX):
# check if mouse is inside positionRect
if (value >= (self.guiRect[0] + self.positionRect[0])) and (value <= (self.guiRect[0] + self.positionRect[2])):
# redraw if marker got focus
if (not self.mouseFocusX) and self.mouseFocusY:
Blender.Draw.Redraw(1)
self.mouseFocusX = 1
else:
# redraw if marker lost focus
if self.mouseFocusX and self.mouseFocusY:
Blender.Draw.Redraw(1)
self.mouseFocusX = 0
elif (event == Blender.Draw.MOUSEY):
# check if mouse is inside positionRect
if (value >= (self.guiRect[1] + self.positionRect[1])) and (value <= (self.guiRect[1] + self.positionRect[3])):
self.mouseFocusY = 1
# relative mouse position
self.mousePositionY = value - self.guiRect[1]
if ((self.mousePositionY > self.markerRect[1]) and (self.mousePositionY < self.markerRect[3])):
# redraw if marker got focus
if self.mouseFocusX and (not self.markerFocusY):
Blender.Draw.Redraw(1)
self.markerFocusY = 1
else:
# redraw if marker lost focus
if self.mouseFocusX and self.markerFocusY:
Blender.Draw.Redraw(1)
self.markerFocusY = 0
# move marker
if (self.mousePressed == 1):
# calculate step from distance to marker
if (self.mousePositionY > self.markerRect[3]):
# up
self.up(1)
Blender.Draw.Draw()
elif (self.mousePositionY < self.markerRect[1]):
# down
self.down(1)
Blender.Draw.Draw()
# redraw if marker lost focus
if self.mouseFocusX and self.mouseFocusY:
Blender.Draw.Redraw(1)
else:
# redraw if marker lost focus
if self.mouseFocusX and self.markerFocusY:
Blender.Draw.Redraw(1)
self.markerFocusY = 0
self.mouseFocusY = 0
elif ((event == Blender.Draw.LEFTMOUSE) and (self.mouseFocusX == 1) and (self.mouseFocusY == 1)):
self.mousePressed = 1
# move marker
if (self.mousePositionY > self.markerRect[3]):
# up
self.up(1)
Blender.Draw.Redraw(1)
elif (self.mousePositionY < self.markerRect[1]):
# down
self.down(1)
Blender.Draw.Redraw(1)
elif (Blender.Get("version") >= 234):
if (event == Blender.Draw.WHEELUPMOUSE):
self.up(1)
Blender.Draw.Redraw(1)
elif (event == Blender.Draw.WHEELDOWNMOUSE):
self.down(1)
Blender.Draw.Redraw(1)
else: # released keys and buttons
if (event == Blender.Draw.LEFTMOUSE):
self.mousePressed = 0
return
def getMinimumSize(self):
return [20, 60]
def getPreferredSize(self):
return [20, Widget.INFINITY]
def addButtons(self, parent):
self.buttonUpEvent = parent.addButtonAction(VerticalScrollbar.UpAction(self))
self.buttonDownEvent = parent.addButtonAction(VerticalScrollbar.DownAction(self))
return
class UpAction(Action):
def __init__(self, scrollbar):
self.scrollbar = scrollbar
return
def execute(self):
self.scrollbar.up()
Blender.Draw.Redraw(1)
return
class DownAction(Action):
def __init__(self, scrollbar):
self.scrollbar = scrollbar
return
def execute(self):
self.scrollbar.down()
Blender.Draw.Redraw(1)
return
class ProgressBar(Widget):
def __init__(self):
Widget.__init__(self)
# percentage of attained progress
self.percent = 0.0
self.minimumSize = [104, 24]
self.preferredSize = [Widget.INFINITY, 15]
self.event = None
return
def progress(self, percent):
self.percent = percent
Blender.Draw.Redraw(1)
return
def draw(self, rect):
# border
glColor3f(0.0, 0.0, 0.0)
glBegin(GL_LINE_STRIP)
glVertex2i(rect[0], rect[1])
glVertex2i(rect[0], rect[3])
glVertex2i(rect[2], rect[3])
glVertex2i(rect[2], rect[1])
glVertex2i(rect[0], rect[1])
glEnd()
# percentage bar
width = rect[2] - rect[0] - 4
barWidth = int(width*self.percent)
Blender.Draw.Toggle("%d%%" % (self.percent*100), self.event, rect[0]+2, rect[1]+2, barWidth, rect[3]-rect[1]-4, 0)
return
def addButtons(self, parent):
self.event = parent.addButtonAction(ProgressBar.NoToggle())
def getMinimumSize(self):
return self.minimumSize
def getPreferredSize(self):
return self.preferredSize
class NoToggle(Action):
def execute(self):
Blender.Draw.Redraw(1)
return
class Screen:
"""Represents the complete script window.
A screen represents the complete script window. It handles
drawing and events and can consist of several user interface
components.
@cvar current Current active screen.
"""
current = None
def __init__(self):
"""Constructor.
"""
# buttonHandler event number management
self.nButtonEvent = 0
# buttonEventDict key: iButtonEvent, value: Action
self.buttonEventDict = {}
# default widget layout
self.layout = VerticalLayout()
return
def activate(self):
"""Makes the current screen active.
This method calls Blender.Draw.Register to register itself to
be responsible for windowing.
"""
self.layout.addButtons(self)
Screen.current = self
Blender.Draw.Register(self._draw, self._eventHandler, self._buttonHandler)
return
def addWidget(self, widget, name):
"""Adds a widget to this screen.
@param widget Widget to add to this screen.
@param name Unique name for the widget.
"""
self.layout.addWidget(widget, name)
return
def removeWidget(self, name):
"""Removes widget from this screen.
@param name Name of the widget to remove.
@see addWidget
"""
self.layout.removeWidget(name)
return
def addButtonAction(self, action):
"""Registers an action for a button event.
@param action Action to execute on receive of the returned button event number.
@return eventNumber Event number to use for the button that corresponds to that action.
"""
# workaround for Blender 2.37 event 8 bug:
shiftEvents = 100
# get a free event number
if (len(self.buttonEventDict) == self.nButtonEvent):
self.nButtonEvent += 1
eventNumber = self.nButtonEvent + shiftEvents
else:
eventNumber = [(x+1+shiftEvents) for x in range(self.nButtonEvent) if (x+1+shiftEvents) not in self.buttonEventDict.keys()][0]
# assign action to that event
self.buttonEventDict[eventNumber] = action
return eventNumber
def removeButtonAction(self, eventNumber):
"""Action for the given event number will no longer be called.
@param eventNumber Event number for the action.
"""
if self.buttonEventDict.has_key(eventNumber):
del self.buttonEventDict[eventNumber]
return
# callbacks for Blender.Draw.Register
def _draw(self):
"""Draws the screen.
Callback function for Blender.Draw.Register
"""
# clear background
theme = Blender.Window.Theme.Get()[0]
bgColor = [color/255.0 for color in theme.get('buts').back]
glClearColor(*bgColor)
glClear(GL_COLOR_BUFFER_BIT)
# size of the script window
size = list(Blender.Window.GetAreaSize())
minimumSize = self.layout.getMinimumSize()
if size[0] < minimumSize[0]:
size[0] = minimumSize[0]
if size[1] < minimumSize[1]:
size[1] = minimumSize[1]
screenRect = [0, 0, size[0]-1, size[1]-1]
# draw widgets
self.layout.draw(screenRect)
return
def _eventHandler(self, event, value):
"""Handles keyboard and mouse input events.
Callback function for Blender.Draw.Register
"""
self.layout.eventFilter(event, value)
return
def _buttonHandler(self, event):
"""Handles draw button events.
Callback function for Blender.Draw.Register
"""
if self.buttonEventDict.has_key(event):
self.buttonEventDict[event].execute()
return
###
# specific classes
class OgreFrame(Decorator):
"""Ogre Logo, Title and border.
"""
OGRE_LOGO = Buffer(GL_BYTE, [48,122*4],[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,64,0,0,0,95,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,95,0,0,0,127,0,0,0,127,0,1,0,127,0,2,0,127,2,5,2,127,2,5,2,127,4,6,4,127,5,8,5,127,8,11,8,127,8,11,8,127,3,5,3,127,2,3,2,127,0,1,0,127,0,1,0,127,0,1,0,127,0,1,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,64,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,95,0,0,0,127,1,2,1,127,4,6,4,127,10,13,10,127,18,22,18,127,23,28,23,127,24,30,24,127,25,31,25,127,25,31,25,127,26,32,26,127,26,32,26,127,26,32,26,127,25,31,25,127,24,30,24,127,18,23,18,127,3,5,3,127,4,6,4,127,8,11,8,127,9,12,9,127,13,17,13,127,17,22,17,127,15,19,15,127,7,9,7,127,1,2,1,127,0,0,0,127,0,0,0,95,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,127,2,4,2,127,4,6,4,127,18,22,18,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,18,22,18,127,15,19,15,127,20,26,20,127,25,31,25,127,26,32,26,127,26,32,26,127,25,31,25,127,25,31,25,127,25,31,25,127,26,32,26,127,24,30,24,127,16,20,16,127,4,5,4,127,0,0,0,95,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,95,1,1,1,127,13,15,13,127,12,15,12,127,24,29,24,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,23,29,23,127,24,30,24,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,23,28,23,127,3,5,3,127,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,95,1,1,1,127,19,24,19,127,11,15,11,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,23,28,23,127,17,21,17,127,22,28,22,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,23,28,23,127,3,5,3,127,0,0,0,127,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,127,20,24,20,127,16,20,16,127,20,25,20,127,24,30,24,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,22,28,22,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,23,28,23,127,3,5,3,127,0,0,0,127,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,64,5,7,5,127,26,32,26,127,15,19,15,127,41,48,41,127,38,45,38,127,24,30,24,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,23,28,23,127,3,4,3,127,0,0,0,127,58,66,58,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,127,20,24,20,127,27,34,27,127,26,32,26,127,47,55,47,127,47,55,47,127,39,46,39,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,11,16,11,127,0,1,0,127,3,3,3,127,94,106,94,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,127,33,39,33,127,45,52,45,127,28,32,28,127,47,55,47,127,44,51,44,127,39,46,39,127,27,33,27,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,21,26,21,127,0,2,0,127,0,0,0,127,23,26,23,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,127,24,28,24,127,33,40,33,127,18,22,18,127,29,35,29,127,25,31,25,127,24,30,24,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,5,8,5,127,1,2,1,127,0,0,0,127,70,79,70,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,94,105,94,127,70,79,70,127,76,86,76,127,90,101,90,127,103,116,103,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,64,0,0,0,127,4,6,4,127,12,16,12,127,22,27,22,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,23,29,23,127,28,34,28,127,35,42,35,127,28,35,28,127,25,31,25,127,23,29,23,127,23,29,23,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,17,21,17,127,0,2,0,127,0,0,0,127,31,36,31,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,100,112,100,127,92,103,92,127,103,116,103,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,100,112,100,127,81,92,81,127,68,77,68,127,65,73,65,127,65,73,65,127,76,86,76,127,78,88,78,127,83,94,83,127,92,103,92,127,85,95,85,127,31,35,31,127,6,7,6,127,6,7,6,127,13,14,13,127,13,14,13,127,19,21,19,127,26,29,26,127,26,29,26,127,48,54,48,127,96,108,96,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,70,78,70,127,3,3,3,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,12,13,11,127,23,26,23,127,36,40,36,127,49,55,49,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,64,0,0,0,127,2,4,2,127,16,20,16,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,24,30,24,127,26,33,26,127,59,68,59,127,81,91,81,127,87,98,87,127,86,96,86,127,80,90,80,127,71,79,71,127,59,66,59,127,36,41,35,127,23,29,23,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,24,31,24,127,26,32,26,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,5,8,5,127,0,1,0,127,18,20,18,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,91,103,91,127,58,65,58,127,29,33,29,127,6,7,6,127,0,0,0,127,0,0,0,127,1,2,1,127,22,24,22,127,54,61,54,127,94,106,94,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,88,99,88,127,51,58,51,127,18,21,18,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,17,19,17,127,48,54,48,127,80,91,80,127,102,115,102,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,29,33,29,127,0,0,0,127,41,31,14,127,33,25,11,127,18,14,6,127,2,2,1,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,127,2,3,2,127,24,29,24,127,26,32,26,127,24,30,24,127,25,31,25,127,24,30,24,127,24,30,24,127,24,30,24,127,23,29,23,127,34,41,34,127,78,88,78,127,87,98,87,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,87,97,87,127,87,97,87,127,84,93,84,127,62,69,62,127,34,40,34,127,24,30,24,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,23,28,23,127,26,30,26,127,36,38,36,127,47,50,46,127,39,42,37,127,34,40,34,127,30,37,30,127,24,30,24,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,15,19,15,127,0,1,0,127,0,0,0,127,102,115,102,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,94,106,94,127,43,48,43,127,4,5,4,127,0,0,0,127,0,0,0,127,0,0,0,127,6,5,2,127,16,12,5,127,2,2,1,127,0,0,0,127,0,0,0,127,7,8,7,127,58,65,58,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,96,108,96,127,41,47,41,127,1,1,1,127,0,0,0,127,0,0,0,127,6,5,2,127,27,21,9,127,42,33,14,127,46,36,16,127,46,36,16,127,33,25,11,127,31,24,11,127,25,19,9,127,16,12,5,127,12,9,4,127,0,0,0,127,107,82,36,127,115,88,38,127,107,82,36,127,107,82,36,127,100,76,33,127,92,71,31,127,88,68,30,127,0,0,0,127,4,3,2,127,0,0,0,127,0,0,0,127,0,0,0,127,13,15,13,127,65,73,65,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,13,14,13,127,0,0,0,127,107,82,36,127,122,94,41,127,122,94,41,127,122,94,41,127,109,84,36,127,96,73,32,127,80,62,27,127,65,50,22,127,52,40,17,127,37,28,12,127,21,16,7,127,2,2,1,127,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,127,9,11,9,127,48,56,48,127,45,53,45,127,41,48,41,127,33,40,33,127,34,41,34,127,37,44,37,127,54,62,54,127,77,87,77,127,87,97,87,127,87,97,87,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,79,88,79,127,61,69,61,127,25,31,25,127,25,31,25,127,23,28,23,127,19,23,19,127,42,43,41,127,60,60,59,127,61,61,59,127,61,61,59,127,63,63,61,127,35,37,34,127,38,45,38,127,33,39,33,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,15,19,15,127,0,1,0,127,0,0,0,127,102,115,102,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,81,91,81,127,9,11,9,127,0,0,0,127,2,2,1,127,44,34,15,127,86,66,29,127,115,88,38,127,122,94,41,127,122,94,41,127,121,92,40,127,94,72,31,127,39,30,13,127,0,0,0,127,0,0,0,127,40,45,40,127,101,114,101,127,105,118,105,127,105,118,105,127,105,118,105,127,85,95,85,127,11,13,11,127,0,0,0,127,4,3,2,127,50,38,17,127,94,72,31,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,92,71,31,127,0,0,0,127,107,82,36,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,100,76,33,127,2,2,1,127,105,81,35,127,98,75,33,127,60,46,20,127,23,18,8,127,0,0,0,127,1,1,1,127,90,102,90,127,105,118,105,127,105,118,105,127,105,118,105,127,6,7,6,127,0,0,0,127,115,88,38,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,8,6,3,127,0,0,0,95,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,127,3,5,3,127,45,53,45,127,46,54,46,127,46,54,46,127,47,55,47,127,46,54,46,127,68,78,68,127,87,98,87,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,87,98,87,127,67,76,67,127,38,46,38,127,21,26,21,127,50,52,50,127,60,60,59,127,61,61,59,127,60,60,58,127,60,60,58,127,60,60,58,127,61,61,59,127,39,41,38,127,52,59,52,127,67,76,67,127,23,29,23,127,25,31,25,127,25,31,25,127,25,31,25,127,15,19,15,127,0,1,0,127,0,0,0,127,102,115,102,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,59,67,59,127,1,1,1,127,0,0,0,127,35,27,12,127,105,81,35,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,86,66,29,127,8,6,3,127,0,0,0,127,36,40,36,127,105,118,105,127,105,118,105,127,82,92,82,127,7,7,7,127,0,0,0,127,31,24,10,127,107,82,36,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,80,62,27,127,0,0,0,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,82,63,28,127,46,36,16,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,27,21,9,127,0,0,0,127,78,88,78,127,105,118,105,127,105,118,105,127,105,118,105,127,0,0,0,127,0,0,0,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,100,76,33,127,0,0,0,127,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,127,0,2,0,127,41,49,41,127,46,54,46,127,46,54,46,127,49,56,49,127,77,87,77,127,87,98,87,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,85,96,85,127,55,64,55,127,44,52,44,127,23,28,23,127,17,22,17,127,90,92,90,127,84,84,82,127,60,60,58,127,60,60,58,127,60,60,58,127,60,60,58,127,61,61,59,127,39,41,38,127,54,62,54,127,62,71,62,127,23,29,23,127,25,31,25,127,25,31,25,127,25,31,25,127,15,20,15,127,0,1,0,127,0,0,0,127,102,115,102,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,81,90,81,127,1,1,1,127,0,0,0,127,61,47,21,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,103,79,34,127,12,9,4,127,0,0,0,127,47,52,47,127,93,104,93,127,8,9,8,127,0,0,0,127,52,40,17,127,121,92,40,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,77,59,26,127,0,0,0,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,63,49,21,127,105,81,35,127,122,94,41,127,122,94,41,127,122,94,41,127,100,76,33,127,0,0,0,127,9,11,9,127,101,113,101,127,105,118,105,127,105,118,105,127,105,118,105,127,0,0,0,127,0,0,0,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,69,53,23,127,0,0,0,127,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,127,0,1,0,127,37,44,37,127,46,54,46,127,49,57,49,127,79,89,79,127,87,97,87,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,56,64,56,127,46,53,46,127,25,31,25,127,22,27,22,127,25,31,25,127,44,47,44,127,116,116,115,127,59,59,57,127,60,60,58,127,60,60,58,127,60,60,58,127,61,61,59,127,38,41,37,127,69,78,69,127,45,53,45,127,24,30,24,127,25,31,25,127,25,31,25,127,25,31,25,127,15,20,15,127,0,0,0,127,5,6,5,127,104,117,104,127,105,118,105,127,105,118,105,127,105,118,105,127,93,104,93,127,8,9,8,127,0,0,0,127,61,47,21,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,96,73,32,127,2,2,1,127,0,0,0,127,24,28,24,127,0,0,0,127,37,28,12,127,121,92,40,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,77,59,26,127,10,8,3,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,88,68,30,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,39,30,13,127,0,0,0,127,43,49,43,127,105,118,105,127,105,118,105,127,105,118,105,127,93,105,93,127,0,0,0,127,14,11,5,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,39,30,13,127,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,64,0,1,0,127,21,25,21,127,48,57,49,127,82,92,82,127,87,97,87,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,87,97,87,127,87,98,87,127,60,69,60,127,43,50,43,127,29,36,29,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,116,116,116,127,71,71,70,127,60,60,58,127,60,60,58,127,60,60,58,127,62,62,60,127,30,32,29,127,75,85,75,127,29,36,29,127,25,31,25,127,24,30,24,127,24,30,24,127,23,28,23,127,10,14,10,127,0,0,0,127,40,45,40,127,105,118,105,127,105,118,105,127,105,118,105,127,105,118,105,127,33,38,33,127,0,0,0,127,39,30,13,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,67,52,23,127,0,0,0,127,0,0,0,127,10,8,3,127,113,87,38,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,107,82,36,127,84,65,28,127,71,54,24,127,115,88,38,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,67,51,22,127,16,12,5,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,121,92,40,127,122,94,41,127,122,94,41,127,122,94,41,127,105,81,35,127,2,2,1,127,0,0,0,127,0,0,0,127,18,21,18,127,61,69,61,127,102,115,102,127,92,103,92,127,0,0,0,127,16,12,5,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,60,46,20,127,52,40,17,127,69,53,23,127,86,66,29,127,10,8,3,127,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,127,2,5,2,127,49,57,49,127,87,98,87,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,87,98,87,127,86,97,86,127,75,84,75,127,53,61,53,127,34,41,34,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,22,28,22,127,96,97,96,127,93,93,92,127,59,59,58,127,60,60,58,127,60,60,58,127,61,61,59,127,34,39,34,127,74,84,74,127,23,29,23,127,25,31,25,127,37,39,34,127,47,47,41,127,44,45,39,127,17,18,16,127,0,0,0,127,52,59,52,127,105,118,105,127,105,118,105,127,105,118,105,127,81,92,81,127,0,0,0,127,8,6,3,127,111,85,37,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,121,92,40,127,50,38,17,127,16,12,5,127,33,25,11,127,103,79,34,127,122,94,41,127,122,94,41,127,122,94,41,127,121,92,40,127,23,18,8,127,0,0,0,127,69,53,23,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,77,59,26,127,27,21,9,127,0,0,0,127,0,0,0,127,0,0,0,127,92,71,31,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,61,47,21,127,18,14,6,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,117,90,39,127,88,68,29,127,54,41,18,127,14,11,5,127,0,0,0,127,0,0,0,127,17,18,17,127,68,76,68,127,0,0,0,127,21,16,7,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,31,24,11,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,95,0,0,0,127,37,43,37,127,89,100,89,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,87,97,87,127,88,99,88,127,82,92,82,127,61,69,61,127,36,42,36,127,27,32,27,127,23,29,23,127,23,29,23,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,23,29,23,127,78,80,76,127,102,102,102,127,58,58,57,127,60,60,58,127,60,60,58,127,58,58,56,127,40,47,40,127,56,64,56,127,24,29,23,127,44,45,40,127,49,49,43,127,49,49,43,127,46,46,41,127,41,42,37,127,0,0,0,127,38,43,38,127,105,118,105,127,105,118,105,127,105,118,105,127,33,37,33,127,0,0,0,127,61,47,21,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,77,59,26,127,0,0,0,127,0,0,0,127,0,0,0,127,12,9,4,127,113,87,38,127,122,94,41,127,122,94,41,127,122,94,41,127,84,65,28,127,4,3,2,127,115,88,38,127,122,94,41,127,122,94,41,127,122,94,41,127,121,92,40,127,42,33,14,127,0,0,0,127,119,91,40,127,102,78,34,127,75,57,25,127,52,40,17,127,88,68,29,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,61,47,21,127,31,24,11,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,121,92,40,127,84,65,28,127,19,15,7,127,0,0,0,127,4,5,4,127,0,0,0,127,31,24,11,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,111,85,37,127,115,88,38,127,122,94,41,127,122,94,41,127,48,37,16,127,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,32,0,0,0,127,6,7,5,127,67,75,67,127,89,100,89,127,87,97,87,127,87,97,87,127,87,98,87,127,88,99,88,127,88,98,88,127,80,90,80,127,62,71,62,127,45,52,45,127,39,46,39,127,57,65,57,127,65,74,65,127,59,67,59,127,54,61,54,127,55,61,55,127,28,34,28,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,24,30,24,127,64,67,64,127,109,109,108,127,58,58,57,127,60,60,58,127,61,60,59,127,50,50,47,127,47,55,47,127,33,39,33,127,44,44,39,127,48,48,42,127,48,48,42,127,28,30,25,127,36,37,31,127,48,48,42,127,1,2,1,127,36,41,36,127,105,118,105,127,105,118,105,127,99,111,99,127,4,5,4,127,2,2,1,127,113,87,38,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,65,50,22,127,0,0,0,127,30,34,30,127,27,30,27,127,0,0,0,127,67,51,22,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,58,44,19,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,71,54,24,127,0,0,0,127,18,14,6,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,54,41,18,127,31,24,11,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,121,92,40,127,56,43,19,127,0,0,0,127,0,0,0,127,31,24,11,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,37,28,12,127,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,95,0,0,0,127,2,3,2,127,28,32,28,127,58,65,58,127,56,64,56,127,50,57,50,127,46,54,46,127,42,49,42,127,43,50,43,127,62,71,62,127,80,90,80,127,87,98,87,127,87,98,87,127,87,97,87,127,87,98,87,127,86,97,87,127,78,85,78,127,46,52,46,127,24,30,24,127,25,31,25,127,25,31,25,127,25,31,25,127,24,30,24,127,64,67,64,127,104,104,104,127,58,58,57,127,60,60,58,127,62,61,60,127,34,38,33,127,37,43,37,127,50,51,44,127,48,48,42,127,48,48,42,127,23,27,22,127,32,36,30,127,95,95,82,127,43,45,39,127,0,0,0,127,45,51,45,127,105,118,105,127,105,118,105,127,71,80,71,127,0,0,0,127,35,27,12,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,103,79,35,127,2,2,1,127,0,0,0,127,11,13,11,127,0,0,0,127,65,50,22,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,121,92,40,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,23,18,8,127,0,0,0,127,35,27,12,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,46,36,16,127,41,31,14,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,119,91,40,127,37,28,12,127,50,38,17,127,73,56,24,127,107,82,36,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,69,53,23,127,0,0,0,127,44,34,15,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,27,21,9,127,0,0,0,127,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,8,10,8,127,51,59,51,127,84,95,84,127,87,98,87,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,87,127,63,71,63,127,23,29,23,127,25,31,25,127,25,31,25,127,25,31,25,127,23,29,23,127,76,78,75,127,100,100,99,127,58,58,57,127,61,60,59,127,53,54,51,127,24,30,24,127,29,33,28,127,77,76,63,127,47,48,42,127,29,32,27,127,24,30,24,127,30,35,29,127,90,91,84,127,28,29,25,127,0,0,0,127,77,86,76,127,105,118,105,127,105,118,105,127,44,50,44,127,0,0,0,127,69,53,23,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,81,62,27,127,4,3,2,127,0,0,0,127,12,9,4,127,107,82,36,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,4,3,2,127,0,0,0,127,54,41,18,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,46,36,16,127,46,36,16,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,100,76,33,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,48,37,16,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,42,33,14,127,46,36,16,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,16,12,5,127,0,0,0,127,0,0,0,127,4,3,2,127,6,5,2,127,0,0,0,95,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,64,0,0,0,95,1,1,1,127,60,68,60,127,87,98,87,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,87,97,87,127,73,82,73,127,24,30,24,127,25,31,25,127,25,31,25,127,25,31,25,127,22,28,22,127,89,92,89,127,87,87,86,127,59,59,58,127,60,59,58,127,31,35,31,127,25,31,25,127,43,45,38,127,74,74,62,127,43,43,38,127,22,28,22,127,25,31,25,127,24,30,24,127,26,32,26,127,13,14,12,127,0,0,0,127,100,113,100,127,105,118,105,127,105,118,105,127,21,24,21,127,0,0,0,127,98,75,33,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,113,87,38,127,92,71,31,127,117,90,39,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,19,15,7,127,0,0,0,127,71,54,24,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,39,30,13,127,50,38,17,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,82,63,28,127,0,0,0,127,23,26,23,127,38,42,38,127,5,7,5,127,0,0,0,127,96,73,32,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,111,85,37,127,54,41,18,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,82,63,28,127,16,12,5,127,16,12,5,127,16,12,5,127,12,9,4,127,46,35,16,127,82,63,28,127,117,90,39,127,46,36,16,127,0,0,0,127,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,127,33,38,33,127,89,99,89,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,84,94,84,127,28,35,28,127,25,31,25,127,25,31,25,127,25,31,25,127,22,28,22,127,100,101,100,127,73,73,71,127,61,60,59,127,35,38,35,127,24,30,24,127,24,30,24,127,48,51,41,127,69,69,57,127,36,37,32,127,24,30,24,127,28,34,28,127,25,31,25,127,25,31,25,127,17,21,17,127,0,0,0,127,80,90,80,127,105,118,105,127,105,118,105,127,6,7,6,127,0,0,0,127,115,88,38,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,56,43,19,127,0,0,0,127,88,68,29,127,117,90,39,127,107,82,36,127,92,71,31,127,80,62,27,127,69,53,23,127,60,46,20,127,46,36,16,127,33,25,11,127,23,18,8,127,4,3,2,127,61,47,21,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,65,50,22,127,0,0,0,127,20,22,20,127,26,30,26,127,0,0,0,127,2,2,1,127,109,84,36,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,100,76,33,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,77,59,26,127,21,16,7,127,60,46,20,127,94,72,31,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,54,41,18,127,0,0,0,127,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,95,6,7,6,127,81,91,81,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,88,98,88,127,60,68,60,127,27,33,27,127,24,30,24,127,25,31,25,127,22,28,22,127,91,91,91,127,57,58,56,127,31,36,31,127,24,30,24,127,25,31,25,127,25,31,25,127,27,31,26,127,70,71,58,127,41,42,36,127,37,43,37,127,66,74,66,127,23,29,23,127,25,31,25,127,19,22,19,127,0,0,0,127,75,84,75,127,105,118,105,127,102,114,102,127,0,0,0,127,4,3,2,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,117,90,39,127,31,24,10,127,2,2,1,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,4,3,2,127,61,47,21,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,46,36,16,127,0,0,0,127,0,0,0,127,0,0,0,127,8,6,3,127,73,56,24,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,121,92,40,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,61,47,21,127,0,0,0,127,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,127,45,52,45,127,87,98,88,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,82,92,82,127,46,54,46,127,34,41,34,127,25,31,25,127,25,31,25,127,26,30,26,127,24,30,24,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,24,30,24,127,33,37,31,127,48,48,42,127,43,43,38,127,66,74,65,127,23,29,23,127,25,31,25,127,20,25,20,127,0,0,0,127,70,78,70,127,105,118,105,127,92,103,92,127,0,0,0,127,16,12,5,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,86,66,29,127,48,37,16,127,31,24,11,127,16,12,5,127,23,18,8,127,33,25,11,127,52,40,17,127,71,54,24,127,96,73,32,127,117,90,39,127,63,49,21,127,73,56,24,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,88,68,29,127,77,59,26,127,77,59,26,127,90,69,30,127,117,90,39,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,73,56,24,127,0,0,0,127,0,0,0,32],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,95,25,28,25,127,88,99,88,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,86,97,86,127,87,98,87,127,70,79,70,127,46,54,46,127,47,55,47,127,45,52,45,127,30,37,30,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,24,30,24,127,44,52,44,127,72,81,72,127,70,79,70,127,23,29,23,127,25,31,25,127,21,25,21,127,0,0,0,127,66,73,65,127,105,118,105,127,92,103,92,127,0,0,0,127,16,12,5,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,80,62,27,127,77,59,26,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,77,59,26,127,0,0,0,127,0,0,0,64],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,1,0,127,64,72,64,127,87,97,87,127,86,97,86,127,86,97,86,127,87,97,87,127,86,97,86,127,86,96,86,127,85,95,85,127,71,80,71,127,47,55,47,127,46,54,46,127,46,54,46,127,46,54,46,127,47,55,47,127,31,38,31,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,23,29,23,127,59,67,59,127,77,87,77,127,58,66,58,127,25,31,25,127,25,31,25,127,22,27,22,127,0,0,0,127,48,54,48,127,105,118,105,127,92,103,92,127,0,0,0,127,16,12,5,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,98,75,33,127,80,62,27,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,92,71,31,127,0,0,0,127,0,0,0,64],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,127,14,16,14,127,88,99,88,127,88,98,88,127,88,98,88,127,72,82,72,127,51,59,51,127,52,61,52,127,55,63,55,127,47,55,47,127,45,53,45,127,45,53,45,127,46,54,46,127,46,54,46,127,46,54,46,127,45,53,45,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,37,44,37,127,76,86,76,127,73,82,73,127,32,39,32,127,23,29,23,127,2,2,2,127,30,34,30,95,105,118,105,64,98,111,98,64,0,0,0,95,4,3,2,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,115,88,38,127,92,71,31,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,119,91,40,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,98,75,33,127,0,0,0,127,0,0,0,64],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,127,21,24,21,127,55,62,55,127,51,57,50,127,64,72,64,127,86,96,86,127,85,95,85,127,84,94,84,127,86,96,86,127,84,95,84,127,82,92,82,127,75,85,75,127,52,60,52,127,46,54,46,127,46,54,46,127,45,53,45,127,26,32,26,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,29,36,29,127,28,34,28,127,24,30,24,127,62,71,62,127,88,99,88,127,66,75,66,127,24,30,24,127,8,11,8,127,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,127,105,81,35,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,98,75,33,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,121,92,40,127,100,76,33,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,107,82,36,127,0,0,0,127,0,0,0,64],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,127,31,36,31,127,35,40,35,127,33,36,32,127,31,34,31,127,47,55,47,127,51,59,51,127,47,55,47,127,39,46,39,127,29,36,29,127,37,43,37,127,52,60,52,127,77,87,77,127,49,58,49,127,46,54,46,127,40,48,40,127,24,30,24,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,29,35,29,127,80,90,80,127,59,67,59,127,24,30,24,127,24,30,24,127,76,86,76,127,87,98,87,127,39,46,39,127,17,22,17,127,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,127,75,57,25,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,79,60,26,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,113,87,38,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,71,55,24,127,103,79,35,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,117,90,39,127,0,0,0,127,0,0,0,64],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,127,41,48,41,127,69,79,69,127,39,45,39,127,47,54,47,127,77,87,77,127,86,97,86,127,88,97,87,127,87,97,86,127,82,93,83,127,57,65,57,127,25,31,25,127,24,30,24,127,26,32,26,127,26,32,26,127,26,32,26,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,75,85,75,127,87,98,87,127,67,75,67,127,23,29,23,127,23,29,23,127,56,64,56,127,85,95,85,127,75,84,75,127,24,30,24,127,3,3,3,127,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,127,29,22,10,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,119,91,40,127,8,6,3,127,109,84,36,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,119,91,40,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,98,75,33,127,6,5,2,127,107,82,36,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,0,0,0,127,0,0,0,64],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,127,12,15,12,127,45,53,46,127,48,56,48,127,65,72,63,127,98,81,79,127,123,119,119,127,117,108,108,127,94,79,76,127,88,88,80,127,64,73,64,127,24,30,24,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,35,41,35,127,86,96,86,127,87,98,87,127,61,69,61,127,23,29,23,127,24,30,24,127,46,53,46,127,84,94,84,127,87,98,87,127,55,63,55,127,10,12,10,127,0,0,0,95,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,127,92,71,31,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,75,57,25,127,0,0,0,127,52,40,17,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,98,75,33,127,12,9,4,127,0,0,0,127,109,84,36,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,14,11,5,127,0,0,0,95],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,127,22,26,22,127,30,37,30,127,23,29,23,127,41,40,35,127,91,73,72,127,113,103,103,127,100,75,75,127,87,58,58,127,83,72,66,127,54,63,55,127,23,29,23,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,30,25,127,34,41,34,127,69,78,69,127,81,91,81,127,34,41,34,127,25,31,25,127,23,29,23,127,61,69,61,127,82,92,82,127,75,85,75,127,82,92,82,127,24,29,24,127,1,1,1,127,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,127,23,18,8,127,119,91,40,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,121,92,40,127,17,14,6,127,0,0,0,127,2,2,1,127,96,73,32,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,75,58,25,127,6,5,2,127,0,0,0,127,0,0,0,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,18,14,6,127,0,0,0,127],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,127,24,29,24,127,48,56,48,127,28,34,28,127,24,30,24,127,25,31,25,127,36,37,32,127,68,55,52,127,82,63,62,127,80,52,52,127,81,82,74,127,28,34,28,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,24,30,24,127,23,29,23,127,25,31,25,127,24,30,24,127,25,31,25,127,24,29,24,127,56,64,56,127,87,97,87,127,70,79,70,127,88,99,88,127,49,57,49,127,10,12,10,127,0,0,0,95,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,127,44,34,15,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,67,52,23,127,0,0,0,127,0,0,0,95,0,0,0,127,12,9,4,127,109,84,36,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,100,76,33,127,33,25,11,127,0,0,0,127,0,0,0,127,0,0,0,95,0,0,0,127,107,82,36,127,117,90,39,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,31,24,11,127,0,0,0,127],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,95,14,16,14,127,81,91,81,127,72,81,72,127,43,51,43,127,23,29,23,127,24,30,24,127,23,30,24,127,23,30,23,127,25,31,25,127,26,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,26,32,26,127,32,39,32,127,30,37,30,127,24,30,24,127,25,31,25,127,25,31,25,127,25,32,25,127,83,93,83,127,77,86,77,127,87,97,87,127,80,90,80,127,22,27,22,127,1,1,1,127,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,127,46,35,15,127,121,92,40,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,96,73,32,127,4,3,2,127,0,0,0,95,0,0,0,0,0,0,0,32,0,0,0,127,12,9,4,127,98,75,33,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,96,73,32,127,40,31,14,127,2,2,1,127,0,0,0,127,0,0,0,64,0,0,0,0,0,0,0,32,0,0,0,127,0,0,0,127,0,0,0,127,2,2,1,127,16,12,5,127,25,19,9,127,33,25,11,127,46,36,16,127,56,43,19,127,61,47,21,127,77,59,26,127,84,65,28,127,92,71,31,127,107,82,36,127,115,88,38,127,122,94,41,127,122,94,41,127,39,30,13,127,0,0,0,127],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,127,18,21,18,127,83,93,83,127,89,100,89,127,71,81,71,127,54,61,54,127,37,44,37,127,24,30,24,127,23,29,23,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,24,30,24,127,42,50,42,127,70,79,70,127,87,98,87,127,74,83,74,127,28,35,28,127,25,31,25,127,24,30,24,127,42,49,42,127,76,86,76,127,86,97,86,127,88,99,88,127,41,49,41,127,11,14,11,127,0,0,0,95,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,127,27,21,9,127,105,81,35,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,98,75,33,127,12,9,4,127,0,0,0,95,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,127,2,2,1,127,58,44,19,127,113,87,38,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,105,81,35,127,63,49,21,127,21,16,7,127,0,0,0,127,0,0,0,127,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,16,12,5,127,6,5,2,127,0,0,0,95],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,127,13,17,13,127,61,70,61,127,85,96,85,127,89,100,89,127,88,98,88,127,77,87,77,127,60,67,60,127,26,32,26,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,25,31,25,127,12,16,12,127,12,15,12,127,40,46,40,127,80,90,80,127,80,89,80,127,34,40,34,127,24,30,24,127,23,29,23,127,51,59,51,127,88,99,88,127,86,97,86,127,76,85,76,127,22,27,22,127,1,2,1,127,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,127,4,3,2,127,59,46,20,127,111,85,37,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,119,91,40,127,65,50,22,127,4,3,2,127,0,0,0,127,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,95,0,0,0,127,4,3,2,127,44,34,15,127,80,62,27,127,111,85,37,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,122,94,41,127,121,92,40,127,100,76,33,127,75,57,25,127,48,37,16,127,18,13,6,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,127,0,0,0,64,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,127,19,23,19,127,46,53,46,127,64,72,64,127,80,90,80,127,85,96,85,127,74,84,74,127,28,34,28,127,25,31,25,127,25,31,25,127,25,30,25,127,25,31,25,127,25,31,25,127,25,31,25,127,17,21,17,127,1,3,1,127,0,1,0,127,0,0,0,127,9,11,9,127,51,59,52,127,82,93,83,127,45,52,45,127,23,29,23,127,24,30,24,127,59,67,59,127,88,99,88,127,85,96,85,127,30,37,30,127,12,15,12,127,0,0,0,95,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,95,0,0,0,127,4,3,2,127,42,33,14,127,82,63,28,127,107,82,36,127,103,79,35,127,84,65,28,127,54,41,18,127,12,9,4,127,0,0,0,127,0,0,0,95,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,95,0,0,0,127,0,0,0,127,0,0,0,127,10,8,3,127,25,19,9,127,31,24,11,127,31,24,11,127,31,24,11,127,31,24,11,127,18,14,6,127,35,27,12,127,105,81,35,127,80,62,27,127,54,41,18,127,29,22,10,127,6,5,2,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,95,0,0,0,64,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,127,8,10,8,127,33,39,33,127,44,51,44,127,46,53,46,127,44,52,44,127,39,46,39,127,25,30,25,127,25,31,25,127,25,31,25,127,24,30,24,127,15,19,15,127,5,7,5,127,0,1,0,127,0,0,0,127,0,0,0,95,0,0,0,64,0,0,0,64,0,1,0,127,21,24,21,127,66,74,66,127,57,66,57,127,24,30,24,127,23,29,23,127,52,60,52,127,40,47,40,127,24,30,24,127,23,28,23,127,1,2,1,127,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,95,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,95,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,64,0,0,0,95,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,64,0,0,0,64,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,95,0,0,0,127,11,13,11,127,23,28,23,127,33,39,33,127,36,43,36,127,23,29,23,127,20,26,20,127,11,15,11,127,3,4,3,127,0,1,0,127,0,0,0,127,0,0,0,95,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,95,3,5,3,127,37,41,37,127,58,66,58,127,27,33,27,127,24,30,24,127,26,32,26,127,25,31,25,127,25,31,25,127,8,9,8,127,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,64,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,95,0,0,0,127,0,0,0,127,0,0,0,127,0,1,0,127,0,0,0,127,0,0,0,127,0,0,0,127,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,127,12,15,12,127,42,49,42,127,32,39,32,127,24,30,24,127,25,31,25,127,25,31,25,127,18,22,18,127,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,2,2,2,127,23,27,23,127,37,43,37,127,26,33,26,127,25,31,25,127,24,30,24,127,4,4,4,127,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,95,4,5,4,127,24,28,23,127,29,35,29,127,25,31,25,127,12,16,12,127,0,0,0,95,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,95,4,4,4,127,11,14,11,127,16,20,16,127,0,0,0,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,64,0,0,0,127,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]])
def __init__(self, childWidget, title):
"""Constructor.
@param title Header title.
"""
Decorator.__init__(self, childWidget)
self.title = title
self.border = 10
return
def draw(self, screenRectangle):
rect = screenRectangle[:]
rect[0] += self.border
rect[1] += self.border
rect[2] -= self.border
rect[3] -= self.border
# title
glColor3ub(210, 236, 210)
glRecti(rect[0],rect[3]-41,rect[2],rect[3]-17)
glColor3ub(50, 62, 50)
glRasterPos2i(rect[0]+126, rect[3]-34)
Blender.Draw.Text(self.title)
glRasterPos2i(rect[0]+127, rect[3]-34)
Blender.Draw.Text(self.title)
# logo
glRasterPos2i(rect[0]+1, rect[3]-48)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glDrawPixels(122, 48, GL_RGBA, GL_BYTE, OgreFrame.OGRE_LOGO)
rect[3] -= 60
glDisable(GL_BLEND)
# child
self.childWidget.draw(rect)
return
def getMaximumSize(self):
size = self.childWidget.getMaximumSize()[:]
size[0] += 2*self.border
size[1] += 2*self.border + 60
width = 2*self.border + Blender.Draw.GetStringWidth(self.title) + 85
if size[0] < width:
size[0] = width
height = 60 + 2*self.border
if size[1] < height:
size[1] = height
return size
def getMinimumSize(self):
size = self.childWidget.getMinimumSize()[:]
size[0] += 2*self.border
size[1] += 2*self.border + 60
width = 2*self.border + Blender.Draw.GetStringWidth(self.title) + 85
if size[0] < width:
size[0] = width
height = 60 + 2*self.border
if size[1] < height:
size[1] = height
return size
def getPreferredSize(self):
size = self.childWidget.getPreferredSize()[:]
size[0] += 2*self.border
size[1] += 2*self.border + 60
width = 2*self.border + Blender.Draw.GetStringWidth(self.title) + 85
if size[0] < width:
size[0] = width
height = 60 + 2*self.border
if size[1] < height:
size[1] = height
return size
class RoundedPanel(Widget):
def __init__(self, radius, color):
self.radius = radius
self.color = color
return
def draw(self, screenRect):
glEnable(GL_BLEND)
glColor4ub(*self.color)
if (((screenRect[2]-screenRect[0]) < 2*self.radius)
or ((screenRect[3]-screenRect[1]) < 2*self.radius)):
# drawing area to small for round edges
glRecti(*screenRect)
else:
glBegin(GL_POLYGON)
# upper left
glVertex2i(screenRect[0], screenRect[3] - self.radius)
glVertex2i(screenRect[0] + self.radius, screenRect[3])
# upper right
glVertex2i(screenRect[2] - self.radius, screenRect[3])
glVertex2i(screenRect[2], screenRect[3] - self.radius)
# lower right
glVertex2i(screenRect[2], screenRect[1] + self.radius)
glVertex2i(screenRect[2] - self.radius, screenRect[1])
# lower left
glVertex2i(screenRect[0] + self.radius, screenRect[1])
glVertex2i(screenRect[0], screenRect[1] + self.radius)
# close polygon
glVertex2i(screenRect[0], screenRect[3] - self.radius)
glEnd()
glDisable(GL_BLEND)
return
class Selectable(Model):
"""Keeps track of selection status.
"""
def __init__(self, selected):
Model.__init__(self)
self.selected = selected
return
def isSelected(self):
return self.selected
def setSelected(self, selected):
self.selected = selected
self._notify()
return
def select(self):
self.selected = 1
self._notify()
return
def deselect(self):
self.selected = 0
self._notify()
return
class SelectableLabel(Widget, View):
def __init__(self, selectable, string):
"""Constructor.
@param selectable Model.
@param string String to display.
"""
#Widget.__init__(self)
View.__init__(self)
self.string = string
self.selectable = selectable
# mouse focus indicator
self.mouseFocusX = 0
self.mouseFocusY = 0
# last drawing location
self.guiRect = [0, 0, 0, 0]
self.positionRect = [0, 0, 0, 0]
return
def draw(self, screenRectangle):
# get size of the GUI window to translate MOUSEX and MOUSEY events
guiRectBuffer = Blender.BGL.Buffer(GL_FLOAT, 4)
Blender.BGL.glGetFloatv(Blender.BGL.GL_SCISSOR_BOX, guiRectBuffer)
# replace element wise to avoid IndexError in eventFilter
self.guiRect[0] = int(guiRectBuffer.list[0])
self.guiRect[1] = int(guiRectBuffer.list[1])
self.guiRect[2] = int(guiRectBuffer.list[2])
self.guiRect[3] = int(guiRectBuffer.list[3])
## differs by one:
## self.guiRect = Blender.Window.GetScreenInfo(Blender.Window.Types['SCRIPT'])[0]['vertices']
self.positionRect = screenRectangle
# draw panel and label
glEnable(GL_BLEND)
color = Blender.Window.Theme.Get()[0].get('ui').menu_back
glColor4ub(*color)
glRecti(*screenRectangle)
if (self.mouseFocusX and self.mouseFocusY):
color = Blender.Window.Theme.Get()[0].get('ui').menu_hilite
else:
color = Blender.Window.Theme.Get()[0].get('ui').menu_item
glColor4ub(*color)
glRecti(screenRectangle[0], screenRectangle[1]+2, screenRectangle[2], screenRectangle[3]-2)
if self.selectable.isSelected():
color = [59, 89, 59, 128]
glColor4ub(*color)
glRecti(screenRectangle[0], screenRectangle[1]+2, screenRectangle[2], screenRectangle[3]-2)
color = Blender.Window.Theme.Get()[0].get('ui').menu_text
glColor4ub(*color)
glRasterPos2i(screenRectangle[0]+4, screenRectangle[1]+7)
Blender.Draw.Text(self.string)
glDisable(GL_BLEND)
return
def eventFilter(self, event, value):
"""Left mouse click on the label toggles selection status.
"""
if (value != 0):
# check focus
if (event == Blender.Draw.MOUSEX):
if ((value >= (self.guiRect[0] + self.positionRect[0]))
and (value <= (self.guiRect[0]) + self.positionRect[2])):
# redraw if widget got focus
if (not self.mouseFocusX) and self.mouseFocusY:
Blender.Draw.Redraw(1)
self.mouseFocusX = 1
else:
# redraw if widget lost focus
if self.mouseFocusX and self.mouseFocusY:
Blender.Draw.Redraw(1)
self.mouseFocusX = 0
elif (event == Blender.Draw.MOUSEY):
if ((value >= (self.guiRect[1] + self.positionRect[1]))
and (value <= (self.guiRect[1] + self.positionRect[3]))):
# redraw if marker got focus
if (not self.mouseFocusY) and self.mouseFocusX:
Blender.Draw.Redraw(1)
self.mouseFocusY = 1
else:
# redraw if marker lost focus
if self.mouseFocusX and self.mouseFocusY:
Blender.Draw.Redraw(1)
self.mouseFocusY = 0
# check selection
elif ((event == Blender.Draw.LEFTMOUSE)
and self.mouseFocusX and self.mouseFocusY):
self.selectable.setSelected(1 - self.selectable.isSelected())
return
def getMinimumSize(self):
return [Blender.Draw.GetStringWidth(self.string), 11+12]
def update(self):
Blender.Draw.Redraw(1)
return
########################################################################################
class Logger:
"""Logs messages and status.
Logs messages as a list of strings and keeps track of the status.
Possible status values are info, warning and error.
@cvar INFO info status
@cvar WARNING warning status
@cvar ERROR error status
"""
INFO, WARNING, ERROR = range(3)
def __init__(self):
"""Constructor.
"""
self.messageList = []
self.status = Logger.INFO
return
def logInfo(self, message):
"""Logs an info message.
@param message message string
"""
self.messageList.append(message)
return
def logWarning(self, message):
"""Logs a warning message.
The status is set to <code>Logger.WARNING</code> if it is not already <code>Logger.ERROR</code>.
@param message message string
"""
self.messageList.append("Warning: "+message)
if not self.status == Logger.ERROR:
self.status = Logger.WARNING
return
def logError(self, message):
"""Logs an error message.
The status is set to <code>Logger.ERROR</code>.
@param message message string
"""
self.messageList.append("Error: "+message)
self.status = Logger.ERROR
return
def getStatus(self):
"""Gets the current status.
The status can be
<ul>
<li><code>Logger.INFO</code>
<li><code>Logger.WARNING</code>
<li><code>Logger.ERROR</code>
</ul>
@return status
"""
return self.status
def getMessageList(self):
"""Returns the list of log messages.
@return list of strings
"""
return self.messageList
# global logger instance
exportLogger = Logger()
class ExportSettings:
"""Global export settings.
"""
def __init__(self):
self.path = os.path.dirname(Blender.Get('filename'))
self.fileName = ''
self.fixUpAxis = 0
self.doProperties = 0
self.rotX = BoundedValueModel(-1000.0, 1000.0, 0.0)
self.rotY = BoundedValueModel(-1000.0, 1000.0, 0.0)
self.rotZ = BoundedValueModel(-1000.0, 1000.0, 0.0)
self.scale = BoundedValueModel(0.0, 1e6, 1.0);
self.load()
return
def getRotX(self):
return self.rotX.getValue()
def getRotY(self):
return self.rotY.getValue()
def getRotZ(self):
return self.rotZ.getValue()
def getScale(self):
return self.scale.getValue()
def load(self):
"""Load settings from registry, if available.
"""
settingsDict = Registry.GetKey('ogredotscene', True)
if settingsDict:
if settingsDict.has_key('path'):
self.path = settingsDict['path']
if settingsDict.has_key('fileName'):
self.fileName = settingsDict['fileName']
if settingsDict.has_key('fixUpAxis'):
self.fixUpAxis = settingsDict['fixUpAxis']
if settingsDict.has_key('doProperties'):
self.doProperties = settingsDict['doProperties']
# float(integer) for compatibility
if settingsDict.has_key('rotX'):
self.rotX.setValue(float(settingsDict['rotX']))
if settingsDict.has_key('rotY'):
self.rotY.setValue(float(settingsDict['rotY']))
if settingsDict.has_key('rotZ'):
self.rotZ.setValue(float(settingsDict['rotZ']))
if settingsDict.has_key('scale'):
self.scale.setValue(settingsDict['scale'])
return
def save(self):
"""Save settings to registry.
"""
settingsDict = {}
settingsDict['path'] = self.path
settingsDict['fileName'] = self.fileName
settingsDict['fixUpAxis'] = self.fixUpAxis
settingsDict['doProperties'] = self.doProperties
settingsDict['rotX'] = self.rotX.getValue()
settingsDict['rotY'] = self.rotY.getValue()
settingsDict['rotZ'] = self.rotZ.getValue()
settingsDict['scale'] = self.scale.getValue()
Registry.SetKey('ogredotscene', settingsDict, True)
return
# Blender.Window.FileSelector does not accept type 'instancemethod' callbacks
# set this to the instancemethod callback
fileSelectorCallbackMethod = None
def fileSelectorCallback(fileName):
"""FileSelector needs callback of PyFunction_Type
"""
fileSelectorCallbackMethod(fileName)
return
class ExportSettingsView(Box):
def __init__(self, exportSettings):
# reference to model
self.exportSettings = exportSettings
self.fixUpAxisCheckBox = CheckBox(ExportSettingsView.FixUpAxisChangeAction(self), \
self.exportSettings.fixUpAxis, \
'Fix Up Axis To Y', \
[Blender.Draw.GetStringWidth('Fix Up Axis To Y')+10,20], \
'Fix up axis as Y instead of Z. This ignores rotation settings.')
self.propertiesCheckBox = CheckBox(ExportSettingsView.PropertiesChangeAction(self), \
self.exportSettings.doProperties, \
'Logic Properties', \
[Blender.Draw.GetStringWidth('Logic Properties')+10,20], \
'Export object logic propterties as userData.')
self.stringButton = StringButton(self.exportSettings.path, \
ExportSettingsView.PathChangedAction(self), \
'Path: ', [200, 20], 'Export directory')
# expand horizontally
self.stringButton.preferredSize = [Widget.INFINITY, 13]
self.button = Button(ExportSettingsView.SelectAction(self), \
'Select', [100, 20], 'Select the export directory')
self.fileStringButton = StringButton(self.exportSettings.fileName, \
ExportSettingsView.FileNameChangedAction(self), \
'Filename: ', [200, 20], 'Export filename (Defaults to <scenename>.xml)')
hLayout = HorizontalLayout()
hLayout.addWidget(self.stringButton,'path')
hLayout.addWidget(self.button,'select')
vLayout = VerticalLayout()
vLayout.addWidget(self.fixUpAxisCheckBox, 'fixUpAxis')
vLayout.addWidget(self.propertiesCheckBox, 'doProperties')
hRotLayout = HorizontalLayout()
hRotLayout.addWidget(NumberView('RotX:', self.exportSettings.rotX, [100, 20], [Widget.INFINITY, 20],
tooltip='Additional rotation around x-axis.'), 'rotX')
hRotLayout.addWidget(NumberView('RotY:', self.exportSettings.rotY, [100, 20], [Widget.INFINITY, 20],
tooltip='Additional rotation around y-axis.'), 'rotY')
hRotLayout.addWidget(NumberView('RotZ:', self.exportSettings.rotZ, [100, 20], [Widget.INFINITY, 20],
tooltip='Additional rotation around z-axis.'), 'rotZ')
vLayout.addWidget(hRotLayout, 'hRotLayout')
#vLayout.addWidget(NumberView('Scale:', self.exportSettings.scale, [100, 20], [Widget.INFINITY, 20],
# tooltip='Factor of additional uniform scaling.'), 'scale')
vLayout.addWidget(hLayout, 'hLayout')
vLayout.addWidget(self.fileStringButton, 'filename')
Box.__init__(self, vLayout, 'Global Settings')
return
def _pathSelectCallback(self, fileName):
self.exportSettings.path = os.path.dirname(fileName)
self.stringButton.string = Blender.Draw.Create(os.path.dirname(fileName))
Blender.Draw.Redraw(1)
return
def _fixUpAxisChange(self):
self.exportSettings.fixUpAxis = self.fixUpAxisCheckBox.isChecked()
return
def _propertiesChange(self):
self.exportSettings.doProperties = self.propertiesCheckBox.isChecked()
return
class FixUpAxisChangeAction(Action):
def __init__(self, exportSettingsView):
self.view = exportSettingsView
return
def execute(self):
self.view._fixUpAxisChange()
return
class PropertiesChangeAction(Action):
def __init__(self, exportSettingsView):
self.view = exportSettingsView
return
def execute(self):
self.view._propertiesChange()
return
class PathChangedAction(Action):
def __init__(self, exportSettingsView):
self.view = exportSettingsView
return
def execute(self):
self.view.exportSettings.path = self.view.stringButton.getString()
return
class FileNameChangedAction(Action):
def __init__(self, exportSettingsView):
self.view = exportSettingsView
return
def execute(self):
self.view.exportSettings.fileName = self.view.fileStringButton.getString()
return
class SelectAction(Action):
def __init__(self, exportSettingsView):
self.view = exportSettingsView
return
def execute(self):
global fileSelectorCallbackMethod
fileSelectorCallbackMethod = self.view._pathSelectCallback
Blender.Window.FileSelector(fileSelectorCallback, "Export Directory", self.view.exportSettings.path)
#Blender.Window.FileSelector(self.view._pathSelectCallback, "Export Directory", self.view.exportSettings.path)
return
class ObjectExporter(Model):
"""Interface. Exports a Blender object to Ogre.
"""
def __init__(self, object, enabled=1, children=None):
"""Constructor.
@param object Blender object to export.
@param enabled Only enabled objects are exported.
@param children List of child ObjectExporters
"""
Model.__init__(self)
# blender object
self.object = object
# export status
self.enabled = enabled
# list of child ObjectExporters
self.children = children or []
return
def isEnabled(self):
return self.enabled
def setEnabled(self, enabled):
self.enabled = enabled
self._notify()
return
def getBlenderObject(self):
return self.object
def addChild(self, objectExporter):
self.children.append(objectExporter)
self._notify()
return
def removeChild(self, objectExporter):
if objectExporter in self.children:
self.children.remove(objectExporter)
self._notify()
return
def getChildren(self):
return self.children
def export(self, sceneExporter, fileObject, indent=0, parentTransform=Blender.Mathutils.Matrix([1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1])):
"""Append node element for this object and all enabled childrens into a given file.
@param sceneExporter Blender sceneExporter
@param fileObject already opened XML file.
@param indent indentation in the XML file.
@param parentTransform transformations are exported in this coordinate system.
"""
if self.isEnabled():
fileObject.write(self._indent(indent) + "<node name=\"%s\">\n" % self.object.getName())
# create transformation matrix relative to parent
objectMatrix = self.object.getMatrix("worldspace")
inverseParentMatrix = Blender.Mathutils.Matrix(*parentTransform)
inverseParentMatrix.invert()
matrix = objectMatrix*inverseParentMatrix
# position
if (sceneExporter.settings.fixUpAxis):
trans = matrix.translationPart()
fileObject.write(self._indent(indent+1) + \
"<position x=\"%.6f\" y=\"%.6f\" z=\"%.6f\"/>\n" % (trans.x, trans.z, -trans.y))
else:
fileObject.write(self._indent(indent+1) + \
"<position x=\"%.6f\" y=\"%.6f\" z=\"%.6f\"/>\n" % tuple(matrix.translationPart()))
# rotation
rot = matrix.toQuat()
if (sceneExporter.settings.fixUpAxis):
fileObject.write(self._indent(indent+1) + \
"<quaternion x=\"%.6f\" y=\"%.6f\" z=\"%.6f\" w=\"%.6f\"/>\n" % (rot.x, rot.z, -rot.y, rot.w))
else:
fileObject.write(self._indent(indent+1) + \
"<quaternion x=\"%.6f\" y=\"%.6f\" z=\"%.6f\" w=\"%.6f\"/>\n" % (rot.x, rot.y, rot.z, rot.w))
# scale
rot.inverse()
inverseRotationMatrix = rot.toMatrix()
inverseRotationMatrix.resize4x4()
scale = matrix*inverseRotationMatrix
if (sceneExporter.settings.fixUpAxis):
fileObject.write(self._indent(indent+1) + \
"<scale x=\"%.6f\" y=\"%.6f\" z=\"%.6f\"/>\n" % (scale[0][0], scale[2][2], scale[1][1]))
else:
fileObject.write(self._indent(indent+1) + \
"<scale x=\"%.6f\" y=\"%.6f\" z=\"%.6f\"/>\n" % (scale[0][0], scale[1][1], scale[2][2]))
# specifics
self.writeSpecificNodeElements(sceneExporter, fileObject, indent+1)
# logic properties
self.writeUserData(sceneExporter, fileObject, indent+1)
for child in self.children:
child.export(sceneExporter, fileObject, indent+1, self.object.getMatrix("worldspace"))
fileObject.write(self._indent(indent)+"</node>\n")
else:
for child in self.children:
child.export(sceneExporter, fileObject, indent, parentTransform)
return
def writeSpecificNodeElements(self, sceneExporter, fileObject, indent=0):
"""Virtual method to write node elements that depend on the object type.
This method is called before the node element is closed. Overwrite
this method in derived classes for specific object types.
"""
return
def propertyFilter(self, property):
"""Filter properties that should not be exported as user data.
@param property the property to test.
@return <code>1</code> if filter applies, otherwise <code>0</code>.
"""
return 0
def writeUserData(self, sceneExporter, fileObject, indent=0):
"""Writes object propreties as userDataReference.
"""
if ((sceneExporter.settings.doProperties) and len(self.object.getAllProperties())):
fileObject.write(self._indent(indent) + "<userData>\n")
for property in self.object.getAllProperties():
if (property and not(self.propertyFilter(property))):
fileObject.write(self._indent(indent + 1) +
"<property type=\"%s\" " % property.getType() +
"name=\"%s\" " % property.getName() +
"data=\"%s\"/>\n" % str(property.getData()))
fileObject.write(self._indent(indent) + "</userData>\n")
return
# protected
def _indent(self, indent):
return " "*indent
class MeshExporter(ObjectExporter):
def __init__(self, object, enabled=1, children=None):
ObjectExporter.__init__(self, object, enabled, children)
return
def writeSpecificNodeElements(self, sceneExporter, fileObject, indent=0):
fileObject.write(self._indent(indent) + "<entity name=\"%s\" meshFile=\"%s\"" \
% (self.object.getName(), self.object.data.name + ".mesh"))
# static property
for property in self.object.getAllProperties():
if (property):
result = self.propertyFilter(property)
if (result == 1):
fileObject.write(" static=\"")
if property.getData(): fileObject.write("true\"")
else: fileObject.write("false\"")
elif (result == 2):
fileObject.write(" visible=\"")
if property.getData(): fileObject.write("true\"")
else: fileObject.write("false\"")
elif (result == 3):
fileObject.write(" castShadows=\"")
if property.getData(): fileObject.write("true\"")
else: fileObject.write("false\"")
elif (result == 4):
fileObject.write(" renderingDistance=\"")
fileObject.write(str(property.getData()))
fileObject.write("/>\n")
return
def propertyFilter(self, property):
filter = 0
if ((property.getType() == "BOOL") and (property.getName() == "static")):
filter = 1
elif ((property.getType() == "BOOL") and (property.getName() == "visible")):
filter = 2
elif ((property.getType() == "BOOL") and (property.getName() == "castShadows")):
filter = 3
elif ((property.getType() == "FLOAT") and (property.getName() == "renderingDistance")):
filter = 4
return filter
class LampExporter(ObjectExporter):
def __init__(self, object, enabled=1, children=None):
ObjectExporter.__init__(self, object, enabled, children)
return
def export(self, sceneExporter, fileObject, indent=0, parentTransform=Blender.Mathutils.Matrix([1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1])):
"""Append node element for this object and all enabled childrens into a given file.
@param sceneExporter Blender sceneExporter
@param fileObject already opened XML file.
@param indent indentation in the XML file.
@param parentTransform transformations are exported in this coordinate system.
"""
if self.isEnabled():
fileObject.write(self._indent(indent) + "<node name=\"%s\">\n" % self.object.getName())
# create transformation matrix relative to parent
objectMatrix = self.object.getMatrix("worldspace")
inverseParentMatrix = Blender.Mathutils.Matrix(*parentTransform)
inverseParentMatrix.invert()
matrix = objectMatrix*inverseParentMatrix
# position
if (sceneExporter.settings.fixUpAxis):
matrix = matrix*Blender.Mathutils.Matrix([1, 0, 0, 0],
[0, 0, -1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1])
fileObject.write(self._indent(indent+1) + \
"<position x=\"%.6f\" y=\"%.6f\" z=\"%.6f\"/>\n" % tuple(matrix.translationPart()))
# rotation
rot = matrix.toQuat()
fileObject.write(self._indent(indent+1) + \
"<quaternion x=\"%.6f\" y=\"%.6f\" z=\"%.6f\" w=\"%.6f\"/>\n" % (rot.x, rot.y, rot.z, rot.w))
# scale
rot.inverse()
inverseRotationMatrix = rot.toMatrix()
inverseRotationMatrix.resize4x4()
scale = matrix*inverseRotationMatrix
fileObject.write(self._indent(indent+1) + \
"<scale x=\"%.6f\" y=\"%.6f\" z=\"%.6f\"/>\n" % (scale[0][0], scale[1][1], scale[2][2]))
# specifics
self.writeSpecificNodeElements(sceneExporter, fileObject, indent+1)
# logic properties
self.writeUserData(sceneExporter, fileObject, indent+1)
for child in self.children:
child.export(sceneExporter, fileObject, indent+1, self.object.getMatrix("worldspace"))
fileObject.write(self._indent(indent)+"</node>\n")
else:
for child in self.children:
child.export(sceneExporter, fileObject, indent, parentTransform)
return
def writeSpecificNodeElements(self, sceneExporter, fileObject, indent=0):
lamp = self.object.data
fileObject.write(self._indent(indent) + "<light name=\"%s\" " % lamp.name)
# type specific parameters
if (lamp.getType() & lamp.Types['Sun']):
self._writeSunNodeElements(sceneExporter, fileObject, indent)
elif (lamp.getType() & lamp.Types['Spot']):
self._writeSpotNodeElements(sceneExporter, fileObject, indent)
else:
self._writeLampNodeElements(sceneExporter, fileObject, indent)
# close light
fileObject.write(self._indent(indent) + "</light>\n")
return
def _attenuation(self, lamp):
# attenuation calculation:
#
# OpenGL attenuation factor f = 1/(c+l*r+q*r^2),
# where r is the distance between the light source and the vertex to be lit.
#
# Ignore Sphere option as it can't be mapped to Ogre settings.
# Note: Multiply lamp colors with Blender's energy factor e.
# => here: e=1.0
c = 1.0
l = 0.0
q = 0.0
if (lamp.getMode() & lamp.Modes['Quad']):
# Blender's intensity:
# f = e*d(d+Q1*r)*d^2/(d^2+Q2*r^2)
# = e*d^3/(d^3 + Q1*d^2*r + d*Q2*r^2 + Q1*Q2*r^3)
# => approximately
# c = d^3/(e*d^3) = 1/e
# l = Q1/(e*d)
# q = Q2/(e*d^2)
l = lamp.getQuad1()/lamp.getDist()
q = lamp.getQuad2()/(lamp.getDist()*lamp.getDist())
else:
# no quad, no sphere
# Blender's intensity:
# f = e*d/(d+r),
# where e is energy and d is distance.
# =>
# c = d/(e*d) = 1/e, l = 1/(e*d), q = 0
l = 1.0/lamp.getDist()
return (c, l, q)
def _colourDiffuse(self, lamp):
if (lamp.getMode() & lamp.Modes['NoDiffuse']):
color = (0, 0, 0)
else:
e = lamp.getEnergy()
rgb = lamp.col
color = (e*rgb[0], e*rgb[1], e*rgb[2])
return color
def _colourSpecular(self, lamp):
if (lamp.getMode() & lamp.Modes['NoSpecular']):
color = (0, 0, 0)
else:
e = lamp.getEnergy()
rgb = lamp.col
color = (e*rgb[0], e*rgb[1], e*rgb[2])
return color
def _writeLampNodeElements(self, sceneExporter, fileObject, indent=0):
# LT_POINT
fileObject.write("type=\"point\">\n")
lamp = self.object.data
fileObject.write(self._indent(indent+1) + \
"<colourDiffuse r=\"%f\" g=\"%f\" b=\"%f\"/>\n" % self._colourDiffuse(lamp))
fileObject.write(self._indent(indent+1) + \
"<colourSpecular r=\"%f\" g=\"%f\" b=\"%f\"/>\n" % self._colourSpecular(lamp))
fileObject.write(self._indent(indent+1) + \
"<lightAttenuation range=\"5000.0\" constant=\"%f\" linear=\"%f\" quadratic=\"%f\"/>\n" \
% self._attenuation(lamp))
return
def _writeSpotNodeElements(self, sceneExporter, fileObject, indent=0):
# LT_SPOT
fileObject.write("type=\"spotLight\" ")
lamp = self.object.data
# castShadows="true" only if Modes['Shadows'] is set
if (lamp.getMode() & lamp.Modes['Shadows']):
fileObject.write("castShadows=\"true\">\n")
range = lamp.getClipEnd()
else:
fileObject.write("castShadows=\"false\">\n")
range = 5000.0
# points locally in -z direction
fileObject.write(self._indent(indent+1) + "<normal x=\"0.0\" y=\"0.0\" z=\"-1.0\"/>\n")
fileObject.write(self._indent(indent+1) + \
"<colourDiffuse r=\"%f\" g=\"%f\" b=\"%f\"/>\n" % self._colourDiffuse(lamp))
fileObject.write(self._indent(indent+1) + \
"<colourSpecular r=\"%f\" g=\"%f\" b=\"%f\"/>\n" % self._colourSpecular(lamp))
# OpenGL parameters:
# GL_SPOT_CUTOFF = spotSize/2.0
# GL_SPOT_EXPONENT = 128.0*spotBlend
# but Ogre::GLRenderSystem Class only uses outer parameter
#angle = lamp.getSpotSize()*math.pi/180.0
# angle in degree
angle = lamp.getSpotSize()
fileObject.write(self._indent(indent+1) + \
"<lightRange inner=\"%f\" outer=\"%f\" falloff=\"1.0\"/>\n" % (angle, angle))
fileObject.write(self._indent(indent+1) +"<lightAttenuation range=\"%f\" " % range)
fileObject.write("constant=\"%f\" linear=\"%f\" quadratic=\"%f\"/>\n" \
% self._attenuation(lamp))
return
def _writeSunNodeElements(self, sceneExporter, fileObject, indent=0):
# LT_DIRECTIONAL
fileObject.write("type=\"directional\">\n")
lamp = self.object.data
# points locally in -z direction
fileObject.write(self._indent(indent+1) + "<normal x=\"0.0\" y=\"0.0\" z=\"-1.0\"/>\n")
fileObject.write(self._indent(indent+1) + \
"<colourDiffuse r=\"%f\" g=\"%f\" b=\"%f\"/>\n" % self._colourDiffuse(lamp))
fileObject.write(self._indent(indent+1) + \
"<colourSpecular r=\"%f\" g=\"%f\" b=\"%f\"/>\n" % self._colourSpecular(lamp))
return
class CameraExporter(ObjectExporter):
def __init__(self, object, enabled=1, children=None):
ObjectExporter.__init__(self, object, enabled, children)
return
def export(self, sceneExporter, fileObject, indent=0, parentTransform=Blender.Mathutils.Matrix([1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1])):
"""Append node element for this object and all enabled childrens into a given file.
@param sceneExporter Blender sceneExporter
@param fileObject already opened XML file.
@param indent indentation in the XML file.
@param parentTransform transformations are exported in this coordinate system.
"""
if self.isEnabled():
fileObject.write(self._indent(indent) + "<node name=\"%s\">\n" % self.object.getName())
# create transformation matrix relative to parent
objectMatrix = self.object.getMatrix("worldspace")
inverseParentMatrix = Blender.Mathutils.Matrix(*parentTransform)
inverseParentMatrix.invert()
matrix = objectMatrix*inverseParentMatrix
# position
if (sceneExporter.settings.fixUpAxis):
matrix = matrix*Blender.Mathutils.Matrix([1, 0, 0, 0],
[0, 0, -1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1])
fileObject.write(self._indent(indent+1) + \
"<position x=\"%.6f\" y=\"%.6f\" z=\"%.6f\"/>\n" % tuple(matrix.translationPart()))
# rotation
rot = matrix.toQuat()
fileObject.write(self._indent(indent+1) + \
"<quaternion x=\"%.6f\" y=\"%.6f\" z=\"%.6f\" w=\"%.6f\"/>\n" % (rot.x, rot.y, rot.z, rot.w))
# scale
rot.inverse()
inverseRotationMatrix = rot.toMatrix()
inverseRotationMatrix.resize4x4()
scale = matrix*inverseRotationMatrix
fileObject.write(self._indent(indent+1) + \
"<scale x=\"%.6f\" y=\"%.6f\" z=\"%.6f\"/>\n" % (scale[0][0], scale[1][1], scale[2][2]))
# specifics
self.writeSpecificNodeElements(sceneExporter, fileObject, indent+1)
# logic properties
self.writeUserData(sceneExporter, fileObject, indent+1)
for child in self.children:
child.export(sceneExporter, fileObject, indent+1, self.object.getMatrix("worldspace"))
fileObject.write(self._indent(indent)+"</node>\n")
else:
for child in self.children:
child.export(sceneExporter, fileObject, indent, parentTransform)
return
def writeSpecificNodeElements(self, sceneExporter, fileObject, indent=0):
# camera element
camera = self.object.data
fileObject.write(self._indent(indent) + "<camera name=\"%s\" " % camera.getName())
# fov calculation
render = sceneExporter.scene.getRenderingContext()
aspX = render.aspectRatioX()
aspY = render.aspectRatioY()
sizeX = render.imageSizeX()
sizeY = render.imageSizeY()
if (camera.getType()==0):
# perspective projection
# FOV calculation
# .
# /|
# / |v = 16
# /a |
#.---'
# u = lens
#
# => FOV = 2*a = 2*arctan(v/u)
#
# Blender's v is in direction of the larger image dimension.
# Ogre's FOV is definied in y direction. Therefore if
# SizeX*AspX > SizeY*AspY the corresponding v in y direction is
# v_y = v*(SizeY*AspY)/(SizeX*AspX).
fovY = 0.0
if (sizeX*aspX > sizeY*aspY):
fovY = 2*math.atan(sizeY*aspY*16.0/(camera.getLens()*sizeX*aspX))
else:
fovY = 2*math.atan(16.0/camera.getLens())
# fov in degree
fovY = fovY*180.0/math.pi
# write fov
fileObject.write("fov=\"%f\"" % fovY)
fileObject.write(" projectionType=\"perspective\">\n")
else:
# orthographic projection
# FOV calculation
#
# In Blender, the displayed area is scale wide in the larger image direction,
# where scale is a ortho camera attribute.
#
# Ogre calculates the with and height of the displayed area from the
# FOVy and the near clipping plane.
# .
# /|
# / |y
# /a |
#.---'
# n
# Here n = near clipping plane and a = FOVy/2.
#
# Hence y = scale/2 and FOVy = 2*atan(scale/(2*n)).
fovY = 0.0
if (sizeX*aspX > sizeY*aspY):
# tan(FOVx/2.0) = x/n = y*a/n,
# where a is the aspect ratio.
# It follows that s/(n*a) = y/n = tan(FOVy/2.0).
fovY = 2.0*math.atan(sizeY*aspY*camera.getScale()/(2.0*camera.getClipStart()*sizeX*aspX))
else:
fovY = 2.0*math.atan(camera.getScale()/(2.0*camera.getClipStart()))
# fov in degree
fovY = fovY*180.0/math.pi
# write fov
fileObject.write("fov=\"%f\"" % fovY)
fileObject.write(" projectionType=\"orthographic\">\n")
# normal (depricated)
# Blender's camera normal always points in -z direction locally.
#fileObject.write(self._indent(indent + 1) + \
# "<normal x=\"0.0\" y=\"0.0\" z=\"-1.0\"/>\n")
# default clipping
# TODO: Why does this scaling work?
scale = sceneExporter.getExportSettings().getScale()
fileObject.write(self._indent(indent + 1) + \
"<clipping nearPlaneDist=\"%f\" farPlaneDist=\"%f\"/>\n" % (camera.getClipStart()/scale, camera.getClipEnd()/scale))
# close camera
fileObject.write(self._indent(indent) + "</camera>\n")
return
class ObjectExporterFactory:
"""Creates ObjectExporter for different object types.
"""
def create(object, enabled):
"""Creates ObjecteExporter for the given Blender object.
@param object Blender object to export
@return ObjectExporter on success, <code>None</code> on failure.
"""
exporter = None
if (object.getType() == "Mesh"):
exporter = MeshExporter(object, enabled)
elif (object.getType() == "Lamp"):
exporter = LampExporter(object, enabled)
elif (object.getType() == "Camera"):
exporter = CameraExporter(object, enabled)
elif (object.getType() == "Empty"):
exporter = ObjectExporter(object, enabled)
elif (object.getType() == "Armature"):
exporter = None
return exporter
create = staticmethod(create)
class ObjectExporterTree(Model):
"""Creates tree of ObjectExporter for a Blender scene.
"""
ENABLEALL, ENABLENONE, ENABLESELECTION = range(3)
def __init__(self, scene, enable=ENABLESELECTION):
"""Constructor.
@param scene Blender.Scene.
@param enable Initial export status.
"""
Model.__init__(self)
self.rootExporterList = []
# create exporter tree
# key: object name, value: ObjectExporter
exporterDict = {}
# 1.) create ObjectExporters for all exportable scene objects
selectedList = []
if Blender.Object.GetSelected():
selectedList = [object.getName() for object in Blender.Object.GetSelected()]
for object in scene.objects:
enabled = 0
if (enable == ObjectExporterTree.ENABLESELECTION):
if object.getName() in selectedList:
enabled = 1
elif (enable == ObjectExporterTree.ENABLEALL):
enabled = 1
exporter = ObjectExporterFactory.create(object, enabled)
if exporter:
# register object
exporterDict[object.getName()] = exporter
# 2.) create tree structure
for exporter in exporterDict.values():
# search for an exportable parent
object = exporter.getBlenderObject().getParent()
searchCompleted = 0
while not searchCompleted:
# object a Blender.Object (possible parent) or none
if object:
parentName = object.getName()
if exporterDict.has_key(parentName):
# exportable parent found
exporterDict[parentName].addChild(exporter)
searchCompleted = 1
else:
# try next possible parent
object = object.getParent()
else:
# exporter object has no exportable parent
self.rootExporterList.append(exporter)
searchCompleted = 1
return
def export(self, sceneExporter, fileObject, indent=0, parentTransform=Blender.Mathutils.Matrix([1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1])):
for exporter in self.rootExporterList:
exporter.export(sceneExporter, fileObject, indent, parentTransform)
return
def enableAll(self):
for exporter in self:
exporter.setEnabled(1)
self._notify()
return
def enableNone(self):
for exporter in self:
exporter.setEnabled(0)
self._notify()
return
def invertEnabled(self):
for exporter in self:
exporter.setEnabled(1 - exporter.isEnabled())
self._notify()
return
def enableLayer(self, layer):
#TODO
self._notify()
return
def disableLayer(self, layer):
self._notify()
#TODO
return
def __iter__(self):
return ObjectExporterTree.ObjectExporterTreeIterator(self)
class ObjectExporterTreeIterator:
def __init__(self, objectExporterTree):
self.stack = objectExporterTree.rootExporterList[:]
return
def next(self):
exporter = None
if len(self.stack):
exporter = self.stack.pop()
self.stack.extend(exporter.getChildren())
else:
raise StopIteration
return exporter
class ObjectExporterTreeView(VerticalLayout, View):
def __init__(self, objectExporterTree):
# call super constructors
VerticalLayout.__init__(self)
View.__init__(self)
# reference to model
self.tree = objectExporterTree
# fully expanded list of all NodeViews alphabetically sorted on each level
self._createNodeList()
# create WidgetList
self.widgetList = WidgetList()
i = 0
for label in self.nodeList:
self.widgetList.addWidget(label, 'label'+str(i))
i +=1
self.addWidget(self.widgetList, 'widgetList')
# Selection Buttons: All, None, Invert
buttonsPanel = HorizontalRatioLayout()
buttonsPanel.addWidget(1.0/3, Button( \
ObjectExporterTreeView.SelectAllAction(self.tree), \
'All',[60,20],'Select all'),'all')
buttonsPanel.addWidget(1.0/3, Button( \
ObjectExporterTreeView.SelectNoneAction(self.tree), \
'None',[60,20],'Select none'),'none')
buttonsPanel.addWidget(1.0/3, Button( \
ObjectExporterTreeView.InvertSelectionAction(self.tree), \
'Invert',[60,20],'Invert selection'),'invert')
self.addWidget(buttonsPanel, 'buttonsPanel')
self.tree.addView(self)
return
def _createNodeList(self):
self.nodeList = []
rootDict = dict([(e.getBlenderObject().getName(), e) for e in self.tree.rootExporterList])
rootDictKeys = rootDict.keys()
rootDictKeys.sort()
rootDictKeys.reverse()
stack = []
for name in rootDictKeys:
stack.append((0, rootDict[name]))
# stack created
childrenDict = {}
while len(stack):
depth, exporter = stack.pop()
self.nodeList.append(ObjectExporterTreeView.NodeView(exporter, depth))
childrenList = exporter.getChildren()
if len(childrenList):
# insert children
childrenDict = dict([(e.getBlenderObject().getName(), e) for e in childrenList])
childrenDictKeys = childrenDict.keys()
childrenDictKeys.sort()
childrenDictKeys.reverse()
for name in childrenDictKeys:
stack.append((depth + 1, childrenDict[name]))
return
def update(self):
Blender.Draw.Redraw(1)
return
class NodeView(SelectableLabel, View):
"""Keeps track of collapse status of the node.
"""
def __init__(self, objectExporter, depth):
# call super constructors
View.__init__(self)
self.depth = depth
self.isCollapsed = 0
label = depth*" " + objectExporter.getBlenderObject().getName()
SelectableLabel.__init__(self,
ObjectExporterTreeView.NodeView.ExporterWrapper(objectExporter), label)
objectExporter.addView(self)
return
def collapse(self, state):
"""@param state 0 to collapse, 1 to expand
"""
self.isCollapsed = state
return
def isCollapsed(self):
"""@return <code>true</code> if collapsed, <code>false</code> if expanded.
"""
return self.isCollapsed
class ExporterWrapper(Selectable, View):
def __init__(self, objectExporter):
self.exporter = objectExporter
Selectable.__init__(self, self.exporter.isEnabled())
self.exporter.addView(self)
return
def select(self):
self.exporter.setEnabled(1)
self._notify()
return
def deselect(self):
self.exporter.setEnabled(0)
self._notify()
return
def isSelected(self):
return self.exporter.isEnabled()
def setSelected(self, selected):
self.exporter.setEnabled(selected)
self._notify()
return
def update(self):
# pass through
self._notify()
return
class SelectAllAction(Action):
def __init__(self, objectExporterTree):
self.tree = objectExporterTree
return
def execute(self):
self.tree.enableAll()
return
class SelectNoneAction(Action):
def __init__(self, objectExporterTree):
self.tree = objectExporterTree
return
def execute(self):
self.tree.enableNone()
return
class InvertSelectionAction(Action):
def __init__(self, objectExporterTree):
self.tree = objectExporterTree
return
def execute(self):
self.tree.invertEnabled()
return
class ProgressListener:
def __init__(self):
self.percent = 0.0
self.string = ''
self.viewList = []
return
def addView(self, view):
self.viewList.append(view)
return
def removeView(self, view):
if view in self.viewList:
self.viewList.remove(view)
return
def progress(self, percent, string):
self.percent = percent
self.string = string
# update views
self._notify()
return
# private
def _notify(self):
"""Notify views.
"""
for view in self.viewList:
view.update()
return
class ProgressListenerView(Widget):
def __init__(self, progressListener):
self.listener = progressListener
self.listener.addView(self)
return
def update(self):
Blender.Draw.Redraw(1)
return
class ProgressListenerProgressBar(ProgressBar, ProgressListenerView):
def __init__(self, progressListener):
ProgressListenerView.__init__(self, progressListener)
ProgressBar.__init__(self)
return
def update(self):
self.progress(self.listener.percent, self.listener.string)
ProgressListenerView.update(self)
return
class ProgressListenerDoneButton(Button, ProgressListenerView):
def __init__(self, progressListener, action, name, size, tooltip=None):
ProgressListenerView.__init__(self, progressListener)
Button(self, action, name, size, tooltip)
if (self.listener.percent >= 100):
self.done = 1
else:
self.done = 0
return
def update(self):
if (self.listener.percent >= 100):
self.done = 1
ProgressListenerView.update(self)
return
def draw(self, rect):
if self.done:
Button.draw(self, rect)
return
class SceneExporter:
"""Exports a scene to a dotScene XML file.
"""
def __init__(self, scene, settings, enable=ObjectExporterTree.ENABLESELECTION):
"""Constructor.
@param scene Blender.Scene.
@param settings ExportSettings.
@param enable Initial export status.
"""
self.scene = scene
self.settings = settings
self.tree = ObjectExporterTree(scene, enable)
return
def getExportSettings(self):
return self.settings
def export(self):
"""Export the scene to dotScene XML file.
"""
# open scene xml file
if (self.settings.fileName == ""):
fileName = self.scene.getName() + ".xml"
else:
fileName = self.settings.fileName
fileObject = open(os.path.join(self.settings.path, fileName), "w")
self._write(fileObject)
fileObject.close()
return
def addProgressListener(self, listener):
self.progressListenerList.append(listener)
return
def removeProgressListener(self, listener):
if listener in self.progressListenerList:
self.progressListenerList.remove(listener)
return
# private
def _progress(self, percent, string):
"""Report progress to the attached ProgressListeners.
"""
for listener in self.progressListenerList:
listener.progress(percent, string)
return
def _write(self, fileObject):
"""Write XML scene into the fileObject.
"""
# header
fileObject.write("<scene formatVersion=\"1.0.0\">\n")
# nodes
self._writeNodes(fileObject, 1)
# externals (material file)
self._writeExternals(fileObject, 1)
# environment
self._writeEnvironment(fileObject, 1)
# footer
fileObject.write("</scene>\n")
return
def _writeNodes(self, fileObject, indent=0):
fileObject.write(self._indent(indent) + "<nodes>\n")
# default: set matrix to 90 degree rotation around x-axis
# rotation order: x, y, z
# WARNING: Blender uses left multiplication! (vector * matrix)
scaleFactor = self.settings.scale.getValue()
scaleMatrix = Mathutils.Matrix(*[[scaleFactor, 0, 0],
[0, scaleFactor, 0 ],
[0, 0, scaleFactor]])
scaleMatrix.resize4x4()
rotationMatrix = Mathutils.Matrix(*[[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
if (not self.settings.fixUpAxis):
rotationMatrix = Mathutils.RotationMatrix(self.settings.rotX.getValue(), 4, 'x')
rotationMatrix *= Mathutils.RotationMatrix(self.settings.rotY.getValue(), 4, 'y')
rotationMatrix *= Mathutils.RotationMatrix(self.settings.rotZ.getValue(), 4, 'z')
self.tree.export(self, fileObject, indent+1, scaleMatrix*rotationMatrix)
fileObject.write(self._indent(indent) + "</nodes>\n")
return
def _writeExternals(self, fileObject, indent=0):
fileObject.write(self._indent(indent) + "<externals>\n")
fileObject.write(self._indent(indent + 1) + "<item type=\"material\">\n")
fileObject.write(self._indent(indent + 2) + "<file name=\"%s\"/>\n" % (self.scene.getName()+".material"))
fileObject.write(self._indent(indent + 1) + "</item>\n")
fileObject.write(self._indent(indent) + "</externals>\n")
return
def _writeEnvironment(self, fileObject, indent=0):
self.scene.makeCurrent()
world = Blender.World.GetCurrent()
if world:
fileObject.write(self._indent(indent) + "<environment>\n")
# can only get the active world of the current scene
if (world.mode & 1):
# Mist enabled
# Color = f*pixelColor + (1-f)*fogColor
#
# Blender's f factor:
# f = (1 - g((z - mistStart)/mistDepth))*(1-mistIntensity)
# where
# g(x)=x^2 for Qua,
# g(x)=x for Lin,
# g(x)=sqrt(x) for Sqr
# and z is the distance of the pixel to the camera.
#
# OpenGL's f factor:
# f = exp(-(density*z)) for GL_EXP,
# f = exp(-(density*z)^2) for GL_EXP2,
# f = (end - z)/(end - start) = (1 - (z - start)/(end - start)) for GL_LINEAR
#
# Assume depth and intensity is small and linear approximate
# all Blender mist types, i.e. ignore intensity and type.
mist = world.getMist()
fileObject.write(self._indent(indent + 1) + \
"<fog linearStart=\"%f\" linearEnd=\"%f\" mode=\"linear\">\n" \
% (mist[1], mist[1]+mist[2]))
fileObject.write(self._indent(indent + 2) + \
"<colourDiffuse r=\"%f\" g=\"%f\" b=\"%f\"/>\n" \
% tuple(world.getHor()))
fileObject.write(self._indent(indent + 1) + "</fog>\n")
# ambient color
fileObject.write(self._indent(indent + 1) + \
"<colourAmbient r=\"%f\" g=\"%f\" b=\"%f\"/>\n" \
% tuple(world.getAmb()))
# horizon color
fileObject.write(self._indent(indent + 1) + \
"<colourBackground r=\"%f\" g=\"%f\" b=\"%f\"/>\n" \
% tuple(world.getHor()))
fileObject.write(self._indent(indent) + "</environment>\n")
return
def _indent(self, indent):
return " "*indent
class SceneExporterView(VerticalLayout):
def __init__(self, sceneExporter):
# call super constructor
VerticalLayout.__init__(self)
# reference to model
self.sceneExporter = sceneExporter
self.addWidget(ObjectExporterTreeView(self.sceneExporter.tree), 'treeView')
self.addWidget(ExportSettingsView(self.sceneExporter.settings), 'settingsView')
return
########################################################################################
#TestCases
class TestWidget(Widget):
def __init__(self, color, preferredSize=[50, 50]):
self.color = color
self.preferredSize = preferredSize
return
def draw(self, rect):
Blender.BGL.glColor3f(*self.color)
Blender.BGL.glRectf(rect[0], rect[1], rect[2], rect[3])
return
def getMinimumSize(self):
return [50, 50]
def getPreferredSize(self):
return self.preferredSize
class ExportAction(Action):
def __init__(self, sceneExporter):
self.sceneExporter = sceneExporter
return
def execute(self):
tmp = Screen.current
ExportAction.WaitScreen().activate()
self.sceneExporter.export()
ExportAction.DoneScreen(ExportAction.DoneAction(tmp)).activate()
return
class WaitScreen(Screen):
def __init__(self):
Screen.__init__(self)
self.addWidget(Label("Exporting, please wait!"), 'label')
return
class DoneScreen(Screen):
def __init__(self, doneAction):
Screen.__init__(self)
vLayout = VerticalLayout()
vLayout.addWidget(Label("Scene Exported!"), 'label1')
vLayout.addWidget(Label(" "), 'label2')
vLayout.addWidget(Label("Note: Don't forget to export all mesh objects with the Blender OGRE Meshes Exporter."), 'label3')
vLayout.addWidget(Spacer([0,0], [Widget.INFINITY, Widget.INFINITY], [Widget.INFINITY, Widget.INFINITY]),'space')
hLayout = HorizontalLayout()
hLayout.addWidget(Button(doneAction, 'Ok', [100, 30]),'button')
vLayout.addWidget(hLayout,'buttonPanel')
self.addWidget(OgreFrame(vLayout, 'Scene Exporter'),'ogreFrame')
return
class DoneAction(Action):
def __init__(self, screen):
self.screen = screen
return
def execute(self):
self.screen.activate()
return
class DotSceneExporterApplication:
"""Controller for the application screen.
"""
def __init__(self):
self.screen = Screen()
self.exportSettings = ExportSettings()
self.sceneExporter = SceneExporter(Blender.Scene.GetCurrent(), self.exportSettings)
self.sceneExporterView = SceneExporterView(self.sceneExporter)
vLayout = VerticalLayout()
vLayout.addWidget(self.sceneExporterView, 'sceneExporterView')
buttonLayout = HorizontalLayout()
buttonLayout.addWidget(Button(ExportAction(self.sceneExporter), 'Export', [100, 30], 'Export scene'), 'exportButton')
buttonLayout.addWidget(Spacer([0, 0], [0, 0], [Widget.INFINITY, 0]), 'spacer')
buttonLayout.addWidget(QuitButton(DotSceneExporterApplication.QuitAction(self.exportSettings), 'Quit', [100, 30], 'Quit'), 'quitButton')
vLayout.addWidget(buttonLayout, 'buttonPanel')
self.screen.addWidget(OgreFrame(vLayout, 'Scene Exporter'),'ogreFrame')
return
def go(self):
"""Start the Application.
"""
self.screen.activate()
return
class QuitAction(Action):
def __init__(self, exportSettings):
self.settings = exportSettings
return
def execute(self):
self.settings.save()
Blender.Draw.Exit()
return
if (__name__ == "__main__"):
application = DotSceneExporterApplication()
application.go()
| Python |
'''
https://svn.blender.org/svnroot/bf-extensions/extern/py/scripts/addons/luxrender/addon_data.py
bl_addon_data = {
(2,5,4): {
(0,7,1): {
'api_compatibility': {
32591:{
(0,7,1): (1105,-1)
}
},
'binary_urls': {
'linux-32': ('http://www.luxrender.net/release/pylux/0.7.1/lin/32/pylux.so.gz',
'4e4fc041da4f90b7b5011fd944437f21'),
'linux-64': ('http://www.luxrender.net/release/pylux/0.7.1/lin/64/pylux.so.gz',
'0ec790ddbdcd295202c0b7b02b37c297'),
'windows-32': ('http://www.luxrender.net/release/pylux/0.7.1/win/32/pylux.pyd.gz',
'38a5621063e5d76fb1a8c8d17f42427e'),
'windows-64': ('http://www.luxrender.net/release/pylux/0.7.1/win/64/pylux.pyd.gz',
'95b352e384810a44fd38580d8ac81a57'),
'osx-intel-32': ('http://www.luxrender.net/release/pylux/0.7.1/mac/intel_32/pylux.so.gz',
'fd88b7ab4c1ea23f932f83ea56b00346'),
'osx-intel-64': ('http://www.luxrender.net/release/pylux/0.7.1/mac/intel_64/pylux.so.gz',
'51c57a3dee3a200ecf34ae98e9372c85'),
'osx-ppc': (),
}
}
}
}
'''
## bug fix dec15th, something wrong with rotation??? ##
##2.49 code reference: "<quaternion x=\"%.6f\" y=\"%.6f\" z=\"%.6f\" w=\"%.6f\"/>\n" % (rot.x, rot.z, -rot.y, rot.w))
def swap(vec):
if not OPTIONS['SWAP_AXIS']: return vec # swap axis should always be true, TODO remove option from UI
else:
if len(vec) == 3: return mathutils.Vector( [vec.x, vec.z, -vec.y] )
elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, vec.x, vec.z, -vec.y] )
else: raise AttributeError
#this is not correct???#elif len(vec) == 4: return mathutils.Quaternion( [ vec.w, vec.x, vec.z, -vec.y] )
#elif len(vec) == 4: # HELP MATTI
# return ( mathutils.Matrix().Rotation( math.radians(90.0), 3, 'X' ) * vec.to_matrix() ).to_quat()
###########################################################################
# Copyright (C) 2005 Michel Reimpell [ blender24 version ]
# Copyright (C) 2010 Brett Hartshorn [ blender25 version ]
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
VERSION = 'Ogre Exporter v26final'
__devnotes__ = '''
--final bug fix milestone--
Nov24:
. fixed triangles flipped wrong
. fixed .xml_mesh, .xml_skeleton (caused ogrecommandlinetools to fail)
Nov30:
. fixed multi-mats preview
. fixed material with use_nodes off but with dangling empty sub-materials
Dec1st:
. added bone class to wrap blenders bone types
Dec2nd:
. fixed bug in armature anim, rest pose xml is "rotation" while keyframe is "rotate"
Dec3rd:
. fixed bug, armature is hidden, can not get into edit_bones
. fixed bug in armature anim, wrong mult order of rotation pose
. fixed restore default INFO header
. fixed vertex colours
. fixed UV seams
Dec4th:
. fixed bone index out of order, and allows extra vertex groups
. started FAQ
. added dot-rex output
. fixed vertex normals edge-split mod bug, reported by Sanni
Dec5th:
. added object hierarchy (preserves parent/child relationships from blender)
Dec8th:
. generateTangents can not be default True because it requires texture coords
. supports more than 65,535 vertices per mesh
. fixed if no normals, then normals set to false (was crashing OgreCommandLineTools)
. added user data (custom properties) to .scene
<node>
<user_data name="mycustprop" type="float" value="1.0"/>
. updated the FAQ
. added MeshMagick merge ( but seems useless? )
. added blender mesh merge
Dec9th:
. fixing bugs in mesh merge
. added physics panel
. added panels for Sensor/Actuator hijacking, and xml output
Dec10th:
. added support for unpacking texture images
. fixed Ogre Logic in all tabs - now only in physics
. added support for classic materials with basic options and Panel
. fixed meshed with zero faces, or submaterials with no faces
Dec11th:
. changed tex-slot.offset to be offset and animation to custom prop
. added material panel
Dec14th:
. dropped to 6 decimal precision
. added support for vertex alpha by using second vertex-color-channel named "alpha"
. added extra tool bake-tex-2-vertex-colors
Dec16th:
. added collision LOD panel
. fixed inverse texture scaling (blender inverse of ogre).
. trying unflipped UV - reported by Reyn
Dec 17th:
. fixed inverse texture scaling (1.0/x) not (-1.0/x)
. added respect blender's slot.use (texture slot on/off)
'''
_faq_ = '''
Q: my model is over 10,000 faces and it seems to take forever to export it!!!
A: the current code uses an inefficient means for dealing with smooth normals,
you can make your export 100x faster by making dense models flat shaded.
(select all; then, View3D->Object Tools->Shading->Flat)
TIP:
Try making the model flat shaded and using a subsurf or multi-res modifer,
this will give you semi-smoothed normals without a speed hit.
Q: i have hundres of objects, is there a way i can merge them on export only?
A: yes, just add them to a group named starting with "merge"
Q: can i use subsurf or multi-res on a mesh with an armature?
A: yes.
Q: can i use subsurf or multi-res on a mesh with shape animation?
A: no.
Q: i don't see any objects when i export?
A: you must select the objects you wish to export.
Q: how can i change the name of my .material file, it is always named Scene.material?
A: rename your scene in blender. The .material script will follow the name of the scene.
Q: i don't see my animations when exported?
A: make sure you created an NLA strip on the armature, and if you keyed bones in pose mode then only those will be exported.
Q: do i need to bake my IK and other constraints into FK on my armature before export?
A: no.
Q: how do i export extra information to my game engine via OgreDotScene?
A: You can assign 'Custom Properties' to objects in blender, and these will be saved to the .scene file.
Q: i want to use a low-resolution mesh as a collision proxy for my high-resolution mesh, how?
A: make the lowres mesh the child of the hires mesh, and name the low res mesh starting with "collision"
Q: i do not want to use triangle mesh collision, can i use simple collision primitives?
A: yes, go to Properties->Physics->Ogre Physics. This gets save to the OgreDotScene file.
Q: what version of this script am i running?
A: %s
''' %VERSION
_doc_installing_ = '''
Installing:
Installing the Addon:
You can simply copy addon_ogreDotScene.py to your blender installation under blender/2.56/scripts/addons/
Or you can use blenders interface, under user-prefs, click addons, and click 'install-addon'
( its a good idea to delete the old version first )
Required:
1. blender2.56 (svn 33087+)
2. Install Ogre Command Line tools to the default path ( C:\\OgreCommandLineTools )
http://www.ogre3d.org/download/tools
(Linux users will need to use Wine)
Optional:
3. Install NVIDIA DDS Legacy Utilities ( install to default path )
http://developer.nvidia.com/object/dds_utilities_legacy.html
(Linux users will need to use Wine)
4. Install Image Magick
http://www.imagemagick.org
5. Copy folder 'myshaders' to C:\\myshaders
(Linux copy to your home folder)
6. Copy OgreMeshy to C:\\OgreMeshy
If your using 64bit Windows, you may need to download a 64bit OgreMeshy
(Linux copy to your home folder)
'''
## Nov23, tried PyOgre, it sucks - new plan: Tundra
## KeyError: 'the length of IDProperty names is limited to 31 characters' - chat with Jesterking request 64
## ICONS are in blender/editors/include/UI_icons.h
## TODO exploit pynodes, currently they are disabled pending python3 support: nodes/intern/SHD_dynamic.c
## TODO future idea: render procedural texture to images, more optimal to save settings and reimplment in Ogre, blender could also benifit from GLSL procedural shaders ##
## TODO request IDProperties support for material-nodes
## TODO check out https://github.com/realXtend/naali/blob/develop/bin/pymodules/webserver/webcontroller.py
## <antont> we looked at adding support for the b2rex xmlrpc methods there, to add b2rex support to tundra
## TODO are 1e-10 exponent numbers ok in the xml files?
## TODO count verts, and count collision verts
## TODO - image compression browser (previews total size)
## useful for online content - texture load is speed hit
bl_addon_info = {
"name": "OGRE Exporter (.scene, .mesh, .skeleton)",
"author": "HartsAntler",
"version": (0,2,6),
"blender": (2, 5, 6),
"location": "INFO Menu",
"description": "Export to Ogre xml and binary formats",
"warning": "",
#"wiki_url": "http://wiki.blender.org/index.php/Extensions:2.5/Py/"\
#"tracker_url": "https://projects.blender.org/tracker/index.php?"\
"category": "Import-Export"}
import os, sys
IMAGE_MAGICK = '/usr/bin/'
if sys.platform.startswith('win'): # win32 and win64
MYSHADERS = 'D:\\myshaders'
OGRETOOLS = 'D:\\Dev\\DualityDevEnv\\Ogre172\\bin\\Release'
NVIDIATOOLS = 'C:\\Program Files\\NVIDIA Corporation\\DDS Utilities'
for name in os.listdir( 'C:\\Program Files' ):
if name.startswith( 'ImageMagick' ):
IMAGE_MAGICK = os.path.join( 'C:\\Program Files', name )
break
del name
elif sys.platform.startswith('linux'): # bug fix reported by Borris
OGRETOOLS = '%s/.wine/drive_c/OgreCommandLineTools' %os.environ['HOME']
NVIDIATOOLS = '%s/.wine/drive_c/Program Files/NVIDIA Corporation/DDS Utilities' %os.environ['HOME']
if sys.platform.startswith('linux') or sys.platform == 'darwin':
MYSHADERS = '%s/myshaders' %os.environ['HOME']
# customize missing material - red flags for users so they can quickly see what they forgot to assign a material to.
# (do not crash if no material on object - thats annoying for the user)
MISSING_MATERIAL = '''
material _missing_material_
{
receive_shadows off
technique
{
pass
{
ambient 0.1 0.1 0.1 1.0
diffuse 0.8 0.0 0.0 1.0
specular 0.5 0.5 0.5 1.0 12.5
emissive 0.3 0.3 0.3 1.0
}
}
}
'''
######
# imports
######
import xml.dom.minidom as dom
import math, subprocess
try:
import bpy, mathutils
from bpy.props import *
except ImportError:
sys.exit("This script is an addon for blender, you must install it from blender.")
class ReportSingleton(object):
def __init__(self): self.reset()
def reset(self):
self.materials = []
self.meshes = []
self.lights = []
self.cameras = []
self.armatures = []
self.armature_animations = []
self.shape_animations = []
self.textures = []
self.vertices = 0
self.faces = 0
self.triangles = 0
self.warnings = []
self.errors = []
def report(self):
r = ['Exporter Results:']
ex = ['Extended Report:']
if self.errors:
r.append( ' ERRORS:' )
for a in self.errors: r.append( ' . %s' %a )
if not bpy.context.selected_objects:
self.warnings.append('YOU DID NOT SELECT ANYTHING TO EXPORT')
if self.warnings:
r.append( ' WARNINGS:' )
for a in self.warnings: r.append( ' . %s' %a )
r.append( ' Total Vertices: %s' %self.vertices )
r.append( ' Total Faces: %s' %self.faces )
r.append( ' Total Triangles: %s' %self.triangles )
## TODO report file sizes, meshes and textures
for tag in 'meshes lights cameras armatures armature_animations shape_animations materials textures'.split():
attr = getattr(self, tag)
name = tag.replace('_',' ').upper()
r.append( ' %s: %s' %(name, len(attr)) )
if attr:
ex.append( ' %s:' %name )
for a in attr: ex.append( ' . %s' %a )
txt = '\n'.join( r )
ex = '\n'.join( ex ) # console only - extended report
print('_'*80)
print(txt)
print(ex)
print('_'*80)
return txt
Report = ReportSingleton()
class MyShadersSingleton(object):
def get(self, name):
if name in self.vertex_progs_by_name: return self.vertex_progs_by_name[ name ]
elif name in self.fragment_progs_by_name: return self.fragment_progs_by_name[ name ]
def __init__(self):
self.path = MYSHADERS
self.files = []
self.vertex_progs = []
self.vertex_progs_by_name = {}
self.fragment_progs = []
self.fragment_progs_by_name = {}
if os.path.isdir( self.path ):
for name in os.listdir( self.path ):
if name.endswith('.program'):
url = os.path.join( self.path, name )
#self.parse(url)
try: self.parse( url )
except: print('WARNING: syntax error in .program!')
def parse(self, url ):
print('parsing .program', url )
data = open( url, 'rb' ).read().decode()
lines = data.splitlines()
lines.reverse()
while lines:
line = lines.pop().strip()
if line:
if line.startswith('vertex_program') or line.startswith('fragment_program'):
ptype, name, tech = line.split()
if tech == 'asm':
print('Warning: asm programs not supported')
else:
prog = Program(name, tech, url)
if ptype == 'vertex_program':
self.vertex_progs.append( prog ); prog.type = 'vertex'
self.vertex_progs_by_name[ prog.name ] = prog
else:
self.fragment_progs.append( prog ); prog.type = 'fragment'
self.fragment_progs_by_name[ prog.name ] = prog
while lines: # continue parsing
subA = lines.pop()
if subA.startswith('}'): break
else:
a = subA = subA.strip()
if a.startswith('//') and len(a) > 2: prog.comments.append( a[2:] )
elif subA.startswith('source'): prog.source = subA.split()[-1]
elif subA.startswith('entry_point'): prog.entry_point = subA.split()[-1]
elif subA.startswith('profiles'): prog.profiles = subA.split()[-1]
elif subA.startswith('compile_arguments'): prog.compile_args = ' '.join( subA.split()[-1].split('-D') )
elif subA.startswith('default_params'):
while lines:
b = lines.pop().strip()
if b.startswith('}'): break
else:
if b.startswith('param_named_auto'):
s = b.split('param_named_auto')[-1].strip()
prog.add_param( s, auto=True )
elif b.startswith('param_named'):
s = b.split('param_named')[-1].strip()
prog.add_param( s )
# end ugly-simple parser #
self.files.append( url )
print('----------------vertex programs----------------')
for p in self.vertex_progs: p.debug()
print('----------------fragment programs----------------')
for p in self.fragment_progs: p.debug()
class Program(object):
def debug( self ):
print('GPU Program')
print(' ', self.name)
print(' ', self.technique)
print(' ', self.file)
for p in self.params + self.params_auto: print(' ', p)
def __init__(self, name, tech, file):
if len(name) >= 31: #KeyError: 'the length of IDProperty names is limited to 31 characters'
if '/' in name: name = name.split('/')[-1]
if len(name) >= 31: name = name[ : 29 ] + '..'
self.name = name; self.technique = tech; self.file = file
self.source = self.entry_point = self.profiles = self.compile_args = self.type = None
self.params = []; self.params_auto = []
self.comments = []
def add_param( self, line, auto=False ):
name = line.split()[0]
value_code = line.split()[1]
p = {'name': name, 'value-code': value_code }
if auto: self.params_auto.append( p )
else: self.params.append( p )
if len( line.split() ) >= 3:
args = line.split( p['value-code'] )[-1]
p['args'] = args.strip()
def get_param( self, name ):
for p in self.params + self.params_auto:
if p['name'] == name: return p
class Ogre_User_Report(bpy.types.Menu):
bl_label = "Ogre Export Mini-Report | (see console for full report)"
def draw(self, context):
layout = self.layout
txt = Report.report()
for line in txt.splitlines():
layout.label(text=line)
############## mesh LOD physics #############
class Ogre_Physics_LOD(bpy.types.Panel):
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "data"
bl_label = "Ogre Collision"
@classmethod
def poll(cls, context):
if context.active_object: return True
else: return False
def draw(self, context):
layout = self.layout
ob = context.active_object
if ob.type != 'MESH': return
layout = self.layout
game = ob.game
box = layout.box()
if ob.name.startswith('collision'):
if ob.parent:
box.label(text='object is a collision proxy for: %s' %ob.parent.name)
else:
box.label(text='WARNING: collision proxy missing parent')
else:
colchild = None
for child in ob.children:
if child.name.startswith('collision'): colchild = child; break
row = box.row()
row.prop( game, 'use_ghost', text='Disable Collision' )
if game.use_ghost:
if ob.show_bounds: ob.show_bounds = False
if ob.show_wire: ob.show_wire = False
if colchild and not colchild.hide: colchild.hide = True
else:
row.prop(game, "use_collision_bounds", text="Use Collision Primitive")
row = box.row()
if game.use_collision_bounds:
if colchild and not colchild.hide: colchild.hide = True
row.prop(game, "collision_bounds_type", text="Primitive Type")
box.prop(game, "collision_margin", text="Collision Margin", slider=True)
btype = game.collision_bounds_type
if btype in 'BOX SPHERE CYLINDER CONE CAPSULE'.split():
if not ob.show_bounds: ob.show_bounds = True
if ob.draw_bounds_type != btype: ob.draw_bounds_type = btype
if ob.show_wire: ob.show_wire = False
elif btype == 'TRIANGLE_MESH':
if ob.show_bounds: ob.show_bounds = False
if not ob.show_wire: ob.show_wire = True
#ob.draw_bounds_type = 'POLYHEDRON' #whats this?
box.label(text='(directly using triangles of mesh as collision)')
else: game.collision_bounds_type = 'BOX'
else:
## without these if tests, object is always redrawn and slows down view
if ob.show_bounds: ob.show_bounds = False
if ob.show_wire: ob.show_wire = False
if not colchild:
box.operator("ogre.create_collision", text="create new collision mesh")
else:
if colchild.hide: colchild.hide = False
if not colchild.select:
colchild.hide_select = False
colchild.select = True
colchild.hide_select = True
row.label(text='collision proxy name: %s' %colchild.name)
if colchild.hide_select:
row.prop( colchild, 'hide_select', text='', icon='LOCKED' )
else:
row.prop( colchild, 'hide_select', text='', icon='UNLOCKED' )
decmod = None
for mod in colchild.modifiers:
if mod.type == 'DECIMATE': decmod = mod; break
if not decmod:
decmod = colchild.modifiers.new('LOD', type='DECIMATE')
decmod.ratio = 0.5
if decmod:
#print(dir(decmod))
#row = box.row()
box.prop( decmod, 'ratio', 'vertex reduction ratio' )
box.label(text='faces: %s' %decmod.face_count )
class Ogre_create_collision_op(bpy.types.Operator):
'''operator: creates new collision'''
bl_idname = "ogre.create_collision"
bl_label = "create collision mesh"
bl_options = {'REGISTER', 'UNDO'} # Options for this panel type
@classmethod
def poll(cls, context): return True
def invoke(self, context, event):
parent = context.active_object
child = parent.copy()
bpy.context.scene.objects.link( child )
child.name = 'collision'
child.matrix_local = mathutils.Matrix()
child.parent = parent
child.hide_select = True
child.draw_type = 'WIRE'
#child.select = False
child.lock_location = [True]*3
child.lock_rotation = [True]*3
child.lock_scale = [True]*3
return {'FINISHED'}
############### extra tools #############
'''
Getting a UV texture's pixel value per vertex, the stupid way.
(this should be rewritten as a C function exposed to Python)
This script does the following hack to get the pixel value:
1. copy the object
2. apply a displace modifier
3. for each RGB set the ImageTexture.<color>_factor to 1.0 and other to 0.0
4. for each RGB bake a mesh (apply the displace modifier)
5. for each RGB find the difference of vertex locations
6. apply the differences as vertex colors
'''
class Harts_Tools(bpy.types.Panel):
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "data"
bl_label = "Harts Extra Tools"
@classmethod
def poll(cls, context):
if context.active_object: return True
else: return False
def draw(self, context):
layout = self.layout
ob = context.active_object
if ob.type != 'MESH': return
layout = self.layout
slot = context.texture_slot
node = context.texture_node
space = context.space_data
tex = context.texture
#idblock = context_tex_datablock(context)
idblock = ob.active_material
tex_collection = space.pin_id is None and type(idblock) != bpy.types.Brush and not node
if not tex_collection: return
box = layout.box()
box.label(text='bake selected texture to vertex colors')
if not ob.data.vertex_colors.active:
box.label(text='please select a vertex color channel to bake to')
else:
row = box.row()
row.operator( "harts.bake_texture_to_vertexcolors", text='bake' )
row.template_list(idblock, "texture_slots", idblock, "active_texture_index", rows=2)
class Harts_bake_texture_vc_op(bpy.types.Operator):
'''operator: bakes texture to vertex colors'''
bl_idname = "harts.bake_texture_to_vertexcolors"
bl_label = "harts extra tools"
bl_options = {'REGISTER', 'UNDO'} # Options for this panel type
@classmethod
def poll(cls, context): return True
def invoke(self, context, event):
ob = context.active_object
#tex = context.texture
tex = ob.active_material.active_texture # slot
o2 = ob.copy()
#bpy.context.scene.objects.link( o2 )#; o2.select = True
while o2.modifiers: o2.modifiers.remove( o2.modifiers[0] )
mod = o2.modifiers.new('_hack_', type='DISPLACE')
mod.texture = tex
mod.texture_coords = 'UV'
mod.mid_level = 1.0
#print(dir(tex))
image = None
mult = 1.0
baked = []
if hasattr(tex, 'image'):
image = tex.image
ua = tex.use_alpha
tex.use_alpha = False
tex.factor_red = 1.0
tex.factor_green = .0
tex.factor_blue = .0
_data = o2.create_mesh(bpy.context.scene, True, "PREVIEW")
baked.append( [] )
for v1 in ob.data.vertices:
v2 = _data.vertices[ v1.index ]
baked[-1].append( (v1.co-v2.co).magnitude*mult )
print('red', baked[-1])
tex.factor_red = .0
tex.factor_green = 1.0
tex.factor_blue = .0
_data = o2.create_mesh(bpy.context.scene, True, "PREVIEW")
baked.append( [] )
for v1 in ob.data.vertices:
v2 = _data.vertices[ v1.index ]
baked[-1].append( (v1.co-v2.co).magnitude*mult )
print('green', baked[-1])
tex.factor_red = .0
tex.factor_green = .0
tex.factor_blue = 1.0
_data = o2.create_mesh(bpy.context.scene, True, "PREVIEW")
baked.append( [] )
for v1 in ob.data.vertices:
v2 = _data.vertices[ v1.index ]
baked[-1].append( (v1.co-v2.co).magnitude*mult )
print('blue', baked[-1])
tex.factor_red = 1.0
tex.factor_green = 1.0
tex.factor_blue = 1.0
tex.use_alpha = ua
#while o2.modifiers: o2.modifiers.remove( o2.modifiers[0] )
vchan = ob.data.vertex_colors.active
for f in ob.data.faces:
for i,vidx in enumerate(f.vertices):
r = baked[0][ vidx ]
g = baked[1][ vidx ]
b = baked[2][ vidx ]
#color = vchan.data[ f.index ].color1
color = getattr( vchan.data[ f.index ], 'color%s' %(i+1) )
color.r = 1.0-r
color.g = 1.0-g
color.b = 1.0-b
return {'FINISHED'}
##################################################################
_game_logic_intro_doc_ = '''
Hijacking the BGE
Blender contains a fully functional game engine (BGE) that is highly useful for learning the concepts of game programming by breaking it down into three simple parts: Sensor, Controller, and Actuator. An Ogre based game engine will likely have similar concepts in its internal API and game logic scripting. Without a custom interface to define game logic, very often game designers may have to resort to having programmers implement their ideas in purely handwritten script. This is prone to breakage because object names then end up being hard-coded. Not only does this lead to non-reusable code, its also a slow process. Why should we have to resort to this when Blender already contains a very rich interface for game logic? By hijacking a subset of the BGE interface we can make this workflow between game designer and game programmer much better.
The OgreDocScene format can easily be extened to include extra game logic data. While the BGE contains some features that can not be easily mapped to other game engines, there are many are highly useful generic features we can exploit, including many of the Sensors and Actuators. Blender uses the paradigm of: 1. Sensor -> 2. Controller -> 3. Actuator. In pseudo-code, this can be thought of as: 1. on-event -> 2. conditional logic -> 3. do-action. The designer is most often concerned with the on-events (the Sensors), and the do-actions (the Actuators); and the BGE interface provides a clear way for defining and editing those. Its a harder task to provide a good interface for the conditional logic (Controller), that is flexible enough to fit everyones different Ogre engine and requirements, so that is outside the scope of this exporter at this time. A programmer will still be required to fill the gap between Sensor and Actuator, but hopefully his work is greatly reduced and can write more generic/reuseable code.
The rules for which Sensors trigger which Actuators is left undefined, as explained above we are hijacking the BGE interface not trying to export and reimplement everything. BGE Controllers and all links are ignored by the exporter, so whats the best way to define Sensor/Actuator relationships? One convention that seems logical is to group Sensors and Actuators by name. More complex syntax could be used in Sensor/Actuators names, or they could be completely ignored and instead all the mapping is done by the game programmer using other rules. This issue is not easily solved so designers and the engine programmers will have to decide upon their own conventions, there is no one size fits all solution.
'''
_ogre_logic_types_doc_ = '''
Supported Sensors:
. Collision
. Near
. Radar
. Touching
. Raycast
. Message
Supported Actuators:
. Shape Action*
. Edit Object
. Camera
. Constraint
. Message
. Motion
. Sound
. Visibility
*note: Shape Action
The most common thing a designer will want to do is have an event trigger an animation. The BGE contains an Actuator called "Shape Action", with useful properties like: start/end frame, and blending. It also contains a property called "Action" but this is hidden because the exporter ignores action names and instead uses the names of NLA strips when exporting Ogre animation tracks. The current workaround is to hijack the "Frame Property" attribute and change its name to "animation". The designer can then simply type the name of the animation track (NLA strip). Any custom syntax could actually be implemented here for calling animations, its up to the engine programmer to define how this field will be used. For example: "*.explode" could be implemented to mean "on all objects" play the "explode" animation.
'''
class Ogre_Physics(bpy.types.Panel):
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "physics"
bl_label = "Ogre Physics"
@classmethod
def poll(cls, context):
if context.active_object: return True
else: return False
def draw(self, context):
layout = self.layout
ob = context.active_object
game = ob.game
#nothing useful here?#soft = ob.game.soft_body
#if game.physics_type: # in ('DYNAMIC', 'RIGID_BODY'):
split = layout.split()
col = split.column()
col.prop(game, "physics_type", text='Type')
col.prop(game, "use_actor")
col.prop(game, "use_ghost")
col = split.column()
col.prop(game, "use_collision_bounds", text="Use Primitive Collision")
col.prop(game, "collision_bounds_type", text="Primitive Type")
col.prop(game, "collision_margin", text="Collision Margin", slider=True)
#col.prop(game, "use_collision_compound", text="Compound") TODO
layout.separator()
split = layout.split()
col = split.column()
col.label(text="Attributes:")
col.prop(game, "mass")
col.prop(game, "radius")
col.prop(game, "form_factor")
col = split.column()
sub = col.column()
#sub.active = (game.physics_type == 'RIGID_BODY')
sub.prop(game, "use_anisotropic_friction")
subsub = sub.column()
subsub.active = game.use_anisotropic_friction
subsub.prop(game, "friction_coefficients", text="", slider=True)
split = layout.split()
col = split.column()
col.label(text="Velocity:")
sub = col.column(align=True)
sub.prop(game, "velocity_min", text="Minimum")
sub.prop(game, "velocity_max", text="Maximum")
col = split.column()
col.label(text="Damping:")
sub = col.column(align=True)
sub.prop(game, "damping", text="Translation", slider=True)
sub.prop(game, "rotation_damping", text="Rotation", slider=True)
layout.separator()
split = layout.split()
col = split.column()
col.prop(game, "lock_location_x", text="Lock Translation: X")
col.prop(game, "lock_location_y", text="Lock Translation: Y")
col.prop(game, "lock_location_z", text="Lock Translation: Z")
col = split.column()
col.prop(game, "lock_rotation_x", text="Lock Rotation: X")
col.prop(game, "lock_rotation_y", text="Lock Rotation: Y")
col.prop(game, "lock_rotation_z", text="Lock Rotation: Z")
#elif game.physics_type == 'STATIC':
#elif game.physics_type in ('SENSOR', 'INVISIBLE', 'NO_COLLISION', 'OCCLUDE'):
class Ogre_game_logic_op(bpy.types.Operator):
'''helper to hijack BGE logic'''
bl_idname = "ogre.gamelogic"
bl_label = "ogre game logic helper"
bl_options = {'REGISTER', 'UNDO'} # Options for this panel type
logictype = StringProperty(name="logic-type", description="...", maxlen=32, default="")
subtype = StringProperty(name="logic-subtype", description="...", maxlen=32, default="")
@classmethod
def poll(cls, context): return True
def invoke(self, context, event):
if self.logictype == 'sensor':
bpy.ops.logic.sensor_add( type=self.subtype )
elif self.logictype == 'actuator':
bpy.ops.logic.actuator_add( type=self.subtype )
return {'FINISHED'}
class _WrapLogic(object):
## custom name hacks ##
SwapName = {
'frame_property' : 'animation',
}
def __init__(self, node):
self.node = node
self.name = node.name
self.type = node.type
def widget(self, layout):
box = layout.box()
row = box.row()
row.label( text=self.type )
row.separator()
row.prop( self.node, 'name', text='' )
if self.type in self.TYPES:
for name in self.TYPES[ self.type ]:
if name in self.SwapName:
box.prop( self.node, name, text=self.SwapName[name] )
else:
box.prop( self.node, name )
def xml( self, doc ):
g = doc.createElement( self.LogicType )
g.setAttribute('name', self.name)
g.setAttribute('type', self.type)
for name in self.TYPES[ self.type ]:
attr = getattr( self.node, name )
if name in self.SwapName: name = self.SwapName[name]
a = doc.createElement( 'component' )
g.appendChild(a)
a.setAttribute('name', name)
if attr is None: a.setAttribute('type', 'POINTER' )
else: a.setAttribute('type', type(attr).__name__)
if type(attr) in (float, int, str, bool): a.setAttribute('value', str(attr))
elif not attr: a.setAttribute('value', '') # None case
elif hasattr(attr,'filepath'): a.setAttribute('value', attr.filepath)
elif hasattr(attr,'name'): a.setAttribute('value', attr.name)
elif hasattr(attr,'x') and hasattr(attr,'y') and hasattr(attr,'z'):
a.setAttribute('value', '%s %s %s' %(attr.x, attr.y, attr.z))
else:
print('ERROR: unknown type', attr)
return g
class WrapSensor( _WrapLogic ):
LogicType = 'sensor'
TYPES = {
'COLLISION': ['property'],
'MESSAGE' : ['subject'],
'NEAR' : ['property', 'distance', 'reset_distance'],
'RADAR' : ['property', 'axis', 'angle', 'distance' ],
'RAY' : ['ray_type', 'property', 'material', 'axis', 'range', 'use_x_ray'],
'TOUCH' : ['material'],
}
class Ogre_Logic_Sensors(bpy.types.Panel):
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "physics" # selects tab within the properties
bl_label = "Ogre Game Logic | Sensors"
@classmethod
def poll(cls, context):
if context.active_object: return True
else: return False
def draw(self, context):
layout = self.layout
ob = context.active_object
game = ob.game
split = layout.split()
col = split.column()
col.label( text='New Sensor:' )
row = col.row()
op = row.operator( 'ogre.gamelogic', text='Near' )
op.logictype = 'sensor'
op.subtype = 'NEAR'
op = row.operator( 'ogre.gamelogic', text='Collision' )
op.logictype = 'sensor'
op.subtype = 'COLLISION'
op = row.operator( 'ogre.gamelogic', text='Radar' )
op.logictype = 'sensor'
op.subtype = 'RADAR'
row = col.row()
op = row.operator( 'ogre.gamelogic', text='Touching' )
op.logictype = 'sensor'
op.subtype = 'TOUCH'
op = row.operator( 'ogre.gamelogic', text='Raycast' )
op.logictype = 'sensor'
op.subtype = 'RAY'
op = row.operator( 'ogre.gamelogic', text='Message' )
op.logictype = 'sensor'
op.subtype = 'MESSAGE'
layout.separator()
split = layout.split()
left = split.column()
right = split.column()
mid = len(game.sensors)/2
for i,sen in enumerate(game.sensors):
w = WrapSensor( sen )
if i < mid: w.widget( left )
else: w.widget( right )
class WrapActuator( _WrapLogic ):
LogicType = 'actuator'
TYPES = {
'CAMERA' : ['object', 'height', 'min', 'max', 'axis'],
'CONSTRAINT' : ['mode', 'limit', 'limit_min', 'limit_max', 'damping'],
'MESSAGE' : ['to_property', 'subject', 'body_message'], #skipping body_type
'OBJECT' : 'damping derivate_coefficient force force_max_x force_max_y force_max_z force_min_x force_min_y force_min_z integral_coefficient linear_velocity mode offset_location offset_rotation proportional_coefficient reference_object torque use_local_location use_local_rotation use_local_torque use_servo_limit_x use_servo_limit_y use_servo_limit_z'.split(),
'SOUND' : 'cone_inner_angle_3d cone_outer_angle_3d cone_outer_gain_3d distance_3d_max distance_3d_reference gain_3d_max gain_3d_min mode pitch rolloff_factor_3d sound use_sound_3d volume'.split(), # note .sound contains .filepath
'VISIBILITY' : 'apply_to_children use_occlusion use_visible'.split(),
'SHAPE_ACTION' : 'frame_blend_in frame_end frame_property frame_start mode property use_continue_last_frame'.split(),
'EDIT_OBJECT' : 'dynamic_operation linear_velocity mass mesh mode object time track_object use_3d_tracking use_local_angular_velocity use_local_linear_velocity use_replace_display_mesh use_replace_physics_mesh'.split(),
}
class Ogre_Logic_Actuators(bpy.types.Panel):
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "physics"
bl_label = "Ogre Game Logic | Actuators"
@classmethod
def poll(cls, context):
if context.active_object: return True
else: return False
def draw(self, context):
layout = self.layout
ob = context.active_object
game = ob.game
split = layout.split()
### actuators
col = split.column()
col.label( text='New Actuator:' )
row = col.row()
op = row.operator( 'ogre.gamelogic', text='Camera' )
op.logictype = 'actuator'
op.subtype = 'CAMERA'
op = row.operator( 'ogre.gamelogic', text='Constrain' )
op.logictype = 'actuator'
op.subtype = 'CONSTRAINT'
op = row.operator( 'ogre.gamelogic', text='Message' )
op.logictype = 'actuator'
op.subtype = 'MESSAGE'
op = row.operator( 'ogre.gamelogic', text='Animation' )
op.logictype = 'actuator'
op.subtype = 'SHAPE_ACTION'
row = col.row()
op = row.operator( 'ogre.gamelogic', text='Motion' )
op.logictype = 'actuator'
op.subtype = 'OBJECT' # blender bug? 'MOTION'
op = row.operator( 'ogre.gamelogic', text='Sound' )
op.logictype = 'actuator'
op.subtype = 'SOUND'
op = row.operator( 'ogre.gamelogic', text='Visibility' )
op.logictype = 'actuator'
op.subtype = 'VISIBILITY'
op = row.operator( 'ogre.gamelogic', text='Change' )
op.logictype = 'actuator'
op.subtype = 'EDIT_OBJECT'
layout.separator()
split = layout.split()
left = split.column()
right = split.column()
mid = len(game.actuators)/2
for i,act in enumerate(game.actuators):
w = WrapActuator( act )
if i < mid: w.widget( left )
else: w.widget( right )
##################################################################
_shader_intro_doc_ = '''
Custom Shader Support | Hijacking Blender's Shader Nodes
You can use custom attributes and a restricted subset of shader nodes to generate custom Ogre shaders that supports all the 'pass' and 'texture' options of the OgreDotMaterial format. This is presented to the user as a 'flat-wrapper' around the OgreDotMaterial format, so a good understanding of how shaders work is required - although once a shader is setup anyone could experiment changing its options.
'''
_shader_using_doc_ = '''
Hijacking The Shader Nodes Interface:
In an effort to streamline the artist workflow (and keep this code clean and bugfree) a different approach is taken to determine the rendering pass order and texturing pass order. Instead of using mixer nodes and their connections, rendering order is simply determined by height of a material or texture node relative to other nodes of the same type. The blending options for a rendering pass are stored as custom attributes at the material or texture level, not in mixer nodes. (Mixer nodes DO NOT map well to OgreDotMaterial blending options, so they are completely ignored)
This sort of hijacking leads to a shader that will not render in blender as it will in Ogre, as a workaround for this problem multiple rendering branches can be used within the same node tree. You may have multiple 'Output' nodes, blender will only use the first one, the Ogre exporter will look for a second 'Output' node and consider only nodes connect to it. This enables you to reuse the same texture nodes with the mapping options kept intact and connecting them to another branch of nodes that connect to the blender 'Output' node. Using this double-branching the artist can preview their work in the blender software renderer, although it may not appear excatly the same - at a minimum texture mapping and animations can be previsualized.
Example - Colored Ambient Setup:
1. check 'use_nodes' to initialize shader nodes for the given material
2. add an 'Extended Material'
(A). optionally add a 'RGB' input, and plug it into the material ambient input.
(B). optionally add a 'Geometry' input, select the first vertex color channel, and plug the vertex color output into the material ambient input.
'''
_shader_tips_doc_ = '''
Hijacked Shader Nodes Advantages:
1. Faster reordering of passes and texture blending order.
(by hijacking the height of a shader node to determine its rendering order)
2. Improved workflow between the 'Shader-Programmer' and blender artist. The experienced shader-programmer can setup node trees in blender with placeholder textures. Later the blender artist can use blender library linking to link the shader into their scene, and update the textures. The integrated OgreDotMaterial documentation can help the artist understand how they might modify the node tree.
3. Users can minimize the number of materials they must manage within blender because some shader options get 'moved-up' to the shader-node-level; and by exploting the nodes this way, we are ineffect instancing a base material and extending it with extra options like the ambient color. In the example above a single base material can be referened by two separate node-enabled-materials. The first node-enabled-material could use a RGB input shader node for the ambient color; while the second node-enabled-material could use a Geometry node (selecting the vertexcolor output).
[this will be improved in the future when blender supports custom properties on shader nodes]
'''
_shader_tex_doc_ = '''
Ogre Shader Doc - Textures
All 'Texture Unit' options of OgreDotMaterial are supported by 'Custom Properties' and the following material nodes:
Add>Input>Texture
. texture
Add>Input>Geometry
. vertex color [only the first layer is supported]
. uv layer
Add>Vector>Mapping
. x and y location
. x rotation
. x and y scaling
'''
_shader_linking_intro_doc_ = '''
Hijacked Shaders and Blender Library Linking:
Ogre offers some very advanced and complex ways to implement shaders. This must be carefully considered by an experienced programmer who is dealing with the high-level shading code. One particular issue is shadows and deforming mesh requires a shader that can easily be broken by an artist who changes the wrong options, or adds options that invalidate the shader. These issues can mostly be solved by using Blender's library linking, because linked data beomes read-only - it in effect provides a layer of control by the shader-programmer over the artist. Done in the right way, these restrictions will not hinder the artist either from experimenting and extending the shader's usefullness. In addition, library linking allows automatic-push of updates downstream to artists; so whenever the shader-programmer updates their shader code and updates his own master .blend with new shader options, the change is propagated to all .blends linking to it.
'''
_shader_linking_steps_doc_ = '''
Shader Linking Steps:
1. Communication: if the shader-programmer and artists do not stay in good communication, things are likely to break. To help make this task simpler. The shader-programmer can put comments in the .program file that will appear as 'notes' within the artists shader interface. Comments declared in the 'shader-program-body' are considered comments the artist will see. Comments in nested structures like 'default_params' are hidden from the artist.
2a. Material Library: the shader-programer first places their .program file in 'myshaders', then when enabling the addon in Blender any .program files found in myshaders will be parsed and each vertex/fragment shader is added to a menu within Blender's shader nodes interface. Next, from the shader nodes interface the vertex/fragment shaders can be assigned to 'Sub-Materials' they create and name accordingly, note that references to a given vertex/fragment program are stored as custom-attributes' on the material.
2b. A Sub-Material is one that does not contain any sub nodes ('use_nodes' is disabled), it however can be used as a sub-material within a shader node tree (to serve as examples and for testing), but its a good idea that these are named '_do_not_link_me_' so that artists do not get confused when linking which materials are 'node-tree-containers' and which are sub-materials that they should link to. Default textures can also be defined, the artist will have the option later to over-ride these in their scene. Finally the shader-programmer will save the file as their material library master .blend, and inform the artists it is ready to link in.
3. Linking: the artist can then link in Sub-Materials from the material library master .blend published by the shader-programmer. The nice thing with linked materials is that their settings and custom-attributes become read-only. The addon will detect when a material is linked, and this hides many options from the users view. The artist can then create their own shader tree and integrate the linked material as the first or any pass they choose. Another option is to link the entire 'node-tree-container' material, but then the artist can not alter the node tree, but still this is useful in some cases.
'''
OPTIONS = {
'FORCE_IMAGE_FORMAT' : None,
'TEXTURES_SUBDIR' : False,
'PATH' : '/tmp',
'TOUCH_TEXTURES' : False,
'SWAP_AXIS' : False,
'BLOCKING' : True,
}
_ogre_doc_classic_textures_ = '''
Ogre texture blending is far more limited than Blender's texture slots. While many of the blending options are the same or similar, only the blend mode "Mix" is allowed to have a variable setting. All other texture blend modes are either on or off, for example you can not use the "Add" blend mode and set the amount to anything other than fully on (1.0). The user also has to take into consideration the hardware multi-texturing limitations of their target platform - for example the GeForce3 can only do four texture blend operations in a single pass. Note that Ogre will fallback to multipass rendering when the hardware won't accelerate it.
==Supported Blending Modes:==
* Mix - blend_manual -
* Multiply - modulate -
* Screen - modulate_x2 -
* Lighten - modulate_x4 -
* Add - add -
* Subtract - subtract -
* Overlay - add_signed -
* Difference - dotproduct -
==Mapping Types:==
* UV
* Sphere environment mapping
* Flat environment mapping
==Animation:==
* scroll animation
* rotation animation
'''
TextureUnitAnimOps = {
'scroll_anim' : '_xspeed _yspeed'.split(),
'rotate_anim' : ['_revs_per_second'],
'wave_xform' : '_xform_type _wave_type _base _freq _phase _amp'.split(),
}
class Ogre_Material_Panel( bpy.types.Panel ):
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "material"
bl_label = "Ogre Material"
def draw(self, context):
if not hasattr(context, "material"): return
if not context.active_object: return
if not context.active_object.active_material: return
mat = context.material
ob = context.object
slot = context.material_slot
layout = self.layout
box = layout.box()
row = box.row()
row.prop(mat, "diffuse_color")
row.prop(mat, "diffuse_intensity")
row = box.row()
row.prop(mat, "specular_color")
row.prop(mat, "specular_intensity")
row = box.row()
row.prop(mat, "specular_hardness")
row = box.row()
row.prop(mat, "emit")
row.prop(mat, "ambient")
row = box.row()
row.prop(mat, "use_shadows")
row.prop(mat, "use_vertex_color_paint", text="Vertex Colors")
row.prop(mat, "use_transparency", text="Transparent")
if mat.use_transparency:
row = box.row()
row.prop(mat, "alpha")
def has_property( a, name ):
for prop in a.items():
n,val = prop
if n == name: return True
class Ogre_Advanced_Material_Panel( bpy.types.Panel ):
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "material"
bl_label = "Ogre Material - Advanced"
def draw(self, context):
if not hasattr(context, "material"): return
if not context.active_object: return
if not context.active_object.active_material: return
mat = context.material
ob = context.object
slot = context.material_slot
layout = self.layout
box = layout.box()
simplemodes = 'add modulate colour_blend alpha_blend'.split()
exmodes = 'one zero dest_colour src_colour one_minus_dest_colour dest_alpha src_alpha one_minus_dest_alpha one_minus_src_alpha'.split()
scene_blend = None
for prop in mat.items():
name,value = prop
if name == 'scene_blend':
scene_blend = value
break
if not scene_blend:
mat['scene_blend'] = scene_blend = 'one zero'
## make sure user set a correct string
invalid = False
test = scene_blend.strip()
if len(test.split()) == 1:
if test not in simplemodes: invalid = True
else:
for a in test.split():
if a and a not in exmodes: invalid = True
if invalid:
box.label(text='you set an invalid mode, resetting to default')
mat['scene_blend'] = scene_blend = 'one zero'
box.prop(mat, "['scene_blend']", text='scene blending')
box.label(text='Sets the kind of blending this pass has with the existing contents of the scene.')
box.label(text='Simple Modes:')
for mode in simplemodes: box.label(text=' %s' %mode)
box.label(text='Extended Format: complete control over the blending operation, by specifying the source and destination blending factors.')
box.label(text='(texture * sourceFactor) + (scene_pixel * destFactor)')
box.label(text='Extended Formats:')
for mode in exmodes: box.label(text=' %s' %mode)
class Ogre_Texture_Panel(bpy.types.Panel):
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "texture"
bl_label = "Ogre Texture"
@classmethod
def poll(cls, context):
if not hasattr(context, "texture_slot"):
return False
else: return True
def draw(self, context):
#if not hasattr(context, "texture_slot"):
# return False
layout = self.layout
#idblock = context_tex_datablock(context)
slot = context.texture_slot
if not slot or not slot.texture: return
box = layout.box()
row = box.row()
row.label(text="Mapping:")
row.prop(slot, "texture_coords", text="")
if slot.texture_coords == 'UV':
row.label(text="UV Layer:")
row.prop(slot, "uv_layer", text="")
else:
row.label(text="Projection:")
row.prop(slot, "mapping", text="")
if hasattr(slot.texture, 'image') and slot.texture.image:
row = box.row()
row.label(text="Repeat Mode:")
row.prop(slot.texture, "extension", text="")
if slot.texture.extension == 'CLIP':
row.label(text="Border Color:")
row.prop(slot, "color", text="")
box = layout.box()
row = box.row()
row.label(text="Blending:")
row.prop(slot, "blend_type", text="")
row.label(text="Alpha Stencil:")
row.prop(slot, "use_stencil", text="")
row = box.row()
if slot.blend_type == 'MIX':
row.label(text="Mixing:")
row.prop(slot, "diffuse_color_factor", text="")
#row.label(text="Enable:")
#row.prop(slot, "use_map_color_diffuse", text="")
row = box.row()
row.label(text="Enable Alpha:")
row.prop(slot, "use_map_alpha", text="")
if context.active_object and context.active_object.active_material:
row.label(text="Transparent:")
row.prop(context.active_object.active_material, "use_transparency", text="")
box = layout.box()
box.prop(slot, "offset", text="X,Y = offset. Z=rotation")
box = layout.box()
box.prop(slot, "scale", text="Scale in X,Y. (Z ignored)")
box = layout.box()
row = box.row()
row.label(text='scrolling animation')
#cant use if its enabled by defaultrow.prop(slot, "use_map_density", text="")
row.prop(slot, "use_map_scatter", text="")
row = box.row()
row.prop(slot, "density_factor", text="X")
row.prop(slot, "emission_factor", text="Y")
box = layout.box()
row = box.row()
row.label(text='rotation animation')
row.prop(slot, "emission_color_factor", text="")
row.prop(slot, "use_map_emission", text="")
#box = layout.box()
#for param in TextureUnitAnimOps[ 'scroll_anim' ]:
# box.prop( node.texture, '["%s"]' % param, text='' )
def guess_uv_layer( layer ):
## small issue: in blender layer is a string, multiple objects may have the same material assigned,
## but having different named UVTex slots, most often the user will never rename these so they get
## named UVTex.000 etc... assume this to always be true.
idx = 0
if '.' in layer:
a = layer.split('.')[-1]
if a.isdigit(): idx = int(a)+1
else: print('warning: it is not allowed to give custom names to UVTexture channels ->', layer)
return idx
class ShaderTree(object):
'''
Sometimes high resolution renderings may be required. The user has the option of using multiple Output nodes, blender will only consider the first one, the second if named starting with 'ogre' will be used by the exporter. This allows the user to have two branches in their node setup, one for blender software rendering, the other for Ogre output. Also useful for baking procedurals, which then can be used by the ogre branch.
'''
@staticmethod
def valid_node_material( mat ): # just incase the user enabled nodes but didn't do anything, then disabled nodes
if mat.node_tree and len(mat.node_tree.nodes):
for node in mat.node_tree.nodes:
if node.type == 'MATERIAL':
if node.material: return True
Materials = []
Output = None
@staticmethod
def parse( mat ): # only called for noded materials
print(' parsing node_tree')
ShaderTree.Materials = []
ShaderTree.Output = None
outputs = []
for link in mat.node_tree.links:
if link.to_node and link.to_node.type == 'OUTPUT': outputs.append( link )
root = None
for link in outputs:
if root is None or link.to_node.name.lower().startswith('ogre'): root = link
if root:
ShaderTree.Output = root.to_node
print('setting Output node', root.to_node)
#tree = ShaderTree( root.from_node, mat )
#tree.parents.append( root.to_node )
tree = ShaderTree( node=root.to_node, parent_material=mat )
return tree
else:
print('warning: no Output shader node found')
def __init__(self, node=None, material=None, parent_material=None ):
if node: print(' shader node ->', node)
if node and node.type.startswith('MATERIAL'):
ShaderTree.Materials.append( self )
self.material = node.material
elif material: # standard material
self.material = material
self.textures = []
self.node = node
if node:
self.type = node.type
self.name = node.name
self.children = []
self.parents = []
self.inputs = {} # socket name : child
self.outputs = {} # parent : socket name
if parent_material:
for link in parent_material.node_tree.links:
if link.to_node and link.to_node.name == self.name:
branch = ShaderTree(
node=link.from_node,
parent_material=parent_material
)
self.children.append( branch )
self.inputs[ link.to_socket.name ] = branch
branch.outputs[ self ] = link.from_socket.name
branch.parents.append( self )
def ancestors(self):
if not self.parents: return []
else: c = []; self._ancestors(c); return c
def _ancestors(self, c):
for p in self.parents: c.append( p ); p._ancestors( c )
def decendents(self):
if not self.children: return []
else: c = []; self._decendents(c); return c
def _decendents(self, c):
for p in self.children: c.append( p ); p._decendents( c )
def is_ogre_branch( self ):
ancestors = []
self._ancestors( ancestors )
for parent in ancestors:
if parent.node.name == ShaderTree.Output.name: return True
print('node not in ogre branch', self.node)
## returns height sorted materials, 'passes' in Ogre speak ##
# called after tree=ShaderTree.parse( nodedmat ); mats=tree.get_passes()
def get_passes( self ):
mats = []
for mat in ShaderTree.Materials:
print(' checking material ancestors:', mat)
# only consider materials that are connected to the ogre Output
#if self.Output in ancestors:
if mat.is_ogre_branch():
print(' material is in ogre branch->', mat)
mats.append( mat )
mats.sort( key=lambda x: x.node.location.y, reverse=True )
if not mats: print('WARNING: no materials connected to Output node')
## collect and sort textures of a material ##
for mat in mats:
mat.textures = []
d = mat.decendents()
for child in d:
if child.node.type == 'TEXTURE': mat.textures.append( child )
mat.textures.sort( key=lambda x: x.node.location.y, reverse=True )
return mats
def get_texture_attributes(self):
M = ''
ops = {}
for prop in self.node.texture.items():
name,value = prop
ops[name]=value
M += indent(4, '%s %s' %prop )
d = self.decendents()
for child in d:
if child.type == 'GEOMETRY' and child.node.uv_layer:
idx = guess_uv_layer( child.node.uv_layer )
M += indent(4, 'tex_coord_set %s' %idx)
elif child.type == 'MAPPING':
snode = child.node
x,y,z = snode.location # bpy bug, mapping node has two .location attrs
if x or y:
M += indent(4, 'scroll %s %s' %(x,y))
angle = math.degrees(snode.rotation.x)
if angle:
M += indent(4, 'rotate %s' %angle)
x,y,z = snode.scale
if x != 1.0 or y != 1.0:
M += indent(4, 'scale %s %s' %(1.0/x,1.0/y)) # reported by Sanni and Reyn
return M
def dotmat_texture(self, texture, texwrapper=None, slot=None):
if not hasattr(texture, 'image'):
print('WARNING: texture must be of type IMAGE->', texture)
return ''
if not texture.image:
print('WARNING: texture has no image assigned->', texture)
return ''
#if slot: print(dir(slot))
if slot and not slot.use: return ''
path = OPTIONS['PATH']
M = ''; _alphahack = None
M += indent(3, 'texture_unit', '{' )
iurl = bpy.path.abspath( texture.image.filepath )
postname = texname = os.path.split(iurl)[-1]
destpath = path
## packed images - dec10th 2010 ##
if texture.image.packed_file:
orig = texture.image.filepath
if sys.platform.startswith('linux'):
iurl = '/tmp/%s' %texname
else:
iurl = 'C:\\tmp\\%s' %texname
if not os.path.isdir( 'C:\\tmp' ):
print('creating tmp directory' )
os.makedirs( 'C:\\tmp' )
if not os.path.isfile( iurl ):
print('MESSAGE: unpacking image: ', iurl)
texture.image.filepath = iurl
texture.image.save()
texture.image.filepath = orig
else:
print('MESSAGE: packed image already in temp, not updating', iurl)
if OPTIONS['FORCE_IMAGE_FORMAT']: postname = self._reformat( texname ) #texname.split('.')[0]+'.dds'
if OPTIONS['TEXTURES_SUBDIR']:
destpath = os.path.join(path,'textures')
if not os.path.isdir( destpath ): os.mkdir( destpath )
M += indent(4, 'texture textures/%s' %postname )
else:
M += indent(4, 'texture %s' %postname )
exmode = texture.extension
if exmode == 'REPEAT':
M += indent(4, 'tex_address_mode wrap' )
elif exmode == 'EXTEND':
M += indent(4, 'tex_address_mode clamp' )
elif exmode == 'CLIP':
M += indent(4, 'tex_address_mode border' )
elif exmode == 'CHECKER':
M += indent(4, 'tex_address_mode mirror' )
if texwrapper: # shader node options
M += texwrapper.get_texture_attributes()
elif slot: # class blender material slot options
if exmode == 'CLIP': M += indent(4, 'tex_border_colour %s %s %s' %(slot.color.r, slot.color.g, slot.color.b) )
M += indent(4, 'scale %s %s' %(1.0/slot.scale.x, 1.0/slot.scale.y) ) # thanks Reyn
if slot.texture_coords != 'UV':
if slot.mapping == 'SPHERE':
M += indent(4, 'env_map spherical' )
elif slot.mapping == 'FLAT':
M += indent(4, 'env_map planar' )
else: print('WARNING: <%s> has a non-UV mapping type (%s) and not picked a proper projection type of: Sphere or Flat' %(texture.name, slot.mapping))
ox,oy,oz = slot.offset
if ox or oy:
M += indent(4, 'scroll %s %s' %(ox,oy) )
if oz:
M += indent(4, 'rotate %s' %oz )
if slot.use_map_emission: # hijacked from volume shaders
M += indent(4, 'rotate_anim %s' %slot.emission_color_factor )
if slot.use_map_scatter: # hijacked from volume shaders
M += indent(4, 'scroll_anim %s %s ' %(slot.density_factor, slot.emission_factor) )
## set uv layer
if slot.uv_layer:
idx = guess_uv_layer( slot.uv_layer )
M += indent(4, 'tex_coord_set %s' %idx)
rgba = False
if texture.image.depth == 32: rgba = True
btype = slot.blend_type
if rgba and slot.use_stencil:
texop = 'blend_current_alpha' # 'blend_texture_alpha' shadeless
elif btype == 'MIX':
texop = 'blend_manual'
elif btype == 'MULTIPLY':
texop = 'modulate'
elif btype == 'SCREEN':
texop = 'modulate_x2'
elif btype == 'LIGHTEN':
texop = 'modulate_x4'
elif btype == 'ADD':
texop = 'add'
elif btype == 'SUBTRACT':
texop = 'subtract'
elif btype == 'OVERLAY':
texop = 'add_signed' # add_smooth not very useful?
elif btype == 'DIFFERENCE':
texop = 'dotproduct' # nothing closely matches blender
else:
texop = 'blend_diffuse_colour'
#factor = .0
#if slot.use_map_color_diffuse:
factor = 1.0 - slot.diffuse_color_factor
if texop == 'blend_manual':
M += indent(4, 'colour_op_ex %s src_current src_texture %s' %(texop, factor) )
else:
M += indent(4, 'colour_op_ex %s src_current src_texture' %texop )
#M += indent(4, 'colour_op_ex %s src_manual src_diffuse %s' %(texop, 1.0-factor) )
#M += indent(4, 'alpha_op_ex blend_manual src_current src_current %s' %factor )
if slot.use_map_alpha:
#alphafactor = 1.0 - slot.alpha_factor
#M += indent(4, 'colour_op_ex blend_manual src_current src_texture %s' %factor )
M += indent(4, 'alpha_op_ex modulate src_current src_texture' )
#else: # fallback to default options
# M += indent(4, 'filtering trilinear' )
M += indent(3, '}' ) # end texture
if OPTIONS['TOUCH_TEXTURES']:
## copy texture only if newer ##
if not os.path.isfile( iurl ): Report.warnings.append( 'missing texture: %s' %iurl )
else:
desturl = os.path.join( destpath, texname )
if not os.path.isfile( desturl ) or os.stat( desturl ).st_mtime < os.stat( iurl ).st_mtime:
f = open( desturl, 'wb' )
f.write( open(iurl,'rb').read() )
f.close()
if OPTIONS['FORCE_IMAGE_FORMAT']:
if OPTIONS['FORCE_IMAGE_FORMAT'] == '.dds': self.DDS_converter( desturl )
else: self.image_magick( desturl )
return M
def dotmat_pass(self): # must be a material
if not self.material:
print('ERROR: material node with no submaterial block chosen')
return ''
mat = self.material
color = mat.diffuse_color
alpha = 1.0
if mat.use_transparency: alpha = mat.alpha
def _helper( child, opname, f ): # python note, define inline function shares variables - copies?
if child.type == 'RGB':
print('warning: RGB shader node bpy rna is incomplete, missing color attributes' )
return indent(3, '%s %s %s %s %s' %(opname, color.r*f, color.g*f, color.b*f, alpha) )
elif child.type == 'GEOMETRY':
if child.outputs[self] != 'Vertex Color': print('warning: you are supposed to connect the vertex color output of geometry')
return indent(3, '%s vertexcolour' %opname)
elif child.type == 'TEXTURE':
print( 'TODO: connecting a texture to this slot will be supported for program-shaders in the future' )
#return indent(3, '%s 1.0 0.0 0.0 1.0' %opname)
return indent(3, '%s %s %s %s %s' %(opname, color.r*f, color.g*f, color.b*f, alpha) )
M = ''
if self.node: # ogre combines passes with the same name, be careful!
passname = '%s__%s' %(self.node.name,mat.name)
passname = passname.replace(' ','_')
M += indent(2, 'pass %s' %passname, '{' ) # be careful with pass names
else:
M += indent(2, 'pass', '{' )
f = mat.ambient
if 'Ambient' in self.inputs:
child = self.inputs['Ambient']
M += _helper( child, 'ambient', f )
elif mat.use_vertex_color_paint:
M += indent(3, 'ambient vertexcolour' )
else: # fall back to basic material
M += indent(3, 'ambient %s %s %s %s' %(color.r*f, color.g*f, color.b*f, alpha) )
f = mat.diffuse_intensity
if 'Color' in self.inputs:
child = self.inputs['Color']
M += _helper( child, 'diffuse', f )
elif mat.use_vertex_color_paint:
M += indent(3, 'diffuse vertexcolour' )
else: # fall back to basic material
M += indent(3, 'diffuse %s %s %s %s' %(color.r*f, color.g*f, color.b*f, alpha) )
f = mat.specular_intensity
if 'Spec' in self.inputs:
child = self.inputs['Spec']
M += _helper( child, 'specular', f ) + ' %s'%(mat.specular_hardness/4.0)
else:
s = mat.specular_color
M += indent(3, 'specular %s %s %s %s %s' %(s.r*f, s.g*f, s.b*f, alpha, mat.specular_hardness/4.0) )
f = mat.emit # remains valid even if material_ex inputs a color node
if 'Emit' in self.inputs:
child = self.inputs['Emit']
M += _helper( child, 'emissive', f )
elif mat.use_vertex_color_light:
M += indent(3, 'emissive vertexcolour' )
else:
M += indent(3, 'emissive %s %s %s %s' %(color.r*f, color.g*f, color.b*f, alpha) )
## textures ##
if not self.textures: ## class style materials
slots = get_image_textures( mat ) # returns texture_slot object
usealpha = False
for slot in slots:
#if slot.use_map_alpha and slot.texture.use_alpha: usealpha = True; break
if slot.use_map_alpha: usealpha = True; break
if usealpha:
for prop in mat.items():
name,val = prop
if not name.startswith('_'): M += indent( 3, '%s %s' %prop )
## if there is alpha force alpha_blend if no blend_blend was given ##
if not has_property( mat, 'scene_blend' ):
M += indent(3, 'scene_blend alpha_blend' ) # defined only once per pass (global attributes)
if mat.use_transparency:
M += indent(3, 'depth_write off' ) # defined only once per pass (global attributes)
else:
for prop in mat.items():
if not prop[0].startswith('_'): M += indent( 3, '%s %s' %prop )
## write shader programs before textures
M += self._write_shader_programs( mat )
for slot in slots:
M += self.dotmat_texture( slot.texture, slot=slot )
elif self.node: # shader nodes
for prop in mat.items():
if not prop[0].startswith('_'): M += indent( 3, '%s %s' %prop )
M += self._write_shader_programs( mat )
for wrap in self.textures:
M += self.dotmat_texture( wrap.node.texture, texwrapper=wrap )
M += indent(2, '}' ) # end pass
return M
def _write_shader_programs( self, mat ):
M = ''
for prop in mat.items():
name,val = prop
if name in '_vprograms_ _fprograms_'.split():
for progname in val:
if name=='_vprograms_': # TODO over-ridden default params
M += indent( 3, 'vertex_program_ref %s' %progname, '{', '}' )
else:
M += indent( 3, 'fragment_program_ref %s' %progname, '{', '}' )
return M
############################################
def _reformat( self, image ): return image[ : image.rindex('.') ] + OPTIONS['FORCE_IMAGE_FORMAT']
def image_magick( self, infile ):
print('[Image Magick Wrapper]', infile )
if sys.platform.startswith('win'): exe = os.path.join(IMAGE_MAGICK,'convert.exe')
else: exe = os.path.join(IMAGE_MAGICK, 'convert')
if not os.path.isfile( exe ): print( 'ERROR: can not find Image Magick - convert', exe ); return
path,name = os.path.split( infile )
outfile = os.path.join( path, self._reformat( name ) )
opts = [ infile, outfile ]
subprocess.call( [exe]+opts )
print( 'image magick->', outfile )
def DDS_converter(self, infile ):
print('[NVIDIA DDS Wrapper]', infile )
exe = os.path.join(NVIDIATOOLS,'nvdxt.exe')
if not os.path.isfile( exe ): print( 'ERROR: can not find nvdxt.exe', exe ); return
opts = '-quality_production -nmips %s -rescale nearest' %self.EX_DDS_MIPS
path,name = os.path.split( infile )
outfile = os.path.join( path, self._reformat( name ) ) #name.split('.')[0]+'.dds' )
opts = opts.split() + ['-file', infile, '-output', '_tmp_.dds']
if sys.platform == 'linux2': subprocess.call( ['/usr/bin/wine', exe]+opts )
else: subprocess.call( [exe]+opts ) ## TODO support OSX
data = open( '_tmp_.dds', 'rb' ).read()
f = open( outfile, 'wb' )
f.write(data)
f.close()
## from scripts/ui/space_node.py
if False:
class NODE_HT_header(bpy.types.Header):
bl_space_type = 'NODE_EDITOR'
def draw(self, context):
layout = self.layout
snode = context.space_data
row = layout.row(align=True)
row.template_header()
if context.area.show_menus:
sub = row.row(align=True)
sub.menu("NODE_MT_view")
sub.menu("NODE_MT_select")
sub.menu("NODE_MT_add")
sub.menu("NODE_MT_node")
row = layout.row()
row.prop(snode, "tree_type", text="", expand=True)
if snode.tree_type == 'MATERIAL':
ob = snode.id_from
snode_id = snode.id
if ob:
layout.template_ID(ob, "active_material", new="material.new")
if snode_id:
layout.prop(snode_id, "use_nodes")
layout.menu( 'INFO_MT_ogre_shader_ref' )
#layout.menu( 'ogre_dot_mat_preview' )
elif snode.tree_type == 'TEXTURE':
row.prop(snode, "texture_type", text="", expand=True)
snode_id = snode.id
id_from = snode.id_from
if id_from:
if snode.texture_type == 'BRUSH':
layout.template_ID(id_from, "texture", new="texture.new")
else:
layout.template_ID(id_from, "active_texture", new="texture.new")
if snode_id:
layout.prop(snode_id, "use_nodes")
elif snode.tree_type == 'COMPOSITING':
scene = snode.id
layout.prop(scene, "use_nodes")
layout.prop(scene.render, "use_free_unused_nodes", text="Free Unused")
layout.prop(snode, "show_backdrop")
layout.separator()
layout.template_running_jobs()
SELECTED_MATERIAL_NODE = None
SELECTED_TEXTURE_NODE = None
## Custom Node Panel ##
class _node_panel_mixin_(object): # bug in bpy_rna.c line: 5005 (/* rare case. can happen when registering subclasses */)
bl_space_type = 'NODE_EDITOR'
bl_region_type = 'UI'
def draw(self, context):
global SELECTED_MATERIAL_NODE, SELECTED_TEXTURE_NODE
layout = self.layout
topmat = context.space_data.id # always returns the toplevel material that contains the node_tree
material = topmat.active_node_material # the currently selected sub-material
if not material: layout.label(text='please enable use_nodes'); return
for node in context.space_data.node_tree.nodes:
if node.type.startswith('MATERIAL') and node.material and node.material.name == material.name:
snode = node
break
else: snode = None
if self.mytype == 'shader':
box = layout.box()
if not material.library: # if linked, hide
row = box.row()
row.menu( 'ogre_dot_mat_preview', icon='TEXT' )
row = box.row()
row.menu('INFO_MT_ogre_shader_pass_attributes', icon='RENDERLAYERS')
row.menu('INFO_MT_ogre_shader_texture_attributes', icon='TEXTURE')
row = box.row()
if MyShaders.vertex_progs:
row.menu('OgreShader_vertexprogs', icon='MESH_CUBE')
if MyShaders.fragment_progs:
row.menu('OgreShader_fragmentprogs', icon='MATERIAL_DATA')
else:
row = box.row()
row.menu( 'ogre_dot_mat_preview', icon='TEXT' )
row.menu('INFO_MT_ogre_shader_texture_attributes', icon='TEXTURE')
box.label( text='linked->'+os.path.split(material.library.filepath)[-1] )
box = layout.box()
row = box.row()
row.prop( topmat, 'use_shadows' )
row.prop( topmat, 'use_transparency' )
box.operator("ogre.new_texture_block", text="new texture", icon='ZOOMIN')
elif self.mytype == 'notes':
if not material or not snode:
print('error: no active node material, enable "use_nodes" and assign a material to the material-node'); return
node = SELECTED_MATERIAL_NODE
if node:
for prop in node.items(): # items is hidden function, dir(com) will not list it! see rna_prop_ui.py
tag,progs = prop
if tag not in '_vprograms_ _fprograms_'.split(): continue
for name in progs: # expects dict/idproperty
if MyShaders.get( name ):
prog = MyShaders.get( name )
if prog.comments:
box = layout.box()
for com in prog.comments: box.label(text=com)
else:
nodes = []
if not material or not snode:
print('error: no active node material, enable "use_nodes" and assign a material to the material-node'); return
if self.mytype == 'material':
nodes.append( material )
SELECTED_MATERIAL_NODE = material
elif self.mytype == 'texture':
#node = material.active_texture # this is not material nodes (classic material texture slots)
#for socket in snode.inputs: #socket only contains: .default_value and .name (links are stores in node_tree.links)
for link in context.space_data.node_tree.links:
if link.from_node and link.to_node: # to_node can be none durring drag
if link.to_node.name == snode.name and link.from_node.type == 'TEXTURE':
if link.from_node.texture:
tex = link.from_node.texture
SELECTED_TEXTURE_NODE = tex # need bpy_rna way to get selected in node editor! TODO
nodes.append( tex )
else:
layout.label(text='<no texture block>'); return
for node in nodes:
layout.label(text=node.name)
for prop in node.items(): # items is hidden function, dir(com) will not list it! see rna_prop_ui.py
key,value = prop
if key.startswith('_'): continue
box = layout.box()
row = box.row()
row.label(text=key)
row.prop( node, '["%s"]' % key, text='' ) # so the dict exposes the props!
if not node.library:
op = row.operator("wm.properties_remove", text="", icon='ZOOMOUT')
#op.property = key
#op.data_path = 'texture' #'material'
#del ob['key'] # works!
if not nodes:
if self.mytype == 'texture':
layout.label(text='no texture nodes directly connected')
else:
layout.label(text='no material')
class _ogre_preview_ogremeshy_op(bpy.types.Operator):
'''helper to open ogremeshy'''
bl_idname = 'ogre.preview_ogremeshy'
bl_label = "opens ogremeshy in a subprocess"
bl_options = {'REGISTER'}
@classmethod
def poll(cls, context):
if context.active_object: return True
def execute(self, context):
if sys.platform == 'linux2':
path = '%s/.wine/drive_c/tmp' %os.environ['HOME']
else:
path = 'C:\\tmp'
mat = context.active_object.active_material
mgroup = MeshMagick.get_merge_group( context.active_object )
merged = None
if not mgroup:
group = get_merge_group( context.active_object )
if group:
print('--------------- has merge group ---------------' )
merged = merge_group( group )
else:
print('--------------- NO merge group ---------------' )
umaterials = []
if mgroup:
for ob in mgroup.objects:
nmats = dot_mesh( ob, path=path )
for m in nmats:
if m not in umaterials: umaterials.append( m )
MeshMagick.merge( mgroup, path=path, force_name='preview' )
elif merged:
umaterials = dot_mesh( merged, path=path, force_name='preview' )
else:
umaterials = dot_mesh( context.active_object, path=path, force_name='preview' )
if mat or umaterials:
OPTIONS['TOUCH_TEXTURES'] = True
OPTIONS['PATH'] = path
data = ''
for umat in umaterials:
data += INFO_OT_createOgreExport.gen_dot_material( umat, path=path )
f=open( os.path.join( path, 'preview.material' ), 'wb' )
f.write( bytes(data,'utf-8') ); f.close()
if merged: context.scene.objects.unlink( merged )
if sys.platform == 'linux2':
subprocess.call(
['/usr/bin/wine',
'%s/OgreMeshy/Ogre Meshy.exe' %os.environ['HOME'],
'C:\\tmp\\preview.mesh'])
else:
subprocess.call( [ 'C:\\OgreMeshy\\Ogre Meshy.exe', 'C:\\tmp\\preview.mesh' ] )
return {'FINISHED'}
class _ogre_new_tex_block(bpy.types.Operator):
'''helper to create new texture block'''
bl_idname = "ogre.new_texture_block"
bl_label = "helper creates a new texture block"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context): return True
def execute(self, context):
tex = bpy.data.textures.new('Tex', type='IMAGE')
if len(bpy.data.images): tex.image = bpy.data.images[0] # give a default
return {'FINISHED'}
class NODE_PT_shader_toplevel(bpy.types.Panel, _node_panel_mixin_):
bl_label = "Ogre Shader"
mytype = 'shader'
########## panels appear in order defined ? #############
class OgreShader_shaderprogs(bpy.types.Panel):
bl_label = "Ogre Shader: Programs"
bl_space_type = 'NODE_EDITOR'
bl_region_type = 'UI'
def draw(self, context):
layout = self.layout
node = SELECTED_MATERIAL_NODE
if node:
for prop in node.items(): # items is hidden function, dir(com) will not list it! see rna_prop_ui.py
tag,progs = prop
if tag not in '_vprograms_ _fprograms_'.split(): continue
box = layout.box()
for name in progs: # expects dict/idproperty
row = box.row()
#row.label(text=name)
#row.prop( node, '["%s"]["%s"]' % (key,sname), text=sname ) # so the dict exposes the props!
#op = row.operator("ogre.add_shader_program_param", text=name, icon='SETTINGS')
if MyShaders.get( name ):
_prog = MyShaders.get( name )
_name = '%s | %s' %(name, _prog.source)
if node.library:
row.label(text=_name)
elif _prog.type == 'vertex':
op = row.operator("ogre.add_shader_program_param", text=_name, icon='MESH_CUBE')
op.program_name = name
elif _prog.type == 'fragment':
op = row.operator("ogre.add_shader_program_param", text=_name, icon='MATERIAL_DATA')
op.program_name = name
#row.label(text=_prog.source)
else: # can't find the shader
op = row.operator("ogre.add_shader_program_param", text=name, icon='QUESTION')
op.program_name = name
if not node.library:
op = row.operator("wm.properties_remove", text="", icon='ZOOMOUT')
col = box.column()
for param_name in progs[name]:
param = progs[name][ param_name ]
txt = ' %s %s' %(param['name'], param['value-code'])
if 'args' in param: txt += ' ' + param['args']
row = col.row()
row.label(text=txt) # TODO support over-ride value-code and args
#row.prop( node, '["%s"]["%s"]["%s"]["value-code"]' %(tag,name,param_name) )
#op = row.operator("wm.properties_remove", text="", icon='ZOOMOUT')
###########################
class NODE_PT_material_props(bpy.types.Panel, _node_panel_mixin_):
bl_label = "Ogre Shader: Pass"; mytype = 'material'
class NODE_PT_texture_props(bpy.types.Panel, _node_panel_mixin_):
bl_label = "Ogre Shader: Textures"; mytype = 'texture'
class NODE_PT_texture_props(bpy.types.Panel, _node_panel_mixin_):
bl_label = "Ogre Shader: User Notes"; mytype = 'notes'
class _ogre_op_shader_program_param(bpy.types.Operator):
'''helper to create new texture block'''
bl_idname = "ogre.add_shader_program_param"
bl_label = "assign program shader to material"
bl_options = {'REGISTER', 'UNDO'}
program_name = StringProperty('prog-name')
@classmethod
def poll(cls, context): return True
def execute(self, context):
print( self.program_name )
MyShaders.Selected = self.program_name
bpy.ops.wm.call_menu( name='_ogre_shader_prog_param_menu_' )
return {'FINISHED'}
class _ogre_shader_prog_param_menu_(bpy.types.Menu):
bl_label = "Vertex Program Params"
def draw(self, context):
layout = self.layout
pname = MyShaders.Selected
prog = MyShaders.get( pname )
for a in 'name file source technique entry_point profiles'.split():
attr = getattr(prog, a)
if attr: layout.label(text='%s=%s' %(a,attr.strip()))
for p in prog.params_auto:
name = p['name']
vcode = p['value-code']
txt = name + '|' + vcode
if 'args' in p: txt += ' ' + p['args']
op = layout.operator("ogre.add_shader_program_subparam", text=txt, icon='ZOOMIN')
op.program_name = prog.name
op.param_name = name
class _ogre_op_shader_program_subparam(bpy.types.Operator):
'''helper to...'''
bl_idname = "ogre.add_shader_program_subparam"
bl_label = "assign program shader subparam to material"
bl_options = {'REGISTER', 'UNDO'}
program_name = StringProperty('prog-name')
param_name = StringProperty('param-name')
@classmethod
def poll(cls, context): return True
def execute(self, context):
print( self.program_name )
prog = MyShaders.get(self.program_name)
param = prog.get_param( self.param_name )
node = SELECTED_MATERIAL_NODE
if node:
if prog.type == 'vertex': P = node['_vprograms_']
else: P = node['_fprograms_']
P[ prog.name ][ self.param_name ] = param.copy()
context.area.tag_redraw()
return {'FINISHED'}
#############################
class _ogre_shader_progs_mixin_(object): # TODO chat with jesterking, layout.menu should return menu
def draw(self, context):
layout = self.layout
if self.mytype == 'vertex':
for prog in MyShaders.vertex_progs:
op = layout.operator("ogre.add_shader_program", text=prog.name, icon='ZOOMIN')
op.program_name = prog.name
else:
for prog in MyShaders.fragment_progs:
op = layout.operator("ogre.add_shader_program", text=prog.name, icon='ZOOMIN')
op.program_name = prog.name
class OgreShader_vertexprogs(bpy.types.Menu, _ogre_shader_progs_mixin_):
bl_label = "Vertex Programs"
mytype = 'vertex'
class OgreShader_fragmentprogs(bpy.types.Menu, _ogre_shader_progs_mixin_):
bl_label = "Fragment Programs"
mytype = 'fragment'
class _ogre_op_shader_programs(bpy.types.Operator):
'''helper to create new texture block'''
bl_idname = "ogre.add_shader_program"
bl_label = "assign program shader to material"
bl_options = {'REGISTER', 'UNDO'}
program_name = StringProperty('prog-name')
@classmethod
def poll(cls, context): return True
def execute(self, context):
print( self.program_name )
prog = MyShaders.get( self.program_name )
mat = SELECTED_MATERIAL_NODE
if prog.type == 'vertex':
if '_vprograms_' not in mat: mat['_vprograms_'] = {}
d = mat['_vprograms_']
else:
if '_fprograms_' not in mat: mat['_fprograms_'] = {}
d = mat['_fprograms_']
d[ prog.name ] = {}
return {'FINISHED'}
#############################
def wordwrap( txt ):
r = ['']
for word in txt.split(' '): # do not split on tabs
word = word.replace('\t', ' '*3)
r[-1] += word + ' '
if len(r[-1]) > 90: r.append( '' )
return r
_OGRE_DOCS_ = []
_OGRE_SHADER_REF_ = []
_OGRE_SHADER_REF_TEX_ = []
def ogredoc( cls ):
tag = cls.__name__.split('_ogredoc_')[-1]
if tag.startswith('Shader_Nodes_'):
cls.bl_label = cls.ogre_shader_op = tag.split('Shader_Nodes_')[-1]
cls.ogre_shader_params = []
if cls.ogre_shader_op not in 'ambient diffuse specular emissive'.split():
for line in cls.mydoc.splitlines():
if line.strip().startswith('@'): # custom markup
cls.ogre_shader_params.append( line.strip()[1:] )
_OGRE_SHADER_REF_.append( cls )
elif tag.startswith('TEX_'):
cls.bl_label = cls.ogre_shader_tex_op = tag.split('TEX_')[-1]
cls.ogre_shader_params = []
if cls.ogre_shader_tex_op not in 'texture tex_coord_set'.split():
for line in cls.mydoc.splitlines():
if line.strip().startswith('@'): # custom markup
cls.ogre_shader_params.append( line.strip()[1:] )
_OGRE_SHADER_REF_TEX_.append( cls )
else:
cls.bl_label = tag.replace('_', ' ')
_OGRE_DOCS_.append( cls )
return cls
class ogre_dot_mat_preview(bpy.types.Menu):
bl_label = 'preview'
def draw(self, context):
layout = self.layout
mat = context.active_object.active_material
if mat:
OPTIONS['TOUCH_TEXTURES'] = False
preview = INFO_OT_createOgreExport.gen_dot_material( mat )
for line in preview.splitlines():
if line.strip():
for ww in wordwrap( line ): layout.label(text=ww)
class INFO_MT_ogre_helper(bpy.types.Menu):
bl_label = '_overloaded_'
def draw(self, context):
layout = self.layout
#row = self.layout.box().split(percentage=0.05)
#col = row.column(align=False)
#print(dir(col))
#row.scale_x = 0.1
#row.alignment = 'RIGHT'
for line in self.mydoc.splitlines():
if line.strip():
for ww in wordwrap( line ): layout.label(text=ww)
layout.separator()
if hasattr(self, 'ogre_shader_params') and self.ogre_shader_params:
for param in self.ogre_shader_params:
if hasattr(self, 'ogre_shader_tex_op'):
txt = '%s %s' %(self.ogre_shader_tex_op, param)
op = layout.operator("ogre.set_shader_tex_param", text=txt, icon='ZOOMIN')
op.shader_tex = self.ogre_shader_tex_op # bpy op API note: uses slots to prevent an op from having dynamic attributes
op.shader_tex_param = param
else:
txt = '%s %s' %(self.ogre_shader_op, param)
op = layout.operator("ogre.set_shader_param", text=txt, icon='ZOOMIN')
op.shader_pass = self.ogre_shader_op # bpy op API note: uses slots to prevent an op from having dynamic attributes
op.shader_pass_param = param
class INFO_OT_ogre_set_shader_param(bpy.types.Operator):
'''assign ogre shader param'''
bl_idname = "ogre.set_shader_param"
bl_label = "Ogre Shader Param"
bl_options = {'REGISTER', 'UNDO'}
shader_pass = StringProperty(name="shader operation", description="", maxlen=64, default="")
shader_pass_param = StringProperty(name="shader param", description="", maxlen=64, default="")
@classmethod
def poll(cls, context): return True
def execute(self, context):
SELECTED_MATERIAL_NODE[ self.shader_pass ] = self.shader_pass_param
context.area.tag_redraw()
return {'FINISHED'}
class INFO_OT_ogre_set_shader_tex_param(bpy.types.Operator):
'''assign ogre shader texture param'''
bl_idname = "ogre.set_shader_tex_param"
bl_label = "Ogre Shader Texture Param"
bl_options = {'REGISTER', 'UNDO'}
shader_tex = StringProperty(name="shader operation", description="", maxlen=64, default="")
shader_tex_param = StringProperty(name="shader param", description="", maxlen=64, default="")
@classmethod
def poll(cls, context): return True
def execute(self, context):
SELECTED_TEXTURE_NODE[ self.shader_tex ] = self.shader_tex_param
context.area.tag_redraw()
return {'FINISHED'}
class INFO_MT_ogre_docs(bpy.types.Menu):
bl_label = "Ogre Help"
def draw(self, context):
layout = self.layout
for cls in _OGRE_DOCS_:
layout.menu( cls.__name__ )
layout.separator()
layout.separator()
layout.label(text='bug reports to: bhartsho@yahoo.com')
class INFO_MT_ogre_shader_pass_attributes(bpy.types.Menu):
bl_label = "Shader-Pass"
def draw(self, context):
layout = self.layout
for cls in _OGRE_SHADER_REF_:
layout.menu( cls.__name__ )
class INFO_MT_ogre_shader_texture_attributes(bpy.types.Menu):
bl_label = "Shader-Texture"
def draw(self, context):
layout = self.layout
for cls in _OGRE_SHADER_REF_TEX_:
layout.menu( cls.__name__ )
@ogredoc
class _ogredoc_Installing( INFO_MT_ogre_helper ):
mydoc = _doc_installing_
@ogredoc
class _ogredoc_FAQ( INFO_MT_ogre_helper ):
mydoc = _faq_
@ogredoc
class _ogredoc_Exporter_Features( INFO_MT_ogre_helper ):
mydoc = '''
Ogre Exporter Features:
Export .scene:
pos, rot, scl
environment colors
fog settings
lights, colors
array modifier (constant offset only)
optimize instances
selected only
force cameras
force lamps
BGE physics
collisions prims and external meshes
Export .mesh
verts, normals, uv
LOD (Ogre Command Line Tools)
export `meshes` subdirectory
bone weights
shape animation (using NLA-hijacking)
Export .material
diffuse color
ambient intensity
emission
specular
receive shadows on/off
multiple materials per mesh
exports `textures` subdirectory
Export .skeleton
bones
animation
multi-tracks using NLA-hijacking
'''
@ogredoc
class _ogredoc_Texture_Options( INFO_MT_ogre_helper ):
mydoc = _ogre_doc_classic_textures_
@ogredoc
class _ogredoc_Game_Logic_Intro( INFO_MT_ogre_helper ):
mydoc = _game_logic_intro_doc_
@ogredoc
class _ogredoc_Game_Logic_Types( INFO_MT_ogre_helper ):
mydoc = _ogre_logic_types_doc_
@ogredoc
class _ogredoc_Animation_System( INFO_MT_ogre_helper ):
mydoc = '''
Armature Animation System | OgreDotSkeleton
Quick Start:
1. select your armature and set a single keyframe on the object (loc,rot, or scl)
. note, this step is just a hack for creating an action so you can then create an NLA track.
. do not key in pose mode, unless you want to only export animation on the keyed bones.
2. open the NLA, and convert the action into an NLA strip
3. name the NLA strip
4. set the in and out frames for the strip
** note that you DO NOT need to bake your constaint animation, you can keep the constaints, simply export!
The OgreDotSkeleton (.skeleton) format supports multiple named tracks that can contain some or all of the bones of an armature. This feature can be exploited by a game engine for segmenting and animation blending. For example: lets say we want to animate the upper torso independently of the lower body while still using a single armature. This can be done by hijacking the NLA of the armature.
NLA Hijacking:
. define an action and keyframe the bones you want to 'group', ie. key all the upper torso bones
. import the action into the NLA
. name the NLA track (this becomes the track name in Ogre)
. adjust the start and end frames of the strip (only the first strip is considered)
Benefits:
. cleaner and lighter source code
. blender user can stay within blender's interface, that they are already familiar with
. frame ranges and groupings are saved in the blend file and easy to adjust
Cons:
. the user has to remember which bones were keyed per action grouping
...if the user names their actions clearly, then its not an issue
. what if the user wants to mix constraints and forward kinematics driven by the NLA?
...can work if the track is not muted...
...do constraints override the NLA?
'''
@ogredoc
class _ogredoc_Unresolved_Development_Issues( INFO_MT_ogre_helper ):
mydoc = '''
Unresolved Development Issues:
1. Texture Face (texface) - NOT SUPPORTED
from object-data tab, when in game-mode, meshes with a UV texture are allowed to have per-face options that affect BGE, the old exporter had limited support for these per-face options.
pros:
. per face control of double sided
. per face control over transparency blending (but with limited options: opaque, add, alpha, clip alpha)
. per face visible
. per face object color (very old option, why would any one want object color when vertex colors can be used?)
cons:
. generates a new material shader for each combination of options (slower rendering, could end up with many submeshes)
. limited blender viewport visual feedback, the artist can easily lose track of which faces have which settings. Blender has no select-all by texface option, and only double-sided and visible are shown in the viewport.
. many of the options make sense only for the BGE
user workarounds:
. per face control of double sided: user breaks into muliple objects when he needs control over single/double sided and uses object level double sided option (under Object tab -> Normals panel)
. per face transparency blending options: user creates mutiple shaders, this should help the user stay more organized, and help the user keep track of performance bottlenecks
. per face visible: user creates mutiple objects, and sets visiblity per object.
programmed workarounds (pending):
. per face collision is cool, and does not require generating multiple shaders per mesh. Not that hard to script: delete those faces and auto-assign a collision mesh. Although there is already support for user defined collision meshes, and they should be used most of the time because its optimal, so the user can delete those faces while making the collision mesh.
'''
@ogredoc
class _ogredoc_Physics( INFO_MT_ogre_helper ):
mydoc = '''
Ogre Dot Scene + BGE Physics
extended format including external collision mesh, and BGE physics settings
<node name="...">
<entity name="..." meshFile="..." collisionFile="..." collisionPrim="..." [and all BGE physics attributes] />
</node>
collisionFile : sets path to .mesh that is used for collision (ignored if collisionPrim is set)
collisionPrim : sets optimal collision type [ cube, sphere, capsule, cylinder ]
*these collisions are static meshes, animated deforming meshes should give the user a warning that they have chosen a static mesh collision type with an object that has an armature
Blender Collision Setup:
1. If a mesh object has a child mesh with a name starting with 'collision', then the child becomes the collision mesh for the parent mesh.
2. If 'Collision Bounds' game option is checked, the bounds type [box, sphere, etc] is used. This will override above rule.
3. Instances (and instances generated by optimal array modifier) will share the same collision type of the first instance, you DO NOT need to set the collision type for each instance.
Tips and Tricks:
. instance your mesh, parent it under the source, add a Decimate modifier, set the draw type to wire. boom! easy optimized collision mesh
. sphere collision type is the fastest
TODO support composite collision objects?
'''
@ogredoc
class _ogredoc_Warnings( INFO_MT_ogre_helper ):
mydoc = '''
General Warnings:
. extra vertex groups, can mess up an armature weights (new vgroups must come after armature assignment, not before)
. no sharp vertex color edges (face level vertex colors)
. quadratic lights falloff not supported (needs pre calc)
. do not enable subsurf modifier on meshes that have shape or armature animation.
(Any modifier that changes the vertex count is bad with shape anim or armature anim)
Current Shader Issues:
1. You can not create a shader that ends up being more than 16 passes (Ogre limitation)
2. Shader nodes do not support custom attributes, this limits material attribute overloading.
3. At this time GLSL in Blender can not compile complex node trees, this will prevent
you from seeing the output of the shader in the viewport, not seeing your textures in
the viewport is a serious problem. There are two workarounds:
(a) disable 'use_nodes' and assign textures to the material in the normal manner.
[ the shader nodes are still exported to Ogre ]
(b) use a second branch connected to the first 'Output' and preview with software renderer.
'''
@ogredoc
class _ogredoc_Bugs( INFO_MT_ogre_helper ):
mydoc = '''
Possible Bugs:
. bone animation has wrong offset
. fix is calc armature space or some other space
. Ogre does not support quads
. fix is triangulate
. Something is flipped wrong
. fix check all self.swap (fixUpAxis)
. vertex colors are not correct
. figure out how to access color1,2,3,4 properly
Final TODO - Nov15th 2010:
. vertex-colors
. dds to format xxx
. normal maps and complex shaders
'''
@ogredoc
class _ogredoc_Node_Shaders_Introduction( INFO_MT_ogre_helper ):
mydoc = _shader_intro_doc_
@ogredoc
class _ogredoc_Node_Shaders_Doc( INFO_MT_ogre_helper ):
mydoc = _shader_using_doc_
@ogredoc
class _ogredoc_Node_Shaders_Tips_and_Tricks( INFO_MT_ogre_helper ):
mydoc = _shader_tips_doc_
@ogredoc
class _ogredoc_Node_Shaders_Textures( INFO_MT_ogre_helper ):
mydoc = _shader_tex_doc_
@ogredoc
class _ogredoc_Node_Shaders_Linking_Intro( INFO_MT_ogre_helper ):
mydoc = _shader_linking_intro_doc_
@ogredoc
class _ogredoc_Node_Shaders_Linking_Steps( INFO_MT_ogre_helper ):
mydoc = _shader_linking_steps_doc_
############ Ogre v.17 Doc ######
@ogredoc
class _ogredoc_Shader_Nodes_ambient( INFO_MT_ogre_helper ):
mydoc = '''
Sets the ambient colour reflectance properties of this pass. This attribute has no effect if a asm, CG, or HLSL shader program is used. With GLSL, the shader can read the OpenGL material state.
Format: ambient (<red> <green> <blue> [<alpha>]| vertexcolour)
NB valid colour values are between 0.0 and 1.0.
Example: ambient 0.0 0.8 0.0
The base colour of a pass is determined by how much red, green and blue light is reflects at each vertex. This property determines how much ambient light (directionless global light) is reflected. It is also possible to make the ambient reflectance track the vertex colour as defined in the mesh by using the keyword vertexcolour instead of the colour values. The default is full white, meaning objects are completely globally illuminated. Reduce this if you want to see diffuse or specular light effects, or change the blend of colours to make the object have a base colour other than white. This setting has no effect if dynamic lighting is disabled using the 'lighting off' attribute, or if any texture layer has a 'colour_op replace' attribute.
Default: ambient 1.0 1.0 1.0 1.0
'''
@ogredoc
class _ogredoc_Shader_Nodes_diffuse( INFO_MT_ogre_helper ):
mydoc = '''
Sets the diffuse colour reflectance properties of this pass. This attribute has no effect if a asm, CG, or HLSL shader program is used. With GLSL, the shader can read the OpenGL material state.
Format: diffuse (<red> <green> <blue> [<alpha>]| vertexcolour)
NB valid colour values are between 0.0 and 1.0.
Example: diffuse 1.0 0.5 0.5
The base colour of a pass is determined by how much red, green and blue light is reflects at each vertex. This property determines how much diffuse light (light from instances of the Light class in the scene) is reflected. It is also possible to make the diffuse reflectance track the vertex colour as defined in the mesh by using the keyword vertexcolour instead of the colour values. The default is full white, meaning objects reflect the maximum white light they can from Light objects. This setting has no effect if dynamic lighting is disabled using the 'lighting off' attribute, or if any texture layer has a 'colour_op replace' attribute.
Default: diffuse 1.0 1.0 1.0 1.0
'''
@ogredoc
class _ogredoc_Shader_Nodes_specular( INFO_MT_ogre_helper ):
mydoc = '''
Sets the specular colour reflectance properties of this pass. This attribute has no effect if a asm, CG, or HLSL shader program is used. With GLSL, the shader can read the OpenGL material state.
Format: specular (<red> <green> <blue> [<alpha>]| vertexcolour) <shininess>
NB valid colour values are between 0.0 and 1.0. Shininess can be any value greater than 0.
Example: specular 1.0 1.0 1.0 12.5
The base colour of a pass is determined by how much red, green and blue light is reflects at each vertex. This property determines how much specular light (highlights from instances of the Light class in the scene) is reflected. It is also possible to make the diffuse reflectance track the vertex colour as defined in the mesh by using the keyword vertexcolour instead of the colour values. The default is to reflect no specular light. The colour of the specular highlights is determined by the colour parameters, and the size of the highlights by the separate shininess parameter.. The higher the value of the shininess parameter, the sharper the highlight ie the radius is smaller. Beware of using shininess values in the range of 0 to 1 since this causes the the specular colour to be applied to the whole surface that has the material applied to it. When the viewing angle to the surface changes, ugly flickering will also occur when shininess is in the range of 0 to 1. Shininess values between 1 and 128 work best in both DirectX and OpenGL renderers. This setting has no effect if dynamic lighting is disabled using the 'lighting off' attribute, or if any texture layer has a 'colour_op replace' attribute.
Default: specular 0.0 0.0 0.0 0.0 0.0
'''
@ogredoc
class _ogredoc_Shader_Nodes_emissive( INFO_MT_ogre_helper ):
mydoc = '''
emissive
Sets the amount of self-illumination an object has. This attribute has no effect if a asm, CG, or HLSL shader program is used. With GLSL, the shader can read the OpenGL material state.
Format: emissive (<red> <green> <blue> [<alpha>]| vertexcolour)
NB valid colour values are between 0.0 and 1.0.
Example: emissive 1.0 0.0 0.0
If an object is self-illuminating, it does not need external sources to light it, ambient or otherwise. It's like the object has it's own personal ambient light. Unlike the name suggests, this object doesn't act as a light source for other objects in the scene (if you want it to, you have to create a light which is centered on the object). It is also possible to make the emissive colour track the vertex colour as defined in the mesh by using the keyword vertexcolour instead of the colour values. This setting has no effect if dynamic lighting is disabled using the 'lighting off' attribute, or if any texture layer has a 'colour_op replace' attribute.
Default: emissive 0.0 0.0 0.0 0.0
'''
@ogredoc
class _ogredoc_Shader_Nodes_scene_blend( INFO_MT_ogre_helper ):
mydoc = '''
scene_blend
Sets the kind of blending this pass has with the existing contents of the scene. Wheras the texture blending operations seen in the texture_unit entries are concerned with blending between texture layers, this blending is about combining the output of this pass as a whole with the existing contents of the rendering target. This blending therefore allows object transparency and other special effects. There are 2 formats, one using predefined blend types, the other allowing a roll-your-own approach using source and destination factors.
Format1: scene_blend <add|modulate|alpha_blend|colour_blend>
Example: scene_blend add
This is the simpler form, where the most commonly used blending modes are enumerated using a single parameter. Valid <blend_type> parameters are:
@add
The colour of the rendering output is added to the scene. Good for explosions, flares, lights, ghosts etc. Equivalent to 'scene_blend one one'.
@modulate
The colour of the rendering output is multiplied with the scene contents. Generally colours and darkens the scene, good for smoked glass, semi-transparent objects etc. Equivalent to 'scene_blend dest_colour zero'.
@colour_blend
Colour the scene based on the brightness of the input colours, but don't darken. Equivalent to 'scene_blend src_colour one_minus_src_colour'
@alpha_blend
The alpha value of the rendering output is used as a mask. Equivalent to 'scene_blend src_alpha one_minus_src_alpha'
'''
@ogredoc
class _ogredoc_Shader_Nodes_separate_scene_blend( INFO_MT_ogre_helper ):
mydoc = '''
separate_scene_blend
This option operates in exactly the same way as scene_blend, except that it allows you to specify the operations to perform between the rendered pixel and the frame buffer separately for colour and alpha components. By nature this option is only useful when rendering to targets which have an alpha channel which you'll use for later processing, such as a render texture.
Format1: separate_scene_blend <simple_colour_blend> <simple_alpha_blend>
Example: separate_scene_blend add modulate
This example would add colour components but multiply alpha components. The blend modes available are as in scene_blend. The more advanced form is also available:
Params:
@add modulate
@add alpha_blend
@add color_blend
@modulate add
@modulate alpha_blend
@modulate color_blend
@alpha_blend add
@alpha_blend modulate
@alpha_blend color_blend
@colour_blend add
@colour_blend modulate
@colour_blend alpha_blend
Format2: separate_scene_blend <colour_src_factor> <colour_dest_factor> <alpha_src_factor> <alpha_dest_factor>
Example: separate_scene_blend one one_minus_dest_alpha one one
Again the options available in the second format are the same as those in the second format of scene_blend.
'''
@ogredoc
class _ogredoc_Shader_Nodes_scene_blend_op( INFO_MT_ogre_helper ):
mydoc = '''
scene_blend_op
This directive changes the operation which is applied between the two components of the scene blending equation, which by default is 'add' (sourceFactor * source + destFactor * dest). You may change this to 'add', 'subtract', 'reverse_subtract', 'min' or 'max'.
Format: scene_blend_op <add|subtract|reverse_subtract|min|max>
Default: scene_blend_op add
Params:
@add
@subtract
@reverse_subtract
@min
@max
----------------------------------------------------
Math shader node can support: add, subtract, min and max
'''
@ogredoc
class _ogredoc_Shader_Nodes_separate_scene_blend_op( INFO_MT_ogre_helper ):
mydoc = '''
separate_scene_blend_op
This directive is as scene_blend_op, except that you can set the operation for colour and alpha separately.
Format: separate_scene_blend_op <colourOp> <alphaOp>
Default: separate_scene_blend_op add add
Params:
@add subtract
@add reverse_subtract
@add min
@add max
@subtract add
@subtract reverse_subtract
@subtract min
@subtract max
@reverse_subtract subtract
@reverse_subtract add
@reverse_subtract min
@reverse_subtract max
@min add
@min subtract
@min reverse_subtract
@min max
@max add
@max subtract
@max reverse_subtract
@max min
'''
@ogredoc
class _ogredoc_Shader_Nodes_depth_check( INFO_MT_ogre_helper ):
mydoc = '''
depth_check
Params:
@on
@off
Sets whether or not this pass renders with depth-buffer checking on or not.
Format: depth_check <on|off>
If depth-buffer checking is on, whenever a pixel is about to be written to the frame buffer the depth buffer is checked to see if the pixel is in front of all other pixels written at that point. If not, the pixel is not written. If depth checking is off, pixels are written no matter what has been rendered before. Also see depth_func for more advanced depth check configuration.
Default: depth_check on
'''
@ogredoc
class _ogredoc_Shader_Nodes_depth_write( INFO_MT_ogre_helper ):
mydoc = '''
depth_write
Params:
@on
@off
Sets whether or not this pass renders with depth-buffer writing on or not.
Format: depth_write <on|off>
If depth-buffer writing is on, whenever a pixel is written to the frame buffer the depth buffer is updated with the depth value of that new pixel, thus affecting future rendering operations if future pixels are behind this one. If depth writing is off, pixels are written without updating the depth buffer. Depth writing should normally be on but can be turned off when rendering static backgrounds or when rendering a collection of transparent objects at the end of a scene so that they overlap each other correctly.
Default: depth_write on
'''
@ogredoc
class _ogredoc_Shader_Nodes_depth_func( INFO_MT_ogre_helper ):
mydoc = '''
depth_func
Sets the function used to compare depth values when depth checking is on.
Format: depth_func <func>
If depth checking is enabled (see depth_check) a comparison occurs between the depth value of the pixel to be written and the current contents of the buffer. This comparison is normally less_equal, i.e. the pixel is written if it is closer (or at the same distance) than the current contents. The possible functions are:
@always_fail
Never writes a pixel to the render target
@always_pass
Always writes a pixel to the render target
@less
Write if (new_Z < existing_Z)
@less_equal
Write if (new_Z <= existing_Z)
@equal
Write if (new_Z == existing_Z)
@not_equal
Write if (new_Z != existing_Z)
@greater_equal
Write if (new_Z >= existing_Z)
@greater
Write if (new_Z >existing_Z)
Default: depth_func less_equal
'''
@ogredoc
class _ogredoc_Shader_Nodes_depth_bias( INFO_MT_ogre_helper ):
mydoc = '''
depth_bias
Params:
@1
@2
@3
@4
Sets the bias applied to the depth value of this pass. Can be used to make coplanar polygons appear on top of others e.g. for decals.
Format: depth_bias <constant_bias> [<slopescale_bias>]
The final depth bias value is constant_bias * minObservableDepth + maxSlope * slopescale_bias. Slope scale biasing is relative to the angle of the polygon to the camera, which makes for a more appropriate bias value, but this is ignored on some older hardware. Constant biasing is expressed as a factor of the minimum depth value, so a value of 1 will nudge the depth by one 'notch' if you will. Also see iteration_depth_bias
'''
@ogredoc
class _ogredoc_Shader_Nodes_iteration_depth_bias( INFO_MT_ogre_helper ):
mydoc = '''
iteration_depth_bias
Params:
@1
@2
@3
@4
Sets an additional bias derived from the number of times a given pass has been iterated. Operates just like depth_bias except that it applies an additional bias factor to the base depth_bias value, multiplying the provided value by the number of times this pass has been iterated before, through one of the iteration variants. So the first time the pass will get the depth_bias value, the second time it will get depth_bias + iteration_depth_bias, the third time it will get depth_bias + iteration_depth_bias * 2, and so on. The default is zero.
Format: iteration_depth_bias <bias_per_iteration>
'''
@ogredoc
class _ogredoc_Shader_Nodes_alpha_rejection( INFO_MT_ogre_helper ):
mydoc = '''
alpha_rejection
Params:
@always_pass
@greater_equal 0
@greater_equal 16
@greater_equal 32
@greater_equal 64
Sets the way the pass will have use alpha to totally reject pixels from the pipeline.
Format: alpha_rejection <function> <value>
Example: alpha_rejection greater_equal 128
The function parameter can be any of the options listed in the material depth_function attribute. The value parameter can theoretically be any value between 0 and 255, but is best limited to 0 or 128 for hardware compatibility.
Default: alpha_rejection always_pass
'''
@ogredoc
class _ogredoc_Shader_Nodes_alpha_to_coverage( INFO_MT_ogre_helper ):
mydoc = '''
alpha_to_coverage
Params:
@on
@off
Sets whether this pass will use 'alpha to coverage', a way to multisample alpha texture edges so they blend more seamlessly with the background. This facility is typically only available on cards from around 2006 onwards, but it is safe to enable it anyway - Ogre will just ignore it if the hardware does not support it. The common use for alpha to coverage is foliage rendering and chain-link fence style textures.
Format: alpha_to_coverage <on|off>
Default: alpha_to_coverage off
'''
@ogredoc
class _ogredoc_Shader_Nodes_light_scissor( INFO_MT_ogre_helper ):
mydoc = '''
light_scissor
Params:
@on
@off
Sets whether when rendering this pass, rendering will be limited to a screen-space scissor rectangle representing the coverage of the light(s) being used in this pass, derived from their attenuation ranges.
Format: light_scissor <on|off>
Default: light_scissor off
This option is usually only useful if this pass is an additive lighting pass, and is at least the second one in the technique. Ie areas which are not affected by the current light(s) will never need to be rendered. If there is more than one light being passed to the pass, then the scissor is defined to be the rectangle which covers all lights in screen-space. Directional lights are ignored since they are infinite.
This option does not need to be specified if you are using a standard additive shadow mode, i.e. SHADOWTYPE_STENCIL_ADDITIVE or SHADOWTYPE_TEXTURE_ADDITIVE, since it is the default behaviour to use a scissor for each additive shadow pass. However, if you're not using shadows, or you're using Integrated Texture Shadows where passes are specified in a custom manner, then this could be of use to you.
'''
@ogredoc
class _ogredoc_Shader_Nodes_light_clip_planes( INFO_MT_ogre_helper ):
mydoc = '''
light_clip_planes
Params:
@on
@off
Sets whether when rendering this pass, triangle setup will be limited to clipping volume covered by the light. Directional lights are ignored, point lights clip to a cube the size of the attenuation range or the light, and spotlights clip to a pyramid bounding the spotlight angle and attenuation range.
Format: light_clip_planes <on|off>
Default: light_clip_planes off
This option will only function if there is a single non-directional light being used in this pass. If there is more than one light, or only directional lights, then no clipping will occur. If there are no lights at all then the objects won't be rendered at all.
When using a standard additive shadow mode, ie SHADOWTYPE_STENCIL_ADDITIVE or SHADOWTYPE_TEXTURE_ADDITIVE, you have the option of enabling clipping for all light passes by calling SceneManager::setShadowUseLightClipPlanes regardless of this pass setting, since rendering is done lightwise anyway. This is off by default since using clip planes is not always faster - it depends on how much of the scene the light volumes cover. Generally the smaller your lights are the more chance you'll see a benefit rather than a penalty from clipping. If you're not using shadows, or you're using Integrated Texture Shadows where passes are specified in a custom manner, then specify the option per-pass using this attribute.
A specific note about OpenGL: user clip planes are completely ignored when you use an ARB vertex program. This means light clip planes won't help much if you use ARB vertex programs on GL, although OGRE will perform some optimisation of its own, in that if it sees that the clip volume is completely off-screen, it won't perform a render at all. When using GLSL, user clipping can be used but you have to use glClipVertex in your shader, see the GLSL documentation for more information. In Direct3D user clip planes are always respected.
'''
@ogredoc
class _ogredoc_Shader_Nodes_illumination_stage( INFO_MT_ogre_helper ):
mydoc = '''
illumination_stage
Params:
@ambient
@per_light
@decal
When using an additive lighting mode (SHADOWTYPE_STENCIL_ADDITIVE or SHADOWTYPE_TEXTURE_ADDITIVE), the scene is rendered in 3 discrete stages, ambient (or pre-lighting), per-light (once per light, with shadowing) and decal (or post-lighting). Usually OGRE figures out how to categorise your passes automatically, but there are some effects you cannot achieve without manually controlling the illumination. For example specular effects are muted by the typical sequence because all textures are saved until the 'decal' stage which mutes the specular effect. Instead, you could do texturing within the per-light stage if it's possible for your material and thus add the specular on after the decal texturing, and have no post-light rendering.
If you assign an illumination stage to a pass you have to assign it to all passes in the technique otherwise it will be ignored. Also note that whilst you can have more than one pass in each group, they cannot alternate, ie all ambient passes will be before all per-light passes, which will also be before all decal passes. Within their categories the passes will retain their ordering though. Format: illumination_stage <ambient|per_light|decal>
Default: none (autodetect)
'''
@ogredoc
class _ogredoc_Shader_Nodes_normalise_normals( INFO_MT_ogre_helper ):
mydoc = '''
normalise_normals
Params:
@on
@off
Sets whether or not this pass renders with all vertex normals being automatically re-normalised.
Format: normalise_normals <on|off>
Scaling objects causes normals to also change magnitude, which can throw off your lighting calculations. By default, the SceneManager detects this and will automatically re-normalise normals for any scaled object, but this has a cost. If you'd prefer to control this manually, call SceneManager::setNormaliseNormalsOnScale(false) and then use this option on materials which are sensitive to normals being resized.
Default: normalise_normals off
'''
@ogredoc
class _ogredoc_Shader_Nodes_transparent_sorting( INFO_MT_ogre_helper ):
mydoc = '''
transparent_sorting
Params:
@on
@off
@force
Sets if transparent textures should be sorted by depth or not.
Format: transparent_sorting <on|off|force>
By default all transparent materials are sorted such that renderables furthest away from the camera are rendered first. This is usually the desired behaviour but in certain cases this depth sorting may be unnecessary and undesirable. If for example it is necessary to ensure the rendering order does not change from one frame to the next. In this case you could set the value to 'off' to prevent sorting.
You can also use the keyword 'force' to force transparent sorting on, regardless of other circumstances. Usually sorting is only used when the pass is also transparent, and has a depth write or read which indicates it cannot reliably render without sorting. By using 'force', you tell OGRE to sort this pass no matter what other circumstances are present.
Default: transparent_sorting on
'''
@ogredoc
class _ogredoc_Shader_Nodes_cull_hardware( INFO_MT_ogre_helper ):
mydoc = '''
cull_hardware
Params:
@clockwise
@anticlockwise
@none
Sets the hardware culling mode for this pass.
Format: cull_hardware <clockwise|anticlockwise|none>
A typical way for the hardware rendering engine to cull triangles is based on the 'vertex winding' of triangles. Vertex winding refers to the direction in which the vertices are passed or indexed to in the rendering operation as viewed from the camera, and will wither be clockwise or anticlockwise (that's 'counterclockwise' for you Americans out there ;). If the option 'cull_hardware clockwise' is set, all triangles whose vertices are viewed in clockwise order from the camera will be culled by the hardware. 'anticlockwise' is the reverse (obviously), and 'none' turns off hardware culling so all triagles are rendered (useful for creating 2-sided passes).
Default: cull_hardware clockwise
NB this is the same as OpenGL's default but the opposite of Direct3D's default (because Ogre uses a right-handed coordinate system like OpenGL).
'''
@ogredoc
class _ogredoc_Shader_Nodes_cull_software( INFO_MT_ogre_helper ):
mydoc = '''
cull_software
Params:
@back
@front
@none
Sets the software culling mode for this pass.
Format: cull_software <back|front|none>
In some situations the engine will also cull geometry in software before sending it to the hardware renderer. This setting only takes effect on SceneManager's that use it (since it is best used on large groups of planar world geometry rather than on movable geometry since this would be expensive), but if used can cull geometry before it is sent to the hardware. In this case the culling is based on whether the 'back' or 'front' of the triangle is facing the camera - this definition is based on the face normal (a vector which sticks out of the front side of the polygon perpendicular to the face). Since Ogre expects face normals to be on anticlockwise side of the face, 'cull_software back' is the software equivalent of 'cull_hardware clockwise' setting, which is why they are both the default. The naming is different to reflect the way the culling is done though, since most of the time face normals are pre-calculated and they don't have to be the way Ogre expects - you could set 'cull_hardware none' and completely cull in software based on your own face normals, if you have the right SceneManager which uses them.
Default: cull_software back
'''
@ogredoc
class _ogredoc_Shader_Nodes_lighting( INFO_MT_ogre_helper ):
mydoc = '''
lighting
Params:
@on
@off
Sets whether or not dynamic lighting is turned on for this pass or not. If lighting is turned off, all objects rendered using the pass will be fully lit. This attribute has no effect if a vertex program is used.
Format: lighting <on|off>
Turning dynamic lighting off makes any ambient, diffuse, specular, emissive and shading properties for this pass redundant. When lighting is turned on, objects are lit according to their vertex normals for diffuse and specular light, and globally for ambient and emissive.
Default: lighting on
'''
@ogredoc
class _ogredoc_Shader_Nodes_shading( INFO_MT_ogre_helper ):
mydoc = '''
shading
Params:
@flat
@gouraud
@phong
Sets the kind of shading which should be used for representing dynamic lighting for this pass.
Format: shading <flat|gouraud|phong>
When dynamic lighting is turned on, the effect is to generate colour values at each vertex. Whether these values are interpolated across the face (and how) depends on this setting.
flat
No interpolation takes place. Each face is shaded with a single colour determined from the first vertex in the face.
gouraud
Colour at each vertex is linearly interpolated across the face.
phong
Vertex normals are interpolated across the face, and these are used to determine colour at each pixel. Gives a more natural lighting effect but is more expensive and works better at high levels of tessellation. Not supported on all hardware.
Default: shading gouraud
'''
@ogredoc
class _ogredoc_Shader_Nodes_polygon_mode( INFO_MT_ogre_helper ):
mydoc = '''
polygon_mode
Params:
@solid
@wireframe
@points
Sets how polygons should be rasterised, i.e. whether they should be filled in, or just drawn as lines or points.
Format: polygon_mode <solid|wireframe|points>
solid
The normal situation - polygons are filled in.
wireframe
Polygons are drawn in outline only.
points
Only the points of each polygon are rendered.
Default: polygon_mode solid
'''
@ogredoc
class _ogredoc_Shader_Nodes_polygon_mode_overrideable( INFO_MT_ogre_helper ):
mydoc = '''
polygon_mode_overrideable
Params:
@true
@false
Sets whether or not the polygon_mode set on this pass can be downgraded by the camera, if the camera itself is set to a lower polygon mode. If set to false, this pass will always be rendered at its own chosen polygon mode no matter what the camera says. The default is true.
Format: polygon_mode_overrideable <true|false>
'''
@ogredoc
class _ogredoc_Shader_Nodes_fog_override( INFO_MT_ogre_helper ):
mydoc = '''
fog_override
Params:
@true
@false
@true exp 1 1 1 0.002 100 10000
Tells the pass whether it should override the scene fog settings, and enforce it's own. Very useful for things that you don't want to be affected by fog when the rest of the scene is fogged, or vice versa. Note that this only affects fixed-function fog - the original scene fog parameters are still sent to shaders which use the fog_params parameter binding (this allows you to turn off fixed function fog and calculate it in the shader instead; if you want to disable shader fog you can do that through shader parameters anyway).
Format: fog_override <override?> [<type> <colour> <density> <start> <end>]
Default: fog_override false
If you specify 'true' for the first parameter and you supply the rest of the parameters, you are telling the pass to use these fog settings in preference to the scene settings, whatever they might be. If you specify 'true' but provide no further parameters, you are telling this pass to never use fogging no matter what the scene says. Here is an explanation of the parameters:
type
none = No fog, equivalent of just using 'fog_override true'
linear = Linear fog from the <start> and <end> distances
exp = Fog increases exponentially from the camera (fog = 1/e^(distance * density)), use <density> param to control it
exp2 = Fog increases at the square of FOG_EXP, i.e. even quicker (fog = 1/e^(distance * density)^2), use <density> param to control it
colour
Sequence of 3 floating point values from 0 to 1 indicating the red, green and blue intensities
density
The density parameter used in the 'exp' or 'exp2' fog types. Not used in linear mode but param must still be there as a placeholder
start
The start distance from the camera of linear fog. Must still be present in other modes, even though it is not used.
end
The end distance from the camera of linear fog. Must still be present in other modes, even though it is not used.
Example: fog_override true exp 1 1 1 0.002 100 10000
'''
@ogredoc
class _ogredoc_Shader_Nodes_colour_write( INFO_MT_ogre_helper ):
mydoc = '''
colour_write
Params:
@on
@off
Sets whether or not this pass renders with colour writing on or not.
Format: colour_write <on|off>
If colour writing is off no visible pixels are written to the screen during this pass. You might think this is useless, but if you render with colour writing off, and with very minimal other settings, you can use this pass to initialise the depth buffer before subsequently rendering other passes which fill in the colour data. This can give you significant performance boosts on some newer cards, especially when using complex fragment programs, because if the depth check fails then the fragment program is never run.
Default: colour_write on
'''
@ogredoc
class _ogredoc_Shader_Nodes_start_light( INFO_MT_ogre_helper ):
mydoc = '''
start_light
Params:
@0
@1
@2
@3
@4
@5
@6
Sets the first light which will be considered for use with this pass.
Format: start_light <number>
You can use this attribute to offset the starting point of the lights for this pass. In other words, if you set start_light to 2 then the first light to be processed in that pass will be the third actual light in the applicable list. You could use this option to use different passes to process the first couple of lights versus the second couple of lights for example, or use it in conjunction with the iteration option to start the iteration from a given point in the list (e.g. doing the first 2 lights in the first pass, and then iterating every 2 lights from then on perhaps).
Default: start_light 0
'''
@ogredoc
class _ogredoc_Shader_Nodes_max_lights( INFO_MT_ogre_helper ):
mydoc = '''
max_lights
Params:
@1
@2
@3
@4
@5
@6
Sets the maximum number of lights which will be considered for use with this pass.
Format: max_lights <number>
The maximum number of lights which can be used when rendering fixed-function materials is set by the rendering system, and is typically set at 8. When you are using the programmable pipeline (See section 3.1.9 Using Vertex/Geometry/Fragment Programs in a Pass) this limit is dependent on the program you are running, or, if you use 'iteration once_per_light' or a variant (See section iteration), it effectively only bounded by the number of passes you are willing to use. If you are not using pass iteration, the light limit applies once for this pass. If you are using pass iteration, the light limit applies across all iterations of this pass - for example if you have 12 lights in range with an 'iteration once_per_light' setup but your max_lights is set to 4 for that pass, the pass will only iterate 4 times.
Default: max_lights 8
'''
@ogredoc
class _ogredoc_Shader_Nodes_iteration( INFO_MT_ogre_helper ):
mydoc = '''
iteration
Params:
@once
@once_per_light
@1 once
@1 once_per_light
@2 once
@2 once_per_light
Sets whether or not this pass is iterated, i.e. issued more than once.
Format 1: iteration <once | once_per_light> [lightType]
Format 2: iteration <number> [<per_light> [lightType]]
Format 3: iteration <number> [<per_n_lights> <num_lights> [lightType]]
Examples:
iteration once
The pass is only executed once which is the default behaviour.
iteration once_per_light point
The pass is executed once for each point light.
iteration 5
The render state for the pass will be setup and then the draw call will execute 5 times.
iteration 5 per_light point
The render state for the pass will be setup and then the draw call will execute 5 times. This will be done for each point light.
iteration 1 per_n_lights 2 point
The render state for the pass will be setup and the draw call executed once for every 2 lights.
By default, passes are only issued once. However, if you use the programmable pipeline, or you wish to exceed the normal limits on the number of lights which are supported, you might want to use the once_per_light option. In this case, only light index 0 is ever used, and the pass is issued multiple times, each time with a different light in light index 0. Clearly this will make the pass more expensive, but it may be the only way to achieve certain effects such as per-pixel lighting effects which take into account 1..n lights.
Using a number instead of "once" instructs the pass to iterate more than once after the render state is setup. The render state is not changed after the initial setup so repeated draw calls are very fast and ideal for passes using programmable shaders that must iterate more than once with the same render state i.e. shaders that do fur, motion blur, special filtering.
If you use once_per_light, you should also add an ambient pass to the technique before this pass, otherwise when no lights are in range of this object it will not get rendered at all; this is important even when you have no ambient light in the scene, because you would still want the objects silhouette to appear.
The lightType parameter to the attribute only applies if you use once_per_light, per_light, or per_n_lights and restricts the pass to being run for lights of a single type (either 'point', 'directional' or 'spot'). In the example, the pass will be run once per point light. This can be useful because when you're writing a vertex / fragment program it is a lot easier if you can assume the kind of lights you'll be dealing with. However at least point and directional lights can be dealt with in one way.
Default: iteration once
'''
@ogredoc
class _ogredoc_Shader_Nodes_point_size( INFO_MT_ogre_helper ):
mydoc = '''
point_size
Params:
@4
@16
@32
This setting allows you to change the size of points when rendering a point list, or a list of point sprites. The interpretation of this command depends on the point_size_attenuation option - if it is off (the default), the point size is in screen pixels, if it is on, it expressed as normalised screen coordinates (1.0 is the height of the screen) when the point is at the origin.
NOTE: Some drivers have an upper limit on the size of points they support - this can even vary between APIs on the same card! Don't rely on point sizes that cause the points to get very large on screen, since they may get clamped on some cards. Upper sizes can range from 64 to 256 pixels.
Format: point_size <size>
Default: point_size 1.0
'''
@ogredoc
class _ogredoc_Shader_Nodes_point_sprites( INFO_MT_ogre_helper ):
mydoc = '''
point_sprites
Params:
@on
@off
This setting specifies whether or not hardware point sprite rendering is enabled for this pass. Enabling it means that a point list is rendered as a list of quads rather than a list of dots. It is very useful to use this option if you're using a BillboardSet and only need to use point oriented billboards which are all of the same size. You can also use it for any other point list render.
Format: point_sprites <on|off>
Default: point_sprites off
'''
@ogredoc
class _ogredoc_Shader_Nodes_point_size_attenuation( INFO_MT_ogre_helper ):
mydoc = '''
point_size_attenuation
Params:
@on
@off
@on constant
@on linear
@on quadratic
Defines whether point size is attenuated with view space distance, and in what fashion. This option is especially useful when you're using point sprites (See section point_sprites) since it defines how they reduce in size as they get further away from the camera. You can also disable this option to make point sprites a constant screen size (like points), or enable it for points so they change size with distance.
You only have to provide the final 3 parameters if you turn attenuation on. The formula for attenuation is that the size of the point is multiplied by 1 / (constant + linear * dist + quadratic * d^2); therefore turning it off is equivalent to (constant = 1, linear = 0, quadratic = 0) and standard perspective attenuation is (constant = 0, linear = 1, quadratic = 0). The latter is assumed if you leave out the final 3 parameters when you specify 'on'.
Note that the resulting attenuated size is clamped to the minimum and maximum point size, see the next section.
Format: point_size_attenuation <on|off> [constant linear quadratic] Default: point_size_attenuation off
'''
@ogredoc
class _ogredoc_Shader_Nodes_point_size_min( INFO_MT_ogre_helper ):
mydoc = '''
point_size_min
Params:
@1
@4
@8
Sets the minimum point size after attenuation (point_size_attenuation). For details on the size metrics, See section point_size.
Format: point_size_min <size> Default: point_size_min 0
'''
@ogredoc
class _ogredoc_Shader_Nodes_point_size_max( INFO_MT_ogre_helper ):
mydoc = '''
point_size_max
Params:
@32
@64
@128
Sets the maximum point size after attenuation (point_size_attenuation). For details on the size metrics, See section point_size. A value of 0 means the maximum is set to the same as the max size reported by the current card.
Format: point_size_max <size> Default: point_size_max 0
'''
## Ogre 1.7 doc - 3.1.3 Texture Units ##
@ogredoc
class _ogredoc_TEX_texture_alias( INFO_MT_ogre_helper ):
mydoc = '''
texture_alias
Params:
@myname
Sets the alias name for this texture unit.
Format: texture_alias <name>
Example: texture_alias NormalMap
Setting the texture alias name is useful if this material is to be inherited by other other materials and only the textures will be changed in the new material.(See section 3.1.12 Texture Aliases)
Default: If a texture_unit has a name then the texture_alias defaults to the texture_unit name.
'''
@ogredoc
class _ogredoc_TEX_texture( INFO_MT_ogre_helper ):
mydoc = '''
texture
Sets the name of the static texture image this layer will use.
Format: texture <texturename> [<type>] [unlimited | numMipMaps] [alpha] [<PixelFormat>] [gamma]
Example: texture funkywall.jpg
This setting is mutually exclusive with the anim_texture attribute. Note that the texture file cannot include spaces. Those of you Windows users who like spaces in filenames, please get over it and use underscores instead.
The 'type' parameter allows you to specify a the type of texture to create - the default is '2d', but you can override this; here's the full list:
1d
A 1-dimensional texture; that is, a texture which is only 1 pixel high. These kinds of textures can be useful when you need to encode a function in a texture and use it as a simple lookup, perhaps in a fragment program. It is important that you use this setting when you use a fragment program which uses 1-dimensional texture coordinates, since GL requires you to use a texture type that matches (D3D will let you get away with it, but you ought to plan for cross-compatibility). Your texture widths should still be a power of 2 for best compatibility and performance.
2d
The default type which is assumed if you omit it, your texture has a width and a height, both of which should preferably be powers of 2, and if you can, make them square because this will look best on the most hardware. These can be addressed with 2D texture coordinates.
3d
A 3 dimensional texture i.e. volume texture. Your texture has a width, a height, both of which should be powers of 2, and has depth. These can be addressed with 3d texture coordinates i.e. through a pixel shader.
cubic
This texture is made up of 6 2D textures which are pasted around the inside of a cube. Can be addressed with 3D texture coordinates and are useful for cubic reflection maps and normal maps.
The 'numMipMaps' option allows you to specify the number of mipmaps to generate for this texture. The default is 'unlimited' which means mips down to 1x1 size are generated. You can specify a fixed number (even 0) if you like instead. Note that if you use the same texture in many material scripts, the number of mipmaps generated will conform to the number specified in the first texture_unit used to load the texture - so be consistent with your usage.
The 'alpha' option allows you to specify that a single channel (luminance) texture should be loaded as alpha, rather than the default which is to load it into the red channel. This can be helpful if you want to use alpha-only textures in the fixed function pipeline. Default: none
'''
@ogredoc
class _ogredoc_TEX_anim_texture( INFO_MT_ogre_helper ):
mydoc = '''
anim_texture
Sets the images to be used in an animated texture layer. In this case an animated texture layer means one which has multiple frames, each of which is a separate image file. There are 2 formats, one for implicitly determined image names, one for explicitly named images.
Format1 (short): anim_texture <base_name> <num_frames> <duration>
Example: anim_texture flame.jpg 5 2.5
This sets up an animated texture layer made up of 5 frames named flame_0.jpg, flame_1.jpg, flame_2.jpg etc, with an animation length of 2.5 seconds (2fps). If duration is set to 0, then no automatic transition takes place and frames must be changed manually in code.
Format2 (long): anim_texture <frame1> <frame2> ... <duration>
Example: anim_texture flamestart.jpg flamemore.png flameagain.jpg moreflame.jpg lastflame.tga 2.5
This sets up the same duration animation but from 5 separately named image files. The first format is more concise, but the second is provided if you cannot make your images conform to the naming standard required for it.
Default: none
'''
@ogredoc
class _ogredoc_TEX_cubic_texture( INFO_MT_ogre_helper ):
mydoc = '''
cubic_texture
@mybasename separateUV
@mybasename combinedUVW
@front.jpg front.jpg back.jpg left.jpg right.jpg up.jpg down.jpg separateUV
Sets the images used in a cubic texture, i.e. one made up of 6 individual images making up the faces of a cube. These kinds of textures are used for reflection maps (if hardware supports cubic reflection maps) or skyboxes. There are 2 formats, a brief format expecting image names of a particular format and a more flexible but longer format for arbitrarily named textures.
Format1 (short): cubic_texture <base_name> <combinedUVW|separateUV>
The base_name in this format is something like 'skybox.jpg', and the system will expect you to provide skybox_fr.jpg, skybox_bk.jpg, skybox_up.jpg, skybox_dn.jpg, skybox_lf.jpg, and skybox_rt.jpg for the individual faces.
Format2 (long): cubic_texture <front> <back> <left> <right> <up> <down> separateUV
In this case each face is specified explicitly, incase you don't want to conform to the image naming standards above. You can only use this for the separateUV version since the combinedUVW version requires a single texture name to be assigned to the combined 3D texture (see below).
In both cases the final parameter means the following:
combinedUVW
The 6 textures are combined into a single 'cubic' texture map which is then addressed using 3D texture coordinates with U, V and W components. Necessary for reflection maps since you never know which face of the box you are going to need. Note that not all cards support cubic environment mapping.
separateUV
The 6 textures are kept separate but are all referenced by this single texture layer. One texture at a time is active (they are actually stored as 6 frames), and they are addressed using standard 2D UV coordinates. This type is good for skyboxes since only one face is rendered at one time and this has more guaranteed hardware support on older cards.
Default: none
'''
@ogredoc
class _ogredoc_TEX_binding_type( INFO_MT_ogre_helper ):
mydoc = '''
binding_type
Params:
@vertex
@fragment
Tells this texture unit to bind to either the fragment processing unit or the vertex processing unit (for 3.1.10 Vertex Texture Fetch).
Format: binding_type <vertex|fragment> Default: binding_type fragment
'''
@ogredoc
class _ogredoc_TEX_content_type( INFO_MT_ogre_helper ):
mydoc = '''
content_type
@compositor DepthCompositor OutputTexture
Tells this texture unit where it should get its content from. The default is to get texture content from a named texture, as defined with the texture, cubic_texture, anim_texture attributes. However you can also pull texture information from other automated sources. The options are:
@named
The default option, this derives texture content from a texture name, loaded by ordinary means from a file or having been manually created with a given name.
@shadow
This option allows you to pull in a shadow texture, and is only valid when you use texture shadows and one of the 'custom sequence' shadowing types (See section 7. Shadows). The shadow texture in question will be from the 'n'th closest light that casts shadows, unless you use light-based pass iteration or the light_start option which may start the light index higher. When you use this option in multiple texture units within the same pass, each one references the next shadow texture. The shadow texture index is reset in the next pass, in case you want to take into account the same shadow textures again in another pass (e.g. a separate specular / gloss pass). By using this option, the correct light frustum projection is set up for you for use in fixed-function, if you use shaders just reference the texture_viewproj_matrix auto parameter in your shader.
@compositor
This option allows you to reference a texture from a compositor, and is only valid when the pass is rendered within a compositor sequence. This can be either in a render_scene directive inside a compositor script, or in a general pass in a viewport that has a compositor attached. Note that this is a reference only, meaning that it does not change the render order. You must make sure that the order is reasonable for what you are trying to achieve (for example, texture pooling might cause the referenced texture to be overwritten by something else by the time it is referenced).
The extra parameters for the content_type are only required for this type:
The first is the name of the compositor being referenced. (Required)
The second is the name of the texture to reference in the compositor. (Required)
The third is the index of the texture to take, in case of an MRT. (Optional)
Format: content_type <named|shadow|compositor> [<Referenced Compositor Name>] [<Referenced Texture Name>] [<Referenced MRT Index>]
Default: content_type named
Example: content_type compositor DepthCompositor OutputTexture
'''
@ogredoc
class _ogredoc_TEX_tex_coord_set( INFO_MT_ogre_helper ):
mydoc = '''
tex_coord_set
Sets which texture coordinate set is to be used for this texture layer. A mesh can define multiple sets of texture coordinates, this sets which one this material uses.
Format: tex_coord_set <set_num>
Example: tex_coord_set 2
Default: tex_coord_set 0
'''
@ogredoc
class _ogredoc_TEX_tex_address_mode( INFO_MT_ogre_helper ):
mydoc = '''
tex_address_mode
Defines what happens when texture coordinates exceed 1.0 for this texture layer.You can use the simple format to specify the addressing mode for all 3 potential texture coordinates at once, or you can use the 2/3 parameter extended format to specify a different mode per texture coordinate.
Simple Format: tex_address_mode <uvw_mode>
Extended Format: tex_address_mode <u_mode> <v_mode> [<w_mode>]
@wrap
Any value beyond 1.0 wraps back to 0.0. Texture is repeated.
@clamp
Values beyond 1.0 are clamped to 1.0. Texture 'streaks' beyond 1.0 since last line of pixels is used across the rest of the address space. Useful for textures which need exact coverage from 0.0 to 1.0 without the 'fuzzy edge' wrap gives when combined with filtering.
@mirror
Texture flips every boundary, meaning texture is mirrored every 1.0 u or v
@border
Values outside the range [0.0, 1.0] are set to the border colour, you might also set the tex_border_colour attribute too.
Default: tex_address_mode wrap
'''
@ogredoc
class _ogredoc_TEX_tex_border_colour( INFO_MT_ogre_helper ):
mydoc = '''
tex_border_colour
@0.0 0.5 0.0 0.25
Sets the border colour of border texture address mode (see tex_address_mode).
Format: tex_border_colour <red> <green> <blue> [<alpha>]
NB valid colour values are between 0.0 and 1.0.
Example: tex_border_colour 0.0 1.0 0.3
Default: tex_border_colour 0.0 0.0 0.0 1.0
'''
@ogredoc
class _ogredoc_TEX_filtering( INFO_MT_ogre_helper ):
mydoc = '''
filtering
Sets the type of texture filtering used when magnifying or minifying a texture. There are 2 formats to this attribute, the simple format where you simply specify the name of a predefined set of filtering options, and the complex format, where you individually set the minification, magnification, and mip filters yourself.
Simple Format
Format: filtering <none|bilinear|trilinear|anisotropic>
Default: filtering bilinear
With this format, you only need to provide a single parameter which is one of the following:
@none
No filtering or mipmapping is used. This is equivalent to the complex format 'filtering point point none'.
@bilinear
2x2 box filtering is performed when magnifying or reducing a texture, and a mipmap is picked from the list but no filtering is done between the levels of the mipmaps. This is equivalent to the complex format 'filtering linear linear point'.
@trilinear
2x2 box filtering is performed when magnifying and reducing a texture, and the closest 2 mipmaps are filtered together. This is equivalent to the complex format 'filtering linear linear linear'.
@anisotropic
This is the same as 'trilinear', except the filtering algorithm takes account of the slope of the triangle in relation to the camera rather than simply doing a 2x2 pixel filter in all cases. This makes triangles at acute angles look less fuzzy. Equivalent to the complex format 'filtering anisotropic anisotropic linear'. Note that in order for this to make any difference, you must also set the max_anisotropy attribute too.
'''
@ogredoc
class _ogredoc_TEX_max_anisotropy( INFO_MT_ogre_helper ):
mydoc = '''
max_anisotropy
@2
@4
@8
@16
Sets the maximum degree of anisotropy that the renderer will try to compensate for when filtering textures. The degree of anisotropy is the ratio between the height of the texture segment visible in a screen space region versus the width - so for example a floor plane, which stretches on into the distance and thus the vertical texture coordinates change much faster than the horizontal ones, has a higher anisotropy than a wall which is facing you head on (which has an anisotropy of 1 if your line of sight is perfectly perpendicular to it). You should set the max_anisotropy value to something greater than 1 to begin compensating; higher values can compensate for more acute angles. The maximum value is determined by the hardware, but it is usually 8 or 16.
In order for this to be used, you have to set the minification and/or the magnification filtering option on this texture to anisotropic. Format: max_anisotropy <value>
Default: max_anisotropy 1
'''
@ogredoc
class _ogredoc_TEX_mipmap_bias( INFO_MT_ogre_helper ):
mydoc = '''
mipmap_bias
@1
@4
@8
Sets the bias value applied to the mipmapping calculation, thus allowing you to alter the decision of which level of detail of the texture to use at any distance. The bias value is applied after the regular distance calculation, and adjusts the mipmap level by 1 level for each unit of bias. Negative bias values force larger mip levels to be used, positive bias values force smaller mip levels to be used. The bias is a floating point value so you can use values in between whole numbers for fine tuning.
In order for this option to be used, your hardware has to support mipmap biasing (exposed through the render system capabilities), and your minification filtering has to be set to point or linear. Format: mipmap_bias <value>
Default: mipmap_bias 0
'''
@ogredoc
class _ogredoc_TEX_colour_op( INFO_MT_ogre_helper ):
mydoc = '''
colour_op
Determines how the colour of this texture layer is combined with the one below it (or the lighting effect on the geometry if this is the first layer).
Format: colour_op <replace|add|modulate|alpha_blend>
This method is the simplest way to blend texture layers, because it requires only one parameter, gives you the most common blending types, and automatically sets up 2 blending methods: one for if single-pass multitexturing hardware is available, and another for if it is not and the blending must be achieved through multiple rendering passes. It is, however, quite limited and does not expose the more flexible multitexturing operations, simply because these can't be automatically supported in multipass fallback mode. If want to use the fancier options, use colour_op_ex, but you'll either have to be sure that enough multitexturing units will be available, or you should explicitly set a fallback using colour_op_multipass_fallback.
@replace
Replace all colour with texture with no adjustment.
@add
Add colour components together.
@modulate
Multiply colour components together.
@alpha_blend
Blend based on texture alpha.
Default: colour_op modulate
'''
@ogredoc
class _ogredoc_TEX_colour_op_ex( INFO_MT_ogre_helper ):
mydoc = '''
colour_op_ex
@add_signed src_manual src_current 0.5
This is an extended version of the colour_op attribute which allows extremely detailed control over the blending applied between this and earlier layers. Multitexturing hardware can apply more complex blending operations that multipass blending, but you are limited to the number of texture units which are available in hardware.
Format: colour_op_ex <operation> <source1> <source2> [<manual_factor>] [<manual_colour1>] [<manual_colour2>]
Example colour_op_ex add_signed src_manual src_current 0.5
See the IMPORTANT note below about the issues between multipass and multitexturing that using this method can create. Texture colour operations determine how the final colour of the surface appears when rendered. Texture units are used to combine colour values from various sources (e.g. the diffuse colour of the surface from lighting calculations, combined with the colour of the texture). This method allows you to specify the 'operation' to be used, i.e. the calculation such as adds or multiplies, and which values to use as arguments, such as a fixed value or a value from a previous calculation.
Operation options:
source1
Use source1 without modification
source2
Use source2 without modification
modulate
Multiply source1 and source2 together.
modulate_x2
Multiply source1 and source2 together, then by 2 (brightening).
modulate_x4
Multiply source1 and source2 together, then by 4 (brightening).
add
Add source1 and source2 together.
add_signed
Add source1 and source2 then subtract 0.5.
add_smooth
Add source1 and source2, subtract the product
subtract
Subtract source2 from source1
blend_diffuse_alpha
Use interpolated alpha value from vertices to scale source1, then add source2 scaled by (1-alpha).
blend_texture_alpha
As blend_diffuse_alpha but use alpha from texture
blend_current_alpha
As blend_diffuse_alpha but use current alpha from previous stages (same as blend_diffuse_alpha for first layer)
blend_manual
As blend_diffuse_alpha but use a constant manual alpha value specified in <manual>
dotproduct
The dot product of source1 and source2
blend_diffuse_colour
Use interpolated colour value from vertices to scale source1, then add source2 scaled by (1-colour).
Source1 and source2 options:
src_current
The colour as built up from previous stages.
src_texture
The colour derived from the texture assigned to this layer.
src_diffuse
The interpolated diffuse colour from the vertices (same as 'src_current' for first layer).
src_specular
The interpolated specular colour from the vertices.
src_manual
The manual colour specified at the end of the command.
For example 'modulate' takes the colour results of the previous layer, and multiplies them with the new texture being applied. Bear in mind that colours are RGB values from 0.0-1.0 so multiplying them together will result in values in the same range, 'tinted' by the multiply. Note however that a straight multiply normally has the effect of darkening the textures - for this reason there are brightening operations like modulate_x2. Note that because of the limitations on some underlying APIs (Direct3D included) the 'texture' argument can only be used as the first argument, not the second.
Note that the last parameter is only required if you decide to pass a value manually into the operation. Hence you only need to fill these in if you use the 'blend_manual' operation.
'''
@ogredoc
class _ogredoc_TEX_colour_op_multipass_fallback( INFO_MT_ogre_helper ):
mydoc = '''
colour_op_multipass_fallback
@one one_minus_dest_alpha
Sets the multipass fallback operation for this layer, if you used colour_op_ex and not enough multitexturing hardware is available.
Format: colour_op_multipass_fallback <src_factor> <dest_factor>
Example: colour_op_multipass_fallback one one_minus_dest_alpha
Because some of the effects you can create using colour_op_ex are only supported under multitexturing hardware, if the hardware is lacking the system must fallback on multipass rendering, which unfortunately doesn't support as many effects. This attribute is for you to specify the fallback operation which most suits you.
The parameters are the same as in the scene_blend attribute; this is because multipass rendering IS effectively scene blending, since each layer is rendered on top of the last using the same mechanism as making an object transparent, it's just being rendered in the same place repeatedly to get the multitexture effect. If you use the simpler (and less flexible) colour_op attribute you don't need to call this as the system sets up the fallback for you.
'''
@ogredoc
class _ogredoc_TEX_alpha_op_ex( INFO_MT_ogre_helper ):
mydoc = '''
alpha_op_ex
Behaves in exactly the same away as colour_op_ex except that it determines how alpha values are combined between texture layers rather than colour values.The only difference is that the 2 manual colours at the end of colour_op_ex are just single floating-point values in alpha_op_ex.
'''
@ogredoc
class _ogredoc_TEX_env_map( INFO_MT_ogre_helper ):
mydoc = '''
env_map
Turns on/off texture coordinate effect that makes this layer an environment map.
Format: env_map <off|spherical|planar|cubic_reflection|cubic_normal>
Environment maps make an object look reflective by using automatic texture coordinate generation depending on the relationship between the objects vertices or normals and the eye.
@spherical
A spherical environment map. Requires a single texture which is either a fish-eye lens view of the reflected scene, or some other texture which looks good as a spherical map (a texture of glossy highlights is popular especially in car sims). This effect is based on the relationship between the eye direction and the vertex normals of the object, so works best when there are a lot of gradually changing normals, i.e. curved objects.
@planar
Similar to the spherical environment map, but the effect is based on the position of the vertices in the viewport rather than vertex normals. This effect is therefore useful for planar geometry (where a spherical env_map would not look good because the normals are all the same) or objects without normals.
@cubic_reflection
A more advanced form of reflection mapping which uses a group of 6 textures making up the inside of a cube, each of which is a view if the scene down each axis. Works extremely well in all cases but has a higher technical requirement from the card than spherical mapping. Requires that you bind a cubic_texture to this texture unit and use the 'combinedUVW' option.
@cubic_normal
Generates 3D texture coordinates containing the camera space normal vector from the normal information held in the vertex data. Again, full use of this feature requires a cubic_texture with the 'combinedUVW' option.
Default: env_map off
'''
@ogredoc
class _ogredoc_TEX_scroll( INFO_MT_ogre_helper ):
mydoc = '''
scroll
Sets a fixed scroll offset for the texture.
Format: scroll <x> <y>
This method offsets the texture in this layer by a fixed amount. Useful for small adjustments without altering texture coordinates in models. However if you wish to have an animated scroll effect, see the scroll_anim attribute.
[use mapping node location x and y]
'''
@ogredoc
class _ogredoc_TEX_scroll_anim( INFO_MT_ogre_helper ):
mydoc = '''
scroll_anim
@0.1 0.1
@0.5 0.5
@2.0 3.0
Sets up an animated scroll for the texture layer. Useful for creating fixed-speed scrolling effects on a texture layer (for varying scroll speeds, see wave_xform).
Format: scroll_anim <xspeed> <yspeed>
'''
@ogredoc
class _ogredoc_TEX_rotate( INFO_MT_ogre_helper ):
mydoc = '''
rotate
Rotates a texture to a fixed angle. This attribute changes the rotational orientation of a texture to a fixed angle, useful for fixed adjustments. If you wish to animate the rotation, see rotate_anim.
Format: rotate <angle>
The parameter is a anti-clockwise angle in degrees.
[ use mapping node rotation x ]
'''
@ogredoc
class _ogredoc_TEX_rotate_anim( INFO_MT_ogre_helper ):
mydoc = '''
rotate_anim
@0.1
@0.2
@0.4
Sets up an animated rotation effect of this layer. Useful for creating fixed-speed rotation animations (for varying speeds, see wave_xform).
Format: rotate_anim <revs_per_second>
The parameter is a number of anti-clockwise revolutions per second.
'''
@ogredoc
class _ogredoc_TEX_scale( INFO_MT_ogre_helper ):
mydoc = '''
scale
Adjusts the scaling factor applied to this texture layer. Useful for adjusting the size of textures without making changes to geometry. This is a fixed scaling factor, if you wish to animate this see wave_xform.
Format: scale <x_scale> <y_scale>
Valid scale values are greater than 0, with a scale factor of 2 making the texture twice as big in that dimension etc.
[ use mapping node scale x and y ]
'''
@ogredoc
class _ogredoc_TEX_wave_xform( INFO_MT_ogre_helper ):
mydoc = '''
wave_xform
@scale_x sine 1.0 0.2 0.0 5.0
Sets up a transformation animation based on a wave function. Useful for more advanced texture layer transform effects. You can add multiple instances of this attribute to a single texture layer if you wish.
Format: wave_xform <xform_type> <wave_type> <base> <frequency> <phase> <amplitude>
Example: wave_xform scale_x sine 1.0 0.2 0.0 5.0
xform_type:
scroll_x
Animate the x scroll value
scroll_y
Animate the y scroll value
rotate
Animate the rotate value
scale_x
Animate the x scale value
scale_y
Animate the y scale value
wave_type
sine
A typical sine wave which smoothly loops between min and max values
triangle
An angled wave which increases & decreases at constant speed, changing instantly at the extremes
square
Max for half the wavelength, min for the rest with instant transition between
sawtooth
Gradual steady increase from min to max over the period with an instant return to min at the end.
inverse_sawtooth
Gradual steady decrease from max to min over the period, with an instant return to max at the end.
base
The base value, the minimum if amplitude > 0, the maximum if amplitude < 0
frequency
The number of wave iterations per second, i.e. speed
phase
Offset of the wave start
amplitude
The size of the wave
The range of the output of the wave will be {base, base+amplitude}. So the example above scales the texture in the x direction between 1 (normal size) and 5 along a sine wave at one cycle every 5 second (0.2 waves per second).
'''
@ogredoc
class _ogredoc_TEX_transform( INFO_MT_ogre_helper ):
mydoc = '''
transform
@m00 m01 m02 m03 m10 m11 m12 m13 m20 m21 m22 m23 m30 m31 m32 m33
This attribute allows you to specify a static 4x4 transformation matrix for the texture unit, thus replacing the individual scroll, rotate and scale attributes mentioned above.
Format: transform m00 m01 m02 m03 m10 m11 m12 m13 m20 m21 m22 m23 m30 m31 m32 m33
The indexes of the 4x4 matrix value above are expressed as m<row><col>.
'''
def _mesh_entity_helper( doc, ob, o ):
## extended format - BGE Physics ##
o.setAttribute('mass', str(ob.game.mass))
o.setAttribute('mass_radius', str(ob.game.radius))
o.setAttribute('physics_type', ob.game.physics_type)
o.setAttribute('actor', str(ob.game.use_actor))
o.setAttribute('ghost', str(ob.game.use_ghost))
o.setAttribute('velocity_min', str(ob.game.velocity_min))
o.setAttribute('velocity_max', str(ob.game.velocity_max))
o.setAttribute('lock_trans_x', str(ob.game.lock_location_x))
o.setAttribute('lock_trans_y', str(ob.game.lock_location_y))
o.setAttribute('lock_trans_z', str(ob.game.lock_location_z))
o.setAttribute('lock_rot_x', str(ob.game.lock_rotation_x))
o.setAttribute('lock_rot_y', str(ob.game.lock_rotation_y))
o.setAttribute('lock_rot_z', str(ob.game.lock_rotation_z))
o.setAttribute('anisotropic_friction', str(ob.game.use_anisotropic_friction))
x,y,z = ob.game.friction_coefficients
o.setAttribute('friction_x', str(x))
o.setAttribute('friction_y', str(y))
o.setAttribute('friction_z', str(z))
o.setAttribute('damping_trans', str(ob.game.damping))
o.setAttribute('damping_rot', str(ob.game.rotation_damping))
o.setAttribute('inertia_tensor', str(ob.game.form_factor))
# Ogre supports .dds in both directx and opengl
# http://www.ogre3d.org/forums/viewtopic.php?f=5&t=46847
IMAGE_FORMATS = {
'dds',
'png',
'jpg'
}
#class _type(bpy.types.IDPropertyGroup):
# name = StringProperty(name="jpeg format", description="", maxlen=64, default="")
OptionsEx = {
'mesh-sub-dir' : False,
'shape-anim' : True,
'trim-bone-weights' : 0.01,
'armature-anim' : True,
'lodLevels' : 0,
'lodDistance' : 100,
'lodPercent' : 40,
'nuextremityPoints' : 0,
'generateEdgeLists' : False,
'generateTangents' : False,
'tangentSemantic' : "uvw",
'tangentUseParity' : 4,
'tangentSplitMirrored' : False,
'tangentSplitRotated' : False,
'reorganiseBuffers' : True,
'optimiseAnimations' : True,
}
class INFO_OT_createOgreExport(bpy.types.Operator):
'''Export Ogre Scene'''
bl_idname = "ogre.export"
bl_label = "Export Ogre"
bl_options = {'REGISTER', 'UNDO'}
filepath= StringProperty(name="File Path", description="Filepath used for exporting Ogre .scene file", maxlen=1024, default="")
#_force_image_format = None
## Options ##
EX_SCENE= BoolProperty(name="Export Scene", description="export current scene (OgreDotScene xml)", default=True)
EX_SELONLY = BoolProperty(name="Export Selected Only", description="export selected", default=True)
EX_FORCE_CAMERA = BoolProperty(name="Force Camera", description="export active camera", default=True)
EX_FORCE_LAMPS = BoolProperty(name="Force Lamps", description="export all lamps", default=True)
EX_MESH = BoolProperty(name="Export Meshes", description="export meshes", default=True)
EX_MESH_OVERWRITE = BoolProperty(name="Export Meshes (overwrite)", description="export meshes (overwrite existing files)", default=True)
EX_ANIM = BoolProperty(name="Armature Animation", description="export armature animations - updates the .skeleton file", default=True)
EX_SHAPE_ANIM = BoolProperty(name="Shape Animation", description="export shape animations - updates the .mesh file", default=True)
EX_LAYERS = BoolProperty(name="Active/All-Layers", description="toggle export active/all-layers", default=False)
EX_INSTANCES = BoolProperty(name="Optimize Instances", description="optimize instances in OgreDotScene xml", default=True)
EX_ARRAY = BoolProperty(name="Optimize Arrays", description="optimize array modifiers as instances (constant offset only)", default=True)
#EX_CONVERT_TEXTURES = BoolProperty( name="Enable Convert Textures", default=False )
#EX_IMAGE_FORMAT = CollectionProperty(IMAGE_FORMATS, type=_type, description="convert textures for platform\n\tinstall python -> c:\\python26\n\t\t.install PIL (http://www.pythonware.com/products/pil/)\n\tinstall Nvidia DDS tools http://developer.nvidia.com/object/dds_utilities_legacy.html")
EX_CONVERT_DDS = BoolProperty( name="Convert DDS Files", default=True )
#EX_DDS_TO_FORMAT = CollectionProperty({'jpg','png'}, description="convert only DDS textures to selected format", default='png')
#EX_TEX_SIZE_MAX = CollectionProperty({128,256,512,1024}, description="limit texture size to", default=512)
EX_LIMIT_TEX_SIZE = BoolProperty( name="Enable Limit Tex Size", default=False )
EX_MATERIALS = BoolProperty(name="Export Materials", description="exports .material script", default=True)
EX_MESH_SUBDIR = BoolProperty(name="Mesh Subdir", description="exports .mesh and .xml files to ./meshes subdirectory", default=False)
EX_TEXTURES_SUBDIR = BoolProperty(name="Texture Subdir", description="exports textures to ./textures subdirectory", default=False)
EX_FORCE_IMAGE = StringProperty(name="Convert Textures", description="convert texture maps using Image Magick (or Nvidia DDS)\nrequires image magick to be installed\ntype name of format or leave blank (do not convert)", maxlen=5, default="")
EX_DDS_MIPS = IntProperty(name="DDS Mips", description="number of mip maps (DDS)", default=3, min=0, max=16)
EX_SWAP_AXIS = BoolProperty(name="Swap Axis", description="fix up axis (swap y and z, and negate y)", default=False)
EX_TRIM_BONE_WEIGHTS = FloatProperty(name="Trim Weights", description="ignore bone weights below this value\n(Ogre may only support 4 bones per vertex", default=0.01, min=0.0, max=0.1)
lodLevels = IntProperty(name="LOD Levels", description="MESH number of LOD levels", default=0, min=0, max=32)
lodDistance = IntProperty(name="LOD Distance", description="MESH distance increment to reduce LOD", default=100, min=0, max=2000)
lodPercent = IntProperty(name="LOD Percentage", description="LOD percentage reduction", default=40, min=0, max=99)
nuextremityPoints = IntProperty(name="Extremity Points", description="MESH Extremity Points", default=0, min=0, max=65536)
generateEdgeLists = BoolProperty(name="Edge Lists", description="MESH generate edge lists (for stencil shadows)", default=False)
generateTangents = BoolProperty(name="Tangents", description="MESH generate tangents", default=False)
tangentSemantic = StringProperty(name="Tangent Semantic", description="MESH tangent semantic", maxlen=3, default="uvw")
tangentUseParity = IntProperty(name="Tangent Parity", description="MESH tangent use parity", default=4, min=0, max=16)
tangentSplitMirrored = BoolProperty(name="Tangent Split Mirrored", description="MESH split mirrored tangents", default=False)
tangentSplitRotated = BoolProperty(name="Tangent Split Rotated", description="MESH split rotated tangents", default=False)
reorganiseBuffers = BoolProperty(name="Reorganise Buffers", description="MESH reorganise vertex buffers", default=True)
optimiseAnimations = BoolProperty(name="Optimize Animations", description="MESH optimize animations", default=True)
@classmethod
def poll(cls, context): return True
def invoke(self, context, event):
wm= context.window_manager; wm.fileselect_add(self) # writes to filepath
return {'RUNNING_MODAL'}
def execute(self, context): self.ogre_export( self.filepath, context ); return {'FINISHED'}
def dot_material( self, meshes, path='/tmp' ):
print('updating .material')
mats = []
for ob in meshes:
if len(ob.data.materials):
for mat in ob.data.materials:
if mat not in mats: mats.append( mat )
if not mats: print('WARNING: no materials, not writting .material script'); return
M = MISSING_MATERIAL + '\n'
for mat in mats:
Report.materials.append( mat.name )
M += self.gen_dot_material( mat, path, convert_textures=True )
url = os.path.join(path, '%s.material' %bpy.context.scene.name)
f = open( url, 'wb' ); f.write( bytes(M,'utf-8') ); f.close()
print('saved', url)
## python note: classmethods prefer attributes defined at the classlevel, kinda makes sense, (even if called by an instance)
@classmethod
def gen_dot_material( self, mat, path='/tmp', convert_textures=False ): # TODO deprecated context_textures...
M = ''
M += 'material %s \n{\n' %mat.name
if mat.use_shadows: M += indent(1, 'receive_shadows on')
else: M += indent(1, 'receive_shadows off')
M += indent(1, 'technique', '{' ) # technique GLSL
#if mat.use_vertex_color_paint:
M += self.gen_dot_material_pass( mat, path, convert_textures )
M += indent(1, '}' ) # end technique
M += '}\n' # end material
return M
@classmethod
def gen_dot_material_pass( self, mat, path, convert_textures ):
print('gen_dot_material_pass', mat)
OPTIONS['PATH'] = path
M = ''
#if mat.node_tree and len(mat.node_tree.nodes):
if ShaderTree.valid_node_material( mat ):
print(' material has nodes')
tree = ShaderTree.parse( mat )
passes = tree.get_passes()
for P in passes:
print(' shader pass:', P)
M += P.dotmat_pass()
else:
print(' standard material')
tree = ShaderTree( material=mat )
M += tree.dotmat_pass()
return M
def dot_mesh( self, ob, path='/tmp', force_name=None, ignore_shape_animation=False ):
opts = {
'mesh-sub-dir' : self.EX_MESH_SUBDIR,
'shape-anim' : self.EX_SHAPE_ANIM,
'trim-bone-weights' : self.EX_TRIM_BONE_WEIGHTS,
'armature-anim' : self.EX_ANIM,
'lodLevels' : self.lodLevels,
'lodDistance' : self.lodDistance,
'lodPercent' : self.lodPercent,
'nuextremityPoints' : self.nuextremityPoints,
'generateEdgeLists' : self.generateEdgeLists,
'generateTangents' : self.generateTangents,
'tangentSemantic' : self.tangentSemantic,
'tangentUseParity' : self.tangentUseParity,
'tangentSplitMirrored' : self.tangentSplitMirrored,
'tangentSplitRotated' : self.tangentSplitRotated,
'reorganiseBuffers' : self.reorganiseBuffers,
'optimiseAnimations' : self.optimiseAnimations,
}
dot_mesh( ob, path, force_name, ignore_shape_animation=False, opts=opts )
def rex_entity( self, doc, ob ): # does rex flatten the hierarchy? or keep it like ogredotscene?
e = doc.createElement( 'entity' )
doc.documentElement.appendChild( e )
e.setAttribute('id', str(len(doc.documentElement.childNodes)) )
c = doc.createElement('component'); e.appendChild( c )
c.setAttribute('type', "EC_Mesh")
c.setAttribute('sync', '1')
a = doc.createElement('attribute'); c.appendChild(a)
a.setAttribute('name', "Mesh ref" )
a.setAttribute('value', "file://%s.mesh"%ob.data.name )
a = doc.createElement('attribute'); c.appendChild(a)
a.setAttribute('name', "Mesh materials" )
a.setAttribute('value', "file://%s.material"%bpy.context.scene.name )
if ob.find_armature():
a = doc.createElement('attribute'); c.appendChild(a)
a.setAttribute('name', "Skeleton ref" )
a.setAttribute('value', "file://%s.skeleton"%ob.data.name )
a = doc.createElement('attribute'); c.appendChild(a)
a.setAttribute('name', "Draw distance" )
a.setAttribute('value', "0" )
a = doc.createElement('attribute'); c.appendChild(a)
a.setAttribute('name', "Cast shadows" )
a.setAttribute('value', "false" )
c = doc.createElement('component'); e.appendChild( c )
c.setAttribute('type', "EC_Name")
c.setAttribute('sync', '1')
a = doc.createElement('attribute'); c.appendChild(a)
a.setAttribute('name', "name" )
a.setAttribute('value', ob.data.name )
a = doc.createElement('attribute'); c.appendChild(a)
a.setAttribute('name', "description" )
a.setAttribute('value', "" )
a = doc.createElement('attribute'); c.appendChild(a)
a.setAttribute('name', "user-defined" )
a.setAttribute('value', "false" )
c = doc.createElement('component'); e.appendChild( c )
c.setAttribute('type', "EC_Placeable")
c.setAttribute('sync', '1')
a = doc.createElement('attribute'); c.appendChild(a)
a.setAttribute('name', "Transform" )
loc = '%6f,%6f,%6f' %tuple(ob.matrix_world.translation_part())
rot = '%6f,%6f,%6f' %tuple(ob.matrix_world.rotation_part().to_euler())
scl = '%6f,%6f,%6f' %tuple(ob.matrix_world.scale_part())
a.setAttribute('value', "%s,%s,%s" %(loc,rot,scl) )
a = doc.createElement('attribute'); c.appendChild(a)
a.setAttribute('name', "Show bounding box" )
a.setAttribute('value', "false" )
## realXtend internal Naali format ##
if ob.game.physics_type == 'RIGID_BODY':
com = doc.createElement('component'); e.appendChild( com )
com.setAttribute('type', 'EC_RigidBody')
com.setAttribute('sync', '1')
a = doc.createElement('attribute'); com.appendChild( a )
a.setAttribute('name', 'Mass')
a.setAttribute('value', str(ob.game.mass))
a = doc.createElement('attribute'); com.appendChild( a )
a.setAttribute('name', 'Friction')
avg = sum( ob.game.friction_coefficients ) / 3.0
a.setAttribute('value', str(avg))
a = doc.createElement('attribute'); com.appendChild( a )
a.setAttribute('name', 'Linear damping')
a.setAttribute('value', str(ob.game.damping))
a = doc.createElement('attribute'); com.appendChild( a )
a.setAttribute('name', 'Angular damping')
a.setAttribute('value', str(ob.game.rotation_damping))
a = doc.createElement('attribute'); com.appendChild( a )
a.setAttribute('name', 'Phantom') # is this no collide or hide from view?
a.setAttribute('value', str(ob.game.use_ghost).lower() )
def ogre_export(self, url, context ):
global OPTIONS
OPTIONS['TEXTURES_SUBDIR'] = self.EX_TEXTURES_SUBDIR
OPTIONS['FORCE_IMAGE_FORMAT'] = None
OPTIONS['TOUCH_TEXTURES'] = True
OPTIONS['SWAP_AXIS'] = self.EX_SWAP_AXIS
OPTIONS['BLOCKING'] = False
Report.reset()
if self.EX_FORCE_IMAGE:
fmt = self.EX_FORCE_IMAGE.lower()
if not fmt.startswith('.'): fmt = '.'+fmt
OPTIONS['FORCE_IMAGE_FORMAT'] = fmt
meshes = []
mesh_collision_prims = {}
mesh_collision_files = {}
print('ogre export->', url)
prefix = url.split('.')[0]
rex = dom.Document() # realxtend .rex
rex.appendChild( rex.createElement('scene') )
doc = dom.Document()
scn = doc.createElement('scene')
doc.appendChild( scn )
nodes = doc.createElement('nodes')
extern = doc.createElement('externals')
environ = doc.createElement('environment')
for n in (nodes,extern,environ): scn.appendChild( n )
############################
## extern files ##
item = doc.createElement('item'); extern.appendChild( item )
item.setAttribute('type','material')
a = doc.createElement('file'); item.appendChild( a )
a.setAttribute('name', '%s.material' %context.scene.name) # .material file (scene mats)
## environ settings ##
world = context.scene.world
_c = {'colorAmbient':world.ambient_color, 'colorBackground':world.horizon_color, 'colorDiffuse':world.horizon_color}
for ctag in _c:
a = doc.createElement(ctag); environ.appendChild( a )
color = _c[ctag]
a.setAttribute('r', '%s'%color.r)
a.setAttribute('g', '%s'%color.g)
a.setAttribute('b', '%s'%color.b)
if world.mist_settings.use_mist:
a = doc.createElement('fog'); environ.appendChild( a )
a.setAttribute('linearStart', '%s'%world.mist_settings.start )
a.setAttribute('mode', world.mist_settings.falloff.lower() ) # only linear supported?
a.setAttribute('linearEnd', '%s' %(world.mist_settings.start+world.mist_settings.depth))
## nodes (objects) ##
objects = [] # gather because macros will change selection state
for ob in bpy.data.objects:
if ob.name.startswith('collision'): continue
if self.EX_SELONLY and not ob.select:
if ob.type == 'CAMERA' and self.EX_FORCE_CAMERA: pass
elif ob.type == 'LAMP' and self.EX_FORCE_LAMPS: pass
else: continue
objects.append( ob )
## find merge groups
mgroups = []
mobjects = []
for ob in objects:
group = get_merge_group( ob )
if group:
for member in group.objects:
if member not in mobjects: mobjects.append( member )
if group not in mgroups: mgroups.append( group )
for rem in mobjects:
if rem in objects: objects.remove( rem )
temps = []
for group in mgroups:
merged = merge_group( group )
objects.append( merged )
temps.append( merged )
## gather roots because ogredotscene supports parents and children ##
def _flatten( _c, _f ):
if _c.parent in objects: _f.append( _c.parent )
if _c.parent: _flatten( _c.parent, _f )
else: _f.append( _c )
roots = []
for ob in objects:
flat = []
_flatten( ob, flat )
root = flat[-1]
if root not in roots: roots.append( root )
exported_meshes = [] # don't export same data multiple times
for root in roots:
print('--------------- exporting root ->', root )
self._node_export( root,
url=url, doc = doc, rex = rex,
exported_meshes = exported_meshes,
meshes = meshes,
mesh_collision_prims = mesh_collision_prims,
mesh_collision_files = mesh_collision_files,
prefix = prefix,
objects=objects,
xmlparent=nodes
)
if self.EX_SCENE:
data = rex.toprettyxml()
f = open( url+'.rex', 'wb' ); f.write( bytes(data,'utf-8') ); f.close()
print('realxtend scene dumped', url)
data = doc.toprettyxml()
if not url.endswith('.scene'): url += '.scene'
f = open( url, 'wb' ); f.write( bytes(data,'utf-8') ); f.close()
print('ogre scene dumped', url)
if self.EX_MATERIALS: self.dot_material( meshes, os.path.split(url)[0] )
for ob in temps:
context.scene.objects.unlink( ob )
OPTIONS['BLOCKING'] = True
bpy.ops.wm.call_menu( name='Ogre_User_Report' )
############# node export - recursive ###############
def _node_export( self, ob, url='', doc=None, rex=None, exported_meshes=[], meshes=[], mesh_collision_prims={}, mesh_collision_files={}, prefix='', objects=[], xmlparent=None ):
o = _ogre_node_helper( doc, ob, objects )
xmlparent.appendChild(o)
## custom user props ##
for prop in ob.items():
propname, propvalue = prop
if not propname.startswith('_'):
user = doc.createElement('user_data')
o.appendChild( user )
user.setAttribute( 'name', propname )
user.setAttribute( 'value', str(propvalue) )
user.setAttribute( 'type', type(propvalue).__name__ )
## BGE subset ##
game = doc.createElement('game')
o.appendChild( game )
sens = doc.createElement('sensors')
game.appendChild( sens )
acts = doc.createElement('actuators')
game.appendChild( acts )
for sen in ob.game.sensors:
sens.appendChild( WrapSensor(sen).xml(doc) )
for act in ob.game.actuators:
acts.appendChild( WrapActuator(act).xml(doc) )
if ob.type == 'MESH' and len(ob.data.faces):
self.rex_entity( rex, ob ) # is dotREX flat?
collisionFile = None
collisionPrim = None
if ob.data.name in mesh_collision_prims: collisionPrim = mesh_collision_prims[ ob.data.name ]
if ob.data.name in mesh_collision_files: collisionFile = mesh_collision_files[ ob.data.name ]
meshes.append( ob )
e = doc.createElement('entity')
o.appendChild(e); e.setAttribute('name', ob.data.name)
prefix = ''
if self.EX_MESH_SUBDIR: prefix = 'meshes/'
e.setAttribute('meshFile', '%s%s.mesh' %(prefix,ob.data.name) )
if not collisionPrim and not collisionFile:
if ob.game.use_collision_bounds:
collisionPrim = ob.game.collision_bounds_type.lower()
mesh_collision_prims[ ob.data.name ] = collisionPrim
else:
for child in ob.children:
if child.name.startswith('collision'): # double check, instances with decimate modifier are ok?
collisionFile = '%s_collision_%s.mesh' %(prefix,ob.data.name)
break
if collisionFile:
mesh_collision_files[ ob.data.name ] = collisionFile
self.dot_mesh(
child,
path=os.path.split(url)[0],
force_name='_collision_%s' %ob.data.name
)
if collisionPrim: e.setAttribute('collisionPrim', collisionPrim )
elif collisionFile: e.setAttribute('collisionFile', collisionFile )
_mesh_entity_helper( doc, ob, e )
if self.EX_MESH:
murl = os.path.join( os.path.split(url)[0], '%s.mesh'%ob.data.name )
exists = os.path.isfile( murl )
if not exists or (exists and self.EX_MESH_OVERWRITE):
if ob.data.name not in exported_meshes:
exported_meshes.append( ob.data.name )
self.dot_mesh( ob, os.path.split(url)[0] )
## deal with Array mod ##
vecs = [ ob.matrix_world.translation_part() ]
for mod in ob.modifiers:
if mod.type == 'ARRAY':
if mod.fit_type != 'FIXED_COUNT':
print( 'WARNING: unsupport array-modifier type->', mod.fit_type )
continue
if not mod.use_constant_offset:
print( 'WARNING: unsupport array-modifier mode, must be "constant offset" type' )
continue
else:
#v = ob.matrix_world.translation_part()
newvecs = []
for prev in vecs:
for i in range( mod.count-1 ):
v = prev + mod.constant_offset_displace
newvecs.append( v )
ao = _ogre_node_helper( doc, ob, objects, prefix='_array_%s_'%len(vecs+newvecs), pos=v )
xmlparent.appendChild(ao)
e = doc.createElement('entity')
ao.appendChild(e); e.setAttribute('name', ob.data.name)
if self.EX_MESH_SUBDIR: e.setAttribute('meshFile', 'meshes/%s.mesh' %ob.data.name)
else: e.setAttribute('meshFile', '%s.mesh' %ob.data.name)
if collisionPrim: e.setAttribute('collisionPrim', collisionPrim )
elif collisionFile: e.setAttribute('collisionFile', collisionFile )
vecs += newvecs
elif ob.type == 'CAMERA':
Report.cameras.append( ob.name )
c = doc.createElement('camera')
o.appendChild(c); c.setAttribute('name', ob.data.name)
aspx = bpy.context.scene.render.pixel_aspect_x
aspy = bpy.context.scene.render.pixel_aspect_y
sx = bpy.context.scene.render.resolution_x
sy = bpy.context.scene.render.resolution_y
fovY = 0.0
if (sx*aspx > sy*aspy):
fovY = 2*math.atan(sy*aspy*16.0/(ob.data.lens*sx*aspx))
else:
fovY = 2*math.atan(16.0/ob.data.lens)
# fov in degree
fov = fovY*180.0/math.pi
c.setAttribute('fov', '%s'%fov)
c.setAttribute('projectionType', "perspective")
a = doc.createElement('clipping'); c.appendChild( a )
a.setAttribute('nearPlaneDist', '%s' %ob.data.clip_start)
a.setAttribute('farPlaneDist', '%s' %ob.data.clip_end)
elif ob.type == 'LAMP':
Report.lights.append( ob.name )
l = doc.createElement('light')
o.appendChild(l); l.setAttribute('name', ob.data.name)
l.setAttribute('type', ob.data.type.lower() )
a = doc.createElement('lightAttenuation'); l.appendChild( a )
a.setAttribute('range', '5000' ) # is this an Ogre constant?
a.setAttribute('constant', '1.0') # TODO support quadratic light
a.setAttribute('linear', '%s'%(1.0/ob.data.distance))
a.setAttribute('quadratic', '0.0')
## actually need to precompute light brightness by adjusting colors below ##
if ob.data.use_diffuse:
a = doc.createElement('colorDiffuse'); l.appendChild( a )
a.setAttribute('r', '%s'%ob.data.color.r)
a.setAttribute('g', '%s'%ob.data.color.g)
a.setAttribute('b', '%s'%ob.data.color.b)
if ob.data.use_specular:
a = doc.createElement('colorSpecular'); l.appendChild( a )
a.setAttribute('r', '%s'%ob.data.color.r)
a.setAttribute('g', '%s'%ob.data.color.g)
a.setAttribute('b', '%s'%ob.data.color.b)
## bug reported by C.L.B ##
if ob.data.type != 'HEMI': # hemi lights should actually provide info for fragment/vertex-program ambient shaders
if ob.data.shadow_method != 'NOSHADOW': # just a guess - is this Ogre API?
a = doc.createElement('colorShadow'); l.appendChild( a )
a.setAttribute('r', '%s'%ob.data.color.r)
a.setAttribute('g', '%s'%ob.data.color.g)
a.setAttribute('b', '%s'%ob.data.color.b)
l.setAttribute('shadow','true')
for child in ob.children:
self._node_export( child,
url = url, doc = doc, rex = rex,
exported_meshes = exported_meshes,
meshes = meshes,
mesh_collision_prims = mesh_collision_prims,
mesh_collision_files = mesh_collision_files,
prefix = prefix,
objects=objects,
xmlparent=o
)
## end _node_export
def get_parent_matrix( ob, objects ):
if not ob.parent: return mathutils.Matrix([1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1])
else:
if ob.parent in objects: return ob.parent.matrix_world.copy()
else: return get_parent_matrix( ob.parent, objects )
def _ogre_node_helper( doc, ob, objects, prefix='', pos=None, rot=None, scl=None ):
mat = get_parent_matrix(ob, objects).invert() * ob.matrix_world
o = doc.createElement('node')
o.setAttribute('name',prefix+ob.name)
p = doc.createElement('position')
q = doc.createElement('quaternion')
s = doc.createElement('scale')
for n in (p,q,s): o.appendChild(n)
if pos: v = swap(pos)
else: v = swap( mat.translation_part() )
p.setAttribute('x', '%6f'%v.x)
p.setAttribute('y', '%6f'%v.y)
p.setAttribute('z', '%6f'%v.z)
if rot: v = swap(rot)
else: v = swap( mat.rotation_part().to_quat() )
q.setAttribute('x', '%6f'%v.x)
q.setAttribute('y', '%6f'%v.y)
q.setAttribute('z', '%6f'%v.z)
q.setAttribute('w','%6f'%v.w)
if scl: # this should not be used
v = swap(scl)
s.setAttribute('x', '%6f'%v.x)
s.setAttribute('y', '%6f'%v.y)
s.setAttribute('z', '%6f'%v.z)
else: # scale is different in Ogre from blender
ri = mat.rotation_part().to_quat().inverse().to_matrix()
scale = ri.to_4x4() * mat
## do not use swap() because that negates the y axis
if OPTIONS['SWAP_AXIS']:
s.setAttribute('x', '%6f' %scale[0][0])
s.setAttribute('y', '%6f' %scale[2][2])
s.setAttribute('z', '%6f' %scale[1][1])
else:
s.setAttribute('x', '%6f' %scale[0][0])
s.setAttribute('y', '%6f' %scale[1][1])
s.setAttribute('z', '%6f' %scale[2][2])
return o
def merge_group( group ):
print('--------------- merge group ->', group )
copies = []
for ob in group.objects:
if ob.type == 'MESH':
print( '\t group member', ob.name )
o2 = ob.copy(); copies.append( o2 )
o2.data = o2.create_mesh(bpy.context.scene, True, "PREVIEW") # collaspe modifiers
while o2.modifiers: o2.modifiers.remove( o2.modifiers[0] )
bpy.context.scene.objects.link( o2 )#; o2.select = True
merged = merge( copies )
merged.name = group.name
merged.data.name = group.name
return merged
def merge( objects ):
for ob in bpy.context.selected_objects: ob.select = False
for ob in objects: ob.select = True
bpy.context.scene.objects.active = ob
bpy.ops.object.join()
return bpy.context.active_object
def get_merge_group( ob, prefix='merge' ):
m = []
for grp in ob.users_group:
if grp.name.lower().startswith(prefix): m.append( grp )
if len(m)==1:
#if ob.data.users != 1:
# print( 'WARNING: an instance can not be in a merge group' )
# return
return m[0]
elif m:
print('WARNING: an object can not be in two merge groups at the same time', ob)
return
############ Ogre Command Line Tools ###########
class MeshMagick(object):
''' Usage: MeshMagick [global_options] toolname [tool_options] infile(s) -- [outfile(s)]
Available Tools
===============
info - print information about the mesh.
meshmerge - Merge multiple submeshes into a single mesh.
optimise - Optimise meshes and skeletons.
rename - Rename different elements of meshes and skeletons.
transform - Scale, rotate or otherwise transform a mesh.
'''
@staticmethod
def get_merge_group( ob ): return get_merge_group( ob, prefix='magicmerge' )
@staticmethod
def merge( group, path='/tmp', force_name=None ):
print('-'*80)
print(' mesh magick - merge ')
exe = os.path.join(OGRETOOLS, 'MeshMagick.exe')
if not os.path.isfile( exe ):
print( 'ERROR: can not find MeshMagick.exe' )
print( exe )
return
files = []
for ob in group.objects:
if ob.data.users == 1: # single users only
files.append( os.path.join( path, ob.data.name+'.mesh' ) )
print( files[-1] )
opts = 'meshmerge'
if sys.platform == 'linux2': cmd = '/usr/bin/wine %s %s' %(exe, opts)
else: cmd = '%s %s' %(exe, opts)
if force_name: output = force_name + '.mesh'
else: output = '_%s_.mesh' %group.name
cmd = cmd.split() + files + ['--', os.path.join(path,output) ]
subprocess.call( cmd )
print(' mesh magick - complete ')
print('-'*80)
_ogre_command_line_tools_doc = '''
Bug reported by CLB: converter expects .mesh.xml or .skeleton.xml to determine the type - fixed nov24
Usage: OgreXMLConverter [options] sourcefile [destfile]
Available options:
-i = interactive mode - prompt for options
(The next 4 options are only applicable when converting XML to Mesh)
-l lodlevels = number of LOD levels
-d loddist = distance increment to reduce LOD
-p lodpercent = Percentage triangle reduction amount per LOD
-f lodnumtris = Fixed vertex reduction per LOD
-e = DON'T generate edge lists (for stencil shadows)
-r = DON'T reorganise vertex buffers to OGRE recommended format.
-t = Generate tangents (for normal mapping)
-o = DON'T optimise out redundant tracks & keyframes
-d3d = Prefer D3D packed colour formats (default on Windows)
-gl = Prefer GL packed colour formats (default on non-Windows)
-E endian = Set endian mode 'big' 'little' or 'native' (default)
-q = Quiet mode, less output
-log filename = name of the log file (default: 'OgreXMLConverter.log')
sourcefile = name of file to convert
destfile = optional name of file to write to. If you don't
specify this OGRE works it out through the extension
and the XML contents if the source is XML. For example
test.mesh becomes test.xml, test.xml becomes test.mesh
if the XML document root is <mesh> etc.
'''
def OgreXMLConverter( infile, opts ):
print('[Ogre Tools Wrapper]', infile )
exe = os.path.join(OGRETOOLS,'OgreXmlConverter.exe')
if not os.path.isfile( exe ):
print( 'ERROR: can not find OgreXmlConverter.exe' )
print( exe )
return
basicArguments = ''
if opts['lodLevels']:
basicArguments += ' -l %s -d %s -p %s' %(opts['lodLevels'], opts['lodDistance'], opts['lodPercent'])
if opts['nuextremityPoints'] > 0:
basicArguments += ' -x %s' %opts['nuextremityPoints']
if not opts['generateEdgeLists']:
basicArguments += ' -e'
if opts['generateTangents']:
basicArguments += ' -t'
if opts['tangentSemantic']:
basicArguments += ' -td %s' %opts['tangentSemantic']
if opts['tangentUseParity']:
basicArguments += ' -ts %s' %opts['tangentUseParity']
if opts['tangentSplitMirrored']:
basicArguments += ' -tm'
if opts['tangentSplitRotated']:
basicArguments += ' -tr'
if not opts['reorganiseBuffers']:
basicArguments += ' -r'
if not opts['optimiseAnimations']:
basicArguments += ' -o'
opts = '-log _ogre_debug.txt %s' %basicArguments
path,name = os.path.split( infile )
#if infile.endswith('_mesh'): # THANKS TO CLB
# outfile = os.path.join(path, name.split('.xml')[0]+'.mesh')
#elif infile.endswith('_skeleton'):
# outfile = os.path.join(path, name.split('.xml')[0]+'.skeleton')
if sys.platform == 'linux2': cmd = '/usr/bin/wine %s %s' %(exe, opts)
else: cmd = '%s %s' %(exe, opts)
print(cmd)
cmd = cmd.split() + [infile] #, outfile] #[ infile.replace(' ','\\ '), outfile.replace(' ','\\ ') ]
## this is not the bottle neck, smooth normal look up is ##
#if MULTIPROCESS and not OPTIONS['BLOCKING']:
# print( 'subprocess (nonblocking mode)' )
# subprocess.Popen( cmd )
#else:
# print( 'subprocess (blocking mode)' )
subprocess.call( cmd )
#if not os.path.isfile( outfile ): print('warning: OgreXmlConverter failed')
def find_bone_index( ob, arm, groupidx): # sometimes the groups are out of order, this finds the right index.
vg = ob.vertex_groups[ groupidx ]
for i,bone in enumerate(arm.pose.bones):
if bone.name == vg.name: return i
def mesh_is_smooth( mesh ):
for face in mesh.faces:
if face.use_smooth: return True
def dot_mesh( ob, path='/tmp', force_name=None, ignore_shape_animation=False, opts=OptionsEx ):
print('mesh to Ogre mesh XML format', ob.name)
if not os.path.isdir( path ):
print('creating directory', path )
os.makedirs( path )
Report.meshes.append( ob.data.name )
Report.faces += len( ob.data.faces )
Report.vertices += len( ob.data.vertices )
copy = ob.copy()
rem = []
for mod in copy.modifiers: # remove armature and array modifiers before collaspe
if mod.type in 'ARMATURE ARRAY'.split(): rem.append( mod )
for mod in rem: copy.modifiers.remove( mod )
## bake mesh ##
_mesh_normals = copy.create_mesh(bpy.context.scene, True, "PREVIEW") # collaspe
_lookup_normals = mesh_is_smooth( _mesh_normals )
## hijack blender's edge-split modifier to make this easy ##
e = copy.modifiers.new('_hack_', type='EDGE_SPLIT')
e.use_edge_angle = False
e.use_edge_sharp = True
for edge in copy.data.edges: edge.use_edge_sharp = True
## bake mesh ##
mesh = copy.create_mesh(bpy.context.scene, True, "PREVIEW") # collaspe
prefix = ''
if opts['mesh-sub-dir']: #self.EX_MESH_SUBDIR:
mdir = os.path.join(path,'meshes')
if not os.path.isdir( mdir ): os.mkdir( mdir )
prefix = 'meshes/'
doc = dom.Document()
root = doc.createElement('mesh'); doc.appendChild( root )
sharedgeo = doc.createElement('sharedgeometry')
root.appendChild( sharedgeo )
sharedgeo.setAttribute('vertexcount', '%s' %len(mesh.vertices))
if len(mesh.vertices) > 65535:
sharedgeo.setAttribute("use32bitindexes", 'true')
subs = doc.createElement('submeshes')
root.appendChild( subs )
arm = ob.find_armature()
if arm:
skel = doc.createElement('skeletonlink')
skel.setAttribute('name', '%s%s.skeleton' %(prefix, force_name or ob.data.name) )
root.appendChild( skel )
## verts ##
print(' writing shared geometry')
#geo = doc.createElement('geometry')
#sm.appendChild( geo )
#geo.setAttribute('vertexcount', '%s' %len(mesh.vertices))
vb = doc.createElement('vertexbuffer')
vb.setAttribute('positions','true')
#buffix dec8th#vb.setAttribute('normals','true')
hasnormals = False
sharedgeo.appendChild( vb )
if arm:
bweights = doc.createElement('boneassignments')
root.appendChild( bweights )
if opts['shape-anim'] and ob.data.shape_keys and len(ob.data.shape_keys.keys):
print(' writing shape animation')
poses = doc.createElement('poses'); root.appendChild( poses )
for sidx, skey in enumerate(ob.data.shape_keys.keys):
if sidx == 0: continue
pose = doc.createElement('pose'); poses.appendChild( pose )
pose.setAttribute('name', skey.name)
pose.setAttribute('index', str(sidx-1))
pose.setAttribute('target', 'mesh') # If target is 'mesh', targets the shared geometry, if target is submesh, targets the submesh identified by 'index'.
for i,p in enumerate( skey.data ):
x,y,z = swap( ob.data.vertices[i].co - p.co )
if x==.0 and y==.0 and z==.0: continue # the older exporter optimized this way, is it safe?
po = doc.createElement('poseoffset'); pose.appendChild( po )
po.setAttribute('x', '%6f' %x)
po.setAttribute('y', '%6f' %y)
po.setAttribute('z', '%6f' %z)
po.setAttribute('index', str(i)) # this was 3 values in old exporter, from triangulation?
if ob.data.shape_keys.animation_data and len(ob.data.shape_keys.animation_data.nla_tracks):
anims = doc.createElement('animations'); root.appendChild( anims )
for nla in ob.data.shape_keys.animation_data.nla_tracks:
strip = nla.strips[0]
anim = doc.createElement('animation'); anims.appendChild( anim )
anim.setAttribute('name', nla.name) # do not use the action's name
anim.setAttribute('length', str((strip.frame_end-strip.frame_start)/30.0) ) # TODO proper fps
tracks = doc.createElement('tracks'); anim.appendChild( tracks )
track = doc.createElement('track'); tracks.appendChild( track )
track.setAttribute('type','pose')
track.setAttribute('target','mesh')
track.setAttribute('index','0')
keyframes = doc.createElement('keyframes')
track.appendChild( keyframes )
for frame in range( int(strip.frame_start), int(strip.frame_end), 2): # every other frame
bpy.context.scene.frame_current = frame
keyframe = doc.createElement('keyframe')
keyframes.appendChild( keyframe )
keyframe.setAttribute('time', str(frame/30.0))
for sidx, skey in enumerate( ob.data.shape_keys.keys ):
if sidx == 0: continue
poseref = doc.createElement('poseref'); keyframe.appendChild( poseref )
poseref.setAttribute('poseindex', str(sidx))
poseref.setAttribute('influence', str(skey.value) )
## write all verts, even if not in material index, inflates xml, should not bloat .mesh (TODO is this true?)
print(' writing vertex data' )
badverts = 0
for vidx, v in enumerate(mesh.vertices):
if arm:
check = 0
for vgroup in v.groups:
if vgroup.weight > opts['trim-bone-weights']: #self.EX_TRIM_BONE_WEIGHTS: # optimized
bnidx = find_bone_index(copy,arm,vgroup.group)
if bnidx is not None: # allows other vertex groups, not just armature vertex groups
vba = doc.createElement('vertexboneassignment')
bweights.appendChild( vba )
vba.setAttribute( 'vertexindex', str(vidx) )
vba.setAttribute( 'boneindex', str(bnidx) )
vba.setAttribute( 'weight', str(vgroup.weight) )
check += 1
if check > 4:
badverts += 1
print('WARNING: vertex %s is in more than 4 vertex groups (bone weights)\n(this maybe Ogre incompatible)' %vidx)
vertex = doc.createElement('vertex')
p = doc.createElement('position')
n = doc.createElement('normal')
vb.appendChild( vertex )
vertex.appendChild( p )
vertex.appendChild( n )
x,y,z = swap( v.co )
p.setAttribute('x', '%6f' %x)
p.setAttribute('y', '%6f' %y)
p.setAttribute('z', '%6f' %z)
## edge_split modifier causes normals to break
# this can not be done because the indices have changed
#ov = _mesh_normals.vertices[ vidx ]
#hasnormals = True
#x,y,z = swap( ov.normal )
#n.setAttribute('x', str(x))
#n.setAttribute('y', str(y))
#n.setAttribute('z', str(z))
if _lookup_normals:
# this is very expensive (TODO manual face split - get rid of edgesplit-mod-hack)
for ov in _mesh_normals.vertices: #fixed dec8th ob.data.vertices:
if ov.co == v.co:
hasnormals = True
x,y,z = swap( ov.normal )
n.setAttribute('x', '%6f' %x)
n.setAttribute('y', '%6f' %y)
n.setAttribute('z', '%6f' %z)
break
else:
hasnormals = True
x,y,z = swap( v.normal )
n.setAttribute('x', '%6f' %x)
n.setAttribute('y', '%6f' %y)
n.setAttribute('z', '%6f' %z)
## vertex colors ##
if len( mesh.vertex_colors ): # TODO need to do proper face lookup for color1,2,3,4
vb.setAttribute('colours_diffuse','true') # fixed Dec3rd
cd = doc.createElement( 'colour_diffuse' ) #'color_diffuse')
vertex.appendChild( cd )
vchan = mesh.vertex_colors[0]
valpha = None ## hack support for vertex color alpha
for bloc in mesh.vertex_colors:
if bloc.name.lower().startswith('alpha'):
valpha = bloc; break
for f in mesh.faces:
if vidx in f.vertices:
k = list(f.vertices).index(vidx)
r,g,b = getattr( vchan.data[ f.index ], 'color%s'%(k+1) )
if valpha:
ra,ga,ba = getattr( valpha.data[ f.index ], 'color%s'%(k+1) )
cd.setAttribute('value', '%6f %6f %6f %6f' %(r,g,b,ra) )
else:
cd.setAttribute('value', '%6f %6f %6f 1.0' %(r,g,b) )
break
## texture maps ##
if mesh.uv_textures.active:
vb.setAttribute('texture_coords', '%s' %len(mesh.uv_textures) )
for layer in mesh.uv_textures:
for fidx, uvface in enumerate(layer.data):
face = mesh.faces[ fidx ]
if vidx in face.vertices:
uv = uvface.uv[ list(face.vertices).index(vidx) ]
tcoord = doc.createElement('texcoord')
tcoord.setAttribute('u', '%6f' %uv[0] )
tcoord.setAttribute('v', '%6f' %(1.0-uv[1]) )
#tcoord.setAttribute('v', '%6f' %uv[1] )
vertex.appendChild( tcoord )
break
## end vert loop
if hasnormals: vb.setAttribute('normals','true')
#else: vb.setAttribute('normals','false')
if badverts:
Report.warnings.append( '%s has %s vertices weighted to too many bones (Ogre limits a vertex to 4 bones)\n[try increaseing the Trim-Weights threshold option]' %(mesh.name, badverts) )
######################################################
used_materials = []
matnames = []
for mat in ob.data.materials:
if mat: matnames.append( mat.name )
else: print('warning: bad material data', ob)
if not matnames: matnames.append( '_missing_material_' )
print(' writing submeshes' )
for matidx, matname in enumerate( matnames ):
if not len(mesh.faces): # bug fix dec10th, reported by Matti
print('WARNING: submesh without faces, skipping!', ob)
continue
sm = doc.createElement('submesh') # material split?
sm.setAttribute('usesharedvertices', 'true')
sm.setAttribute('material', matname)
subs.appendChild( sm )
## faces ##
faces = doc.createElement('faces')
for F in mesh.faces: #ob.data.faces:
## skip faces not in this material index ##
if F.material_index != matidx: continue
if matname not in used_materials: used_materials.append( matname )
## Ogre only supports triangles
tris = []
tris.append( (F.vertices[0], F.vertices[1], F.vertices[2]) )
if len(F.vertices) >= 4: #TODO split face on shortest edge? or will that mess up triangle-strips?
#correct-but-flipped#tris.append( (F.vertices[2], F.vertices[0], F.vertices[3]) )
tris.append( (F.vertices[0], F.vertices[2], F.vertices[3]) )
for tri in tris:
v1,v2,v3 = tri
face = doc.createElement('face')
face.setAttribute('v1', str(v1))
face.setAttribute('v2', str(v2))
face.setAttribute('v3', str(v3))
faces.appendChild(face)
faces.setAttribute('count', '%s' %len(faces.childNodes))
Report.triangles += len(faces.childNodes)
sm.appendChild( faces )
bpy.data.objects.remove(copy)
bpy.data.meshes.remove(mesh)
name = force_name or ob.data.name
data = doc.documentElement.toprettyxml()
xmlfile = os.path.join(path, '%s%s.mesh.xml' %(prefix,name) )
f = open( xmlfile, 'wb' )
f.write( bytes(data,'utf-8') )
f.close()
OgreXMLConverter( xmlfile, opts )
if arm and opts['armature-anim']: #self.EX_ANIM:
skel = Skeleton( ob )
data = skel.to_xml()
name = force_name or ob.data.name
xmlfile = os.path.join(path, '%s%s.skeleton.xml' %(prefix,name) )
f = open( xmlfile, 'wb' )
f.write( bytes(data,'utf-8') )
f.close()
OgreXMLConverter( xmlfile, opts )
mats = []
for name in used_materials:
if name != '_missing_material_':
mats.append( bpy.data.materials[name] )
return mats
## end dot_mesh ##
class Bone(object):
''' EditBone
['__doc__', '__module__', '__slots__', 'align_orientation', 'align_roll', 'bbone_in', 'bbone_out', 'bbone_segments', 'bl_rna', 'envelope_distance', 'envelope_weight', 'head', 'head_radius', 'hide', 'hide_select', 'layers', 'lock', 'matrix', 'name', 'parent', 'rna_type', 'roll', 'select', 'select_head', 'select_tail', 'show_wire', 'tail', 'tail_radius', 'transform', 'use_connect', 'use_cyclic_offset', 'use_deform', 'use_envelope_multiply', 'use_inherit_rotation', 'use_inherit_scale', 'use_local_location']
'''
def update(self): # called on frame update
pose = self.bone.matrix * self.skeleton.object_space_transformation
pose = self.skeleton.object_space_transformation * self.bone.matrix
self._inverse_total_trans_pose = pose.copy().invert()
# calculate difference to parent bone
if self.parent:
pose = self.parent._inverse_total_trans_pose * pose
#elif self.fixUpAxis:
# pose = mathutils.Matrix([1,0,0,0],[0,0,-1,0],[0,1,0,0],[0,0,0,1]) * pose
# get transformation values
# translation relative to parent coordinate system orientation
# and as difference to rest pose translation
#blender2.49#translation -= self.ogreRestPose.translationPart()
self.pose_location = pose.translation_part() - self.ogre_rest_matrix.translation_part()
# rotation (and scale) relative to local coordiante system
# calculate difference to rest pose
#blender2.49#poseTransformation *= self.inverseOgreRestPose
#pose = pose * self.inverse_ogre_rest_matrix # this was wrong, fixed Dec3rd
pose = self.inverse_ogre_rest_matrix * pose
self.pose_rotation = pose.rotation_part().to_quat()
self.pose_scale = pose.scale_part().copy()
#self.pose_location = self.bone.location.copy()
#self.pose_rotation = self.bone.rotation_quaternion.copy()
for child in self.children: child.update()
def __init__(self, matrix, pbone, skeleton):
self.skeleton = skeleton
self.name = pbone.name
self.matrix = matrix
#self.matrix *= mathutils.Matrix([1,0,0,0],[0,0,-1,0],[0,1,0,0],[0,0,0,1])
self.bone = pbone # safe to hold pointer to pose bone, not edit bone!
if not pbone.bone.use_deform: print('warning: bone <%s> is non-deformabled, this is inefficient!' %self.name)
#TODO test#if pbone.bone.use_inherit_scale: print('warning: bone <%s> is using inherit scaling, Ogre has no support for this' %self.name)
self.parent = pbone.parent
self.children = []
self.fixUpAxis = False
def rebuild_tree( self ): # called first on all bones
if self.parent:
self.parent = self.skeleton.get_bone( self.parent.name )
self.parent.children.append( self )
def compute_rest( self ): # called second, only on root bones
if self.parent:
inverseParentMatrix = self.parent.inverse_total_trans
#elif (self.fixUpAxis):
# inverseParentMatrix = mathutils.Matrix([1,0,0,0],[0,0,-1,0],[0,1,0,0],[0,0,0,1])
else:
inverseParentMatrix = mathutils.Matrix([1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1])
# bone matrix relative to armature object
self.ogre_rest_matrix = self.matrix.copy()
# relative to mesh object origin
#self.ogre_rest_matrix *= self.skeleton.object_space_transformation # 2.49 style
self.ogre_rest_matrix = self.skeleton.object_space_transformation * self.ogre_rest_matrix
# store total inverse transformation
self.inverse_total_trans = self.ogre_rest_matrix.copy().invert()
# relative to OGRE parent bone origin
#self.ogre_rest_matrix *= inverseParentMatrix # 2.49 style
self.ogre_rest_matrix = inverseParentMatrix * self.ogre_rest_matrix
self.inverse_ogre_rest_matrix = self.ogre_rest_matrix.copy().invert()
## recursion ##
for child in self.children:
child.compute_rest()
class Skeleton(object):
def get_bone( self, name ):
for b in self.bones:
if b.name == name: return b
def __init__(self, ob ):
self.object = ob
self.bones = []
mats = {}
self.arm = arm = ob.find_armature()
## ob.pose.bones[0].matrix is not the same as ob.data.edit_bones[0].matrix
#bug?#layers = list(arm.layers)
arm.hide = False
arm.layers = [True]*20
prev = bpy.context.scene.objects.active
bpy.context.scene.objects.active = arm # arm needs to be in edit mode to get to .edit_bones
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
bpy.ops.object.mode_set(mode='EDIT', toggle=False)
for bone in arm.data.edit_bones: mats[ bone.name ] = bone.matrix.copy()
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
#bpy.ops.object.mode_set(mode='POSE', toggle=False)
bpy.context.scene.objects.active = prev
for pbone in arm.pose.bones:
mybone = Bone( mats[pbone.name] ,pbone, self )
self.bones.append( mybone )
if arm.name not in Report.armatures: Report.armatures.append( arm.name )
# additional transformation for root bones:
# from armature object space into mesh object space, i.e.,
# (x,y,z,w)*AO*MO^(-1)
self.object_space_transformation = arm.matrix_local * ob.matrix_local.copy().invert()
#self.object_space_transformation = ob.matrix_local.copy().invert() * arm.matrix_local
## setup bones for Ogre format ##
for b in self.bones: b.rebuild_tree()
## walk bones, convert them ##
self.roots = []
for b in self.bones:
if not b.parent:
b.compute_rest()
self.roots.append( b )
def to_xml( self ):
doc = dom.Document()
root = doc.createElement('skeleton'); doc.appendChild( root )
bones = doc.createElement('bones'); root.appendChild( bones )
bh = doc.createElement('bonehierarchy'); root.appendChild( bh )
for i,bone in enumerate(self.bones):
b = doc.createElement('bone')
b.setAttribute('name', bone.name)
b.setAttribute('id', str(i) )
bones.appendChild( b )
mat = bone.ogre_rest_matrix.copy()
if bone.parent:
bp = doc.createElement('boneparent')
bp.setAttribute('bone', bone.name)
bp.setAttribute('parent', bone.parent.name)
bh.appendChild( bp )
pos = doc.createElement( 'position' ); b.appendChild( pos )
x,y,z = mat.translation_part()
pos.setAttribute('x', '%6f' %x )
pos.setAttribute('y', '%6f' %y )
pos.setAttribute('z', '%6f' %z )
rot = doc.createElement( 'rotation' ) # note "rotation", not "rotate"
b.appendChild( rot )
q = mat.rotation_part().to_quat()
rot.setAttribute('angle', '%6f' %q.angle )
axis = doc.createElement('axis'); rot.appendChild( axis )
x,y,z = q.axis
axis.setAttribute('x', '%6f' %x )
axis.setAttribute('y', '%6f' %y )
axis.setAttribute('z', '%6f' %z )
## Ogre bones do not have initial scaling? ##
if 0:
scale = doc.createElement('scale'); b.appendChild( scale )
x,y,z = swap( mat.scale_part() )
scale.setAttribute('x', str(x))
scale.setAttribute('y', str(y))
scale.setAttribute('z', str(z))
## NOTE: Ogre bones by default do not pass down their scaling in animation, in blender all bones are like 'do-not-inherit-scaling'
arm = self.arm
if arm.animation_data:
anims = doc.createElement('animations'); root.appendChild( anims )
anim_data = arm.animation_data
if not len( anim_data.nla_tracks ):
Report.warnings.append('you must assign an NLA strip to armature (%s) that defines the start and end frames' %arm.name)
nla_tracks = anim_data.nla_tracks
for nla in nla_tracks: # NLA required, lone actions not supported
if not len(nla.strips): continue
if len( nla.strips ) > 1:
Report.warnings.append('NLA track with multiple strips on armature (%s), using only the first strip, use multiple NLA tracks not multiple NLA strips.' %arm.name)
nla.mute = False # TODO is this required?
for i in range(len(nla_tracks)):
if nla_tracks[i] != nla:
nla_tracks[i].mute = True
strip = nla.strips[0]
anim = doc.createElement('animation'); anims.appendChild( anim )
tracks = doc.createElement('tracks'); anim.appendChild( tracks )
Report.armature_animations.append( '%s : %s [start frame=%s end frame=%s]' %(arm.name, nla.name, strip.frame_start, strip.frame_end) )
anim.setAttribute('name', nla.name) # do not use the action's name
# get FPS
fps = bpy.context.scene.render.fps
anim.setAttribute('length', str( (strip.frame_end-strip.frame_start)/fps ) ) # TODO proper fps
## using the fcurves directly is useless, because:
## we need to support constraints and the interpolation between keys
## is Ogre smart enough that if a track only has a set of bones, then blend animation with current animation?
## the exporter will not be smart enough to know which bones are active for a given track...
## can hijack blender NLA, user sets a single keyframe for only selected bones, and keys last frame
stripbones = []
for group in strip.action.groups: # check if the user has keyed only some of the bones (for anim blending)
if group.name in arm.pose.bones: stripbones.append( group.name )
if not stripbones: # otherwise we use all bones
for bone in arm.pose.bones: stripbones.append( bone.name )
print('NLA-strip:', nla.name)
_keyframes = {}
for bonename in stripbones:
track = doc.createElement('track')
track.setAttribute('bone', bonename)
tracks.appendChild( track )
keyframes = doc.createElement('keyframes')
track.appendChild( keyframes )
_keyframes[ bonename ] = keyframes
print('\t', bonename)
for frame in range( int(strip.frame_start), int(strip.frame_end), 2): # every other frame
#bpy.context.scene.frame_current = frame
bpy.context.scene.frame_set(frame)
#self.object.update( bpy.context.scene )
#bpy.context.scene.update()
for bone in self.roots: bone.update()
print('\t\t', frame)
for bonename in stripbones:
bone = self.get_bone( bonename )
_loc = bone.pose_location
_rot = bone.pose_rotation
_scl = bone.pose_scale
keyframe = doc.createElement('keyframe')
keyframe.setAttribute('time', str(frame/25.0))
_keyframes[ bonename ].appendChild( keyframe )
trans = doc.createElement('translate')
keyframe.appendChild( trans )
x,y,z = _loc
trans.setAttribute('x', '%6f' %x)
trans.setAttribute('y', '%6f' %y)
trans.setAttribute('z', '%6f' %z)
rot = doc.createElement( 'rotate' ) # note "rotate" - bug fixed Dec2nd
keyframe.appendChild( rot )
q = _rot #swap( mat.rotation_part().to_quat() )
rot.setAttribute('angle', '%6f' %q.angle )
axis = doc.createElement('axis'); rot.appendChild( axis )
x,y,z = q.axis
axis.setAttribute('x', '%6f' %x )
axis.setAttribute('y', '%6f' %y )
axis.setAttribute('z', '%6f' %z )
scale = doc.createElement('scale')
keyframe.appendChild( scale )
x,y,z = _scl #swap( mat.scale_part() )
scale.setAttribute('x', '%6f' %x)
scale.setAttribute('y', '%6f' %y)
scale.setAttribute('z', '%6f' %z)
return doc.documentElement.toprettyxml()
## below _convertRestpose is from blender2.49 script
'''
#meshObjectSpaceTransformation = armatureExporter.getAdditionalRootBoneTransformation()
#track.addKeyframe(pose, frameTime, meshObjectSpaceTransformation)
def _convertRestpose(self):
"""Convert rest pose of Blender skeleton.
Note that not every Blender bone has a corresponding OGRE bone.
Root bones need an additional transformation caused by the
possibliy different object coordinate systems of Blender's
armature object and Blender's mesh object.
"""
# Warning: Blender uses left-multiplication: vector*matrix
# additional transformation caused by the objects
inverseMeshObjectMatrix = Blender.Mathutils.Matrix(*self.bMeshObject.getMatrix())
inverseMeshObjectMatrix.invert()
armatureObjectMatrix = Blender.Mathutils.Matrix(*self.bArmatureObject.getMatrix())
# additional transformation for root bones:
# from armature object space into mesh object space, i.e.,
# (x,y,z,w)*AO*MO^(-1)
self.additionalRootBoneTransformation = armatureObjectMatrix*inverseMeshObjectMatrix
'''
def get_image_textures( mat ):
r = []
for s in mat.texture_slots:
if s and s.texture.type == 'IMAGE': r.append( s )
return r
def indent( level, *args ):
if not args: return '\t' * level
else:
a = ''
for line in args:
a += '\t' * level
a += line
a += '\n'
return a
############ extra tools ##############
def gather_instances():
instances = {}
for ob in bpy.data.objects:
if ob.data and ob.data.users > 1:
if ob.data not in instances: instances[ ob.data ] = []
instances[ ob.data ].append( ob )
return instances
def select_instances( context, name ):
for ob in bpy.data.objects: ob.select = False
ob = bpy.data.objects[ name ]
if ob.data:
inst = gather_instances()
for ob in inst[ ob.data ]: ob.select = True
bpy.context.scene.objects.active = ob
def select_group( context, name, options={} ):
for ob in bpy.data.objects: ob.select = False
for grp in bpy.data.groups:
if grp.name == name:
#context.scene.objects.active = grp.objects
#Note that the context is read-only. These values cannot be modified directly, though they may be changed by running API functions or by using the data API. So bpy.context.object = obj will raise an error. But bpy.context.scene.objects.active = obj will work as expected. - http://wiki.blender.org/index.php?title=Dev:2.5/Py/API/Intro&useskin=monobook
bpy.context.scene.objects.active = grp.objects[0]
for ob in grp.objects: ob.select = True
else: pass
class INFO_MT_instances(bpy.types.Menu):
bl_label = "Instances"
def draw(self, context):
layout = self.layout
inst = gather_instances()
for data in inst:
ob = inst[data][0]
op = layout.operator("select_instances", text=ob.name) # operator has no variable for button name?
op.mystring = ob.name
layout.separator()
class INFO_MT_instance(bpy.types.Operator):
'''select instance group'''
bl_idname = "select_instances"
bl_label = "Select Instance Group"
bl_options = {'REGISTER', 'UNDO'} # Options for this panel type
mystring= StringProperty(name="MyString", description="...", maxlen=1024, default="my string")
@classmethod
def poll(cls, context):
return True
def invoke(self, context, event):
print( 'invoke select_instances op', event )
select_instances( context, self.mystring )
return {'FINISHED'}
class INFO_MT_groups(bpy.types.Menu):
bl_label = "Groups"
def draw(self, context):
layout = self.layout
for group in bpy.data.groups:
op = layout.operator("select_group", text=group.name) # operator no variable for button name?
op.mystring = group.name
#op = layout.operator("mark_group_export_combine")
#op.groupname = group.name
layout.separator()
#TODO
class INFO_MT_group_mark(bpy.types.Operator):
'''mark group auto combine on export'''
bl_idname = "mark_group_export_combine"
bl_label = "Group Auto Combine"
bl_options = {'REGISTER', 'UNDO'} # Options for this panel type
mybool= BoolProperty(name="groupautocombine", description="set group auto-combine", default=False)
mygroups = {}
@classmethod
def poll(cls, context): return True
def invoke(self, context, event):
self.mygroups[ op.groupname ] = self.mybool
return {'FINISHED'}
class INFO_MT_group(bpy.types.Operator):
'''select group'''
bl_idname = "select_group"
bl_label = "Select Group" # The panel label, http://www.blender.org/documentation/250PythonDoc/bpy.types.Panel.html
bl_options = {'REGISTER', 'UNDO'} # Options for this panel type
mystring= StringProperty(name="MyString", description="...", maxlen=1024, default="my string")
@classmethod
def poll(cls, context):
print('----poll group, below context -----')
print( dir(context) )
#return context.active_object != None # as long as something is selected, return the active Object?
return True
def invoke(self, context, event):
select_group( context, self.mystring )
return {'FINISHED'}
#############
class INFO_MT_actors(bpy.types.Menu):
bl_label = "Actors"
def draw(self, context):
layout = self.layout
for ob in bpy.data.objects:
if ob.game.use_actor:
op = layout.operator("select_actor", text=ob.name)
op.mystring = ob.name
layout.separator()
class INFO_MT_actor(bpy.types.Operator):
'''select actor'''
bl_idname = "select_actor"
bl_label = "Select Actor"
bl_options = {'REGISTER', 'UNDO'} # Options for this panel type
mystring= StringProperty(name="MyString", description="...", maxlen=1024, default="my string")
@classmethod
def poll(cls, context): return True
def invoke(self, context, event):
bpy.data.objects[self.mystring].select = True
return {'FINISHED'}
class INFO_MT_dynamics(bpy.types.Menu):
bl_label = "Dynamics"
def draw(self, context):
layout = self.layout
for ob in bpy.data.objects:
if ob.game.physics_type in 'DYNAMIC SOFT_BODY RIGID_BODY'.split():
op = layout.operator("select_dynamic", text=ob.name)
op.mystring = ob.name
layout.separator()
class INFO_MT_dynamic(bpy.types.Operator):
'''select dynamic'''
bl_idname = "select_dynamic"
bl_label = "Select Dynamic"
bl_options = {'REGISTER', 'UNDO'} # Options for this panel type
mystring= StringProperty(name="MyString", description="...", maxlen=1024, default="my string")
@classmethod
def poll(cls, context): return True
def invoke(self, context, event):
bpy.data.objects[self.mystring].select = True
return {'FINISHED'}
class INFO_HT_myheader(bpy.types.Header):
bl_space_type = 'INFO'
def draw(self, context):
layout = self.layout
wm = context.window_manager
window = context.window
scene = context.scene
rd = scene.render
layout.operator("wm.window_fullscreen_toggle", icon='FULLSCREEN_ENTER', text="")
layout.operator("ogre.export", text="Ogre")
layout.operator( 'ogre.preview_ogremeshy', text='', icon='PLUGIN' )
row = layout.row(align=True)
sub = row.row(align=True)
sub.menu("INFO_MT_instances")
sub.menu("INFO_MT_groups")
if True: #context.area.show_menus:
sub.menu("INFO_MT_file")
sub.menu("INFO_MT_add")
if rd.use_game_engine: sub.menu("INFO_MT_game")
else: sub.menu("INFO_MT_render")
layout.separator()
if window.screen.show_fullscreen:
layout.operator("screen.back_to_previous", icon='SCREEN_BACK', text="Back to Previous")
layout.separator()
else:
layout.template_ID(context.window, "screen", new="screen.new", unlink="screen.delete")
layout.separator()
layout.template_running_jobs()
layout.template_reports_banner()
layout.separator()
if rd.has_multiple_engines:
layout.prop(rd, "engine", text="")
layout.template_header()
if context.area.show_menus:
layout.template_ID(context.screen, "scene", new="scene.new", unlink="scene.delete")
layout.label(text=scene.statistics())
#layout.menu( "INFO_MT_help" )
layout.menu( "INFO_MT_ogre_docs" )
else:
screen = context.screen
row = layout.row(align=True)
row.operator("screen.frame_jump", text="", icon='REW').end = False
row.operator("screen.keyframe_jump", text="", icon='PREV_KEYFRAME').next = False
if not screen.is_animation_playing:
row.operator("screen.animation_play", text="", icon='PLAY_REVERSE').reverse = True
row.operator("screen.animation_play", text="", icon='PLAY')
else:
sub = row.row()
sub.scale_x = 2.0
sub.operator("screen.animation_play", text="", icon='PAUSE')
row.operator("screen.keyframe_jump", text="", icon='NEXT_KEYFRAME').next = True
row.operator("screen.frame_jump", text="", icon='FF').end = True
row = layout.row(align=True)
if not scene.use_preview_range:
row.prop(scene, "frame_start", text="Start")
row.prop(scene, "frame_end", text="End")
else:
row.prop(scene, "frame_preview_start", text="Start")
row.prop(scene, "frame_preview_end", text="End")
layout.prop(scene, "frame_current", text="")
layout.menu("INFO_MT_actors")
layout.menu("INFO_MT_dynamics")
_header_ = None
MyShaders = None
def register():
print( VERSION )
global MyShaders, _header_
_header_ = bpy.types.INFO_HT_header
bpy.types.unregister( bpy.types.INFO_HT_header )
MyShaders = MyShadersSingleton()
def unregister():
print('unreg-> ogre exporter')
bpy.types.register( _header_ )
if __name__ == "__main__": register()
NVDXT_DOC = '''
Version 8.30
NVDXT
This program
compresses images
creates normal maps from color or alpha
creates DuDv map
creates cube maps
writes out .dds file
does batch processing
reads .tga, .bmp, .gif, .ppm, .jpg, .tif, .cel, .dds, .png, .psd, .rgb, *.bw and .rgba
filters MIP maps
Options:
-profile <profile name> : Read a profile created from the Photoshop plugin
-quick : use fast compression method
-quality_normal : normal quality compression
-quality_production : production quality compression
-quality_highest : highest quality compression (this can be very slow)
-rms_threshold <int> : quality RMS error. Above this, an extensive search is performed.
-prescale <int> <int>: rescale image to this size first
-rescale <nearest | hi | lo | next_lo>: rescale image to nearest, next highest or next lowest power of two
-rel_scale <float, float> : relative scale of original image. 0.5 is half size Default 1.0, 1.0
Optional Filtering for rescaling. Default cube filter:
-RescalePoint
-RescaleBox
-RescaleTriangle
-RescaleQuadratic
-RescaleCubic
-RescaleCatrom
-RescaleMitchell
-RescaleGaussian
-RescaleSinc
-RescaleBessel
-RescaleHanning
-RescaleHamming
-RescaleBlackman
-RescaleKaiser
-clamp <int, int> : maximum image size. image width and height are clamped
-clampScale <int, int> : maximum image size. image width and height are scaled
-window <left, top, right, bottom> : window of original window to compress
-nomipmap : don't generate MIP maps
-nmips <int> : specify the number of MIP maps to generate
-rgbe : Image is RGBE format
-dither : add dithering
-sharpenMethod <method>: sharpen method MIP maps
<method> is
None
Negative
Lighter
Darker
ContrastMore
ContrastLess
Smoothen
SharpenSoft
SharpenMedium
SharpenStrong
FindEdges
Contour
EdgeDetect
EdgeDetectSoft
Emboss
MeanRemoval
UnSharp <radius, amount, threshold>
XSharpen <xsharpen_strength, xsharpen_threshold>
Custom
-pause : wait for keyboard on error
-flip : flip top to bottom
-timestamp : Update only changed files
-list <filename> : list of files to convert
-cubeMap : create cube map .
Cube faces specified with individual files with -list option
positive x, negative x, positive y, negative y, positive z, negative z
Use -output option to specify filename
Cube faces specified in one file. Use -file to specify input filename
-volumeMap : create volume texture.
Volume slices specified with individual files with -list option
Use -output option to specify filename
Volume specified in one file. Use -file to specify input filename
-all : all image files in current directory
-outdir <directory>: output directory
-deep [directory]: include all subdirectories
-outsamedir : output directory same as input
-overwrite : if input is .dds file, overwrite old file
-forcewrite : write over readonly files
-file <filename> : input file to process. Accepts wild cards
-output <filename> : filename to write to [-outfile can also be specified]
-append <filename_append> : append this string to output filename
-8 <dxt1c | dxt1a | dxt3 | dxt5 | u1555 | u4444 | u565 | u8888 | u888 | u555 | L8 | A8> : compress 8 bit images with this format
-16 <dxt1c | dxt1a | dxt3 | dxt5 | u1555 | u4444 | u565 | u8888 | u888 | u555 | A8L8> : compress 16 bit images with this format
-24 <dxt1c | dxt1a | dxt3 | dxt5 | u1555 | u4444 | u565 | u8888 | u888 | u555> : compress 24 bit images with this format
-32 <dxt1c | dxt1a | dxt3 | dxt5 | u1555 | u4444 | u565 | u8888 | u888 | u555> : compress 32 bit images with this format
-swapRB : swap rb
-swapRG : swap rg
-gamma <float value>: gamma correcting during filtering
-outputScale <float, float, float, float>: scale the output by this (r,g,b,a)
-outputBias <float, float, float, float>: bias the output by this amount (r,g,b,a)
-outputWrap : wraps overflow values modulo the output format
-inputScale <float, float, float, float>: scale the inpput by this (r,g,b,a)
-inputBias <float, float, float, float>: bias the input by this amount (r,g,b,a)
-binaryalpha : treat alpha as 0 or 1
-alpha_threshold <byte>: [0-255] alpha reference value
-alphaborder : border images with alpha = 0
-alphaborderLeft : border images with alpha (left) = 0
-alphaborderRight : border images with alpha (right)= 0
-alphaborderTop : border images with alpha (top) = 0
-alphaborderBottom : border images with alpha (bottom)= 0
-fadeamount <int>: percentage to fade each MIP level. Default 15
-fadecolor : fade map (color, normal or DuDv) over MIP levels
-fadetocolor <hex color> : color to fade to
-custom_fade <n> <n fadeamounts> : set custom fade amount. n is number number of fade amounts. fadeamount are [0,1]
-fadealpha : fade alpha over MIP levels
-fadetoalpha <byte>: [0-255] alpha to fade to
-border : border images with color
-bordercolor <hex color> : color for border
-force4 : force DXT1c to use always four colors
-weight <float, float, float>: Compression weightings for R G and B
-luminance : convert color values to luminance for L8 formats
-greyScale : Convert to grey scale
-greyScaleWeights <float, float, float, float>: override greyscale conversion weights of (0.3086, 0.6094, 0.0820, 0)
-brightness <float, float, float, float>: per channel brightness. Default 0.0 usual range [0,1]
-contrast <float, float, float, float>: per channel contrast. Default 1.0 usual range [0.5, 1.5]
Texture Format Default DXT3:
-dxt1c : DXT1 (color only)
-dxt1a : DXT1 (one bit alpha)
-dxt3 : DXT3
-dxt5 : DXT5n
-u1555 : uncompressed 1:5:5:5
-u4444 : uncompressed 4:4:4:4
-u565 : uncompressed 5:6:5
-u8888 : uncompressed 8:8:8:8
-u888 : uncompressed 0:8:8:8
-u555 : uncompressed 0:5:5:5
-p8c : paletted 8 bit (256 colors)
-p8a : paletted 8 bit (256 colors with alpha)
-p4c : paletted 4 bit (16 colors)
-p4a : paletted 4 bit (16 colors with alpha)
-a8 : 8 bit alpha channel
-cxv8u8 : normal map format
-v8u8 : EMBM format (8, bit two component signed)
-v16u16 : EMBM format (16 bit, two component signed)
-A8L8 : 8 bit alpha channel, 8 bit luminance
-fp32x4 : fp32 four channels (A32B32G32R32F)
-fp32 : fp32 one channel (R32F)
-fp16x4 : fp16 four channels (A16B16G16R16F)
-dxt5nm : dxt5 style normal map
-3Dc : 3DC
-g16r16 : 16 bit in, two component
-g16r16f : 16 bit float, two components
Mip Map Filtering Options. Default box filter:
-Point
-Box
-Triangle
-Quadratic
-Cubic
-Catrom
-Mitchell
-Gaussian
-Sinc
-Bessel
-Hanning
-Hamming
-Blackman
-Kaiser
***************************
To make a normal or dudv map, specify one of
-n4 : normal map 4 sample
-n3x3 : normal map 3x3 filter
-n5x5 : normal map 5x5 filter
-n7x7 : normal map 7x7 filter
-n9x9 : normal map 9x9 filter
-dudv : DuDv
and source of height info:
-alpha : alpha channel
-rgb : average rgb
-biased : average rgb biased
-red : red channel
-green : green channel
-blue : blue channel
-max : max of (r,g,b)
-colorspace : mix of r,g,b
-norm : normalize mip maps (source is a normal map)
-toHeight : create a height map (source is a normal map)
Normal/DuDv Map dxt:
-aheight : store calculated height in alpha field
-aclear : clear alpha channel
-awhite : set alpha channel = 1.0
-scale <float> : scale of height map. Default 1.0
-wrap : wrap texture around. Default off
-minz <int> : minimum value for up vector [0-255]. Default 0
***************************
To make a depth sprite, specify:
-depth
and source of depth info:
-alpha : alpha channel
-rgb : average rgb (default)
-red : red channel
-green : green channel
-blue : blue channel
-max : max of (r,g,b)
-colorspace : mix of r,g,b
Depth Sprite dxt:
-aheight : store calculated depth in alpha channel
-aclear : store 0.0 in alpha channel
-awhite : store 1.0 in alpha channel
-scale <float> : scale of depth sprite (default 1.0)
-alpha_modulate : multiplies color by alpha during filtering
-pre_modulate : multiplies color by alpha before processing
Examples
nvdxt -cubeMap -list cubemapfile.lst -output cubemap.dds
nvdxt -cubeMap -file cubemapfile.tga
nvdxt -file test.tga -dxt1c
nvdxt -file *.tga
nvdxt -file c:\temp\*.tga
nvdxt -file temp\*.tga
nvdxt -file height_field_in_alpha.tga -n3x3 -alpha -scale 10 -wrap
nvdxt -file grey_scale_height_field.tga -n5x5 -rgb -scale 1.3
nvdxt -file normal_map.tga -norm
nvdxt -file image.tga -dudv -fade -fadeamount 10
nvdxt -all -dxt3 -gamma -outdir .\dds_dir -time
nvdxt -file *.tga -depth -max -scale 0.5
'''
def gen_normal_map_shader( normal, color ):
NORMAL_MAP_SHADER = """
technique
{
pass
{
ambient 1 1 1
diffuse 0 0 0
specular 0 0 0 0
vertex_program_ref Ogre/BasicVertexPrograms/AmbientOneTexture
{
param_named_auto worldViewProj worldviewproj_matrix
param_named_auto ambient ambient_light_colour
}
}
pass
{
ambient 0 0 0
iteration once_per_light
scene_blend add
vertex_program_ref Examples/BumpMapVPSpecular
{
param_named_auto lightPosition light_position_object_space 0
param_named_auto eyePosition camera_position_object_space
param_named_auto worldViewProj worldviewproj_matrix
}
fragment_program_ref Examples/BumpMapFPSpecular
{
param_named_auto lightDiffuse light_diffuse_colour 0
param_named_auto lightSpecular light_specular_colour 0
}
texture_unit
{
texture %s
colour_op replace
}
texture_unit
{
cubic_texture nm.png combinedUVW
tex_coord_set 1
tex_address_mode clamp
}
texture_unit
{
cubic_texture nm.png combinedUVW
tex_coord_set 2
tex_address_mode clamp
}
}
pass
{
lighting off
vertex_program_ref Ogre/BasicVertexPrograms/AmbientOneTexture
{
param_named_auto worldViewProj worldviewproj_matrix
param_named ambient float4 1 1 1 1
}
scene_blend dest_colour zero
texture_unit
{
texture %s
}
}
}
technique
{
pass
{
ambient 1 1 1
diffuse 0 0 0
specular 0 0 0 0
vertex_program_ref Ogre/BasicVertexPrograms/AmbientOneTexture
{
param_named_auto worldViewProj worldviewproj_matrix
param_named_auto ambient ambient_light_colour
}
}
pass
{
ambient 0 0 0
iteration once_per_light
scene_blend add
vertex_program_ref Examples/BumpMapVP
{
param_named_auto lightPosition light_position_object_space 0
param_named_auto eyePosition camera_position_object_space
param_named_auto worldViewProj worldviewproj_matrix
}
texture_unit
{
texture %s
colour_op replace
}
texture_unit
{
cubic_texture nm.png combinedUVW
tex_coord_set 1
tex_address_mode clamp
colour_op_ex dotproduct src_texture src_current
colour_op_multipass_fallback dest_colour zero
}
}
pass
{
lighting off
vertex_program_ref Ogre/BasicVertexPrograms/AmbientOneTexture
{
param_named_auto worldViewProj worldviewproj_matrix
param_named ambient float4 1 1 1 1
}
scene_blend dest_colour zero
texture_unit
{
texture %s
}
}
}
""" % (norImage, colImage, norImage, colImage)
| Python |
###########################################################################
# program: jacobi_eigen_solver.py
# author: Chunlei Xu
# version: 2.0
# date: Mar, 1, 2014
# description: Solve the generalized eigenvalue problem for a system
# with sparse mass & stiffness matrices in Jacobi method
#
###########################################################################
from numarray import array,zeros,identity,diagonal,pi,Float64
from numarray import dot,sqrt,matrixmultiply,transpose
###########################################################################
###########################################################################
#a=np.array(input_reader._test().ToArray())
#n = 6
###########################################################################
###########################################################################
## module stdForm
''' h,t = stdForm(a,b)
Transforms the eigenvalue problem [a]{x} = lambda[b]{x}
to the standard form [h]{z} = lambda{z}. The eigenvectors
are related by {x} = [t]{z}.
'''
def stdForm(a,b):
#################################
## module Dec_LLT_Choleski
''' L= Dec_LLT_Choleski(a).
Dec_LLT_Choleski decomposition: [L][L]transpose = [a].
'''
def Dec_LLT_Choleski(a):
n = len(a)
L = ([[0.0] * n for i in xrange(n)])
L = array(L)
for i in xrange(n):
for k in xrange(i+1):
tmp_sum = sum(L[i][j] * L[k][j] for j in xrange(k))
if (i == k): # Diagonal elements
L[i][k] = sqrt(a[i][i] - tmp_sum)
else:
L[i][k] = (1.0 / L[k][k] * (a[i][k] - tmp_sum))
return L
#################################
## module Inverse_L
def Inverse_L(L):
def solveLb(L, b):
n = len(L)
if len(b) != n:
raise ValueError, "incompatible dimensions"
x = [0.0] * n
for i in range(n):
S = b[i]
for j in range(i):
S-= L[i][j]*x[j]
x[i] = S/L[i][i]
return x
n = len(L)
b = [0.0] *n
invL = [[0.0] * n for i in range(n)]
for i in range(n):
b[i] = 1.0
x = solveLb(L, b)
for j in range(n):
invL[j][i] = x[j]
b[i] = 0.0
return invL
#################################
L = Dec_LLT_Choleski(b)
invL= Inverse_L(L)
h= matrixmultiply(matrixmultiply(invL,a),transpose(invL))
return h,transpose(invL)
###########################################################################
def Jacobi_Eig_Solver(a,tol = 1.0e-9):
'''lam,x = Jacobi_Eig_Solver(a,tol = 1.0e-9).
Solution of std.eigenvalue problem [a]{x} = lambda{x}
by Jacobi's method. Returns eigenvalues in vector {lam}
and the eigenvectors as columns of matrix [x].
'''
def maxElem(a): # Find largest off-diag. element a[k,l]
n = len(a)
aMax = 0.0
for i in range(n-1):
for j in range(i+1,n):
if abs(a[i,j]) >= aMax:
aMax = abs(a[i,j])
k = i; l = j
return aMax,k,l
def rotate(a,p,k,l): # Rotate to make a[k,l] = 0
n = len(a)
aDiff = a[l,l] - a[k,k]
if abs(a[k,l]) < abs(aDiff)*1.0e-36: t = a[k,l]/aDiff
else:
phi = aDiff/(2.0*a[k,l])
t = 1.0/(abs(phi) + sqrt(phi**2 + 1.0))
if phi < 0.0: t = -t
c = 1.0/sqrt(t**2 + 1.0); s = t*c
tau = s/(1.0 + c)
temp = a[k,l]
a[k,l] = 0.0
a[k,k] = a[k,k] - t*temp
a[l,l] = a[l,l] + t*temp
for i in range(k): # Case of i < k
temp = a[i,k]
a[i,k] = temp - s*(a[i,l] + tau*temp)
a[i,l] = a[i,l] + s*(temp - tau*a[i,l])
for i in range(k+1,l): # Case of k < i < l
temp = a[k,i]
a[k,i] = temp - s*(a[i,l] + tau*a[k,i])
a[i,l] = a[i,l] + s*(temp - tau*a[i,l])
for i in range(l+1,n): # Case of i > l
temp = a[k,i]
a[k,i] = temp - s*(a[l,i] + tau*temp)
a[l,i] = a[l,i] + s*(temp - tau*a[l,i])
for i in range(n): # Update transformation matrix
temp = p[i,k]
p[i,k] = temp - s*(p[i,l] + tau*p[i,k])
p[i,l] = p[i,l] + s*(temp - tau*p[i,l])
n = len(a)
maxRot = 5*(n**2) # Set limit on number of rotations
p = identity(n)*1.0 # Initialize transformation matrix
for i in range(maxRot): # Jacobi rotation loop
aMax,k,l = maxElem(a)
if aMax < tol: return diagonal(a),p
rotate(a,p,k,l)
print "Jacobi method did not converge"
###########################################################################
###########################################################################
def runEigenSolve(stiff,mass):
# eigen-problem Calculation by jacobi method
h,t = stdForm(stiff,mass) # Convert to std. form
lam,z = Jacobi_Eig_Solver(h) # Solve by Jacobi mthd.
v = matrixmultiply(t,z) # Eigenvectors of orig. prob.
###########################################################################
# Natural Frequency Calculation
n=len(stiff)
omega = [0.0] * n
Natural_frequency = [0.0] * n
for i in range(n):
omega[i] = sqrt(lam[i])
Natural_frequency[i] = omega[i]/(2*pi)
###########################################################################
# Mass Normalize Eigenvectors
temp=zeros((n,n),'f')
scm=zeros((n,n),'f')
temp=dot(mass,v)
Madal_shape=zeros((n,n),'f')
#.T,same as self.transpose()
scm=dot(v.T,temp) #transpose
nf=zeros(n,'f')
for i in range (0,n):
nf[i]=sqrt(scm[i][i])
for j in range (0,n):
Madal_shape[j][i]=v[j][i]/nf[i]
# sorting command should be inserted here, Vecor of U needed
return Natural_frequency,Madal_shape
###########################################################################
###########################################################################
def _test():
stiff=[[1.055605320000000E+005, 0.0, 0.0, -5.278026600000000E+004, 0.0, 0.0],
[0.0, 5.066905536000000E+002, 0.0, 0.0, -2.533452768000000E+002, 6.333631920000001E+003],
[0.0, 0.0, 4.222421280000000E+005, 0.0, -6.333631920000001E+003, 1.055605320000000E+005],
[-5.278026600000000E+004, 0.0, 0.0, 5.278026600000000E+004, 0.0, 0.0],
[0.0, -2.533452768000000E+002, -6.333631920000001E+003, 0.0, 2.533452768000000E+002, -6.333631920000001E+003],
[0.0, 6.333631920000001E+003, 1.055605320000000E+005, 0.0, -6.333631920000001E+003, 2.111210640000000E+005]]
mass=[[ 3.288294350000000E-003, 0.0, 0.0, 8.220735875000000E-004, 0.0, 0.0],
[ 0.0, 3.668834562435429E-003, 0.0, 0.0,6.318034812822856E-004, -7.623675572307143E-003],
[ 0.0, 0.0, 2.361934855971429E-001, 0.0, 7.623675572307143E-003, -8.824372766392859E-002],
[8.220735875000000E-004, 0.0, 0.0, 1.644147175000000E-003, 0.0, 0.0],
[0.0, 6.318034812822856E-004, 7.623675572307143E-003, 0.0, 1.834417281217714E-003, -1.292816411519286E-002],
[0.0, -7.623675572307143E-003, -8.824372766392859E-002, 0.0, -1.292816411519286E-002, 1.180967427985714E-001]]
Madal_shape,Natural_frequency=runEigenSolve(stiff,mass)
Natural_frequency=sorted(Natural_frequency)
#print "Eigenvalues:\n",lam[0:6]
#print "\nEigenvectors:\n",v[:,0:6]
print "\nNatural_frequency:\n",Natural_frequency[0:6]
print "\nMode_shape:\n",Madal_shape[0:6]
if __name__=="__main__":
_test()
| Python |
"""numerictypes: Define the numeric type objects
This module is designed so 'from numerictypes import *' is safe.
Exported symbols include:
Dictionary with all registered number types (including aliases):
typeDict
Numeric type objects:
Bool
Int8 Int16 Int32 Int64
UInt8 UInt16 UInt32 UInt64
Float32 Double64
Complex32 Complex64
Numeric type classes:
NumericType
BooleanType
SignedType
UnsignedType
IntegralType
SignedIntegralType
UnsignedIntegralType
FloatingType
ComplexType
$Id: numerictypes.py,v 1.55 2005/12/01 16:22:03 jaytmiller Exp $
"""
__all__ = ['NumericType','HasUInt64','typeDict','IsType',
'BooleanType', 'SignedType', 'UnsignedType', 'IntegralType',
'SignedIntegralType', 'UnsignedIntegralType', 'FloatingType',
'ComplexType', 'AnyType', 'ObjectType', 'Any', 'Object',
'Bool', 'Int8', 'Int16', 'Int32', 'Int64', 'Float32',
'Float64', 'UInt8', 'UInt16', 'UInt32', 'UInt64',
'Complex32', 'Complex64', 'Byte', 'Short', 'Int','Long',
'Float', 'Complex', 'genericTypeRank', 'pythonTypeRank',
'pythonTypeMap', 'scalarTypeMap', 'genericCoercions',
'typecodes', 'genericPromotionExclusions','MaximumType',
'getType','scalarTypes', 'typefrom']
MAX_ALIGN = 8
MAX_INT_SIZE = 8
import numpy
LP64 = numpy.intp(0).itemsize == 8
HasUInt64 = 1
try:
numpy.int64(0)
except:
HasUInt64 = 0
#from typeconv import typeConverters as _typeConverters
#import numinclude
#from _numerictype import _numerictype, typeDict
# Enumeration of numarray type codes
typeDict = {}
_tAny = 0
_tBool = 1
_tInt8 = 2
_tUInt8 = 3
_tInt16 = 4
_tUInt16 = 5
_tInt32 = 6
_tUInt32 = 7
_tInt64 = 8
_tUInt64 = 9
_tFloat32 = 10
_tFloat64 = 11
_tComplex32 = 12
_tComplex64 = 13
_tObject = 14
def IsType(rep):
"""Determines whether the given object or string, 'rep', represents
a numarray type."""
return isinstance(rep, NumericType) or rep in typeDict
def _register(name, type, force=0):
"""Register the type object. Raise an exception if it is already registered
unless force is true.
"""
if name in typeDict and not force:
raise ValueError("Type %s has already been registered" % name)
typeDict[name] = type
return type
class NumericType(object):
"""Numeric type class
Used both as a type identification and the repository of
characteristics and conversion functions.
"""
def __new__(type, name, bytes, default, typeno):
"""__new__() implements a 'quasi-singleton pattern because attempts
to create duplicate types return the first created instance of that
particular type parameterization, i.e. the second time you try to
create "Int32", you get the original Int32, not a new one.
"""
if name in typeDict:
self = typeDict[name]
if self.bytes != bytes or self.default != default or \
self.typeno != typeno:
raise ValueError("Redeclaration of existing NumericType "\
"with different parameters.")
return self
else:
self = object.__new__(type)
self.name = "no name"
self.bytes = None
self.default = None
self.typeno = -1
return self
def __init__(self, name, bytes, default, typeno):
if not isinstance(name, str):
raise TypeError("name must be a string")
self.name = name
self.bytes = bytes
self.default = default
self.typeno = typeno
self._conv = None
_register(self.name, self)
def __getnewargs__(self):
"""support the pickling protocol."""
return (self.name, self.bytes, self.default, self.typeno)
def __getstate__(self):
"""support pickling protocol... no __setstate__ required."""
False
class BooleanType(NumericType):
pass
class SignedType:
"""Marker class used for signed type check"""
pass
class UnsignedType:
"""Marker class used for unsigned type check"""
pass
class IntegralType(NumericType):
pass
class SignedIntegralType(IntegralType, SignedType):
pass
class UnsignedIntegralType(IntegralType, UnsignedType):
pass
class FloatingType(NumericType):
pass
class ComplexType(NumericType):
pass
class AnyType(NumericType):
pass
class ObjectType(NumericType):
pass
# C-API Type Any
Any = AnyType("Any", None, None, _tAny)
Object = ObjectType("Object", None, None, _tObject)
# Numeric Types:
Bool = BooleanType("Bool", 1, 0, _tBool)
Int8 = SignedIntegralType( "Int8", 1, 0, _tInt8)
Int16 = SignedIntegralType("Int16", 2, 0, _tInt16)
Int32 = SignedIntegralType("Int32", 4, 0, _tInt32)
Int64 = SignedIntegralType("Int64", 8, 0, _tInt64)
Float32 = FloatingType("Float32", 4, 0.0, _tFloat32)
Float64 = FloatingType("Float64", 8, 0.0, _tFloat64)
UInt8 = UnsignedIntegralType( "UInt8", 1, 0, _tUInt8)
UInt16 = UnsignedIntegralType("UInt16", 2, 0, _tUInt16)
UInt32 = UnsignedIntegralType("UInt32", 4, 0, _tUInt32)
UInt64 = UnsignedIntegralType("UInt64", 8, 0, _tUInt64)
Complex32 = ComplexType("Complex32", 8, complex(0.0), _tComplex32)
Complex64 = ComplexType("Complex64", 16, complex(0.0), _tComplex64)
Object.dtype = 'O'
Bool.dtype = '?'
Int8.dtype = 'i1'
Int16.dtype = 'i2'
Int32.dtype = 'i4'
Int64.dtype = 'i8'
UInt8.dtype = 'u1'
UInt16.dtype = 'u2'
UInt32.dtype = 'u4'
UInt64.dtype = 'u8'
Float32.dtype = 'f4'
Float64.dtype = 'f8'
Complex32.dtype = 'c8'
Complex64.dtype = 'c16'
# Aliases
Byte = _register("Byte", Int8)
Short = _register("Short", Int16)
Int = _register("Int", Int32)
if LP64:
Long = _register("Long", Int64)
if HasUInt64:
_register("ULong", UInt64)
MaybeLong = _register("MaybeLong", Int64)
__all__.append('MaybeLong')
else:
Long = _register("Long", Int32)
_register("ULong", UInt32)
MaybeLong = _register("MaybeLong", Int32)
__all__.append('MaybeLong')
_register("UByte", UInt8)
_register("UShort", UInt16)
_register("UInt", UInt32)
Float = _register("Float", Float64)
Complex = _register("Complex", Complex64)
# short forms
_register("b1", Bool)
_register("u1", UInt8)
_register("u2", UInt16)
_register("u4", UInt32)
_register("i1", Int8)
_register("i2", Int16)
_register("i4", Int32)
_register("i8", Int64)
if HasUInt64:
_register("u8", UInt64)
_register("f4", Float32)
_register("f8", Float64)
_register("c8", Complex32)
_register("c16", Complex64)
# NumPy forms
_register("1", Int8)
_register("B", Bool)
_register("c", Int8)
_register("b", UInt8)
_register("s", Int16)
_register("w", UInt16)
_register("i", Int32)
_register("N", Int64)
_register("u", UInt32)
_register("U", UInt64)
if LP64:
_register("l", Int64)
else:
_register("l", Int32)
_register("d", Float64)
_register("f", Float32)
_register("D", Complex64)
_register("F", Complex32)
# scipy.base forms
def _scipy_alias(scipy_type, numarray_type):
_register(scipy_type, eval(numarray_type))
globals()[scipy_type] = globals()[numarray_type]
_scipy_alias("bool_", "Bool")
_scipy_alias("bool8", "Bool")
_scipy_alias("int8", "Int8")
_scipy_alias("uint8", "UInt8")
_scipy_alias("int16", "Int16")
_scipy_alias("uint16", "UInt16")
_scipy_alias("int32", "Int32")
_scipy_alias("uint32", "UInt32")
_scipy_alias("int64", "Int64")
_scipy_alias("uint64", "UInt64")
_scipy_alias("float64", "Float64")
_scipy_alias("float32", "Float32")
_scipy_alias("complex128", "Complex64")
_scipy_alias("complex64", "Complex32")
# The rest is used by numeric modules to determine conversions
# Ranking of types from lowest to highest (sorta)
if not HasUInt64:
genericTypeRank = ['Bool','Int8','UInt8','Int16','UInt16',
'Int32', 'UInt32', 'Int64',
'Float32','Float64', 'Complex32', 'Complex64', 'Object']
else:
genericTypeRank = ['Bool','Int8','UInt8','Int16','UInt16',
'Int32', 'UInt32', 'Int64', 'UInt64',
'Float32','Float64', 'Complex32', 'Complex64', 'Object']
pythonTypeRank = [ bool, int, long, float, complex ]
# The next line is not platform independent XXX Needs to be generalized
if not LP64:
pythonTypeMap = {
int:("Int32","int"),
long:("Int64","int"),
float:("Float64","float"),
complex:("Complex64","complex")}
scalarTypeMap = {
int:"Int32",
long:"Int64",
float:"Float64",
complex:"Complex64"}
else:
pythonTypeMap = {
int:("Int64","int"),
long:("Int64","int"),
float:("Float64","float"),
complex:("Complex64","complex")}
scalarTypeMap = {
int:"Int64",
long:"Int64",
float:"Float64",
complex:"Complex64"}
pythonTypeMap.update({bool:("Bool","bool") })
scalarTypeMap.update({bool:"Bool"})
# Generate coercion matrix
def _initGenericCoercions():
global genericCoercions
genericCoercions = {}
# vector with ...
for ntype1 in genericTypeRank:
nt1 = typeDict[ntype1]
rank1 = genericTypeRank.index(ntype1)
ntypesize1, inttype1, signedtype1 = nt1.bytes, \
isinstance(nt1, IntegralType), isinstance(nt1, SignedIntegralType)
for ntype2 in genericTypeRank:
# vector
nt2 = typeDict[ntype2]
ntypesize2, inttype2, signedtype2 = nt2.bytes, \
isinstance(nt2, IntegralType), isinstance(nt2, SignedIntegralType)
rank2 = genericTypeRank.index(ntype2)
if (signedtype1 != signedtype2) and inttype1 and inttype2:
# mixing of signed and unsigned ints is a special case
# If unsigned same size or larger, final size needs to be bigger
# if possible
if signedtype1:
if ntypesize2 >= ntypesize1:
size = min(2*ntypesize2, MAX_INT_SIZE)
else:
size = ntypesize1
else:
if ntypesize1 >= ntypesize2:
size = min(2*ntypesize1, MAX_INT_SIZE)
else:
size = ntypesize2
outtype = "Int"+str(8*size)
else:
if rank1 >= rank2:
outtype = ntype1
else:
outtype = ntype2
genericCoercions[(ntype1, ntype2)] = outtype
for ntype2 in pythonTypeRank:
# scalar
mapto, kind = pythonTypeMap[ntype2]
if ((inttype1 and kind=="int") or (not inttype1 and kind=="float")):
# both are of the same "kind" thus vector type dominates
outtype = ntype1
else:
rank2 = genericTypeRank.index(mapto)
if rank1 >= rank2:
outtype = ntype1
else:
outtype = mapto
genericCoercions[(ntype1, ntype2)] = outtype
genericCoercions[(ntype2, ntype1)] = outtype
# scalar-scalar
for ntype1 in pythonTypeRank:
maptype1 = scalarTypeMap[ntype1]
genericCoercions[(ntype1,)] = maptype1
for ntype2 in pythonTypeRank:
maptype2 = scalarTypeMap[ntype2]
genericCoercions[(ntype1, ntype2)] = genericCoercions[(maptype1, maptype2)]
# Special cases more easily dealt with outside of the loop
genericCoercions[("Complex32", "Float64")] = "Complex64"
genericCoercions[("Float64", "Complex32")] = "Complex64"
genericCoercions[("Complex32", "Int64")] = "Complex64"
genericCoercions[("Int64", "Complex32")] = "Complex64"
genericCoercions[("Complex32", "UInt64")] = "Complex64"
genericCoercions[("UInt64", "Complex32")] = "Complex64"
genericCoercions[("Int64","Float32")] = "Float64"
genericCoercions[("Float32", "Int64")] = "Float64"
genericCoercions[("UInt64","Float32")] = "Float64"
genericCoercions[("Float32", "UInt64")] = "Float64"
genericCoercions[(float, "Bool")] = "Float64"
genericCoercions[("Bool", float)] = "Float64"
genericCoercions[(float,float,float)] = "Float64" # for scipy.special
genericCoercions[(int,int,float)] = "Float64" # for scipy.special
_initGenericCoercions()
# If complex is subclassed, the following may not be necessary
genericPromotionExclusions = {
'Bool': (),
'Int8': (),
'Int16': (),
'Int32': ('Float32','Complex32'),
'UInt8': (),
'UInt16': (),
'UInt32': ('Float32','Complex32'),
'Int64' : ('Float32','Complex32'),
'UInt64' : ('Float32','Complex32'),
'Float32': (),
'Float64': ('Complex32',),
'Complex32':(),
'Complex64':()
} # e.g., don't allow promotion from Float64 to Complex32 or Int64 to Float32
# Numeric typecodes
typecodes = {'Integer': '1silN',
'UnsignedInteger': 'bBwuU',
'Float': 'fd',
'Character': 'c',
'Complex': 'FD' }
if HasUInt64:
_MaximumType = {
Bool : UInt64,
Int8 : Int64,
Int16 : Int64,
Int32 : Int64,
Int64 : Int64,
UInt8 : UInt64,
UInt16 : UInt64,
UInt32 : UInt64,
UInt8 : UInt64,
Float32 : Float64,
Float64 : Float64,
Complex32 : Complex64,
Complex64 : Complex64
}
else:
_MaximumType = {
Bool : Int64,
Int8 : Int64,
Int16 : Int64,
Int32 : Int64,
Int64 : Int64,
UInt8 : Int64,
UInt16 : Int64,
UInt32 : Int64,
UInt8 : Int64,
Float32 : Float64,
Float64 : Float64,
Complex32 : Complex64,
Complex64 : Complex64
}
def MaximumType(t):
"""returns the type of highest precision of the same general kind as 't'"""
return _MaximumType[t]
def getType(type):
"""Return the numeric type object for type
type may be the name of a type object or the actual object
"""
if isinstance(type, NumericType):
return type
try:
return typeDict[type]
except KeyError:
raise TypeError("Not a numeric type")
scalarTypes = (bool,int,long,float,complex)
_scipy_dtypechar = {
Int8 : 'b',
UInt8 : 'B',
Int16 : 'h',
UInt16 : 'H',
Int32 : 'i',
UInt32 : 'I',
Int64 : 'q',
UInt64 : 'Q',
Float32 : 'f',
Float64 : 'd',
Complex32 : 'F', # Note the switchup here:
Complex64 : 'D' # numarray.Complex32 == scipy.complex64, etc.
}
_scipy_dtypechar_inverse = {}
for key,value in _scipy_dtypechar.items():
_scipy_dtypechar_inverse[value] = key
_val = numpy.int_(0).itemsize
if _val == 8:
_scipy_dtypechar_inverse['l'] = Int64
_scipy_dtypechar_inverse['L'] = UInt64
elif _val == 4:
_scipy_dtypechar_inverse['l'] = Int32
_scipy_dtypechar_inverse['L'] = UInt32
del _val
if LP64:
_scipy_dtypechar_inverse['p'] = Int64
_scipy_dtypechar_inverse['P'] = UInt64
else:
_scipy_dtypechar_inverse['p'] = Int32
_scipy_dtypechar_inverse['P'] = UInt32
def typefrom(obj):
return _scipy_dtypechar_inverse[obj.dtype.char]
| Python |
__all__ = ['NewAxis', 'ArrayType']
from numpy import newaxis as NewAxis, ndarray as ArrayType
| Python |
__all__ = ['abs', 'absolute', 'add', 'arccos', 'arccosh', 'arcsin', 'arcsinh',
'arctan', 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_not',
'bitwise_or', 'bitwise_xor', 'ceil', 'cos', 'cosh', 'divide',
'equal', 'exp', 'fabs', 'floor', 'floor_divide',
'fmod', 'greater', 'greater_equal', 'hypot', 'isnan',
'less', 'less_equal', 'log', 'log10', 'logical_and', 'logical_not',
'logical_or', 'logical_xor', 'lshift', 'maximum', 'minimum',
'minus', 'multiply', 'negative', 'not_equal',
'power', 'product', 'remainder', 'rshift', 'sin', 'sinh', 'sqrt',
'subtract', 'sum', 'tan', 'tanh', 'true_divide',
'conjugate', 'sign']
from numpy import absolute as abs, absolute, add, arccos, arccosh, arcsin, \
arcsinh, arctan, arctan2, arctanh, bitwise_and, invert as bitwise_not, \
bitwise_or, bitwise_xor, ceil, cos, cosh, divide, \
equal, exp, fabs, floor, floor_divide, fmod, greater, greater_equal, \
hypot, isnan, less, less_equal, log, log10, logical_and, \
logical_not, logical_or, logical_xor, left_shift as lshift, \
maximum, minimum, negative as minus, multiply, negative, \
not_equal, power, product, remainder, right_shift as rshift, sin, \
sinh, sqrt, subtract, sum, tan, tanh, true_divide, conjugate, sign
| Python |
try:
from stsci.convolve import *
except ImportError:
try:
from scipy.stsci.convolve import *
except ImportError:
msg = \
"""The convolve package is not installed.
It can be downloaded by checking out the latest source from
http://svn.scipy.org/svn/scipy/trunk/Lib/stsci or by downloading and
installing all of SciPy from http://www.scipy.org.
"""
raise ImportError(msg)
| Python |
""" This module contains a "session saver" which saves the state of a
NumPy session to a file. At a later time, a different Python
process can be started and the saved session can be restored using
load().
The session saver relies on the Python pickle protocol to save and
restore objects. Objects which are not themselves picklable (e.g.
modules) can sometimes be saved by "proxy", particularly when they
are global constants of some kind. If it's not known that proxying
will work, a warning is issued at save time. If a proxy fails to
reload properly (e.g. because it's not a global constant), a warning
is issued at reload time and that name is bound to a _ProxyFailure
instance which tries to identify what should have been restored.
First, some unfortunate (probably unnecessary) concessions to doctest
to keep the test run free of warnings.
>>> del _PROXY_ALLOWED
>>> del __builtins__
By default, save() stores every variable in the caller's namespace:
>>> import numpy as na
>>> a = na.arange(10)
>>> save()
Alternately, save() can be passed a comma seperated string of variables:
>>> save("a,na")
Alternately, save() can be passed a dictionary, typically one you already
have lying around somewhere rather than created inline as shown here:
>>> save(dictionary={"a":a,"na":na})
If both variables and a dictionary are specified, the variables to be
saved are taken from the dictionary.
>>> save(variables="a,na",dictionary={"a":a,"na":na})
Remove names from the session namespace
>>> del a, na
By default, load() restores every variable/object in the session file
to the caller's namespace.
>>> load()
load() can be passed a comma seperated string of variables to be
restored from the session file to the caller's namespace:
>>> load("a,na")
load() can also be passed a dictionary to *restore to*:
>>> d = {}
>>> load(dictionary=d)
load can be passed both a list variables of variables to restore and a
dictionary to restore to:
>>> load(variables="a,na", dictionary=d)
>>> na.all(a == na.arange(10))
1
>>> na.__name__
'numpy'
NOTE: session saving is faked for modules using module proxy objects.
Saved modules are re-imported at load time but any "state" in the module
which is not restored by a simple import is lost.
"""
__all__ = ['load', 'save']
import sys
import pickle
SAVEFILE="session.dat"
VERBOSE = False # global import-time override
def _foo(): pass
_PROXY_ALLOWED = (type(sys), # module
type(_foo), # function
type(None)) # None
def _update_proxy_types():
"""Suppress warnings for known un-picklables with working proxies."""
pass
def _unknown(_type):
"""returns True iff _type isn't known as OK to proxy"""
return (_type is not None) and (_type not in _PROXY_ALLOWED)
# caller() from the following article with one extra f_back added.
# from http://www.python.org/search/hypermail/python-1994q1/0506.html
# SUBJECT: import ( how to put a symbol into caller's namespace )
# SENDER: Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
# DATE: Thu, 24 Mar 1994 15:38:53 -0500
def _caller():
"""caller() returns the frame object of the function's caller."""
try:
1 + '' # make an error happen
except: # and return the caller's caller's frame
return sys.exc_traceback.tb_frame.f_back.f_back.f_back
def _callers_globals():
"""callers_globals() returns the global dictionary of the caller."""
frame = _caller()
return frame.f_globals
def _callers_modules():
"""returns a list containing the names of all the modules in the caller's
global namespace."""
g = _callers_globals()
mods = []
for k,v in g.items():
if type(v) == type(sys):
mods.append(getattr(v,"__name__"))
return mods
def _errout(*args):
for a in args:
print >>sys.stderr, a,
print >>sys.stderr
def _verbose(*args):
if VERBOSE:
_errout(*args)
class _ProxyingFailure:
"""Object which is bound to a variable for a proxy pickle which failed to reload"""
def __init__(self, module, name, type=None):
self.module = module
self.name = name
self.type = type
def __repr__(self):
return "ProxyingFailure('%s','%s','%s')" % (self.module, self.name, self.type)
class _ModuleProxy(object):
"""Proxy object which fakes pickling a module"""
def __new__(_type, name, save=False):
if save:
_verbose("proxying module", name)
self = object.__new__(_type)
self.name = name
else:
_verbose("loading module proxy", name)
try:
self = _loadmodule(name)
except ImportError:
_errout("warning: module", name,"import failed.")
return self
def __getnewargs__(self):
return (self.name,)
def __getstate__(self):
return False
def _loadmodule(module):
if module not in sys.modules:
modules = module.split(".")
s = ""
for i in range(len(modules)):
s = ".".join(modules[:i+1])
exec "import " + s
return sys.modules[module]
class _ObjectProxy(object):
"""Proxy object which fakes pickling an arbitrary object. Only global
constants can really be proxied."""
def __new__(_type, module, name, _type2, save=False):
if save:
if _unknown(_type2):
_errout("warning: proxying object", module + "." + name,
"of type", _type2, "because it wouldn't pickle...",
"it may not reload later.")
else:
_verbose("proxying object", module, name)
self = object.__new__(_type)
self.module, self.name, self.type = module, name, str(_type2)
else:
_verbose("loading object proxy", module, name)
try:
m = _loadmodule(module)
except (ImportError, KeyError):
_errout("warning: loading object proxy", module + "." + name,
"module import failed.")
return _ProxyingFailure(module,name,_type2)
try:
self = getattr(m, name)
except AttributeError:
_errout("warning: object proxy", module + "." + name,
"wouldn't reload from", m)
return _ProxyingFailure(module,name,_type2)
return self
def __getnewargs__(self):
return (self.module, self.name, self.type)
def __getstate__(self):
return False
class _SaveSession(object):
"""Tag object which marks the end of a save session and holds the
saved session variable names as a list of strings in the same
order as the session pickles."""
def __new__(_type, keys, save=False):
if save:
_verbose("saving session", keys)
else:
_verbose("loading session", keys)
self = object.__new__(_type)
self.keys = keys
return self
def __getnewargs__(self):
return (self.keys,)
def __getstate__(self):
return False
class ObjectNotFound(RuntimeError):
pass
def _locate(modules, object):
for mname in modules:
m = sys.modules[mname]
if m:
for k,v in m.__dict__.items():
if v is object:
return m.__name__, k
else:
raise ObjectNotFound(k)
def save(variables=None, file=SAVEFILE, dictionary=None, verbose=False):
"""saves variables from a numpy session to a file. Variables
which won't pickle are "proxied" if possible.
'variables' a string of comma seperated variables: e.g. "a,b,c"
Defaults to dictionary.keys().
'file' a filename or file object for the session file.
'dictionary' the dictionary in which to look up the variables.
Defaults to the caller's globals()
'verbose' print additional debug output when True.
"""
global VERBOSE
VERBOSE = verbose
_update_proxy_types()
if isinstance(file, str):
file = open(file, "wb")
if dictionary is None:
dictionary = _callers_globals()
if variables is None:
keys = dictionary.keys()
else:
keys = variables.split(",")
source_modules = _callers_modules() + sys.modules.keys()
p = pickle.Pickler(file, protocol=2)
_verbose("variables:",keys)
for k in keys:
v = dictionary[k]
_verbose("saving", k, type(v))
try: # Try to write an ordinary pickle
p.dump(v)
_verbose("pickled", k)
except (pickle.PicklingError, TypeError, SystemError):
# Use proxies for stuff that won't pickle
if isinstance(v, type(sys)): # module
proxy = _ModuleProxy(v.__name__, save=True)
else:
try:
module, name = _locate(source_modules, v)
except ObjectNotFound:
_errout("warning: couldn't find object",k,
"in any module... skipping.")
continue
else:
proxy = _ObjectProxy(module, name, type(v), save=True)
p.dump(proxy)
o = _SaveSession(keys, save=True)
p.dump(o)
file.close()
def load(variables=None, file=SAVEFILE, dictionary=None, verbose=False):
"""load a numpy session from a file and store the specified
'variables' into 'dictionary'.
'variables' a string of comma seperated variables: e.g. "a,b,c"
Defaults to dictionary.keys().
'file' a filename or file object for the session file.
'dictionary' the dictionary in which to look up the variables.
Defaults to the caller's globals()
'verbose' print additional debug output when True.
"""
global VERBOSE
VERBOSE = verbose
if isinstance(file, str):
file = open(file, "rb")
if dictionary is None:
dictionary = _callers_globals()
values = []
p = pickle.Unpickler(file)
while 1:
o = p.load()
if isinstance(o, _SaveSession):
session = dict(zip(o.keys, values))
_verbose("updating dictionary with session variables.")
if variables is None:
keys = session.keys()
else:
keys = variables.split(",")
for k in keys:
dictionary[k] = session[k]
return None
else:
_verbose("unpickled object", str(o))
values.append(o)
def test():
import doctest, numpy.numarray.session
return doctest.testmod(numpy.numarray.session)
| Python |
from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('numarray',parent_package,top_path)
config.add_data_files('include/numpy/*')
config.add_extension('_capi',
sources=['_capi.c'],
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
| Python |
try:
from ndimage import *
except ImportError:
try:
from scipy.ndimage import *
except ImportError:
msg = \
"""The nd_image package is not installed
It can be downloaded by checking out the latest source from
http://svn.scipy.org/svn/scipy/trunk/Lib/ndimage or by downloading and
installing all of SciPy from http://www.scipy.org.
"""
raise ImportError(msg)
| Python |
from numpy.oldnumeric.mlab import *
import numpy.oldnumeric.mlab as nom
__all__ = nom.__all__
del nom
| Python |
"""
This module converts code written for numpy.numarray to work
with numpy
FIXME: finish this.
"""
#__all__ = ['convertfile', 'convertall', 'converttree']
__all__ = []
import warnings
warnings.warn("numpy.numarray.alter_code2 is not working yet.")
import sys
import os
import glob
def makenewfile(name, filestr):
fid = file(name, 'w')
fid.write(filestr)
fid.close()
def getandcopy(name):
fid = file(name)
filestr = fid.read()
fid.close()
base, ext = os.path.splitext(name)
makenewfile(base+'.orig', filestr)
return filestr
def convertfile(filename):
"""Convert the filename given from using Numeric to using NumPy
Copies the file to filename.orig and then over-writes the file
with the updated code
"""
filestr = getandcopy(filename)
filestr = fromstr(filestr)
makenewfile(filename, filestr)
def fromargs(args):
filename = args[1]
convertfile(filename)
def convertall(direc=os.path.curdir):
"""Convert all .py files to use NumPy (from Numeric) in the directory given
For each file, a backup of <usesnumeric>.py is made as
<usesnumeric>.py.orig. A new file named <usesnumeric>.py
is then written with the updated code.
"""
files = glob.glob(os.path.join(direc,'*.py'))
for afile in files:
convertfile(afile)
def _func(arg, dirname, fnames):
convertall(dirname)
def converttree(direc=os.path.curdir):
"""Convert all .py files in the tree given
"""
os.path.walk(direc, _func, None)
if __name__ == '__main__':
fromargs(sys.argv)
| Python |
from numpy.oldnumeric.linear_algebra import *
import numpy.oldnumeric.linear_algebra as nol
__all__ = list(nol.__all__)
__all__ += ['qr_decomposition']
from numpy.linalg import qr as _qr
def qr_decomposition(a, mode='full'):
res = _qr(a, mode)
if mode == 'full':
return res
return (None, res)
| Python |
from os.path import join
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('numarray',parent_package,top_path)
config.add_data_files('include/numpy/')
config.add_sconscript('SConstruct', source_files = ['_capi.c'])
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
| Python |
from numpy.oldnumeric.ma import *
| Python |
__all__ = ['ArgumentError', 'F', 'beta', 'binomial', 'chi_square',
'exponential', 'gamma', 'get_seed', 'multinomial',
'multivariate_normal', 'negative_binomial', 'noncentral_F',
'noncentral_chi_square', 'normal', 'permutation', 'poisson',
'randint', 'random', 'random_integers', 'standard_normal',
'uniform', 'seed']
from numpy.oldnumeric.random_array import *
| Python |
import os
import numpy as np
__all__ = ['MathDomainError', 'UnderflowError', 'NumOverflowError',
'handleError', 'get_numarray_include_dirs']
class MathDomainError(ArithmeticError):
pass
class UnderflowError(ArithmeticError):
pass
class NumOverflowError(OverflowError, ArithmeticError):
pass
def handleError(errorStatus, sourcemsg):
"""Take error status and use error mode to handle it."""
modes = np.geterr()
if errorStatus & np.FPE_INVALID:
if modes['invalid'] == "warn":
print "Warning: Encountered invalid numeric result(s)", sourcemsg
if modes['invalid'] == "raise":
raise MathDomainError(sourcemsg)
if errorStatus & np.FPE_DIVIDEBYZERO:
if modes['dividebyzero'] == "warn":
print "Warning: Encountered divide by zero(s)", sourcemsg
if modes['dividebyzero'] == "raise":
raise ZeroDivisionError(sourcemsg)
if errorStatus & np.FPE_OVERFLOW:
if modes['overflow'] == "warn":
print "Warning: Encountered overflow(s)", sourcemsg
if modes['overflow'] == "raise":
raise NumOverflowError(sourcemsg)
if errorStatus & np.FPE_UNDERFLOW:
if modes['underflow'] == "warn":
print "Warning: Encountered underflow(s)", sourcemsg
if modes['underflow'] == "raise":
raise UnderflowError(sourcemsg)
def get_numarray_include_dirs():
base = os.path.dirname(np.__file__)
newdirs = [os.path.join(base, 'numarray', 'include')]
return newdirs
| Python |
from numpy.oldnumeric.fft import *
import numpy.oldnumeric.fft as nof
__all__ = nof.__all__
del nof
| Python |
__all__ = ['Matrix']
from numpy import matrix as _matrix
def Matrix(data, typecode=None, copy=1, savespace=0):
return _matrix(data, typecode, copy=copy)
| Python |
# missing Numarray defined names (in from numarray import *)
##__all__ = ['ClassicUnpickler', 'Complex32_fromtype',
## 'Complex64_fromtype', 'ComplexArray', 'Error',
## 'MAX_ALIGN', 'MAX_INT_SIZE', 'MAX_LINE_WIDTH',
## 'NDArray', 'NewArray', 'NumArray',
## 'NumError', 'PRECISION', 'Py2NumType',
## 'PyINT_TYPES', 'PyLevel2Type', 'PyNUMERIC_TYPES', 'PyREAL_TYPES',
## 'SUPPRESS_SMALL',
## 'SuitableBuffer', 'USING_BLAS',
## 'UsesOpPriority',
## 'codegenerator', 'generic', 'libnumarray', 'libnumeric',
## 'make_ufuncs', 'memory',
## 'numarrayall', 'numarraycore', 'numinclude', 'safethread',
## 'typecode', 'typecodes', 'typeconv', 'ufunc', 'ufuncFactory',
## 'ieeemask']
__all__ = ['asarray', 'ones', 'zeros', 'array', 'where']
__all__ += ['vdot', 'dot', 'matrixmultiply', 'ravel', 'indices',
'arange', 'concatenate', 'all', 'allclose', 'alltrue', 'and_',
'any', 'argmax', 'argmin', 'argsort', 'around', 'array_equal',
'array_equiv', 'arrayrange', 'array_str', 'array_repr',
'array2list', 'average', 'choose', 'CLIP', 'RAISE', 'WRAP',
'clip', 'compress', 'copy', 'copy_reg',
'diagonal', 'divide_remainder', 'e', 'explicit_type', 'pi',
'flush_caches', 'fromfile', 'os', 'sys', 'STRICT',
'SLOPPY', 'WARN', 'EarlyEOFError', 'SizeMismatchError',
'SizeMismatchWarning', 'FileSeekWarning', 'fromstring',
'fromfunction', 'fromlist', 'getShape', 'getTypeObject',
'identity', 'info', 'innerproduct', 'inputarray',
'isBigEndian', 'kroneckerproduct', 'lexsort', 'math',
'operator', 'outerproduct', 'put', 'putmask', 'rank',
'repeat', 'reshape', 'resize', 'round', 'searchsorted',
'shape', 'size', 'sometrue', 'sort', 'swapaxes', 'take',
'tcode', 'tname', 'tensormultiply', 'trace', 'transpose',
'types', 'value', 'cumsum', 'cumproduct', 'nonzero', 'newobj',
'togglebyteorder'
]
import copy
import copy_reg
import types
import os
import sys
import math
import operator
from numpy import dot as matrixmultiply, dot, vdot, ravel, concatenate, all,\
allclose, any, argsort, array_equal, array_equiv,\
array_str, array_repr, CLIP, RAISE, WRAP, clip, concatenate, \
diagonal, e, pi, inner as innerproduct, nonzero, \
outer as outerproduct, kron as kroneckerproduct, lexsort, putmask, rank, \
resize, searchsorted, shape, size, sort, swapaxes, trace, transpose
import numpy as np
from numerictypes import typefrom
if sys.version_info[0] >= 3:
import copyreg as copy_reg
isBigEndian = sys.byteorder != 'little'
value = tcode = 'f'
tname = 'Float32'
# If dtype is not None, then it is used
# If type is not None, then it is used
# If typecode is not None then it is used
# If use_default is True, then the default
# data-type is returned if all are None
def type2dtype(typecode, type, dtype, use_default=True):
if dtype is None:
if type is None:
if use_default or typecode is not None:
dtype = np.dtype(typecode)
else:
dtype = np.dtype(type)
if use_default and dtype is None:
dtype = np.dtype('int')
return dtype
def fromfunction(shape, dimensions, type=None, typecode=None, dtype=None):
dtype = type2dtype(typecode, type, dtype, 1)
return np.fromfunction(shape, dimensions, dtype=dtype)
def ones(shape, type=None, typecode=None, dtype=None):
dtype = type2dtype(typecode, type, dtype, 1)
return np.ones(shape, dtype)
def zeros(shape, type=None, typecode=None, dtype=None):
dtype = type2dtype(typecode, type, dtype, 1)
return np.zeros(shape, dtype)
def where(condition, x=None, y=None, out=None):
if x is None and y is None:
arr = np.where(condition)
else:
arr = np.where(condition, x, y)
if out is not None:
out[...] = arr
return out
return arr
def indices(shape, type=None):
return np.indices(shape, type)
def arange(a1, a2=None, stride=1, type=None, shape=None,
typecode=None, dtype=None):
dtype = type2dtype(typecode, type, dtype, 0)
return np.arange(a1, a2, stride, dtype)
arrayrange = arange
def alltrue(x, axis=0):
return np.alltrue(x, axis)
def and_(a, b):
"""Same as a & b
"""
return a & b
def divide_remainder(a, b):
a, b = asarray(a), asarray(b)
return (a/b,a%b)
def around(array, digits=0, output=None):
ret = np.around(array, digits, output)
if output is None:
return ret
return
def array2list(arr):
return arr.tolist()
def choose(selector, population, outarr=None, clipmode=RAISE):
a = np.asarray(selector)
ret = a.choose(population, out=outarr, mode=clipmode)
if outarr is None:
return ret
return
def compress(condition, a, axis=0):
return np.compress(condition, a, axis)
# only returns a view
def explicit_type(a):
x = a.view()
return x
# stub
def flush_caches():
pass
class EarlyEOFError(Exception):
"Raised in fromfile() if EOF unexpectedly occurs."
pass
class SizeMismatchError(Exception):
"Raised in fromfile() if file size does not match shape."
pass
class SizeMismatchWarning(Warning):
"Issued in fromfile() if file size does not match shape."
pass
class FileSeekWarning(Warning):
"Issued in fromfile() if there is unused data and seek() fails"
pass
STRICT, SLOPPY, WARN = range(3)
_BLOCKSIZE=1024
# taken and adapted directly from numarray
def fromfile(infile, type=None, shape=None, sizing=STRICT,
typecode=None, dtype=None):
if isinstance(infile, (str, unicode)):
infile = open(infile, 'rb')
dtype = type2dtype(typecode, type, dtype, True)
if shape is None:
shape = (-1,)
if not isinstance(shape, tuple):
shape = (shape,)
if (list(shape).count(-1)>1):
raise ValueError("At most one unspecified dimension in shape")
if -1 not in shape:
if sizing != STRICT:
raise ValueError("sizing must be STRICT if size complete")
arr = np.empty(shape, dtype)
bytesleft=arr.nbytes
bytesread=0
while(bytesleft > _BLOCKSIZE):
data = infile.read(_BLOCKSIZE)
if len(data) != _BLOCKSIZE:
raise EarlyEOFError("Unexpected EOF reading data for size complete array")
arr.data[bytesread:bytesread+_BLOCKSIZE]=data
bytesread += _BLOCKSIZE
bytesleft -= _BLOCKSIZE
if bytesleft > 0:
data = infile.read(bytesleft)
if len(data) != bytesleft:
raise EarlyEOFError("Unexpected EOF reading data for size complete array")
arr.data[bytesread:bytesread+bytesleft]=data
return arr
##shape is incompletely specified
##read until EOF
##implementation 1: naively use memory blocks
##problematic because memory allocation can be double what is
##necessary (!)
##the most common case, namely reading in data from an unchanging
##file whose size may be determined before allocation, should be
##quick -- only one allocation will be needed.
recsize = dtype.itemsize * np.product([i for i in shape if i != -1])
blocksize = max(_BLOCKSIZE/recsize, 1)*recsize
##try to estimate file size
try:
curpos=infile.tell()
infile.seek(0,2)
endpos=infile.tell()
infile.seek(curpos)
except (AttributeError, IOError):
initsize=blocksize
else:
initsize=max(1,(endpos-curpos)/recsize)*recsize
buf = np.newbuffer(initsize)
bytesread=0
while 1:
data=infile.read(blocksize)
if len(data) != blocksize: ##eof
break
##do we have space?
if len(buf) < bytesread+blocksize:
buf=_resizebuf(buf,len(buf)+blocksize)
## or rather a=resizebuf(a,2*len(a)) ?
assert len(buf) >= bytesread+blocksize
buf[bytesread:bytesread+blocksize]=data
bytesread += blocksize
if len(data) % recsize != 0:
if sizing == STRICT:
raise SizeMismatchError("Filesize does not match specified shape")
if sizing == WARN:
_warnings.warn("Filesize does not match specified shape",
SizeMismatchWarning)
try:
infile.seek(-(len(data) % recsize),1)
except AttributeError:
_warnings.warn("Could not rewind (no seek support)",
FileSeekWarning)
except IOError:
_warnings.warn("Could not rewind (IOError in seek)",
FileSeekWarning)
datasize = (len(data)/recsize) * recsize
if len(buf) != bytesread+datasize:
buf=_resizebuf(buf,bytesread+datasize)
buf[bytesread:bytesread+datasize]=data[:datasize]
##deduce shape from len(buf)
shape = list(shape)
uidx = shape.index(-1)
shape[uidx]=len(buf) / recsize
a = np.ndarray(shape=shape, dtype=type, buffer=buf)
if a.dtype.char == '?':
np.not_equal(a, 0, a)
return a
def fromstring(datastring, type=None, shape=None, typecode=None, dtype=None):
dtype = type2dtype(typecode, type, dtype, True)
if shape is None:
count = -1
else:
count = np.product(shape)
res = np.fromstring(datastring, dtype=dtype, count=count)
if shape is not None:
res.shape = shape
return res
# check_overflow is ignored
def fromlist(seq, type=None, shape=None, check_overflow=0, typecode=None, dtype=None):
dtype = type2dtype(typecode, type, dtype, False)
return np.array(seq, dtype)
def array(sequence=None, typecode=None, copy=1, savespace=0,
type=None, shape=None, dtype=None):
dtype = type2dtype(typecode, type, dtype, 0)
if sequence is None:
if shape is None:
return None
if dtype is None:
dtype = 'l'
return np.empty(shape, dtype)
if isinstance(sequence, file):
return fromfile(sequence, dtype=dtype, shape=shape)
if isinstance(sequence, str):
return fromstring(sequence, dtype=dtype, shape=shape)
if isinstance(sequence, buffer):
arr = np.frombuffer(sequence, dtype=dtype)
else:
arr = np.array(sequence, dtype, copy=copy)
if shape is not None:
arr.shape = shape
return arr
def asarray(seq, type=None, typecode=None, dtype=None):
if isinstance(seq, np.ndarray) and type is None and \
typecode is None and dtype is None:
return seq
return array(seq, type=type, typecode=typecode, copy=0, dtype=dtype)
inputarray = asarray
def getTypeObject(sequence, type):
if type is not None:
return type
try:
return typefrom(np.array(sequence))
except:
raise TypeError("Can't determine a reasonable type from sequence")
def getShape(shape, *args):
try:
if shape is () and not args:
return ()
if len(args) > 0:
shape = (shape, ) + args
else:
shape = tuple(shape)
dummy = np.array(shape)
if not issubclass(dummy.dtype.type, np.integer):
raise TypeError
if len(dummy) > np.MAXDIMS:
raise TypeError
except:
raise TypeError("Shape must be a sequence of integers")
return shape
def identity(n, type=None, typecode=None, dtype=None):
dtype = type2dtype(typecode, type, dtype, True)
return np.identity(n, dtype)
def info(obj, output=sys.stdout, numpy=0):
if numpy:
bp = lambda x: x
else:
bp = lambda x: int(x)
cls = getattr(obj, '__class__', type(obj))
if numpy:
nm = getattr(cls, '__name__', cls)
else:
nm = cls
print >> output, "class: ", nm
print >> output, "shape: ", obj.shape
strides = obj.strides
print >> output, "strides: ", strides
if not numpy:
print >> output, "byteoffset: 0"
if len(strides) > 0:
bs = obj.strides[0]
else:
bs = obj.itemsize
print >> output, "bytestride: ", bs
print >> output, "itemsize: ", obj.itemsize
print >> output, "aligned: ", bp(obj.flags.aligned)
print >> output, "contiguous: ", bp(obj.flags.contiguous)
if numpy:
print >> output, "fortran: ", obj.flags.fortran
if not numpy:
print >> output, "buffer: ", repr(obj.data)
if not numpy:
extra = " (DEBUG ONLY)"
tic = "'"
else:
extra = ""
tic = ""
print >> output, "data pointer: %s%s" % (hex(obj.ctypes._as_parameter_.value), extra)
print >> output, "byteorder: ",
endian = obj.dtype.byteorder
if endian in ['|','=']:
print >> output, "%s%s%s" % (tic, sys.byteorder, tic)
byteswap = False
elif endian == '>':
print >> output, "%sbig%s" % (tic, tic)
byteswap = sys.byteorder != "big"
else:
print >> output, "%slittle%s" % (tic, tic)
byteswap = sys.byteorder != "little"
print >> output, "byteswap: ", bp(byteswap)
if not numpy:
print >> output, "type: ", typefrom(obj).name
else:
print >> output, "type: %s" % obj.dtype
#clipmode is ignored if axis is not 0 and array is not 1d
def put(array, indices, values, axis=0, clipmode=RAISE):
if not isinstance(array, np.ndarray):
raise TypeError("put only works on subclass of ndarray")
work = asarray(array)
if axis == 0:
if array.ndim == 1:
work.put(indices, values, clipmode)
else:
work[indices] = values
elif isinstance(axis, (int, long, np.integer)):
work = work.swapaxes(0, axis)
work[indices] = values
work = work.swapaxes(0, axis)
else:
def_axes = range(work.ndim)
for x in axis:
def_axes.remove(x)
axis = list(axis)+def_axes
work = work.transpose(axis)
work[indices] = values
work = work.transpose(axis)
def repeat(array, repeats, axis=0):
return np.repeat(array, repeats, axis)
def reshape(array, shape, *args):
if len(args) > 0:
shape = (shape,) + args
return np.reshape(array, shape)
import warnings as _warnings
def round(*args, **keys):
_warnings.warn("round() is deprecated. Switch to around()",
DeprecationWarning)
return around(*args, **keys)
def sometrue(array, axis=0):
return np.sometrue(array, axis)
#clipmode is ignored if axis is not an integer
def take(array, indices, axis=0, outarr=None, clipmode=RAISE):
array = np.asarray(array)
if isinstance(axis, (int, long, np.integer)):
res = array.take(indices, axis, outarr, clipmode)
if outarr is None:
return res
return
else:
def_axes = range(array.ndim)
for x in axis:
def_axes.remove(x)
axis = list(axis) + def_axes
work = array.transpose(axis)
res = work[indices]
if outarr is None:
return res
outarr[...] = res
return
def tensormultiply(a1, a2):
a1, a2 = np.asarray(a1), np.asarray(a2)
if (a1.shape[-1] != a2.shape[0]):
raise ValueError("Unmatched dimensions")
shape = a1.shape[:-1] + a2.shape[1:]
return np.reshape(dot(np.reshape(a1, (-1, a1.shape[-1])),
np.reshape(a2, (a2.shape[0],-1))),
shape)
def cumsum(a1, axis=0, out=None, type=None, dim=0):
return np.asarray(a1).cumsum(axis,dtype=type,out=out)
def cumproduct(a1, axis=0, out=None, type=None, dim=0):
return np.asarray(a1).cumprod(axis,dtype=type,out=out)
def argmax(x, axis=-1):
return np.argmax(x, axis)
def argmin(x, axis=-1):
return np.argmin(x, axis)
def newobj(self, type):
if type is None:
return np.empty_like(self)
else:
return np.empty(self.shape, type)
def togglebyteorder(self):
self.dtype=self.dtype.newbyteorder()
def average(a, axis=0, weights=None, returned=0):
return np.average(a, axis, weights, returned)
| Python |
"""
This module converts code written for numarray to run with numpy
Makes the following changes:
* Changes import statements
import numarray.package
--> import numpy.numarray.package as numarray_package
with all numarray.package in code changed to numarray_package
import numarray --> import numpy.numarray as numarray
import numarray.package as <yyy> --> import numpy.numarray.package as <yyy>
from numarray import <xxx> --> from numpy.numarray import <xxx>
from numarray.package import <xxx>
--> from numpy.numarray.package import <xxx>
package can be convolve, image, nd_image, mlab, linear_algebra, ma,
matrix, fft, random_array
* Makes search and replace changes to:
- .imaginary --> .imag
- .flat --> .ravel() (most of the time)
- .byteswapped() --> .byteswap(False)
- .byteswap() --> .byteswap(True)
- .info() --> numarray.info(self)
- .isaligned() --> .flags.aligned
- .isbyteswapped() --> (not .dtype.isnative)
- .typecode() --> .dtype.char
- .iscontiguous() --> .flags.contiguous
- .is_c_array() --> .flags.carray and .dtype.isnative
- .is_fortran_contiguous() --> .flags.fortran
- .is_f_array() --> .dtype.isnative and .flags.farray
- .itemsize() --> .itemsize
- .nelements() --> .size
- self.new(type) --> numarray.newobj(self, type)
- .repeat(r) --> .repeat(r, axis=0)
- .size() --> .size
- self.type() -- numarray.typefrom(self)
- .typecode() --> .dtype.char
- .stddev() --> .std()
- .togglebyteorder() --> numarray.togglebyteorder(self)
- .getshape() --> .shape
- .setshape(obj) --> .shape=obj
- .getflat() --> .ravel()
- .getreal() --> .real
- .setreal() --> .real =
- .getimag() --> .imag
- .setimag() --> .imag =
- .getimaginary() --> .imag
- .setimaginary() --> .imag
"""
__all__ = ['convertfile', 'convertall', 'converttree', 'convertsrc']
import sys
import os
import re
import glob
def changeimports(fstr, name, newname):
importstr = 'import %s' % name
importasstr = 'import %s as ' % name
fromstr = 'from %s import ' % name
fromall=0
name_ = name
if ('.' in name):
name_ = name.replace('.','_')
fstr = re.sub(r'(import\s+[^,\n\r]+,\s*)(%s)' % name,
"\\1%s as %s" % (newname, name), fstr)
fstr = fstr.replace(importasstr, 'import %s as ' % newname)
fstr = fstr.replace(importstr, 'import %s as %s' % (newname,name_))
if (name_ != name):
fstr = fstr.replace(name, name_)
ind = 0
Nlen = len(fromstr)
Nlen2 = len("from %s import " % newname)
while 1:
found = fstr.find(fromstr,ind)
if (found < 0):
break
ind = found + Nlen
if fstr[ind] == '*':
continue
fstr = "%sfrom %s import %s" % (fstr[:found], newname, fstr[ind:])
ind += Nlen2 - Nlen
return fstr, fromall
flatindex_re = re.compile('([.]flat(\s*?[[=]))')
def addimport(astr):
# find the first line with import on it
ind = astr.find('import')
start = astr.rfind(os.linesep, 0, ind)
astr = "%s%s%s%s" % (astr[:start], os.linesep,
"import numpy.numarray as numarray",
astr[start:])
return astr
def replaceattr(astr):
astr = astr.replace(".imaginary", ".imag")
astr = astr.replace(".byteswapped()",".byteswap(False)")
astr = astr.replace(".byteswap()", ".byteswap(True)")
astr = astr.replace(".isaligned()", ".flags.aligned")
astr = astr.replace(".iscontiguous()",".flags.contiguous")
astr = astr.replace(".is_fortran_contiguous()",".flags.fortran")
astr = astr.replace(".itemsize()",".itemsize")
astr = astr.replace(".size()",".size")
astr = astr.replace(".nelements()",".size")
astr = astr.replace(".typecode()",".dtype.char")
astr = astr.replace(".stddev()",".std()")
astr = astr.replace(".getshape()", ".shape")
astr = astr.replace(".getflat()", ".ravel()")
astr = astr.replace(".getreal", ".real")
astr = astr.replace(".getimag", ".imag")
astr = astr.replace(".getimaginary", ".imag")
# preserve uses of flat that should be o.k.
tmpstr = flatindex_re.sub(r"@@@@\2",astr)
# replace other uses of flat
tmpstr = tmpstr.replace(".flat",".ravel()")
# put back .flat where it was valid
astr = tmpstr.replace("@@@@", ".flat")
return astr
info_re = re.compile(r'(\S+)\s*[.]\s*info\s*[(]\s*[)]')
new_re = re.compile(r'(\S+)\s*[.]\s*new\s*[(]\s*(\S+)\s*[)]')
toggle_re = re.compile(r'(\S+)\s*[.]\s*togglebyteorder\s*[(]\s*[)]')
type_re = re.compile(r'(\S+)\s*[.]\s*type\s*[(]\s*[)]')
isbyte_re = re.compile(r'(\S+)\s*[.]\s*isbyteswapped\s*[(]\s*[)]')
iscarr_re = re.compile(r'(\S+)\s*[.]\s*is_c_array\s*[(]\s*[)]')
isfarr_re = re.compile(r'(\S+)\s*[.]\s*is_f_array\s*[(]\s*[)]')
repeat_re = re.compile(r'(\S+)\s*[.]\s*repeat\s*[(]\s*(\S+)\s*[)]')
setshape_re = re.compile(r'(\S+)\s*[.]\s*setshape\s*[(]\s*(\S+)\s*[)]')
setreal_re = re.compile(r'(\S+)\s*[.]\s*setreal\s*[(]\s*(\S+)\s*[)]')
setimag_re = re.compile(r'(\S+)\s*[.]\s*setimag\s*[(]\s*(\S+)\s*[)]')
setimaginary_re = re.compile(r'(\S+)\s*[.]\s*setimaginary\s*[(]\s*(\S+)\s*[)]')
def replaceother(astr):
# self.info() --> numarray.info(self)
# self.new(type) --> numarray.newobj(self, type)
# self.togglebyteorder() --> numarray.togglebyteorder(self)
# self.type() --> numarray.typefrom(self)
(astr, n1) = info_re.subn('numarray.info(\\1)', astr)
(astr, n2) = new_re.subn('numarray.newobj(\\1, \\2)', astr)
(astr, n3) = toggle_re.subn('numarray.togglebyteorder(\\1)', astr)
(astr, n4) = type_re.subn('numarray.typefrom(\\1)', astr)
if (n1+n2+n3+n4 > 0):
astr = addimport(astr)
astr = isbyte_re.sub('not \\1.dtype.isnative', astr)
astr = iscarr_re.sub('\\1.dtype.isnative and \\1.flags.carray', astr)
astr = isfarr_re.sub('\\1.dtype.isnative and \\1.flags.farray', astr)
astr = repeat_re.sub('\\1.repeat(\\2, axis=0)', astr)
astr = setshape_re.sub('\\1.shape = \\2', astr)
astr = setreal_re.sub('\\1.real = \\2', astr)
astr = setimag_re.sub('\\1.imag = \\2', astr)
astr = setimaginary_re.sub('\\1.imag = \\2', astr)
return astr
import datetime
def fromstr(filestr):
savestr = filestr[:]
filestr, fromall = changeimports(filestr, 'numarray', 'numpy.numarray')
base = 'numarray'
newbase = 'numpy.numarray'
for sub in ['', 'convolve', 'image', 'nd_image', 'mlab', 'linear_algebra',
'ma', 'matrix', 'fft', 'random_array']:
if sub != '':
sub = '.'+sub
filestr, fromall = changeimports(filestr, base+sub, newbase+sub)
filestr = replaceattr(filestr)
filestr = replaceother(filestr)
if savestr != filestr:
name = os.path.split(sys.argv[0])[-1]
today = datetime.date.today().strftime('%b %d, %Y')
filestr = '## Automatically adapted for '\
'numpy.numarray %s by %s\n\n%s' % (today, name, filestr)
return filestr, 1
return filestr, 0
def makenewfile(name, filestr):
fid = file(name, 'w')
fid.write(filestr)
fid.close()
def convertfile(filename, orig=1):
"""Convert the filename given from using Numarray to using NumPy
Copies the file to filename.orig and then over-writes the file
with the updated code
"""
fid = open(filename)
filestr = fid.read()
fid.close()
filestr, changed = fromstr(filestr)
if changed:
if orig:
base, ext = os.path.splitext(filename)
os.rename(filename, base+".orig")
else:
os.remove(filename)
makenewfile(filename, filestr)
def fromargs(args):
filename = args[1]
convertfile(filename)
def convertall(direc=os.path.curdir, orig=1):
"""Convert all .py files to use numpy.oldnumeric (from Numeric) in the directory given
For each file, a backup of <usesnumeric>.py is made as
<usesnumeric>.py.orig. A new file named <usesnumeric>.py
is then written with the updated code.
"""
files = glob.glob(os.path.join(direc,'*.py'))
for afile in files:
if afile[-8:] == 'setup.py': continue
convertfile(afile, orig)
header_re = re.compile(r'(numarray/libnumarray.h)')
def convertsrc(direc=os.path.curdir, ext=None, orig=1):
"""Replace Numeric/arrayobject.h with numpy/oldnumeric.h in all files in the
directory with extension give by list ext (if ext is None, then all files are
replaced)."""
if ext is None:
files = glob.glob(os.path.join(direc,'*'))
else:
files = []
for aext in ext:
files.extend(glob.glob(os.path.join(direc,"*.%s" % aext)))
for afile in files:
fid = open(afile)
fstr = fid.read()
fid.close()
fstr, n = header_re.subn(r'numpy/libnumarray.h',fstr)
if n > 0:
if orig:
base, ext = os.path.splitext(afile)
os.rename(afile, base+".orig")
else:
os.remove(afile)
makenewfile(afile, fstr)
def _func(arg, dirname, fnames):
convertall(dirname, orig=0)
convertsrc(dirname, ['h','c'], orig=0)
def converttree(direc=os.path.curdir):
"""Convert all .py files in the tree given
"""
os.path.walk(direc, _func, None)
if __name__ == '__main__':
converttree(sys.argv)
| Python |
from util import *
from numerictypes import *
from functions import *
from ufuncs import *
from compat import *
from session import *
import util
import numerictypes
import functions
import ufuncs
import compat
import session
__all__ = ['session', 'numerictypes']
__all__ += util.__all__
__all__ += numerictypes.__all__
__all__ += functions.__all__
__all__ += ufuncs.__all__
__all__ += compat.__all__
__all__ += session.__all__
del util
del functions
del ufuncs
del compat
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
| Python |
try:
from stsci.image import *
except ImportError:
try:
from scipy.stsci.image import *
except ImportError:
msg = \
"""The image package is not installed
It can be downloaded by checking out the latest source from
http://svn.scipy.org/svn/scipy/trunk/Lib/stsci or by downloading and
installing all of SciPy from http://www.scipy.org.
"""
raise ImportError(msg)
| Python |
#===============================================================================
# encoding utf-8
# author :kanchan mahajan
# module : this module is a part of educational project
# and the calculations here are done according to conventional theory
# book of Finite Elelement Methods
#
# CAUTION: This code is onlly for educational purpose and not for commercial purpose
# DISCLAIMER : Author is not responsible any result pertaining certain analysis
#===============================================================================
import os
from pprint import pformat
from Reading_and_Stiffness import input_reader
from Reading_and_Stiffness.assembly import Assembly
from BC_and_Reduction import processing_BC
from BC_and_Reduction import reduction
from Direct_solver.direct_solve import directsolve_LU
from Direct_solver.ConjG_solve import iterative
from Direct_solver.direct_solve_cholesky import Directsolve_cholesky
from Direct_solver.LDL_solve import directsolve_LDL
from Direct_solver.Pre_ConjG_solve import iterative_num
from Eigensolver.jacobi_eigen_solver import runEigenSolve
from Postprocess import mayavi_plots
from Reading_and_Stiffness.errors import guarded_call
from numpy import ndarray
from mayavi import mlab
from collections import OrderedDict
from math import sqrt
Print_verbose=True
inputFilePath = os.path.join(".", "Reading_and_Stiffness", "input_files", "2d_beam_10DOF-1_a.inp")
@guarded_call
def runMain(filePath=None, solver=None,show_results=True):
global solver_mapping
if not filePath:
filePath = inputFilePath
if not solver:
solver = "direct"
myprint("entered input file is ", filePath)
myprint("entered Solver is ", solver)
#===========================================================================
# read input file
# TODO : change to sys.argv
#===========================================================================
input_data = input_reader.reader(filePath=filePath)
u = [a for aa in input_data.nodes for a in aa]
#===========================================================================
# create assembly object and get stiffness and mass matrices
#===========================================================================
assembly_obj = Assembly(input_data)
stiffness_matrix, mass_matrix = assembly_obj.assemble_mat(input_data.elementType)
myprint("material for the assembly is ", input_data.materials)
myprint("sections for the assembly is ", input_data.sections)
myprint("boundary_conditions for the assembly is ", input_data.boundary_conditions)
myprint("loads for the assembly is ", input_data.loads)
myprint("node_sets for the assembly is ", input_data.node_sets)
#===========================================================================
# converting input boundary conditions data in DOF based data
#===========================================================================
u_reduced = processing_BC.u_vector(input_data.boundary_conditions, input_data.node_sets)
F = processing_BC.force_vector(input_data.loads, input_data.node_sets)
F_vector=dict_to_vector(F, len(u))
F_reduced=processing_BC.get_reduced_force_vector(F_vector,input_data.boundary_conditions, input_data.node_sets)
myprint("reduced deformation vector is as follows", u_reduced)
myprint("original force vector is as follows", F)
myprint("reduced force vector is as follows", F_reduced)
#===========================================================================
# creating a reduced matrices from the total matrices
#===========================================================================
reduced_stiffness = reduction.reduction(stiffness_matrix, u_reduced)
myprint("reduced stiffness matrix is as follows", reduced_stiffness)
reduced_mass = reduction.reduction(mass_matrix, u_reduced)
myprint("reduced mass matrix is as follows", reduced_mass)
#===========================================================================
# direct solve
#===========================================================================
deformation = None
if solver in ["direct", "iterative", "cholesky", "PCT", "LDL"]:
myprint("Initiating {0} solver".format(solver))
deformation = solver_mapping[solver](reduced_stiffness, F_reduced)
elif solver in ["eigen"]:
#=======================================================================
# adding the entries in the mass matrix because the size of the mass matrix should be same as that of the stiffness matrix
#=======================================================================
stiffness_rows = reduced_stiffness.get_size()[0]
for row_index in range(1, stiffness_rows + 1):
if (row_index, row_index) not in reduced_mass:
reduced_mass[(row_index, row_index)] = 0.
myprint("Initiating Eigen solver")
eigen_results = eigen_solve(reduced_stiffness.ToArray(), reduced_mass.ToArray())
deformation = get_udef_from_eigen_results(eigen_results)
else :
raise NotImplementedError("entered solver is not implemented")
myprint("reduced deformation is as follows", deformation)
reduced_stiffness_size = reduced_stiffness.get_size()[0]
udef = None
if isinstance(deformation, dict):
udef = dict_to_vector(deformation, reduced_stiffness_size)
elif isinstance(deformation, list):
if len(deformation) - reduced_stiffness_size == 1:
del deformation[0]
udef = deformation
elif isinstance(deformation, ndarray):
udef = list(deformation.flatten())
if len(deformation) - reduced_stiffness_size == 1:
del udef[0]
else:
myprint("Deformation is in {0} and its not supported at the moment".format(type(deformation)))
if udef:
pass
myprint("Converted udef is as follows", udef)
if show_results:
plot_results(u, udef, u_reduced, input_data.elements)
def direct_solve(reduced_stiffness, F):
solver_object = directsolve_LU(reduced_stiffness, F)
solver_object.solve()
return solver_object.x
def direct_solveLDL(reduced_stiffness, F):
solver_object = directsolve_LDL(reduced_stiffness, F)
solver_object.solve()
return solver_object.x
def direct_cholesky(reduced_stiffness, F):
deformtion_solution = Directsolve_cholesky(reduced_stiffness, F)
#===========================================================================
# add conversion of the result to the dict
#===========================================================================
return deformtion_solution
def iterative_solve(reduced_stiffness, F):
solver_object = iterative(reduced_stiffness, F, tol=1.0e-9)
solver_object.solve()
myprint("solution after {0} iterations".format(solver_object.i))
return solver_object.x
def iterative_preConj_solve(reduced_stiffness, F):
n = reduced_stiffness.get_size()[0]
F_array = dict_to_vector(F, n)
solver_object = iterative_num(reduced_stiffness.ToArray(), F_array, tol=1.0e-9)
solver_object.solve()
myprint("solution after {0} iterations".format(solver_object.i))
return solver_object.x
def eigen_solve(reduced_stiffness, reduced_mass):
eigen_result = runEigenSolve(reduced_stiffness, reduced_mass)
#===========================================================================
# add conversion of the result to the dict
#===========================================================================
return eigen_result
solver_mapping = {"direct":direct_solve, "iterative":iterative_solve, "cholesky":direct_cholesky, "PCT":iterative_preConj_solve, "LDL":direct_solveLDL}
def myprint(initial_string, *args):
global Print_verbose
if not Print_verbose:
return
pretty_string = "{0}\n".format(initial_string)
for arg in args:
pretty_string += "{0}\n".format(pformat(arg))
print pretty_string
def dict_to_vector(dictVector, vectorSize):
F_array = [0.] * vectorSize
for key, val in dictVector.iteritems():
F_array[key - 1] = val
return F_array
def get_udef_from_eigen_results(eigen_results):
freq_mode_shapes = get_sorted_modes_dict(eigen_results)
for key, value in freq_mode_shapes.iteritems():
freq_mode_shapes[key] = normalize(value)
plotting_mode = raw_input("which mode is to be plotted 1-{0}: ".format(len(freq_mode_shapes)))
try:
plotting_mode = int(plotting_mode) - 1
except:
raise ValueError("please enter an integer between given range")
scale_factor = raw_input("please enter scaling factor to visualize results clearly: ")
try:
scale_factor = float(scale_factor)
except:
raise ValueError("please enter an float or integer")
freuencies = freq_mode_shapes.keys()
try:
plotting_frequency = freuencies[plotting_mode]
except:
raise NotImplementedError("Its not possible to retrieve entered mode")
udef = freq_mode_shapes[plotting_frequency]
return [x * scale_factor for x in udef]
def _length(vector):
return sqrt(sum([x ** 2 for x in vector]))
def normalize(vector):
l = _length(vector)
return [x / l for x in vector]
def get_sorted_modes_dict(eigen_results):
frequencies = eigen_results[0]
mode_shapes = eigen_results[1]
freq_mode_shapes = OrderedDict()
temp_freq = list()
temp_freq += frequencies
for frequency in sorted(temp_freq):
mode = frequencies.index(frequency)
freq_mode_shapes[frequency] = list(mode_shapes[mode])
return freq_mode_shapes
def get_inputs():
input_filePath = raw_input("please enter input file path or name from input_files folder :\n")
if not os.path.exists(input_filePath):
input_filePath = os.path.join(".", "Reading_and_Stiffness", "input_files", input_filePath)
if not os.path.exists(input_filePath):
raise IOError("could not find the file")
solver = raw_input(_solver_input_string)
if solver not in ["direct", "cholesky", "iterative", "LDL", "PCT", "eigen"]:
raise NotImplementedError("please enter the name of the solver as shown")
return input_filePath, solver
_solver_input_string = """
Please input the solver following solvers are available:
|------------------|-----------------------------------------|
| Solver Name | Solver Method |
|------------------|-----------------------------------------|
| direct | Direct Solver |
| cholesky | Cholesky Direct Solver |
| iterative | Iterative solver |
| LDL | uses LDL decomposition |
| PCT | use Pre conditioned conjugate method |
| eigen | Jacobi Eigen Solver |
|------------------------------------------------------------|\n
"""
@mlab.show
def plot_results(u, udef, u_reduced, elements):
mayavi_plots.plot_deformation(u, udef, u_reduced, elements)
def pyFEM():
filePath, solver = get_inputs()
runMain(filePath=filePath, solver=solver)
def timeTest(s):
global Print_verbose
Print_verbose=False
filePath=os.path.join(".", "Reading_and_Stiffness", "input_files", "2d_beam_10DOF-1_a.inp")
runMain(filePath=filePath, solver=s,show_results=False)
if __name__ == '__main__':
import timeit
import sys
try:
sys.argv[1]=="benchmark"
print(timeit.timeit('timeTest("{0}")'.format(sys.argv[2]), setup="from __main__ import timeTest"))
except Exception as e:
pyFEM()
print e
finally:
print "Exiting the program"
| Python |
###########################################################################
# program: jacobi_eigen_solver.py
# author: Chunlei Xu
# version: 2.0
# date: Mar, 1, 2014
# description: Solve the generalized eigenvalue problem for a system
# with sparse mass & stiffness matrices in Jacobi method
#
###########################################################################
from numarray import array,zeros,identity,diagonal,pi,Float64
from numarray import dot,sqrt,matrixmultiply,transpose
from acm_project_team import input_reader
###########################################################################
###########################################################################
#a=np.array(input_reader._test().ToArray())
n = 2
a = zeros((n,n),type=Float64)
b = zeros((n,n),type=Float64)
for i in range(n):
a[i,i] = 6.0
b[i,i] = 2.0
a[0,0] = 5.0
a[n-1,n-1] = 7.0
for i in range(n-1):
a[i,i+1] = -4.0
a[i+1,i] = -4.0
b[i,i+1] = -1.0
b[i+1,i] = -1.0
for i in range(n-2):
a[i,i+2] = 1.0
a[i+2,i] = 1.0
stiff = a
mass = b
###########################################################################
###########################################################################
## module stdForm
''' h,t = stdForm(a,b)
Transforms the eigenvalue problem [a]{x} = lambda[b]{x}
to the standard form [h]{z} = lambda{z}. The eigenvectors
are related by {x} = [t]{z}.
'''
def stdForm(a,b):
#################################
## module Dec_LLT_Choleski
''' L= Dec_LLT_Choleski(a).
Dec_LLT_Choleski decomposition: [L][L]transpose = [a].
'''
def Dec_LLT_Choleski(a):
n = len(a)
L = ([[0.0] * n for i in xrange(n)])
L = array(L)
for i in xrange(n):
for k in xrange(i+1):
tmp_sum = sum(L[i][j] * L[k][j] for j in xrange(k))
if (i == k): # Diagonal elements
L[i][k] = sqrt(a[i][i] - tmp_sum)
else:
L[i][k] = (1.0 / L[k][k] * (a[i][k] - tmp_sum))
return L
#################################
## module Inverse_L
def Inverse_L(L):
def solveLb(L, b):
n = len(L)
if len(b) != n:
raise ValueError, "incompatible dimensions"
x = [0.0] * n
for i in range(n):
S = b[i]
for j in range(i):
S-= L[i][j]*x[j]
x[i] = S/L[i][i]
return x
n = len(L)
b = [0.0] *n
invL = [[0.0] * n for i in range(n)]
for i in range(n):
b[i] = 1.0
x = solveLb(L, b)
for j in range(n):
invL[j][i] = x[j]
b[i] = 0.0
return invL
#################################
n = len(stiff)
L = Dec_LLT_Choleski(mass)
invL= Inverse_L(L)
h= matrixmultiply(matrixmultiply(invL,stiff),transpose(invL))
return h,transpose(invL)
###########################################################################
def Jacobi_Eig_Solver(a,tol = 1.0e-9):
'''lam,x = Jacobi_Eig_Solver(a,tol = 1.0e-9).
Solution of std.eigenvalue problem [a]{x} = lambda{x}
by Jacobi's method. Returns eigenvalues in vector {lam}
and the eigenvectors as columns of matrix [x].
'''
def maxElem(a): # Find largest off-diag. element a[k,l]
n = len(a)
aMax = 0.0
for i in range(n-1):
for j in range(i+1,n):
if abs(a[i,j]) >= aMax:
aMax = abs(a[i,j])
k = i; l = j
return aMax,k,l
def rotate(a,p,k,l): # Rotate to make a[k,l] = 0
n = len(a)
aDiff = a[l,l] - a[k,k]
if abs(a[k,l]) < abs(aDiff)*1.0e-36: t = a[k,l]/aDiff
else:
phi = aDiff/(2.0*a[k,l])
t = 1.0/(abs(phi) + sqrt(phi**2 + 1.0))
if phi < 0.0: t = -t
c = 1.0/sqrt(t**2 + 1.0); s = t*c
tau = s/(1.0 + c)
temp = a[k,l]
a[k,l] = 0.0
a[k,k] = a[k,k] - t*temp
a[l,l] = a[l,l] + t*temp
for i in range(k): # Case of i < k
temp = a[i,k]
a[i,k] = temp - s*(a[i,l] + tau*temp)
a[i,l] = a[i,l] + s*(temp - tau*a[i,l])
for i in range(k+1,l): # Case of k < i < l
temp = a[k,i]
a[k,i] = temp - s*(a[i,l] + tau*a[k,i])
a[i,l] = a[i,l] + s*(temp - tau*a[i,l])
for i in range(l+1,n): # Case of i > l
temp = a[k,i]
a[k,i] = temp - s*(a[l,i] + tau*temp)
a[l,i] = a[l,i] + s*(temp - tau*a[l,i])
for i in range(n): # Update transformation matrix
temp = p[i,k]
p[i,k] = temp - s*(p[i,l] + tau*p[i,k])
p[i,l] = p[i,l] + s*(temp - tau*p[i,l])
n = len(a)
maxRot = 5*(n**2) # Set limit on number of rotations
p = identity(n)*1.0 # Initialize transformation matrix
for i in range(maxRot): # Jacobi rotation loop
aMax,k,l = maxElem(a)
if aMax < tol: return diagonal(a),p
rotate(a,p,k,l)
print "Jacobi method did not converge"
###########################################################################
###########################################################################
def runEigenSolve(stiff,mass):
# eigen-problem Calculation by jacobi method
h,t = stdForm(stiff,mass) # Convert to std. form
lam,z = Jacobi_Eig_Solver(h) # Solve by Jacobi mthd.
v = matrixmultiply(t,z) # Eigenvectors of orig. prob.
###########################################################################
# Natural Frequency Calculation
omega = [0.0] * n
Natural_frequency = [0.0] * n
for i in range(n):
omega[i] = sqrt(lam[i])
Natural_frequency[i] = omega[i]/(2*pi)
###########################################################################
# Mass Normalize Eigenvectors
temp=zeros((n,n),'f')
scm=zeros((n,n),'f')
temp=dot(mass,v)
Madal_shape=zeros((n,n),'f')
#.T,same as self.transpose()
scm=dot(v.T,temp) #transpose
nf=zeros(n,'f')
for i in range (0,n):
nf[i]=sqrt(scm[i][i])
for j in range (0,n):
Madal_shape[j][i]=v[j][i]/nf[i]
# sorting command should be inserted here, Vecor of U needed
return Madal_shape,Natural_frequency
###########################################################################
###########################################################################
if __name__=="__main__":
Madal_shape,Natural_frequency=runEigenSolve(stiff,mass)
#print "Eigenvalues:\n",lam[0:3]
#print "\nEigenvectors:\n",v[:,0:3]
print "\nNatural_frequency:\n",Natural_frequency[0:3]
print "\nMode_shape:\n",Madal_shape[0:3]
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.