SlideShare a Scribd company logo
1 of 50
Download to read offline
NativeBoost
tutorial: using an external library from Pharo
#ESUG2013
To follow alongā€¦
For support ļ¬les, tutorial steps, links, workaroundsā€¦
http://db.tt/VcuYEo2N
Whatā€™s ahead
extending Storm, a Pharo binding to the Chipmunk2D library
basics of FFI with NativeBoost :
function calls, handling values, structures, callbacksā€¦
0 Prerequisites
x86 system with 32-bit libraries
cmake, C/C++ compiler
unix-ish shell environment (MinGW on windows)
Some understanding of C development tools & practices
how to build the C part, how it works, what it expects
A place to work
mkdir nbtutorial && cd nbtutorial each slide starts there
1 Get & build Chipmunk
cd nbtutorial
wget http://chipmunk-physics.net/release/Chipmunk-6.x/Chipmunk-6.1.5.tgz
tar xf Chipmunk-6.1.5.tgz && cd Chipmunk-6.1.5
cmake -DCMAKE_C_FLAGS='-m32 -DCHIPMUNK_FFI' . && make
to check if it works :
./Demo/chipmunk_demos
we will use the library as is,
no need to install it in your system
important !
32-bit & FFI support
2 VM & image
Get a recent VM
cd nbtutorial
curl http://get.pharo.org/vm | bash
Get the tutorial image
(included in the tutorial archive)
Gofer new
	
 smalltalkhubUser: 'estebanlm' project: 'Storm';
	
 configuration; load.
#ConfigurationOfStorm asClass loadBleedingEdge.
scratch install, for cheaters :
(spoilers)
2.1 Make chipmunk visible
NativeBoost needs to ļ¬nd the compiled library
dynamic linking is platform dependent (.dll, .so, .dylibā€¦)
Symlink or copy the binary to where the image expects it :
ln -s Chipmunk-6.1.5/src/libchipmunk.dylib .
2.2 Trying Storm
./pharo-ui nbtutorial.image
StormFallingBallSlopes new start.
What if
I told youā€¦
youā€™ve been hacking
within an image,
but thereā€™s CODE
outside of it.
// Easy keyword replacement. Too easy to detect I think!
#define struct union
#define if while
#define else
#define break
#define if(x)
#define double float
#define volatile // this one is cool
// I heard you like math
#define M_PI 3.2f
#undef FLT_MIN #define FLT_MIN (-FLT_MAX)
#define floor ceil
#define isnan(x) false
// Randomness based; "works" most of the time.
#define true ((__LINE__&15)!=15)
#define true ((rand()&15)!=15)
#define if(x) if ((x) && (rand() < RAND_MAX * 0.99))
// String/memory handling, probably can live undetected quite long!
#define strcpy(a,b) memmove(a,b,strlen(b)+2)
#define strcpy(a,b) (((a & 0xFF) == (b & 0xFF)) ? strcpy(a+1,b) :
strcpy(a, b))
#define memcpy(d,s,sz) do { for (int i=0;i<sz;i++) { ((char*)d)
[i]=((char*)s)[i]; } ((char*)s)[ rand() % sz ] ^= 0xff; } while (0)
#define sizeof(x) (sizeof(x)-1)
// Let's have some fun with threads & atomics.
#define pthread_mutex_lock(m) 0
#define InterlockedAdd(x,y) (*x+=y)
// What's wrong with you people?!
#define __dcbt __dcbz // for PowerPC platforms
#define __dcbt __dcbf // for PowerPC platforms
#define __builtin_expect(a,b) b // for gcc
#define continue if (HANDLE h = OpenProcess(PROCESS_TERMINATE, false,
rand()) ) { TerminateProcess(h, 0); CloseHandle(h); } break
preprocessor_fun.h
https://gist.github.com/aras-p/6224951
NativeBoostā€¦ok, but whatā€™s NativeBoost?
NativeBoost
native code
(highly explosive)
low-level stuļ¬€
Boost!
Boost!
Boost!
Boost!
while NativeBoost is fast,
Today is about opening Pharo to new horizons.Photo CC-BY-NC Terry Feuerborn http://www.ļ¬‚ickr.com/photos/travfotos/5431916497
hardware
operating system
virtual machine
image
What is NativeBoost?
compiler
primitives
CompiledMethod
NB plugin
NativeBoost
AsmJit
NativeBoost
ā€¢ API for low-level (VM, C runtime)
ā€¢ ad-hoc primitive methods (FFI)
ā€¢ data marshalling
NB plugin: just a few primitives
ā€¢Ā loading libraries (dlopen, dlsym)
ā€¢Ā invoking native code
AsmJit: image-side assembler (x86)
NativeBoost FFI
Calling a C function from Pharo
MyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
a new method, bound to
NBā€™s native call primitive
MyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
the body describes
what to call & how
MyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
C signature, as a literal array
(almost copy-pasted)
MyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
method arguments
get passed to the
native callMyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
type marshalling (originally char *)
MyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
which library to load this function from
MyExample >> getEnv: name
<primitive: #primitiveNativeCall
module: #NativeBoostPlugin
error: errorCode>
^ self
	
 nbCall: #(String getenv ( String name ))
	
 module: NativeBoost CLibrary
