1. Richard Jones
  2. newpy

Commits

resurtm  committed 9c1f1cf Merge

Merged Richard Jones' branch.

  • Participants
  • Parent commits 6a97319, 6918e05
  • Branches default

Comments (0)

Files changed (4)

File cython/newton.pxd

View file
  • Ignore whitespace
     ctypedef void ** VoidPtrPtr 'void **'
     ctypedef void * ConstVoidPtr 'const void *'
 
+
+#---------------------------------------------------------------------------------------------------
+# C standard library stuff
+#---------------------------------------------------------------------------------------------------
+
+cdef extern from "stdlib.h":
+    long random()
+    void srandom(unsigned seed)
+    double floor(double c)
+    long int lrint(double c)
+    ctypedef unsigned long size_t
+    void *malloc(size_t size)
+    void *realloc(void *ptr, size_t size)
+    void free(void *ptr)
+    void *memset(void *b, int c, size_t len)
+    void *memcpy(void *s1, ConstVoidPtr s2, size_t n)
+
+cdef extern from "math.h":
+    double floor(double c)
+    double sqrt(double c)
+    double fabs(double x)
+    double cos(double x)
+    double acos(double x)
+    double atan2(double y, double x)
+    long lrint(double x)
+
+
 #---------------------------------------------------------------------------------------------------
 
 cdef extern from '../newton/Newton.h':

File cython/newton.pyx

View file
  • Ignore whitespace
     def release(self):
         newton.NewtonReleaseCollision(self._world, self._collision)
 
+cdef class TreeCollision(Collision):
+    def begin_build(self):
+        newton.NewtonTreeCollisionBeginBuild(self._collision)
+
+    def add_face(self, vertexes, attribute):
+        cdef float *f_vertexes
+        cdef int i
+        cdef int N = len(vertexes)
+
+        f_vertexes = <float *>malloc(sizeof(float) * N)
+        for i in range(N):
+            f_vertexes[i] = <float>vertexes[i]
+
+        try:
+            newton.NewtonTreeCollisionAddFace(self._collision, N/3, f_vertexes, sizeof(float) * 3, attribute)
+        finally:
+            free(f_vertexes)
+        
+    def end_build(self, int optimize):        newton.NewtonTreeCollisionEndBuild(self._collision, optimize)
+
+#    int NewtonTreeCollisionGetFaceAtribute(NewtonCollisionConstPtr treeCollision, ConstIntPtr faceIndexArray) 
+#    void NewtonTreeCollisionSetFaceAtribute(NewtonCollisionConstPtr treeCollision, ConstIntPtr faceIndexArray, int attribute) 
+#    int NewtonTreeCollisionGetVertexListIndexListInAABB(NewtonCollisionConstPtr treeCollision, ConstFloatPtr p0, ConstFloatPtr p1, ConstFloatPtrPtr vertexArray, int* vertexCount, int* vertexStrideInBytes, ConstIntPtr indexList, int maxIndexCount, ConstIntPtr faceAttribute) 
+
+
+#---------------------------------------------------------------------------------------------------
+# Physics material related functions.
+#---------------------------------------------------------------------------------------------------
+
+cdef class Material:
+    cdef newton.NewtonWorldPtr _world
+    cdef public int _group_id
+    
+    def __repr__(self):
+        return '<Material %d @0x%x>' % (self._group_id, id(self))
+
+    # NewtonMaterialSetDefaultFriction
+    def set_friction(self, Material other, float static, float kinetic):
+        newton.NewtonMaterialSetDefaultFriction(self._world, self._group_id,
+            other._group_id, static, kinetic)
+
+
 #---------------------------------------------------------------------------------------------------
 # Body related functions.
 #---------------------------------------------------------------------------------------------------
         cdef float *_vector = [dx, dy, dz]
         newton.NewtonBodySetAngularDamping(self._body, _vector)
     
-    # NewtonBodyAddForce
-    def add_force(self, forcex, forcey, forcez):
-        cdef float *_vector = [forcex, forcey, forcez]
-        newton.NewtonBodyAddForce(self._body, _vector)
-        
-    # NewtonBodyAddImpulse
+    # NewtonBodyCalculateInverseDynamicsForce
+    def calculate_inverse_dynamics_force(self, dt, dx, dy, dz):
+        cdef float *desired_vector = [dx, dy, dz]
+        cdef float *out_vector = [0, 0, 0]
+        newton.NewtonBodyCalculateInverseDynamicsForce(self._body, dt, desired_vector, out_vector)
+        return out_vector[0], out_vector[1], out_vector[2]
     def add_impulse(self, pointDeltaVelocX, pointDeltaVelocY, pointDeltaVelocZ,
             pointPositX, pointPositY, pointPositZ):
         cdef float *_vector0 = [pointDeltaVelocX, pointDeltaVelocY, pointDeltaVelocZ]
         cdef float _vector[3]
         newton.NewtonBodyGetForce(self._body, _vector)
         return _vector[0], _vector[1], _vector[2]
