473,324 Members | 2,313 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

problem select object in pyode

# test code: http://pyode.sourceforge.net/tutorials/tutorial3.html
#
#i want selecting object in pyode test code.
# what's wrong?
# under modify code
# see selectObject() function

# pyODE example 3: Collision detection

# Originally by Matthias Baas.
# Updated by Pierre Gay to work without pygame or cgkit.

import sys, os, random, time
from math import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

import ode

# geometric utility functions
def scalp (vec, scal):
vec[0] *= scal
vec[1] *= scal
vec[2] *= scal

def length (vec):
return sqrt (vec[0]**2 + vec[1]**2 + vec[2]**2)

obj_map = {}

def _mousefunc(b, s, x, y):
if b == 0 and s == 0:
selectObject(x, y)

def selectObject(x, y):
print x, y

glSelectBuffer(512)
viewport = glGetIntegerv(GL_VIEWPORT)

glMatrixMode(GL_PROJECTION)
glPushMatrix()
glRenderMode(GL_SELECT)
glLoadIdentity()
gluPickMatrix(x, viewport[3]-y, 2, 2, viewport)
gluPerspective (45,1.333,0.1,100)
gluLookAt (2.4, 3.6, 4.8, 0.5, 0.5, 0, 0, 1, 0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
_drawfunc()
buffer = glRenderMode(GL_RENDER)

for hit_record in buffer:
print hit_record
if buffer:
obj_name = buffer[0][2][0]
else:
obj_name = 0
glMatrixMode(GL_PROJECTION)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)

# prepare_GL
def prepare_GL():
"""Prepare drawing.
"""

# Viewport
glViewport(0,0,640,480)

# Initialize
glClearColor(0.8,0.8,0.9,0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST)
glDisable(GL_LIGHTING)
glEnable(GL_LIGHTING)
glEnable(GL_NORMALIZE)
glShadeModel(GL_FLAT)

# Projection
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective (45,1.3333,0.2,20)

# Initialize ModelView matrix
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()

# Light source
glLightfv(GL_LIGHT0,GL_POSITION,[0,0,1,0])
glLightfv(GL_LIGHT0,GL_DIFFUSE,[1,1,1,1])
glLightfv(GL_LIGHT0,GL_SPECULAR,[1,1,1,1])
glEnable(GL_LIGHT0)

# View transformation
gluLookAt (2.4, 3.6, 4.8, 0.5, 0.5, 0, 0, 1, 0)

# draw_body
def draw_body(body):
"""Draw an ODE body.
"""
global obj_map

x,y,z = body.getPosition()
R = body.getRotation()
rot = [R[0], R[3], R[6], 0.,
R[1], R[4], R[7], 0.,
R[2], R[5], R[8], 0.,
x, y, z, 1.0]
glPushMatrix()
glMultMatrixd(rot)
if body.shape=="box":
sx,sy,sz = body.boxsize
glScale(sx, sy, sz)

glPushName(obj_map[body])
glutSolidCube(1)
glPopName()

glPopMatrix()
# create_box
def create_box(world, space, density, lx, ly, lz):
"""Create a box body and its corresponding geom."""

# Create body
body = ode.Body(world)
M = ode.Mass()
M.setBox(density, lx, ly, lz)
body.setMass(M)

# Set parameters for drawing the body
body.shape = "box"
body.boxsize = (lx, ly, lz)

# Create a box geom for collision detection
geom = ode.GeomBox(space, lengths=body.boxsize)
geom.setBody(body)

return body

# drop_object
def drop_object():
"""Drop an object into the scene."""

global bodies, counter, objcount

body = create_box(world, space, 1000, 1.0,0.2,0.2)
body.setPosition( (random.gauss(0,0.1),3.0,random.gauss(0,0.1)) )
theta = random.uniform(0,2*pi)
ct = cos (theta)
st = sin (theta)
body.setRotation([ct, 0., -st, 0., 1., 0., st, 0., ct])
bodies.append(body)
counter=0
objcount+=1

global obj_map
obj_map[body] = objcount

# explosion
def explosion():
"""Simulate an explosion.

Every object is pushed away from the origin.
The force is dependent on the objects distance from the origin.
"""
global bodies

for b in bodies:
l=b.getPosition ()
d = length (l)
a = max(0, 40000*(1.0-0.2*d*d))
l = [l[0] / 4, l[1], l[2] /4]
scalp (l, a / length (l))
b.addForce(l)

# pull
def pull():
"""Pull the objects back to the origin.

Every object will be pulled back to the origin.
Every couple of frames there'll be a thrust upwards so that
the objects won't stick to the ground all the time.
"""
global bodies, counter