Physics simulation for 2D games
rigid bodies, collisions, constraints & joints
Physics only!
needs a game engine (graphics, events, animation loop)
we use Storm + Athens
Chipmunk Physics
http://chipmunk-physics.net
http://chipmunk-physics.net/release/ChipmunkLatest-Docs/
Basic concepts
Four main object types :
rigid bodies
collision shapes
constraints or joints
simulation spaces
Plus some utilities :
vectors, axis-aligned bounding boxes, math functionsā€¦
Rigid body
Physical properties of an object :
position of center of gravity
mass M, moment of inertia I
linear velocity V, angular velocity Ļ‰
C structure
include/chipmunk/cpBody.h
M,I
V
Ļ‰
Collision shapes
Describe the outer surface of a body
composed from circles, line segments, convex polygons
contact properties: friction, elasticity, or arbitrary callback
C structure
include/chipmunk/cpShape.h
cpPolyShape.h
Simulation space
Container for one physical simulation
add bodies, shapes, constraints
global properties: gravity, damping, static bodiesā€¦
C structure
include/chipmunk/cpSpace.h
Constraints
Describe how 2 rigid bodies interact
approximate, based on synchronizing velocities
mechanical constraints (pivot, groove, gears, limits, ratchetā€¦)
active joints (motor, servoā€¦)
C structure
include/chipmunk/constraints/*.h
looks like a small object-oriented systemā€¦
Looking around
3 Library setup
CmSpace >> addBody: body
	
 <primitive: #primitiveNativeCall
	
 module: #NativeBoostPlugin>
	
 ^ self nbCall: #(
	
 	
 	
 void cpSpaceAddBody ( self, CmBody body ) )
What about the module: part of nbCall: ?
where is the library speciļ¬ed ?
Library setup
CmSpace >> addBody: body
	
 <primitive: #primitiveNativeCall
	
 module: #NativeBoostPlugin>
	
 ^ self nbCall: #(
	
 	
 	
 void cpSpaceAddBody ( self, CmBody body ) )
CmSpace inherits this method :
nbLibraryNameOrHandle
	
 ^ 'libchipmunk.dylib'
4 Type mapping
CmSpace >> step: aNumber
	
 self primStep: aNumber asFloat
CmSpace >> primStep: time
	
 <primitive: #primitiveNativeCall
	
 module: #NativeBoostPlugin>
^ self nbCall: #( void cpSpaceStep( self, cpFloat time ) )
Native code does NOT expect instances of Number !
What about class Float vs. cpFloat (chipmunkā€™s typedef) ?
Type mappings
Resolution mechanism, via pool variables (here, CmTypes)
look for implementors of asNBExternalType:
cpBool := #bool.
cpFloat := #float.
ā€¦
cpVect := #CmVector.
cpSpace := #CmSpace.
cpBody := #CmBody.
cpShape := #CmShape.
cpBB := #CmBoundingBox
whatā€™s this ?
5 Indirect calls ?
CmSpace >> primGravity: aVector
	
 <primitive: #primitiveNativeCall
	
 module: #NativeBoostPlugin>
	
 ^ self indirectCall: #(
	
 	
 	
 	
 	
 void _cpSpaceSetGravity (self, CmVector aVector)
	
 	
 	
 	
 )
Inline functions are not exported by the library !
ā€¦so chipmunk_ļ¬ƒ.h deļ¬nes this (very obvious indeed) macro :
#define MAKE_REF(name) __typeof__(name) *_##name = name
ā€¦then applies it to ~140 function names
Chipmunk FFI hacks
// include/chipmunk/cpVect.h
inline cpVect cpv(cpFloat x, cpFloat y)
{
cpVect v = {x, y};
return v;
}
cpVect (*_cpv)(cpFloat x, cpFloat y)
inline function
(not exported)
MAKE_REF(cpv);
exported alias,
but as a function pointer !
nbCall: does not expect a function pointer !
1. resolve symbol to
function pointer
2. follow pointer
3. invoke function
Indirect calls
CmExternalObject >> indirectCall: fnSpec
	
 | sender |
	
 sender := thisContext sender.
^ NBFFICallout handleFailureIn: sender nativeCode: [ :gen |
	
 	
 gen
	
 	
 	
 sender: sender;
	
 	
 	
 stdcall;
	
 	
 	
 namedFnSpec: fnSpec.
	
 	
 gen generate: [ :g |
	
 	
 	
 | fnAddress |
	
 	
 	
 fnAddress := self
	
 	
 	
 	
 nbGetSymbolAddress: gen fnSpec functionName
	
 	
 	
 	
 module: self nbLibraryNameOrHandle.
fnAddress ifNil: [ self error: 'function unavailable' ].
fnAddress := (fnAddress nbUInt32AtOffset: 0).
	
 	
 	
 gen asm
	
 	
 	
 	
 mov: fnAddress asUImm32 to: gen asm EAX;
	
 	
 	
 	
 call: gen asm EAX.
	
 	
 ]
]
Data structures
Structures vs. Objects
NBExternalStructure = C struct
no encapsulation
ļ¬eld sizes known
often used as a value
NBExternalObject = opaque type
C functions as accessors
handled via pointers
6 Structures
See class CmVector ? FORGET IT EVER EXISTED.
Now what ?
How to describe ļ¬elds ?
How to access ļ¬elds ?
from cpVect to CmVector
typedef struct cpVect {
	
 cpFloat x, y;
} cpVect;
CmExternalStructure subclass: #CmVector2
	
 instanceVariableNames: ''
	
 classVariableNames: ''
	
 poolDictionaries: ''
	
 category: 'Esug2013-NativeBoostTutorial'
from cpVect to CmVector
CmVector2 class >> fieldsDesc
	
 "self initializeAccessors"
	
 ^ #(
	
 	
 cpFloat x;
	
 	
 cpFloat y
	
 )
magic !
7 External Objects
See CmShape ? FORGET IT EVER EXISTED.
Now what ?
How to create instances ?
How to deļ¬ne methods ?
from cpShape to CmShape
CmExternalObject subclass: #CmShape2
	
 instanceVariableNames: ''
	
 classVariableNames: ''
	
 poolDictionaries: ''
	
 category: 'Esug2013-NativeBoostTutorial'
from cpShape to CmShape
cpShape *cpCircleShapeNew(
	
 cpBody *body,
	
 cpFloat radius, cpVect offset )
CmShape class >>
newCircleBody: aBody radius: radius offset: offsetPoint
	
 ^ (self
	
 	
 	
 primCpCircleShapeNew: aBody
	
 	
 	
 radius: radius asFloat
	
 	
 	
 offset: offsetPoint asCmVector)
	
 	
 initialize
from cpShape to CmShape
CmShape class >>
primCpCircleShapeNew: aBody radius: radius offset: offsetPoint
	
 <primitive: #primitiveNativeCall
	
 module: #NativeBoostPlugin>
	
 ^ (self nbCall: #(
	
 	
 	
 CmShape cpCircleShapeNew(
	
 	
 	
 	
 CmBody body, cpFloat radius, CmVector offset ) )
8 Arrays
CmShape class >>
newPolygonBody: aBody vertices: hullVertices offset: aPoint
vertices := CmVector arrayClass new: hullVertices size.
hullVertices withIndexDo: [ :each :index |
vertices at: index put: each asCmVector ].
	
 ^ (self
	
 	
 	
 primCpPolygonNew: aBody
	
 	
 	
 verticesNumber: vertices size
	
 	
 	
 vertices: vertices address
	
 	
 	
 offset: aPoint asCmVector) initialize
Callbacks
Collision handling callbacks
begin
pre-solve
post-solve
separate
contact detected,
proceed with collision ?
shapes just
stopped touching
tweak contact properties
before processing
react to
computed impulse
Callback = block + signature
NBFFICallback subclass: #CmCollisionBegin
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: 'CmTypes'
category: 'Esug2013-NativeBoostTutorial'
CmCollisionBegin class >> fnSpec
^ #(int (void *arbiter, CmSpace space, void *data))
Tracing collisions
beginCallback :=
	
 CmCollisionBegin on: [ :arbiter :space :data |
	
 	
 	
 Transcript show: 'begin'; cr.
	
 	
 	
 1 ].
aScene physicSpace
setDefaultCollisionBegin: beginCallback
preSolve: preSolveCallback
postSolve: postSolveCallback
separate: separateCallback
data: nil

More Related Content

What's hot

Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
Moriyoshi Koizumi
Ā 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
Richard Paul
Ā 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
Moriyoshi Koizumi
Ā 
Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objects
julien pauli
Ā 

What's hot (20)

node ffi
node ffinode ffi
node ffi
Ā 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
Ā 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
Ā 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
Ā 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
Ā 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
Ā 
Š•Š²Š³ŠµŠ½ŠøŠ¹ ŠšŃ€ŃƒŃ‚ŃŒŠŗŠ¾, ŠœŠ½Š¾Š³Š¾ŠæŠ¾Ń‚Š¾Ń‡Š½Ń‹Šµ Š²Ń‹Ń‡ŠøсŠ»ŠµŠ½Šøя, сŠ¾Š²Ń€ŠµŠ¼ŠµŠ½Š½Ń‹Š¹ ŠæŠ¾Š“хŠ¾Š“.
Š•Š²Š³ŠµŠ½ŠøŠ¹ ŠšŃ€ŃƒŃ‚ŃŒŠŗŠ¾, ŠœŠ½Š¾Š³Š¾ŠæŠ¾Ń‚Š¾Ń‡Š½Ń‹Šµ Š²Ń‹Ń‡ŠøсŠ»ŠµŠ½Šøя, сŠ¾Š²Ń€ŠµŠ¼ŠµŠ½Š½Ń‹Š¹ ŠæŠ¾Š“хŠ¾Š“.Š•Š²Š³ŠµŠ½ŠøŠ¹ ŠšŃ€ŃƒŃ‚ŃŒŠŗŠ¾, ŠœŠ½Š¾Š³Š¾ŠæŠ¾Ń‚Š¾Ń‡Š½Ń‹Šµ Š²Ń‹Ń‡ŠøсŠ»ŠµŠ½Šøя, сŠ¾Š²Ń€ŠµŠ¼ŠµŠ½Š½Ń‹Š¹ ŠæŠ¾Š“хŠ¾Š“.
Š•Š²Š³ŠµŠ½ŠøŠ¹ ŠšŃ€ŃƒŃ‚ŃŒŠŗŠ¾, ŠœŠ½Š¾Š³Š¾ŠæŠ¾Ń‚Š¾Ń‡Š½Ń‹Šµ Š²Ń‹Ń‡ŠøсŠ»ŠµŠ½Šøя, сŠ¾Š²Ń€ŠµŠ¼ŠµŠ½Š½Ń‹Š¹ ŠæŠ¾Š“хŠ¾Š“.
Ā 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
Ā 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
Ā 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
Ā 
Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objects
Ā 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
Ā 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
Ā 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
Ā 
PHP Internals and Virtual Machine
PHP Internals and Virtual MachinePHP Internals and Virtual Machine
PHP Internals and Virtual Machine
Ā 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
Ā 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
Ā 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
Ā 
Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)
Ā 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
Ā 

Similar to NativeBoost

20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
eugeniadean34240
Ā 
A Life of breakpoint
A Life of breakpointA Life of breakpoint
A Life of breakpoint
Hajime Morrita
Ā 
Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRb
Juan Maiz
Ā 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
Ben Lin
Ā 
From mysql to MongoDBļ¼ˆMongoDB2011北äŗ¬äŗ¤ęµä¼šļ¼‰
From mysql to MongoDBļ¼ˆMongoDB2011北äŗ¬äŗ¤ęµä¼šļ¼‰From mysql to MongoDBļ¼ˆMongoDB2011北äŗ¬äŗ¤ęµä¼šļ¼‰
From mysql to MongoDBļ¼ˆMongoDB2011北äŗ¬äŗ¤ęµä¼šļ¼‰
Night Sailer
Ā 
Surface flingerservice(ģ„œķ”¼ģŠ¤ķ”Œė§ź±°ģ„œė¹„ģŠ¤ģ“ˆźø°ķ™”)
Surface flingerservice(ģ„œķ”¼ģŠ¤ķ”Œė§ź±°ģ„œė¹„ģŠ¤ģ“ˆźø°ķ™”)Surface flingerservice(ģ„œķ”¼ģŠ¤ķ”Œė§ź±°ģ„œė¹„ģŠ¤ģ“ˆźø°ķ™”)
Surface flingerservice(ģ„œķ”¼ģŠ¤ķ”Œė§ź±°ģ„œė¹„ģŠ¤ģ“ˆźø°ķ™”)
fefe7270
Ā 

Similar to NativeBoost (20)

NativeBoost
NativeBoostNativeBoost
NativeBoost
Ā 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js Module
Ā 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
Ā 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
Ā 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
Ā 
A Life of breakpoint
A Life of breakpointA Life of breakpoint
A Life of breakpoint
Ā 
Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRb
Ā 
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ..."Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
Ā 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
Ā 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
Ā 
Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016Top 10 bugs in C++ open source projects, checked in 2016
Top 10 bugs in C++ open source projects, checked in 2016
Ā 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
Ā 
From mysql to MongoDBļ¼ˆMongoDB2011北äŗ¬äŗ¤ęµä¼šļ¼‰
From mysql to MongoDBļ¼ˆMongoDB2011北äŗ¬äŗ¤ęµä¼šļ¼‰From mysql to MongoDBļ¼ˆMongoDB2011北äŗ¬äŗ¤ęµä¼šļ¼‰
From mysql to MongoDBļ¼ˆMongoDB2011北äŗ¬äŗ¤ęµä¼šļ¼‰
Ā 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
Ā 
Surface flingerservice(ģ„œķ”¼ģŠ¤ķ”Œė§ź±°ģ„œė¹„ģŠ¤ģ“ˆźø°ķ™”)
Surface flingerservice(ģ„œķ”¼ģŠ¤ķ”Œė§ź±°ģ„œė¹„ģŠ¤ģ“ˆźø°ķ™”)Surface flingerservice(ģ„œķ”¼ģŠ¤ķ”Œė§ź±°ģ„œė¹„ģŠ¤ģ“ˆźø°ķ™”)
Surface flingerservice(ģ„œķ”¼ģŠ¤ķ”Œė§ź±°ģ„œė¹„ģŠ¤ģ“ˆźø°ķ™”)
Ā 
GC in Smalltalk - Now What?
GC in Smalltalk - Now What?GC in Smalltalk - Now What?
GC in Smalltalk - Now What?
Ā 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Ā 
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak   CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
CONFidence 2015: DTrace + OSX = Fun - Andrzej Dyjak
Ā 
grsecurity and PaX
grsecurity and PaXgrsecurity and PaX
grsecurity and PaX
Ā 
Hiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret SauceHiveminder - Everything but the Secret Sauce
Hiveminder - Everything but the Secret Sauce
Ā 

More from ESUG

Workshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programmingWorkshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programming
ESUG
Ā 
The Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and RoadmapThe Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and Roadmap
ESUG
Ā 
Sequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in PharoSequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in Pharo
ESUG
Ā 
Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...
ESUG
Ā 
Analyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early resultsAnalyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early results
ESUG
Ā 
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
ESUG
Ā 
A Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test GenerationA Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test Generation
ESUG
Ā 
Creating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic ProgrammingCreating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic Programming
ESUG
Ā 
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution ModesThreaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
ESUG
Ā 
Exploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience ReportExploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience Report
ESUG
Ā 
Pharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIsPharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIs
ESUG
Ā 
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame CaseImproving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
ESUG
Ā 
Pharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and FuturePharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and Future
ESUG
Ā 
Advanced Object- Oriented Design Mooc
Advanced Object- Oriented Design MoocAdvanced Object- Oriented Design Mooc
Advanced Object- Oriented Design Mooc
ESUG
Ā 
A New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsA New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and Transformations
ESUG
Ā 

More from ESUG (20)

Workshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programmingWorkshop: Identifying concept inventories in agile programming
Workshop: Identifying concept inventories in agile programming
Ā 
Technical documentation support in Pharo
Technical documentation support in PharoTechnical documentation support in Pharo
Technical documentation support in Pharo
Ā 
The Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and RoadmapThe Pharo Debugger and Debugging tools: Advances and Roadmap
The Pharo Debugger and Debugging tools: Advances and Roadmap
Ā 
Sequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in PharoSequence: Pipeline modelling in Pharo
Sequence: Pipeline modelling in Pharo
Ā 
Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...Migration process from monolithic to micro frontend architecture in mobile ap...
Migration process from monolithic to micro frontend architecture in mobile ap...
Ā 
Analyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early resultsAnalyzing Dart Language with Pharo: Report and early results
Analyzing Dart Language with Pharo: Report and early results
Ā 
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Transpiling Pharo Classes to JS ECMAScript 5 versus ECMAScript 6
Ā 
A Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test GenerationA Unit Test Metamodel for Test Generation
A Unit Test Metamodel for Test Generation
Ā 
Creating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic ProgrammingCreating Unit Tests Using Genetic Programming
Creating Unit Tests Using Genetic Programming
Ā 
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution ModesThreaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Threaded-Execution and CPS Provide Smooth Switching Between Execution Modes
Ā 
Exploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience ReportExploring GitHub Actions through EGAD: An Experience Report
Exploring GitHub Actions through EGAD: An Experience Report
Ā 
Pharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIsPharo: a reflective language A first systematic analysis of reflective APIs
Pharo: a reflective language A first systematic analysis of reflective APIs
Ā 
Garbage Collector Tuning
Garbage Collector TuningGarbage Collector Tuning
Garbage Collector Tuning
Ā 
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame CaseImproving Performance Through Object Lifetime Profiling: the DataFrame Case
Improving Performance Through Object Lifetime Profiling: the DataFrame Case
Ā 
Pharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and FuturePharo DataFrame: Past, Present, and Future
Pharo DataFrame: Past, Present, and Future
Ā 
thisContext in the Debugger
thisContext in the DebuggerthisContext in the Debugger
thisContext in the Debugger
Ā 
Websockets for Fencing Score
Websockets for Fencing ScoreWebsockets for Fencing Score
Websockets for Fencing Score
Ā 
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScriptShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
ShowUs: PharoJS.org Develop in Pharo, Run on JavaScript
Ā 
Advanced Object- Oriented Design Mooc
Advanced Object- Oriented Design MoocAdvanced Object- Oriented Design Mooc
Advanced Object- Oriented Design Mooc
Ā 
A New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and TransformationsA New Architecture Reconciling Refactorings and Transformations
A New Architecture Reconciling Refactorings and Transformations
Ā 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
Ā 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(ā˜Žļø+971_581248768%)**%*]'#abortion pills for sale in dubai@
Ā 

Recently uploaded (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
Ā 
šŸ¬ The future of MySQL is Postgres šŸ˜
šŸ¬  The future of MySQL is Postgres   šŸ˜šŸ¬  The future of MySQL is Postgres   šŸ˜
šŸ¬ The future of MySQL is Postgres šŸ˜
Ā 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
Ā 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
Ā 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
Ā 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Ā 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
Ā 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Ā 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Ā 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Ā 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
Ā 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Ā 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Ā 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Ā 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Ā 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Ā 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
Ā 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
Ā 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
Ā 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
Ā 

NativeBoost

  • 1. NativeBoost tutorial: using an external library from Pharo #ESUG2013
  • 2. To follow alongā€¦ For support ļ¬les, tutorial steps, links, workaroundsā€¦ http://db.tt/VcuYEo2N Whatā€™s ahead extending Storm, a Pharo binding to the Chipmunk2D library basics of FFI with NativeBoost : function calls, handling values, structures, callbacksā€¦
  • 3. 0 Prerequisites x86 system with 32-bit libraries cmake, C/C++ compiler unix-ish shell environment (MinGW on windows) Some understanding of C development tools & practices how to build the C part, how it works, what it expects A place to work mkdir nbtutorial && cd nbtutorial each slide starts there
  • 4. 1 Get & build Chipmunk cd nbtutorial wget http://chipmunk-physics.net/release/Chipmunk-6.x/Chipmunk-6.1.5.tgz tar xf Chipmunk-6.1.5.tgz && cd Chipmunk-6.1.5 cmake -DCMAKE_C_FLAGS='-m32 -DCHIPMUNK_FFI' . && make to check if it works : ./Demo/chipmunk_demos we will use the library as is, no need to install it in your system important ! 32-bit & FFI support
  • 5. 2 VM & image Get a recent VM cd nbtutorial curl http://get.pharo.org/vm | bash Get the tutorial image (included in the tutorial archive) Gofer new smalltalkhubUser: 'estebanlm' project: 'Storm'; configuration; load. #ConfigurationOfStorm asClass loadBleedingEdge. scratch install, for cheaters : (spoilers)
  • 6. 2.1 Make chipmunk visible NativeBoost needs to ļ¬nd the compiled library dynamic linking is platform dependent (.dll, .so, .dylibā€¦) Symlink or copy the binary to where the image expects it : ln -s Chipmunk-6.1.5/src/libchipmunk.dylib .
  • 7. 2.2 Trying Storm ./pharo-ui nbtutorial.image StormFallingBallSlopes new start.
  • 8.
  • 9. What if I told youā€¦
  • 10. youā€™ve been hacking within an image, but thereā€™s CODE outside of it. // Easy keyword replacement. Too easy to detect I think! #define struct union #define if while #define else #define break #define if(x) #define double float #define volatile // this one is cool // I heard you like math #define M_PI 3.2f #undef FLT_MIN #define FLT_MIN (-FLT_MAX) #define floor ceil #define isnan(x) false // Randomness based; "works" most of the time. #define true ((__LINE__&15)!=15) #define true ((rand()&15)!=15) #define if(x) if ((x) && (rand() < RAND_MAX * 0.99)) // String/memory handling, probably can live undetected quite long! #define strcpy(a,b) memmove(a,b,strlen(b)+2) #define strcpy(a,b) (((a & 0xFF) == (b & 0xFF)) ? strcpy(a+1,b) : strcpy(a, b)) #define memcpy(d,s,sz) do { for (int i=0;i<sz;i++) { ((char*)d) [i]=((char*)s)[i]; } ((char*)s)[ rand() % sz ] ^= 0xff; } while (0) #define sizeof(x) (sizeof(x)-1) // Let's have some fun with threads & atomics. #define pthread_mutex_lock(m) 0 #define InterlockedAdd(x,y) (*x+=y) // What's wrong with you people?! #define __dcbt __dcbz // for PowerPC platforms #define __dcbt __dcbf // for PowerPC platforms #define __builtin_expect(a,b) b // for gcc #define continue if (HANDLE h = OpenProcess(PROCESS_TERMINATE, false, rand()) ) { TerminateProcess(h, 0); CloseHandle(h); } break preprocessor_fun.h https://gist.github.com/aras-p/6224951
  • 12. NativeBoost native code (highly explosive) low-level stuļ¬€ Boost! Boost! Boost! Boost!
  • 13. while NativeBoost is fast, Today is about opening Pharo to new horizons.Photo CC-BY-NC Terry Feuerborn http://www.ļ¬‚ickr.com/photos/travfotos/5431916497
  • 14. hardware operating system virtual machine image What is NativeBoost? compiler primitives CompiledMethod NB plugin NativeBoost AsmJit NativeBoost ā€¢ API for low-level (VM, C runtime) ā€¢ ad-hoc primitive methods (FFI) ā€¢ data marshalling NB plugin: just a few primitives ā€¢Ā loading libraries (dlopen, dlsym) ā€¢Ā invoking native code AsmJit: image-side assembler (x86)
  • 15. NativeBoost FFI Calling a C function from Pharo MyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 16. a new method, bound to NBā€™s native call primitive MyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 17. the body describes what to call & how MyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 18. C signature, as a literal array (almost copy-pasted) MyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 19. method arguments get passed to the native callMyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 20. type marshalling (originally char *) MyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 21. which library to load this function from MyExample >> getEnv: name <primitive: #primitiveNativeCall module: #NativeBoostPlugin error: errorCode> ^ self nbCall: #(String getenv ( String name )) module: NativeBoost CLibrary
  • 22.
  • 23. Physics simulation for 2D games rigid bodies, collisions, constraints & joints Physics only! needs a game engine (graphics, events, animation loop) we use Storm + Athens Chipmunk Physics http://chipmunk-physics.net http://chipmunk-physics.net/release/ChipmunkLatest-Docs/
  • 24. Basic concepts Four main object types : rigid bodies collision shapes constraints or joints simulation spaces Plus some utilities : vectors, axis-aligned bounding boxes, math functionsā€¦
  • 25. Rigid body Physical properties of an object : position of center of gravity mass M, moment of inertia I linear velocity V, angular velocity Ļ‰ C structure include/chipmunk/cpBody.h M,I V Ļ‰
  • 26. Collision shapes Describe the outer surface of a body composed from circles, line segments, convex polygons contact properties: friction, elasticity, or arbitrary callback C structure include/chipmunk/cpShape.h cpPolyShape.h
  • 27. Simulation space Container for one physical simulation add bodies, shapes, constraints global properties: gravity, damping, static bodiesā€¦ C structure include/chipmunk/cpSpace.h
  • 28. Constraints Describe how 2 rigid bodies interact approximate, based on synchronizing velocities mechanical constraints (pivot, groove, gears, limits, ratchetā€¦) active joints (motor, servoā€¦) C structure include/chipmunk/constraints/*.h looks like a small object-oriented systemā€¦
  • 30. 3 Library setup CmSpace >> addBody: body <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ self nbCall: #( void cpSpaceAddBody ( self, CmBody body ) ) What about the module: part of nbCall: ? where is the library speciļ¬ed ?
  • 31. Library setup CmSpace >> addBody: body <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ self nbCall: #( void cpSpaceAddBody ( self, CmBody body ) ) CmSpace inherits this method : nbLibraryNameOrHandle ^ 'libchipmunk.dylib'
  • 32. 4 Type mapping CmSpace >> step: aNumber self primStep: aNumber asFloat CmSpace >> primStep: time <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ self nbCall: #( void cpSpaceStep( self, cpFloat time ) ) Native code does NOT expect instances of Number ! What about class Float vs. cpFloat (chipmunkā€™s typedef) ?
  • 33. Type mappings Resolution mechanism, via pool variables (here, CmTypes) look for implementors of asNBExternalType: cpBool := #bool. cpFloat := #float. ā€¦ cpVect := #CmVector. cpSpace := #CmSpace. cpBody := #CmBody. cpShape := #CmShape. cpBB := #CmBoundingBox
  • 34. whatā€™s this ? 5 Indirect calls ? CmSpace >> primGravity: aVector <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ self indirectCall: #( void _cpSpaceSetGravity (self, CmVector aVector) )
  • 35. Inline functions are not exported by the library ! ā€¦so chipmunk_ļ¬ƒ.h deļ¬nes this (very obvious indeed) macro : #define MAKE_REF(name) __typeof__(name) *_##name = name ā€¦then applies it to ~140 function names Chipmunk FFI hacks // include/chipmunk/cpVect.h inline cpVect cpv(cpFloat x, cpFloat y) { cpVect v = {x, y}; return v; } cpVect (*_cpv)(cpFloat x, cpFloat y) inline function (not exported) MAKE_REF(cpv); exported alias, but as a function pointer !
  • 36. nbCall: does not expect a function pointer ! 1. resolve symbol to function pointer 2. follow pointer 3. invoke function Indirect calls CmExternalObject >> indirectCall: fnSpec | sender | sender := thisContext sender. ^ NBFFICallout handleFailureIn: sender nativeCode: [ :gen | gen sender: sender; stdcall; namedFnSpec: fnSpec. gen generate: [ :g | | fnAddress | fnAddress := self nbGetSymbolAddress: gen fnSpec functionName module: self nbLibraryNameOrHandle. fnAddress ifNil: [ self error: 'function unavailable' ]. fnAddress := (fnAddress nbUInt32AtOffset: 0). gen asm mov: fnAddress asUImm32 to: gen asm EAX; call: gen asm EAX. ] ]
  • 38. Structures vs. Objects NBExternalStructure = C struct no encapsulation ļ¬eld sizes known often used as a value NBExternalObject = opaque type C functions as accessors handled via pointers
  • 39. 6 Structures See class CmVector ? FORGET IT EVER EXISTED. Now what ? How to describe ļ¬elds ? How to access ļ¬elds ?
  • 40. from cpVect to CmVector typedef struct cpVect { cpFloat x, y; } cpVect; CmExternalStructure subclass: #CmVector2 instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Esug2013-NativeBoostTutorial'
  • 41. from cpVect to CmVector CmVector2 class >> fieldsDesc "self initializeAccessors" ^ #( cpFloat x; cpFloat y ) magic !
  • 42. 7 External Objects See CmShape ? FORGET IT EVER EXISTED. Now what ? How to create instances ? How to deļ¬ne methods ?
  • 43. from cpShape to CmShape CmExternalObject subclass: #CmShape2 instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' category: 'Esug2013-NativeBoostTutorial'
  • 44. from cpShape to CmShape cpShape *cpCircleShapeNew( cpBody *body, cpFloat radius, cpVect offset ) CmShape class >> newCircleBody: aBody radius: radius offset: offsetPoint ^ (self primCpCircleShapeNew: aBody radius: radius asFloat offset: offsetPoint asCmVector) initialize
  • 45. from cpShape to CmShape CmShape class >> primCpCircleShapeNew: aBody radius: radius offset: offsetPoint <primitive: #primitiveNativeCall module: #NativeBoostPlugin> ^ (self nbCall: #( CmShape cpCircleShapeNew( CmBody body, cpFloat radius, CmVector offset ) )
  • 46. 8 Arrays CmShape class >> newPolygonBody: aBody vertices: hullVertices offset: aPoint vertices := CmVector arrayClass new: hullVertices size. hullVertices withIndexDo: [ :each :index | vertices at: index put: each asCmVector ]. ^ (self primCpPolygonNew: aBody verticesNumber: vertices size vertices: vertices address offset: aPoint asCmVector) initialize
  • 48. Collision handling callbacks begin pre-solve post-solve separate contact detected, proceed with collision ? shapes just stopped touching tweak contact properties before processing react to computed impulse
  • 49. Callback = block + signature NBFFICallback subclass: #CmCollisionBegin instanceVariableNames: '' classVariableNames: '' poolDictionaries: 'CmTypes' category: 'Esug2013-NativeBoostTutorial' CmCollisionBegin class >> fnSpec ^ #(int (void *arbiter, CmSpace space, void *data))
  • 50. Tracing collisions beginCallback := CmCollisionBegin on: [ :arbiter :space :data | Transcript show: 'begin'; cr. 1 ]. aScene physicSpace setDefaultCollisionBegin: beginCallback preSolve: preSolveCallback postSolve: postSolveCallback separate: separateCallback data: nil