-        
-    # NewtonBodySetOmega
-    def set_omega(self, ox, oy, oz):
-        cdef float *_vector = [ox, oy, oz]
-        newton.NewtonBodySetOmega(self._body, _vector)
-           
-    # NewtonBodySetVelocity
-    def set_velocity(self, vx, vy, vz):
-        cdef float *_vector = [vx, vy, vz]
+
+    # NewtonConstraintCreateUpVector
+    def create_up_vector(self, x, y, z):
+        cdef float *vector = [x, y, z]
+        j = Joint()
+        j._world = self._world
+        j._joint = newton.NewtonConstraintCreateUpVector(self._world, vector, self._body)
+        return j
+
+    # NewtonBodySetMaterialGroupID(NewtonBodyConstPtr body, int id)
+    def set_material(self, Material m):
+        newton.NewtonBodySetMaterialGroupID(self._body, m._group_id)
         newton.NewtonBodySetVelocity(self._body, _vector)
-        
-    # NewtonBodySetUserData
-    def set_user_data(self, user_data):
-        self.__user_data = user_data
-        
+
+    # NewtonBodyGetMaterialGroupID
+    def get_material(self):
+        m = Material()
+        m._world = self._world
+        m._group_id = NewtonBodyGetMaterialGroupID(self._body)
+        return m
+
     # NewtonBodyGetUserData
     def get_user_data(self):
         return self.__user_data
-        
+
 #---------------------------------------------------------------------------------------------------
 # Joint and constraints related functions.
 #---------------------------------------------------------------------------------------------------
         newton.NewtonWorldCriticalSectionUnlock(self._world)    
     
     # NewtonSetThreadsCount
-    def get_threads_count(self, threads):
+    def set_threads_count(self, threads):
         newton.NewtonSetThreadsCount(self._world, threads)
     
     # NewtonGetThreadsCount
     # NewtonReadThreadPerformanceTicks
     def read_thread_performance(self, thread_index):
         return newton.NewtonReadThreadPerformanceTicks(self._world, thread_index)
-    
+
+    # NewtonMaterialCreateGroupID
+    def create_material(self):
+        m = Material()
+        m._world = self._world
+        m._group_id = NewtonMaterialCreateGroupID(self._world)
+        return m
+
+    # NewtonCreateSphere
+    def create_sphere(self, float radius_x, float radius_y, float radius_z, int shape_id, offset_matrix=None):
+        cdef float *_matrix
+        if offset_matrix is None:
+            _matrix = NULL
+        else:
+            raise NotImplementedError
+        collision = Collision()
+        collision._world = self._world
+        collision._collision = newton.NewtonCreateSphere(self._world, radius_x, radius_y, radius_z, shape_id, _matrix)
+        return collision
+
     # NewtonCreateBox
     def create_box(self, dx, dy, dz, shapeId=0, offsetMatrix=None):
         ###
         collision._world = self._world
         collision._collision = newton.NewtonCreateBox(self._world, dx, dy, dz, 0, _matrix)
         return collision
+
+    # NewtonCreateTreeCollision
+    def create_tree_collision(self, int shape_id):
+        collision = TreeCollision()
+        collision._world = self._world
+        collision._collision = newton.NewtonCreateTreeCollision(self._world, shape_id)
+        return collision
     
     # NewtonCreateBody
     cpdef create_body(self, Collision collision):
     cpdef create_field(self, width, height, gridsDiagonals, elevationMap, attributeMap, horizontalScale,
             verticalScale, shapeId):
         pass
-    
+    

File mesh2.py