for b in bodies:
l=list (b.getPosition ())
scalp (l, -1000 / length (l))
b.addForce(l)
if counter%60==0:
b.addForce((0,10000,0))

# Collision callback
def near_callback(args, geom1, geom2):
"""Callback function for the collide() method.

This function checks if the given geoms do collide and
creates contact joints if they do.
"""

# Check if the objects do collide
contacts = ode.collide(geom1, geom2)

# Create contact joints
world,contactgroup = args
for c in contacts:
c.setBounce(0.2)
c.setMu(5000)
j = ode.ContactJoint(world, contactgroup, c)
j.attach(geom1.getBody(), geom2.getBody())

################################################## ####################

# Initialize Glut
glutInit ([])

# Open a window
glutInitDisplayMode (GLUT_RGB | GLUT_DOUBLE)

x = 0
y = 0
width = 640
height = 480
glutInitWindowPosition (x, y);
glutInitWindowSize (width, height);
glutCreateWindow ("testode")

# Create a world object
world = ode.World()
world.setGravity( (0,-9.81,0) )
world.setERP(0.8)
world.setCFM(1E-5)

# Create a space object
space = ode.Space()

# Create a plane geom which prevent the objects from falling forever
floor = ode.GeomPlane(space, (0,1,0), 0)

# A list with ODE bodies
bodies = []

# A joint group for the contact joints that are generated whenever
# two bodies collide
contactgroup = ode.JointGroup()

# Some variables used inside the simulation loop
fps = 50
dt = 1.0/fps
running = True
state = 0
counter = 0
objcount = 0
lasttime = time.time()
# keyboard callback
def _keyfunc (c, x, y):
sys.exit (0)

glutKeyboardFunc (_keyfunc)

# draw callback
def _drawfunc ():
# Draw the scene
prepare_GL()
for b in bodies:
draw_body(b)

glutSwapBuffers ()

glutDisplayFunc (_drawfunc)

# idle callback
def _idlefunc ():
global counter, state, lasttime

t = dt - (time.time() - lasttime)
if (t > 0):
time.sleep(t)

counter += 1

if state==0:
if counter==20:
drop_object()
if objcount==30:
state=1
counter=0
# State 1: Explosion and pulling back the objects
elif state==1:
if counter==100:
explosion()
if counter>300:
pull()
if counter==500:
counter=20

glutPostRedisplay ()

# Simulate
n = 2

for i in range(n):
# Detect collisions and create contact joints
space.collide((world,contactgroup), near_callback)

# Simulation step
world.step(dt/n)

# Remove all contact joints
contactgroup.empty()

lasttime = time.time()

glutIdleFunc (_idlefunc)
glutMouseFunc(_mousefunc)

glutMainLoop ()

May 24 '06 #1
0 1325

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Steve Thorpe | last post by:
Hi. I have two sql servers and have ran exec sp_addlinkedserver 'ACSPSM', N'SQL Server' to link one to the other and also vise versa. Each server has two users permissioned. My problem is...
1
by: Covad | last post by:
Hi all, For some reason my change() function is only called when the page loads. I'd much rather it gets called when the select changes. Here's the code: window.onload = init; function...
8
by: rdlebreton | last post by:
Hi, Folks! I've been trying to develop my own version of these draggable layers and I have been limiting myself to IE6...for now. I have looked at some other examples to get ideas of creating...
3
by: Szabolcs Nagy | last post by:
I have to measure the time of a while loop, but with time.clock i always get 0.0s, although python manual sais: "this is the function to use for benchmarking Python or timing algorithms" So i...
1
by: Joe Bloggs | last post by:
I am trying display the contents of a table in a web page, select certain rows from that table and then display the fields that I have selected (now table columns) as text in a Label object....
0
by: mjsterz | last post by:
I've been working with VB .NET for less than a year and this is the first time I've posted on one of these groups, so let me apologize beforehand if I'm being unclear, not posting my issue...
2
by: DC | last post by:
The Code <%@ import namespace="System" %> <%@ import namespace="System.Web" %> <%@ import namespace="System.Web.UI" %> <%@ import namespace="System.Web.UI.HtmlControls" %> <%@ import...
1
by: dhyder | last post by:
OK, like the title says my error is Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done. I have looked into this a lot, but have not...
2
by: cty0000 | last post by:
Please anybody help me... I have some serious problem.. I'm doing to keep equpiment list(string).. In my code, there are 3 page which are having 4 equpiment ID (user control.) like this...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.