View file
  • Ignore whitespace
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import pyglet
+from pyglet.window import key
+from pyglet.gl import *
+import newton
+import euclid
+import shapes
+
+# define vertexes in counter-clockwise order
+ground_tris = [
+    [(-10.0, -5.0, -10.0), (10.0, -5.0, 10.0), (-10.0, 0.0, 10.0)],
+    [(-10.0, -5.0, -10.0), (10.0, 0.0, -10.0), (10.0, -5.0, 10.0)],
+]
+
+def vec(*args):
+    return (GLfloat * len(args))(*args)
+
+#---------------------------------------------------------------------------------------------------
+# Initialize Newton Game Dynamics.
+#---------------------------------------------------------------------------------------------------
+
+world = newton.World()
+world.set_world_size(-9999, -9999, -9999, 9999, 9999, 9999)
+
+class Person:
+    x = 0
+    z = 0
+    # Default callback functions.
+    def force_torque_callback(self, body, dt, threadIndex):
+        # figure the force to apply to move in the direction the player
+        # wishes
+        dz = keyboard[key.DOWN] - keyboard[key.UP]
+        dx = keyboard[key.RIGHT] - keyboard[key.LEFT]
+        fx, fy, fz = body.calculate_inverse_dynamics_force(dt, dx*10, -9.8, dz*10)
+        body.set_force(fx, fy, fz)
+
+    def transform_callback(self, body, matrix, threadIndex):
+        pass
+
+p = Person()
+
+# Create a person
+collision = world.create_box(1, 1, 1, 0)
+person = world.create_body(collision)
+
+person.set_mass_matrix(1, 1, 1, 1)
+#m = euclid.Matrix4.new_translate(0, 0, 0)
+#person.set_matrix(list(m))
+
+person.set_force_torque_callback(p.force_torque_callback)
+person.set_transform_callback(p.transform_callback)
+person.set_linear_damping(0)
+person.set_angular_damping(0, 0, 0)
+#person.create_up_vector(0, 1, 0)
+
+# create the ground mesh
+collision = world.create_tree_collision(1)
+collision.begin_build()
+for face in ground_tris:
+    # define faces here in CLOCKWISE order
+    vertexes = face[0] + face[2] + face[1]
+    collision.add_face(vertexes, 0)
+collision.end_build(1)
+ground = world.create_body(collision)
+
+person_material = world.create_material()
+person.set_material(person_material)
+ground_material = world.create_material()
+ground.set_material(ground_material)
+print person.get_material()
+print ground.get_material()
+
+#---------------------------------------------------------------------------------------------------
+# Main loop.
+#---------------------------------------------------------------------------------------------------
+window = pyglet.window.Window()
+
+glEnable(GL_LIGHTING)
+glEnable(GL_LIGHT0)
+glLightfv(GL_LIGHT0, GL_POSITION, vec(20, 20, 1, 0))
+glLightfv(GL_LIGHT0, GL_DIFFUSE, vec(1, 1, 1, 1))
+
+glEnable(GL_DEPTH_TEST)
+
+keyboard = key.KeyStateHandler()
+window.push_handlers(keyboard)
+        
+pyglet.clock.schedule(world.update)
+
+@window.event
+def on_show():
+    glMatrixMode(GL_PROJECTION)
+    glLoadIdentity()
+    w, h = window.get_size()
+    gluPerspective(70, w / float(h), 2, 1000)
+    gluLookAt(0, 10, 15, 0, 0, 0, 0, 1, 0)
+    
+    glMatrixMode(GL_MODELVIEW)
+    glLoadIdentity()
+
+@window.event
+def on_text(t):
+    if t.isdigit():
+        friction = int(t) * 100
+        person_material.set_friction(ground_material, friction, friction)
+
+@window.event
+def on_draw():   
+    window.clear()
+     
+    # Draw dynamic persones.
+    glPushMatrix()
+    #glMultMatrixf(vec(*person.get_matrix()))
+    l = list(person.get_matrix())
+    m = list(euclid.Matrix4())
+    m[-4:] = l[-4:]
+    glMultMatrixf(vec(*m))
+    shapes.render_cube()
+    glPopMatrix()
+   
+    # draw static ground body
+    glPushMatrix()
+    glMultMatrixf(vec(*ground.get_matrix()))
+    glBegin(GL_TRIANGLES)
+    for a,b,c in ground_tris:
+        glNormal3f(*shapes.surface_normal(a, b, c))
+        glVertex3f(*a)
+        glVertex3f(*b)
+        glVertex3f(*c)
+    glEnd()
+    glPopMatrix()
+
+pyglet.app.run()

File setup.py

View file
  • Ignore whitespace
     'newton',
     ['cython/newton.pyx'],
     language = 'c++',
-    libraries=['newton/newton']
+    libraries=['Newton'],
+    library_dirs=['.'],
 )
 
 setup(
     ext_modules = [ext]
 )
 
-if os.path.isfile('bin/newton.pyd'):
-    os.unlink('bin/newton.pyd')
-os.rename('newton.pyd', 'bin/newton.pyd')
+#for ext in '.so .pyd'.split():
+#    fn = 'newton' + ext
+#    if os.path.exists(fn):
+#        dest = os.path.join('bin', fn)
+#        if os.path.isfile(dest):
+#            os.remove(dest)
+#        os.rename(fn, dest)
+