seperation of body initialization, glider model
[carveJwlIkooP6JGAAIwe30JlM.git] / rigidbody.h
1 /*
2 * Copyright (C) 2021-2023 Mt.ZERO Software, Harry Godden - All Rights Reserved
3 */
4
5 /*
6 * Resources: Box2D - Erin Catto
7 * qu3e - Randy Gaul
8 */
9
10 #include "vg/vg_console.h"
11 #include "bvh.h"
12 #include "scene.h"
13
14 #include <math.h>
15
16 #ifndef RIGIDBODY_H
17 #define RIGIDBODY_H
18
19 /*
20 * -----------------------------------------------------------------------------
21 * (K)onstants
22 * -----------------------------------------------------------------------------
23 */
24
25 static const float
26 k_rb_rate = (1.0/VG_TIMESTEP_FIXED),
27 k_rb_delta = (1.0/k_rb_rate),
28 k_friction = 0.4f,
29 k_damp_linear = 0.1f, /* scale velocity 1/(1+x) */
30 k_damp_angular = 0.1f, /* scale angular 1/(1+x) */
31 k_penetration_slop = 0.01f,
32 k_inertia_scale = 4.0f,
33 k_phys_baumgarte = 0.2f,
34 k_gravity = 9.6f,
35 k_rb_density = 8.0f;
36
37 static float
38 k_limit_bias = 0.02f,
39 k_joint_correction = 0.01f,
40 k_joint_impulse = 1.0f,
41 k_joint_bias = 0.08f; /* positional joints */
42
43 static void rb_register_cvar(void){
44 VG_VAR_F32( k_limit_bias, flags=VG_VAR_CHEAT );
45 VG_VAR_F32( k_joint_bias, flags=VG_VAR_CHEAT );
46 VG_VAR_F32( k_joint_correction, flags=VG_VAR_CHEAT );
47 VG_VAR_F32( k_joint_impulse, flags=VG_VAR_CHEAT );
48 }
49
50 enum rb_shape {
51 k_rb_shape_none = 0,
52 k_rb_shape_box = 1,
53 k_rb_shape_sphere = 2,
54 k_rb_shape_capsule = 3,
55 };
56
57 /*
58 * -----------------------------------------------------------------------------
59 * structure definitions
60 * -----------------------------------------------------------------------------
61 */
62
63 typedef struct rigidbody rigidbody;
64 typedef struct contact rb_ct;
65 typedef struct rb_capsule rb_capsule;
66
67 struct rb_capsule{
68 f32 h, r;
69 };
70
71 struct rigidbody{
72 v3f co, v, w;
73 v4f q;
74
75 f32 inv_mass;
76
77 m3x3f iI, iIw; /* inertia model and inverse world tensor */
78 m4x3f to_world, to_local;
79 };
80
81 static struct contact{
82 rigidbody *rba, *rbb;
83 v3f co, n;
84 v3f t[2];
85 float p, bias, norm_impulse, tangent_impulse[2],
86 normal_mass, tangent_mass[2];
87
88 u32 element_id;
89
90 enum contact_type type;
91 }
92 rb_contact_buffer[256];
93 static int rb_contact_count = 0;
94
95 typedef struct rb_constr_pos rb_constr_pos;
96 typedef struct rb_constr_swingtwist rb_constr_swingtwist;
97
98 struct rb_constr_pos{
99 rigidbody *rba, *rbb;
100 v3f lca, lcb;
101 };
102
103 struct rb_constr_swingtwist{
104 rigidbody *rba, *rbb;
105
106 v4f conevx, conevy; /* relative to rba */
107 v3f view_offset, /* relative to rba */
108 coneva, conevxb;/* relative to rbb */
109
110 int tangent_violation, axis_violation;
111 v3f axis, tangent_axis, tangent_target, axis_target;
112
113 float conet;
114 float tangent_mass, axis_mass;
115
116 f32 conv_tangent, conv_axis;
117 };
118
119 /*
120 * -----------------------------------------------------------------------------
121 * Debugging
122 * -----------------------------------------------------------------------------
123 */
124
125 static void rb_debug_contact( rb_ct *ct ){
126 v3f p1;
127 v3_muladds( ct->co, ct->n, 0.05f, p1 );
128
129 if( ct->type == k_contact_type_default ){
130 vg_line_point( ct->co, 0.0125f, 0xff0000ff );
131 vg_line( ct->co, p1, 0xffffffff );
132 }
133 else if( ct->type == k_contact_type_edge ){
134 vg_line_point( ct->co, 0.0125f, 0xff00ffc0 );
135 vg_line( ct->co, p1, 0xffffffff );
136 }
137 }
138
139 /*
140 * -----------------------------------------------------------------------------
141 * Integration
142 * -----------------------------------------------------------------------------
143 */
144
145 /*
146 * Update ALL matrices and tensors on rigidbody
147 */
148 static void rb_update_matrices( rigidbody *rb ){
149 //q_normalize( rb->q );
150 q_m3x3( rb->q, rb->to_world );
151 v3_copy( rb->co, rb->to_world[3] );
152 m4x3_invert_affine( rb->to_world, rb->to_local );
153
154 /* I = R I_0 R^T */
155 m3x3_mul( rb->to_world, rb->iI, rb->iIw );
156 m3x3_mul( rb->iIw, rb->to_local, rb->iIw );
157 }
158
159 /*
160 * Extrapolate rigidbody into a transform based on vg accumulator.
161 * Useful for rendering
162 */
163 static void rb_extrapolate( rigidbody *rb, v3f co, v4f q ){
164 float substep = vg.time_fixed_extrapolate;
165 v3_muladds( rb->co, rb->v, k_rb_delta*substep, co );
166
167 if( v3_length2( rb->w ) > 0.0f ){
168 v4f rotation;
169 v3f axis;
170 v3_copy( rb->w, axis );
171
172 float mag = v3_length( axis );
173 v3_divs( axis, mag, axis );
174 q_axis_angle( rotation, axis, mag*k_rb_delta*substep );
175 q_mul( rotation, rb->q, q );
176 q_normalize( q );
177 }
178 else{
179 v4_copy( rb->q, q );
180 }
181 }
182
183 /*
184 * Inertia
185 * -----------------------------------------------------------------------------
186 */
187
188 /*
189 * Translate existing inertia tensor
190 */
191 static void rb_translate_inertia( m3x3f inout_inertia, f32 mass, v3f d ){
192 /*
193 * I = I_0 + m*[(d.d)E_3 - d(X)d]
194 *
195 * I: updated tensor
196 * I_0: original tensor
197 * m: scalar mass
198 * d: translation vector
199 * (X): outer product
200 * E_3: identity matrix
201 */
202 m3x3f t, outer, scale;
203 m3x3_diagonal( t, v3_dot(d,d) );
204 m3x3_outer_product( outer, d, d );
205 m3x3_sub( t, outer, t );
206 m3x3_diagonal( scale, mass );
207 m3x3_mul( scale, t, t );
208 m3x3_add( inout_inertia, t, inout_inertia );
209 }
210
211 /*
212 * Rotate existing inertia tensor
213 */
214 static void rb_rotate_inertia( m3x3f inout_inertia, m3x3f rotation ){
215 /*
216 * I = R I_0 R^T
217 *
218 * I: updated tensor
219 * I_0: original tensor
220 * R: rotation matrix
221 * R^T: tranposed rotation matrix
222 */
223
224 m3x3f Rt;
225 m3x3_transpose( rotation, Rt );
226 m3x3_mul( rotation, inout_inertia, inout_inertia );
227 m3x3_mul( inout_inertia, Rt, inout_inertia );
228 }
229 /*
230 * Create inertia tensor for box
231 */
232 static void rb_box_inertia( boxf box, f32 mass, m3x3f out_inertia ){
233 v3f e, com;
234 v3_sub( box[1], box[0], e );
235 v3_muladds( box[0], e, 0.5f, com );
236
237 f32 ex2 = e[0]*e[0],
238 ey2 = e[1]*e[1],
239 ez2 = e[2]*e[2],
240 ix = (ey2+ez2) * mass * (1.0f/12.0f),
241 iy = (ex2+ez2) * mass * (1.0f/12.0f),
242 iz = (ex2+ey2) * mass * (1.0f/12.0f);
243
244 m3x3_identity( out_inertia );
245 m3x3_setdiagonalv3( out_inertia, (v3f){ ix, iy, iz } );
246 rb_translate_inertia( out_inertia, mass, com );
247 }
248
249 /*
250 * Create inertia tensor for sphere
251 */
252 static void rb_sphere_inertia( f32 r, f32 mass, m3x3f out_inertia ){
253 f32 ixyz = r*r * mass * (2.0f/5.0f);
254
255 m3x3_identity( out_inertia );
256 m3x3_setdiagonalv3( out_inertia, (v3f){ ixyz, ixyz, ixyz } );
257 }
258
259 /*
260 * Create inertia tensor for capsule
261 *
262 * TODO: UNTESTED
263 */
264 static void rb_capsule_inertia( f32 r, f32 h, f32 mass, m3x3f out_inertia ){
265 f32 density = mass / vg_capsule_volume( r, h ),
266 ch = h-r*2.0f, /* cylinder height */
267 cm = VG_PIf * ch*r*r * density, /* cylinder mass */
268 hm = VG_TAUf * (1.0f/3.0f) * r*r*r * density, /* hemisphere mass */
269
270 iy = r*r*cm * 0.5f,
271 ixz = iy * 0.5f + cm*ch*ch*(1.0f/12.0f),
272
273 aux0= (hm*2.0f*r*r)/5.0f;
274
275 iy += aux0 * 2.0f;
276
277 f32 aux1= ch*0.5f,
278 aux2= aux0 + hm*(aux1*aux1 + 3.0f*(1.0f/8.0f)*ch*r);
279
280 ixz += aux2*2.0f;
281
282 m3x3_identity( out_inertia );
283 m3x3_setdiagonalv3( out_inertia, (v3f){ ixz, iy, ixz } );
284 }
285
286 static void rb_setbody_capsule( rigidbody *rb, f32 r, f32 h,
287 f32 density, f32 inertia_scale ){
288 f32 vol = vg_capsule_volume( r, h ),
289 mass = vol*density;
290
291 rb->inv_mass = 1.0f/mass;
292
293 m3x3f I;
294 rb_capsule_inertia( r, h, mass * inertia_scale, I );
295 m3x3_inv( I, rb->iI );
296 }
297
298 static void rb_setbody_box( rigidbody *rb, boxf box,
299 f32 density, f32 inertia_scale ){
300 f32 vol = vg_box_volume( box ),
301 mass = vol*density;
302
303 rb->inv_mass = 1.0f/mass;
304
305 m3x3f I;
306 rb_box_inertia( box, mass * inertia_scale, I );
307 m3x3_inv( I, rb->iI );
308 }
309
310 static void rb_setbody_sphere( rigidbody *rb, f32 r,
311 f32 density, f32 inertia_scale ){
312 f32 vol = vg_sphere_volume( r ),
313 mass = vol*density;
314
315 rb->inv_mass = 1.0f/mass;
316 m3x3f I;
317 rb_sphere_inertia( r, mass * inertia_scale, I );
318 m3x3_inv( I, rb->iI );
319 }
320
321 static void rb_iter( rigidbody *rb ){
322 if( !vg_validf( rb->v[0] ) ||
323 !vg_validf( rb->v[1] ) ||
324 !vg_validf( rb->v[2] ) )
325 {
326 vg_fatal_error( "NaN velocity" );
327 }
328
329 v3f gravity = { 0.0f, -9.8f, 0.0f };
330 v3_muladds( rb->v, gravity, k_rb_delta, rb->v );
331
332 /* intergrate velocity */
333 v3_muladds( rb->co, rb->v, k_rb_delta, rb->co );
334 v3_lerp( rb->w, (v3f){0.0f,0.0f,0.0f}, 0.0025f, rb->w );
335
336 /* inegrate inertia */
337 if( v3_length2( rb->w ) > 0.0f ){
338 v4f rotation;
339 v3f axis;
340 v3_copy( rb->w, axis );
341
342 float mag = v3_length( axis );
343 v3_divs( axis, mag, axis );
344 q_axis_angle( rotation, axis, mag*k_rb_delta );
345 q_mul( rotation, rb->q, rb->q );
346 q_normalize( rb->q );
347 }
348 }
349
350 /*
351 * -----------------------------------------------------------------------------
352 * Boolean shape overlap functions
353 * -----------------------------------------------------------------------------
354 */
355
356 /*
357 * Project AABB, and triangle interval onto axis to check if they overlap
358 */
359 static int rb_box_triangle_interval( v3f extent, v3f axis, v3f tri[3] ){
360 float
361
362 r = extent[0] * fabsf(axis[0]) +
363 extent[1] * fabsf(axis[1]) +
364 extent[2] * fabsf(axis[2]),
365
366 p0 = v3_dot( axis, tri[0] ),
367 p1 = v3_dot( axis, tri[1] ),
368 p2 = v3_dot( axis, tri[2] ),
369
370 e = vg_maxf(-vg_maxf(p0,vg_maxf(p1,p2)), vg_minf(p0,vg_minf(p1,p2)));
371
372 if( e > r ) return 0;
373 else return 1;
374 }
375
376 /*
377 * Seperating axis test box vs triangle
378 */
379 static int rb_box_triangle_sat( v3f extent, v3f center,
380 m4x3f to_local, v3f tri_src[3] ){
381 v3f tri[3];
382
383 for( int i=0; i<3; i++ ){
384 m4x3_mulv( to_local, tri_src[i], tri[i] );
385 v3_sub( tri[i], center, tri[i] );
386 }
387
388 v3f f0,f1,f2,n;
389 v3_sub( tri[1], tri[0], f0 );
390 v3_sub( tri[2], tri[1], f1 );
391 v3_sub( tri[0], tri[2], f2 );
392
393
394 v3f axis[9];
395 v3_cross( (v3f){1.0f,0.0f,0.0f}, f0, axis[0] );
396 v3_cross( (v3f){1.0f,0.0f,0.0f}, f1, axis[1] );
397 v3_cross( (v3f){1.0f,0.0f,0.0f}, f2, axis[2] );
398 v3_cross( (v3f){0.0f,1.0f,0.0f}, f0, axis[3] );
399 v3_cross( (v3f){0.0f,1.0f,0.0f}, f1, axis[4] );
400 v3_cross( (v3f){0.0f,1.0f,0.0f}, f2, axis[5] );
401 v3_cross( (v3f){0.0f,0.0f,1.0f}, f0, axis[6] );
402 v3_cross( (v3f){0.0f,0.0f,1.0f}, f1, axis[7] );
403 v3_cross( (v3f){0.0f,0.0f,1.0f}, f2, axis[8] );
404
405 for( int i=0; i<9; i++ )
406 if(!rb_box_triangle_interval( extent, axis[i], tri )) return 0;
407
408 /* u0, u1, u2 */
409 if(!rb_box_triangle_interval( extent, (v3f){1.0f,0.0f,0.0f}, tri )) return 0;
410 if(!rb_box_triangle_interval( extent, (v3f){0.0f,1.0f,0.0f}, tri )) return 0;
411 if(!rb_box_triangle_interval( extent, (v3f){0.0f,0.0f,1.0f}, tri )) return 0;
412
413 /* normal */
414 v3_cross( f0, f1, n );
415 if(!rb_box_triangle_interval( extent, n, tri )) return 0;
416
417 return 1;
418 }
419
420 /*
421 * -----------------------------------------------------------------------------
422 * Manifold
423 * -----------------------------------------------------------------------------
424 */
425
426 static int rb_manifold_apply_filtered( rb_ct *man, int len ){
427 int k = 0;
428
429 for( int i=0; i<len; i++ ){
430 rb_ct *ct = &man[i];
431
432 if( ct->type == k_contact_type_disabled )
433 continue;
434
435 man[k ++] = man[i];
436 }
437
438 return k;
439 }
440
441 /*
442 * Merge two contacts if they are within radius(r) of eachother
443 */
444 static void rb_manifold_contact_weld( rb_ct *ci, rb_ct *cj, float r ){
445 if( v3_dist2( ci->co, cj->co ) < r*r ){
446 cj->type = k_contact_type_disabled;
447 ci->p = (ci->p + cj->p) * 0.5f;
448
449 v3_add( ci->co, cj->co, ci->co );
450 v3_muls( ci->co, 0.5f, ci->co );
451
452 v3f delta;
453 v3_sub( ci->rba->co, ci->co, delta );
454
455 float c0 = v3_dot( ci->n, delta ),
456 c1 = v3_dot( cj->n, delta );
457
458 if( c0 < 0.0f || c1 < 0.0f ){
459 /* error */
460 ci->type = k_contact_type_disabled;
461 }
462 else{
463 v3f n;
464 v3_muls( ci->n, c0, n );
465 v3_muladds( n, cj->n, c1, n );
466 v3_normalize( n );
467 v3_copy( n, ci->n );
468 }
469 }
470 }
471
472 /*
473 *
474 */
475 static void rb_manifold_filter_joint_edges( rb_ct *man, int len, float r ){
476 for( int i=0; i<len-1; i++ ){
477 rb_ct *ci = &man[i];
478 if( ci->type != k_contact_type_edge )
479 continue;
480
481 for( int j=i+1; j<len; j++ ){
482 rb_ct *cj = &man[j];
483 if( cj->type != k_contact_type_edge )
484 continue;
485
486 rb_manifold_contact_weld( ci, cj, r );
487 }
488 }
489 }
490
491 /*
492 * Resolve overlapping pairs
493 */
494 static void rb_manifold_filter_pairs( rb_ct *man, int len, float r ){
495 for( int i=0; i<len-1; i++ ){
496 rb_ct *ci = &man[i];
497 int similar = 0;
498
499 if( ci->type == k_contact_type_disabled ) continue;
500
501 for( int j=i+1; j<len; j++ ){
502 rb_ct *cj = &man[j];
503
504 if( cj->type == k_contact_type_disabled ) continue;
505
506 if( v3_dist2( ci->co, cj->co ) < r*r ){
507 cj->type = k_contact_type_disabled;
508 v3_add( cj->n, ci->n, ci->n );
509 ci->p += cj->p;
510 similar ++;
511 }
512 }
513
514 if( similar ){
515 float n = 1.0f/((float)similar+1.0f);
516 v3_muls( ci->n, n, ci->n );
517 ci->p *= n;
518
519 if( v3_length2(ci->n) < 0.1f*0.1f )
520 ci->type = k_contact_type_disabled;
521 else
522 v3_normalize( ci->n );
523 }
524 }
525 }
526
527 /*
528 * Remove contacts that are facing away from A
529 */
530 static void rb_manifold_filter_backface( rb_ct *man, int len ){
531 for( int i=0; i<len; i++ ){
532 rb_ct *ct = &man[i];
533 if( ct->type == k_contact_type_disabled )
534 continue;
535
536 v3f delta;
537 v3_sub( ct->co, ct->rba->co, delta );
538
539 if( v3_dot( delta, ct->n ) > -0.001f )
540 ct->type = k_contact_type_disabled;
541 }
542 }
543
544 /*
545 * Filter out duplicate coplanar results. Good for spheres.
546 */
547 static void rb_manifold_filter_coplanar( rb_ct *man, int len, float w ){
548 for( int i=0; i<len; i++ ){
549 rb_ct *ci = &man[i];
550 if( ci->type == k_contact_type_disabled ||
551 ci->type == k_contact_type_edge )
552 continue;
553
554 float d1 = v3_dot( ci->co, ci->n );
555
556 for( int j=0; j<len; j++ ){
557 if( j == i )
558 continue;
559
560 rb_ct *cj = &man[j];
561 if( cj->type == k_contact_type_disabled )
562 continue;
563
564 float d2 = v3_dot( cj->co, ci->n ),
565 d = d2-d1;
566
567 if( fabsf( d ) <= w ){
568 cj->type = k_contact_type_disabled;
569 }
570 }
571 }
572 }
573
574 /*
575 * -----------------------------------------------------------------------------
576 * Collision matrix
577 * -----------------------------------------------------------------------------
578 */
579
580 /*
581 * Contact generators
582 *
583 * These do not automatically allocate contacts, an appropriately sized
584 * buffer must be supplied. The function returns the size of the manifold
585 * which was generated.
586 *
587 * The values set on the contacts are: n, co, p, rba, rbb
588 */
589
590 /*
591 * By collecting the minimum(time) and maximum(time) pairs of points, we
592 * build a reduced and stable exact manifold.
593 *
594 * tx: time at point
595 * rx: minimum distance of these points
596 * dx: the delta between the two points
597 *
598 * pairs will only ammend these if they are creating a collision
599 */
600 typedef struct capsule_manifold capsule_manifold;
601 struct capsule_manifold{
602 float t0, t1;
603 float r0, r1;
604 v3f d0, d1;
605 };
606
607 /*
608 * Expand a line manifold with a new pair. t value is the time along segment
609 * on the oriented object which created this pair.
610 */
611 static void rb_capsule_manifold( v3f pa, v3f pb, float t, float r,
612 capsule_manifold *manifold ){
613 v3f delta;
614 v3_sub( pa, pb, delta );
615
616 if( v3_length2(delta) < r*r ){
617 if( t < manifold->t0 ){
618 v3_copy( delta, manifold->d0 );
619 manifold->t0 = t;
620 manifold->r0 = r;
621 }
622
623 if( t > manifold->t1 ){
624 v3_copy( delta, manifold->d1 );
625 manifold->t1 = t;
626 manifold->r1 = r;
627 }
628 }
629 }
630
631 static void rb_capsule_manifold_init( capsule_manifold *manifold ){
632 manifold->t0 = INFINITY;
633 manifold->t1 = -INFINITY;
634 }
635
636 static int rb_capsule__manifold_done( m4x3f mtx, rb_capsule *c,
637 capsule_manifold *manifold,
638 rb_ct *buf ){
639 v3f p0, p1;
640 v3_muladds( mtx[3], mtx[1], -c->h*0.5f+c->r, p0 );
641 v3_muladds( mtx[3], mtx[1], c->h*0.5f-c->r, p1 );
642
643 int count = 0;
644 if( manifold->t0 <= 1.0f ){
645 rb_ct *ct = buf;
646
647 v3f pa;
648 v3_muls( p0, 1.0f-manifold->t0, pa );
649 v3_muladds( pa, p1, manifold->t0, pa );
650
651 float d = v3_length( manifold->d0 );
652 v3_muls( manifold->d0, 1.0f/d, ct->n );
653 v3_muladds( pa, ct->n, -c->r, ct->co );
654
655 ct->p = manifold->r0 - d;
656 ct->type = k_contact_type_default;
657 count ++;
658 }
659
660 if( (manifold->t1 >= 0.0f) && (manifold->t0 != manifold->t1) ){
661 rb_ct *ct = buf+count;
662
663 v3f pa;
664 v3_muls( p0, 1.0f-manifold->t1, pa );
665 v3_muladds( pa, p1, manifold->t1, pa );
666
667 float d = v3_length( manifold->d1 );
668 v3_muls( manifold->d1, 1.0f/d, ct->n );
669 v3_muladds( pa, ct->n, -c->r, ct->co );
670
671 ct->p = manifold->r1 - d;
672 ct->type = k_contact_type_default;
673
674 count ++;
675 }
676
677 /*
678 * Debugging
679 */
680
681 if( count == 2 )
682 vg_line( buf[0].co, buf[1].co, 0xff0000ff );
683
684 return count;
685 }
686
687 #if 0
688 static int rb_capsule_sphere( rb_object *obja, rb_object *objb, rb_ct *buf ){
689 rigidbody *rba = &obja->rb, *rbb = &objb->rb;
690 float h = obja->inf.capsule.h,
691 ra = obja->inf.capsule.r,
692 rb = objb->inf.sphere.r;
693
694 v3f p0, p1;
695 v3_muladds( rba->co, rba->to_world[1], -h*0.5f+ra, p0 );
696 v3_muladds( rba->co, rba->to_world[1], h*0.5f-ra, p1 );
697
698 v3f c, delta;
699 closest_point_segment( p0, p1, rbb->co, c );
700 v3_sub( c, rbb->co, delta );
701
702 float d2 = v3_length2(delta),
703 r = ra + rb;
704
705 if( d2 < r*r ){
706 float d = sqrtf(d2);
707
708 rb_ct *ct = buf;
709 v3_muls( delta, 1.0f/d, ct->n );
710 ct->p = r-d;
711
712 v3f p0, p1;
713 v3_muladds( c, ct->n, -ra, p0 );
714 v3_muladds( rbb->co, ct->n, rb, p1 );
715 v3_add( p0, p1, ct->co );
716 v3_muls( ct->co, 0.5f, ct->co );
717
718 ct->rba = rba;
719 ct->rbb = rbb;
720 ct->type = k_contact_type_default;
721
722 return 1;
723 }
724
725 return 0;
726 }
727 #endif
728
729 static int rb_capsule__capsule( m4x3f mtxA, rb_capsule *ca,
730 m4x3f mtxB, rb_capsule *cb, rb_ct *buf ){
731 f32 ha = ca->h,
732 hb = cb->h,
733 ra = ca->r,
734 rb = cb->r,
735 r = ra+rb;
736
737 v3f p0, p1, p2, p3;
738 v3_muladds( mtxA[3], mtxA[1], -ha*0.5f+ra, p0 );
739 v3_muladds( mtxA[3], mtxA[1], ha*0.5f-ra, p1 );
740 v3_muladds( mtxB[3], mtxB[1], -hb*0.5f+rb, p2 );
741 v3_muladds( mtxB[3], mtxB[1], hb*0.5f-rb, p3 );
742
743 capsule_manifold manifold;
744 rb_capsule_manifold_init( &manifold );
745
746 v3f pa, pb;
747 f32 ta, tb;
748 closest_segment_segment( p0, p1, p2, p3, &ta, &tb, pa, pb );
749 rb_capsule_manifold( pa, pb, ta, r, &manifold );
750
751 ta = closest_point_segment( p0, p1, p2, pa );
752 tb = closest_point_segment( p0, p1, p3, pb );
753 rb_capsule_manifold( pa, p2, ta, r, &manifold );
754 rb_capsule_manifold( pb, p3, tb, r, &manifold );
755
756 closest_point_segment( p2, p3, p0, pa );
757 closest_point_segment( p2, p3, p1, pb );
758 rb_capsule_manifold( p0, pa, 0.0f, r, &manifold );
759 rb_capsule_manifold( p1, pb, 1.0f, r, &manifold );
760
761 return rb_capsule__manifold_done( mtxA, ca, &manifold, buf );
762 }
763
764 #if 0
765 static int rb_sphere_box( rb_object *obja, rb_object *objb, rb_ct *buf ){
766 v3f co, delta;
767 rigidbody *rba = &obja->rb, *rbb = &objb->rb;
768
769 closest_point_obb( rba->co, rbb->bbx, rbb->to_world, rbb->to_local, co );
770 v3_sub( rba->co, co, delta );
771
772 float d2 = v3_length2(delta),
773 r = obja->inf.sphere.radius;
774
775 if( d2 <= r*r ){
776 float d;
777
778 rb_ct *ct = buf;
779 if( d2 <= 0.0001f ){
780 v3_sub( rba->co, rbb->co, delta );
781
782 /*
783 * some extra testing is required to find the best axis to push the
784 * object back outside the box. Since there isnt a clear seperating
785 * vector already, especially on really high aspect boxes.
786 */
787 float lx = v3_dot( rbb->to_world[0], delta ),
788 ly = v3_dot( rbb->to_world[1], delta ),
789 lz = v3_dot( rbb->to_world[2], delta ),
790 px = rbb->bbx[1][0] - fabsf(lx),
791 py = rbb->bbx[1][1] - fabsf(ly),
792 pz = rbb->bbx[1][2] - fabsf(lz);
793
794 if( px < py && px < pz )
795 v3_muls( rbb->to_world[0], vg_signf(lx), ct->n );
796 else if( py < pz )
797 v3_muls( rbb->to_world[1], vg_signf(ly), ct->n );
798 else
799 v3_muls( rbb->to_world[2], vg_signf(lz), ct->n );
800
801 v3_muladds( rba->co, ct->n, -r, ct->co );
802 ct->p = r;
803 }
804 else{
805 d = sqrtf(d2);
806 v3_muls( delta, 1.0f/d, ct->n );
807 ct->p = r-d;
808 v3_copy( co, ct->co );
809 }
810
811 ct->rba = rba;
812 ct->rbb = rbb;
813 ct->type = k_contact_type_default;
814 return 1;
815 }
816
817 return 0;
818 }
819 #endif
820
821 #if 0
822 static int rb_sphere_sphere( rb_object *obja, rb_object *objb, rb_ct *buf ){
823 rigidbody *rba = &obja->rb, *rbb = &objb->rb;
824 v3f delta;
825 v3_sub( rba->co, rbb->co, delta );
826
827 float d2 = v3_length2(delta),
828 r = obja->inf.sphere.radius + objb->inf.sphere.radius;
829
830 if( d2 < r*r ){
831 float d = sqrtf(d2);
832
833 rb_ct *ct = buf;
834 v3_muls( delta, 1.0f/d, ct->n );
835
836 v3f p0, p1;
837 v3_muladds( rba->co, ct->n,-obja->inf.sphere.radius, p0 );
838 v3_muladds( rbb->co, ct->n, objb->inf.sphere.radius, p1 );
839 v3_add( p0, p1, ct->co );
840 v3_muls( ct->co, 0.5f, ct->co );
841 ct->type = k_contact_type_default;
842 ct->p = r-d;
843 ct->rba = rba;
844 ct->rbb = rbb;
845 return 1;
846 }
847
848 return 0;
849 }
850 #endif
851
852 static int rb_sphere__triangle( m4x3f mtxA, f32 r,
853 v3f tri[3], rb_ct *buf ){
854 v3f delta, co;
855 enum contact_type type = closest_on_triangle_1( mtxA[3], tri, co );
856 v3_sub( mtxA[3], co, delta );
857 f32 d2 = v3_length2( delta );
858
859 if( d2 <= r*r ){
860 rb_ct *ct = buf;
861
862 v3f ab, ac, tn;
863 v3_sub( tri[2], tri[0], ab );
864 v3_sub( tri[1], tri[0], ac );
865 v3_cross( ac, ab, tn );
866 v3_copy( tn, ct->n );
867
868 if( v3_length2( ct->n ) <= 0.00001f ){
869 #ifdef RIGIDBODY_CRY_ABOUT_EVERYTHING
870 vg_error( "Zero area triangle!\n" );
871 #endif
872 return 0;
873 }
874
875 v3_normalize( ct->n );
876
877 float d = sqrtf(d2);
878
879 v3_copy( co, ct->co );
880 ct->type = type;
881 ct->p = r-d;
882 return 1;
883 }
884
885 return 0;
886 }
887
888 static int rb_sphere__scene( m4x3f mtxA, f32 r,
889 m4x3f mtxB, bh_tree *scene_bh, rb_ct *buf,
890 u16 ignore ){
891 scene_context *sc = scene_bh->user;
892
893 int count = 0;
894
895 boxf box;
896 v3_sub( mtxA[3], (v3f){ r,r,r }, box[0] );
897 v3_add( mtxA[3], (v3f){ r,r,r }, box[1] );
898
899 bh_iter it;
900 i32 idx;
901 bh_iter_init_box( 0, &it, box );
902
903 while( bh_next( scene_bh, &it, &idx ) ){
904 u32 *ptri = &sc->arrindices[ idx*3 ];
905 v3f tri[3];
906
907 if( sc->arrvertices[ptri[0]].flags & ignore ) continue;
908
909 for( int j=0; j<3; j++ )
910 v3_copy( sc->arrvertices[ptri[j]].co, tri[j] );
911
912 buf[ count ].element_id = ptri[0];
913
914 vg_line( tri[0],tri[1],0x70ff6000 );
915 vg_line( tri[1],tri[2],0x70ff6000 );
916 vg_line( tri[2],tri[0],0x70ff6000 );
917
918 int contact = rb_sphere__triangle( mtxA, r, tri, &buf[count] );
919 count += contact;
920
921 if( count == 16 ){
922 vg_warn( "Exceeding sphere_vs_scene capacity. Geometry too dense!\n" );
923 return count;
924 }
925 }
926
927 return count;
928 }
929
930 static int rb_box__scene( m4x3f mtxA, boxf bbx,
931 m4x3f mtxB, bh_tree *scene_bh,
932 rb_ct *buf, u16 ignore ){
933 scene_context *sc = scene_bh->user;
934 v3f tri[3];
935
936 v3f extent, center;
937 v3_sub( bbx[1], bbx[0], extent );
938 v3_muls( extent, 0.5f, extent );
939 v3_add( bbx[0], extent, center );
940
941 float r = v3_length(extent);
942 boxf world_bbx;
943 v3_fill( world_bbx[0], -r );
944 v3_fill( world_bbx[1], r );
945 for( int i=0; i<2; i++ ){
946 v3_add( center, world_bbx[i], world_bbx[i] );
947 v3_add( mtxA[3], world_bbx[i], world_bbx[i] );
948 }
949
950 m4x3f to_local;
951 m4x3_invert_affine( mtxA, to_local );
952
953 bh_iter it;
954 bh_iter_init_box( 0, &it, world_bbx );
955 int idx;
956 int count = 0;
957
958 vg_line_boxf( world_bbx, VG__RED );
959
960 while( bh_next( scene_bh, &it, &idx ) ){
961 u32 *ptri = &sc->arrindices[ idx*3 ];
962 if( sc->arrvertices[ptri[0]].flags & ignore ) continue;
963
964 for( int j=0; j<3; j++ )
965 v3_copy( sc->arrvertices[ptri[j]].co, tri[j] );
966
967 if( rb_box_triangle_sat( extent, center, to_local, tri ) ){
968 vg_line(tri[0],tri[1],0xff50ff00 );
969 vg_line(tri[1],tri[2],0xff50ff00 );
970 vg_line(tri[2],tri[0],0xff50ff00 );
971 }
972 else{
973 vg_line(tri[0],tri[1],0xff0000ff );
974 vg_line(tri[1],tri[2],0xff0000ff );
975 vg_line(tri[2],tri[0],0xff0000ff );
976 continue;
977 }
978
979 v3f v0,v1,n;
980 v3_sub( tri[1], tri[0], v0 );
981 v3_sub( tri[2], tri[0], v1 );
982 v3_cross( v0, v1, n );
983
984 if( v3_length2( n ) <= 0.00001f ){
985 #ifdef RIGIDBODY_CRY_ABOUT_EVERYTHING
986 vg_error( "Zero area triangle!\n" );
987 #endif
988 return 0;
989 }
990
991 v3_normalize( n );
992
993 /* find best feature */
994 float best = v3_dot( mtxA[0], n );
995 int axis = 0;
996
997 for( int i=1; i<3; i++ ){
998 float c = v3_dot( mtxA[i], n );
999
1000 if( fabsf(c) > fabsf(best) ){
1001 best = c;
1002 axis = i;
1003 }
1004 }
1005
1006 v3f manifold[4];
1007
1008 if( axis == 0 ){
1009 float px = best > 0.0f? bbx[0][0]: bbx[1][0];
1010 manifold[0][0] = px;
1011 manifold[0][1] = bbx[0][1];
1012 manifold[0][2] = bbx[0][2];
1013 manifold[1][0] = px;
1014 manifold[1][1] = bbx[1][1];
1015 manifold[1][2] = bbx[0][2];
1016 manifold[2][0] = px;
1017 manifold[2][1] = bbx[1][1];
1018 manifold[2][2] = bbx[1][2];
1019 manifold[3][0] = px;
1020 manifold[3][1] = bbx[0][1];
1021 manifold[3][2] = bbx[1][2];
1022 }
1023 else if( axis == 1 ){
1024 float py = best > 0.0f? bbx[0][1]: bbx[1][1];
1025 manifold[0][0] = bbx[0][0];
1026 manifold[0][1] = py;
1027 manifold[0][2] = bbx[0][2];
1028 manifold[1][0] = bbx[1][0];
1029 manifold[1][1] = py;
1030 manifold[1][2] = bbx[0][2];
1031 manifold[2][0] = bbx[1][0];
1032 manifold[2][1] = py;
1033 manifold[2][2] = bbx[1][2];
1034 manifold[3][0] = bbx[0][0];
1035 manifold[3][1] = py;
1036 manifold[3][2] = bbx[1][2];
1037 }
1038 else{
1039 float pz = best > 0.0f? bbx[0][2]: bbx[1][2];
1040 manifold[0][0] = bbx[0][0];
1041 manifold[0][1] = bbx[0][1];
1042 manifold[0][2] = pz;
1043 manifold[1][0] = bbx[1][0];
1044 manifold[1][1] = bbx[0][1];
1045 manifold[1][2] = pz;
1046 manifold[2][0] = bbx[1][0];
1047 manifold[2][1] = bbx[1][1];
1048 manifold[2][2] = pz;
1049 manifold[3][0] = bbx[0][0];
1050 manifold[3][1] = bbx[1][1];
1051 manifold[3][2] = pz;
1052 }
1053
1054 for( int j=0; j<4; j++ )
1055 m4x3_mulv( mtxA, manifold[j], manifold[j] );
1056
1057 vg_line( manifold[0], manifold[1], 0xffffffff );
1058 vg_line( manifold[1], manifold[2], 0xffffffff );
1059 vg_line( manifold[2], manifold[3], 0xffffffff );
1060 vg_line( manifold[3], manifold[0], 0xffffffff );
1061
1062 for( int j=0; j<4; j++ ){
1063 rb_ct *ct = buf+count;
1064
1065 v3_copy( manifold[j], ct->co );
1066 v3_copy( n, ct->n );
1067
1068 float l0 = v3_dot( tri[0], n ),
1069 l1 = v3_dot( manifold[j], n );
1070
1071 ct->p = (l0-l1)*0.5f;
1072 if( ct->p < 0.0f )
1073 continue;
1074
1075 ct->type = k_contact_type_default;
1076 count ++;
1077
1078 if( count >= 12 )
1079 return count;
1080 }
1081 }
1082 return count;
1083 }
1084
1085 static int rb_capsule__triangle( m4x3f mtxA, rb_capsule *c,
1086 v3f tri[3], rb_ct *buf ){
1087 v3f pc, p0w, p1w;
1088 v3_muladds( mtxA[3], mtxA[1], -c->h*0.5f+c->r, p0w );
1089 v3_muladds( mtxA[3], mtxA[1], c->h*0.5f-c->r, p1w );
1090
1091 capsule_manifold manifold;
1092 rb_capsule_manifold_init( &manifold );
1093
1094 v3f v0, v1, n;
1095 v3_sub( tri[1], tri[0], v0 );
1096 v3_sub( tri[2], tri[0], v1 );
1097 v3_cross( v0, v1, n );
1098
1099 if( v3_length2( n ) <= 0.00001f ){
1100 #ifdef RIGIDBODY_CRY_ABOUT_EVERYTHING
1101 vg_error( "Zero area triangle!\n" );
1102 #endif
1103 return 0;
1104 }
1105
1106 v3_normalize( n );
1107
1108 #if 1
1109 /* deep penetration recovery. for when we clip through the triangles. so its
1110 * not very 'correct' */
1111 f32 dist;
1112 if( ray_tri( tri, p0w, mtxA[1], &dist, 1 ) ){
1113 f32 l = c->h - c->r*2.0f;
1114 if( (dist >= 0.0f) && (dist < l) ){
1115 v3f co;
1116 v3_muladds( p0w, mtxA[1], dist, co );
1117 vg_line_point( co, 0.02f, 0xffffff00 );
1118
1119 v3f d0, d1;
1120 v3_sub( p0w, co, d0 );
1121 v3_sub( p1w, co, d1 );
1122
1123 f32 p = vg_minf( v3_dot( n, d0 ), v3_dot( n, d1 ) ) - c->r;
1124
1125 rb_ct *ct = buf;
1126 ct->p = -p;
1127 ct->type = k_contact_type_default;
1128 v3_copy( n, ct->n );
1129 v3_muladds( co, n, p, ct->co );
1130
1131 return 1;
1132 }
1133 }
1134 #endif
1135
1136 v3f c0, c1;
1137 closest_on_triangle_1( p0w, tri, c0 );
1138 closest_on_triangle_1( p1w, tri, c1 );
1139
1140 v3f d0, d1, da;
1141 v3_sub( c0, p0w, d0 );
1142 v3_sub( c1, p1w, d1 );
1143 v3_sub( p1w, p0w, da );
1144
1145 v3_normalize(d0);
1146 v3_normalize(d1);
1147 v3_normalize(da);
1148
1149 /* the two balls at the ends */
1150 if( v3_dot( da, d0 ) <= 0.01f )
1151 rb_capsule_manifold( p0w, c0, 0.0f, c->r, &manifold );
1152 if( v3_dot( da, d1 ) >= -0.01f )
1153 rb_capsule_manifold( p1w, c1, 1.0f, c->r, &manifold );
1154
1155 /* the edges to edges */
1156 for( int i=0; i<3; i++ ){
1157 int i0 = i,
1158 i1 = (i+1)%3;
1159
1160 v3f ca, cb;
1161 float ta, tb;
1162 closest_segment_segment( p0w, p1w, tri[i0], tri[i1], &ta, &tb, ca, cb );
1163 rb_capsule_manifold( ca, cb, ta, c->r, &manifold );
1164 }
1165
1166 int count = rb_capsule__manifold_done( mtxA, c, &manifold, buf );
1167 for( int i=0; i<count; i++ )
1168 v3_copy( n, buf[i].n );
1169
1170 return count;
1171 }
1172
1173 /* mtxB is defined only for tradition; it is not used currently */
1174 static int rb_capsule__scene( m4x3f mtxA, rb_capsule *c,
1175 m4x3f mtxB, bh_tree *scene_bh,
1176 rb_ct *buf, u16 ignore ){
1177 int count = 0;
1178
1179 boxf bbx;
1180 v3_sub( mtxA[3], (v3f){ c->h, c->h, c->h }, bbx[0] );
1181 v3_add( mtxA[3], (v3f){ c->h, c->h, c->h }, bbx[1] );
1182
1183 scene_context *sc = scene_bh->user;
1184
1185 bh_iter it;
1186 bh_iter_init_box( 0, &it, bbx );
1187 i32 idx;
1188 while( bh_next( scene_bh, &it, &idx ) ){
1189 u32 *ptri = &sc->arrindices[ idx*3 ];
1190 if( sc->arrvertices[ptri[0]].flags & ignore ) continue;
1191
1192 v3f tri[3];
1193 for( int j=0; j<3; j++ )
1194 v3_copy( sc->arrvertices[ptri[j]].co, tri[j] );
1195
1196 buf[ count ].element_id = ptri[0];
1197
1198 int contact = rb_capsule__triangle( mtxA, c, tri, &buf[count] );
1199 count += contact;
1200
1201 if( count >= 16 ){
1202 vg_warn("Exceeding capsule_vs_scene capacity. Geometry too dense!\n");
1203 return count;
1204 }
1205 }
1206
1207 return count;
1208 }
1209
1210 static int rb_global_has_space( void ){
1211 if( rb_contact_count + 16 > vg_list_size(rb_contact_buffer) )
1212 return 0;
1213
1214 return 1;
1215 }
1216
1217 static rb_ct *rb_global_buffer( void ){
1218 return &rb_contact_buffer[ rb_contact_count ];
1219 }
1220
1221 /*
1222 * -----------------------------------------------------------------------------
1223 * Dynamics
1224 * -----------------------------------------------------------------------------
1225 */
1226
1227 static void rb_solver_reset(void){
1228 rb_contact_count = 0;
1229 }
1230
1231 static rb_ct *rb_global_ct(void){
1232 return rb_contact_buffer + rb_contact_count;
1233 }
1234
1235 static void rb_prepare_contact( rb_ct *ct, float timestep ){
1236 ct->bias = -k_phys_baumgarte * (timestep*3600.0f)
1237 * vg_minf( 0.0f, -ct->p+k_penetration_slop );
1238
1239 v3_tangent_basis( ct->n, ct->t[0], ct->t[1] );
1240 ct->norm_impulse = 0.0f;
1241 ct->tangent_impulse[0] = 0.0f;
1242 ct->tangent_impulse[1] = 0.0f;
1243 }
1244
1245 /* calculate total move. manifold should belong to ONE object only */
1246 static void rb_depenetrate( rb_ct *manifold, int len, v3f dt ){
1247 v3_zero( dt );
1248
1249 for( int j=0; j<7; j++ )
1250 {
1251 for( int i=0; i<len; i++ )
1252 {
1253 struct contact *ct = &manifold[i];
1254
1255 float resolved_amt = v3_dot( ct->n, dt ),
1256 remaining = (ct->p-k_penetration_slop) - resolved_amt,
1257 apply = vg_maxf( remaining, 0.0f ) * 0.4f;
1258
1259 v3_muladds( dt, ct->n, apply, dt );
1260 }
1261 }
1262 }
1263
1264 /*
1265 * Initializing things like tangent vectors
1266 */
1267 static void rb_presolve_contacts( rb_ct *buffer, int len ){
1268 for( int i=0; i<len; i++ ){
1269 rb_ct *ct = &buffer[i];
1270 rb_prepare_contact( ct, k_rb_delta );
1271
1272 v3f ra, rb, raCn, rbCn, raCt, rbCt;
1273 v3_sub( ct->co, ct->rba->co, ra );
1274 v3_sub( ct->co, ct->rbb->co, rb );
1275 v3_cross( ra, ct->n, raCn );
1276 v3_cross( rb, ct->n, rbCn );
1277
1278 /* orient inverse inertia tensors */
1279 v3f raCnI, rbCnI;
1280 m3x3_mulv( ct->rba->iIw, raCn, raCnI );
1281 m3x3_mulv( ct->rbb->iIw, rbCn, rbCnI );
1282
1283 ct->normal_mass = ct->rba->inv_mass + ct->rbb->inv_mass;
1284 ct->normal_mass += v3_dot( raCn, raCnI );
1285 ct->normal_mass += v3_dot( rbCn, rbCnI );
1286 ct->normal_mass = 1.0f/ct->normal_mass;
1287
1288 for( int j=0; j<2; j++ ){
1289 v3f raCtI, rbCtI;
1290 v3_cross( ct->t[j], ra, raCt );
1291 v3_cross( ct->t[j], rb, rbCt );
1292 m3x3_mulv( ct->rba->iIw, raCt, raCtI );
1293 m3x3_mulv( ct->rbb->iIw, rbCt, rbCtI );
1294
1295 ct->tangent_mass[j] = ct->rba->inv_mass + ct->rbb->inv_mass;
1296 ct->tangent_mass[j] += v3_dot( raCt, raCtI );
1297 ct->tangent_mass[j] += v3_dot( rbCt, rbCtI );
1298 ct->tangent_mass[j] = 1.0f/ct->tangent_mass[j];
1299 }
1300
1301 rb_debug_contact( ct );
1302 }
1303 }
1304
1305 /*
1306 * Creates relative contact velocity vector
1307 */
1308 static void rb_rcv( rigidbody *rba, rigidbody *rbb, v3f ra, v3f rb, v3f rv ){
1309 v3f rva, rvb;
1310 v3_cross( rba->w, ra, rva );
1311 v3_add( rba->v, rva, rva );
1312 v3_cross( rbb->w, rb, rvb );
1313 v3_add( rbb->v, rvb, rvb );
1314
1315 v3_sub( rva, rvb, rv );
1316 }
1317
1318 static void rb_contact_restitution( rb_ct *ct, float cr ){
1319 v3f rv, ra, rb;
1320 v3_sub( ct->co, ct->rba->co, ra );
1321 v3_sub( ct->co, ct->rbb->co, rb );
1322 rb_rcv( ct->rba, ct->rbb, ra, rb, rv );
1323
1324 float v = v3_dot( rv, ct->n );
1325
1326 if( v < -1.0f ){
1327 ct->bias += -cr * v;
1328 }
1329 }
1330
1331 /*
1332 * Apply impulse to object
1333 */
1334 static void rb_linear_impulse( rigidbody *rb, v3f delta, v3f impulse ){
1335 /* linear */
1336 v3_muladds( rb->v, impulse, rb->inv_mass, rb->v );
1337
1338 /* Angular velocity */
1339 v3f wa;
1340 v3_cross( delta, impulse, wa );
1341
1342 m3x3_mulv( rb->iIw, wa, wa );
1343 v3_add( rb->w, wa, rb->w );
1344 }
1345
1346 /*
1347 * One iteration to solve the contact constraint
1348 */
1349 static void rb_solve_contacts( rb_ct *buf, int len ){
1350 for( int i=0; i<len; i++ ){
1351 struct contact *ct = &buf[i];
1352
1353 v3f rv, ra, rb;
1354 v3_sub( ct->co, ct->rba->co, ra );
1355 v3_sub( ct->co, ct->rbb->co, rb );
1356 rb_rcv( ct->rba, ct->rbb, ra, rb, rv );
1357
1358 /* Friction */
1359 for( int j=0; j<2; j++ ){
1360 float f = k_friction * ct->norm_impulse,
1361 vt = v3_dot( rv, ct->t[j] ),
1362 lambda = ct->tangent_mass[j] * -vt;
1363
1364 float temp = ct->tangent_impulse[j];
1365 ct->tangent_impulse[j] = vg_clampf( temp + lambda, -f, f );
1366 lambda = ct->tangent_impulse[j] - temp;
1367
1368 v3f impulse;
1369 v3_muls( ct->t[j], lambda, impulse );
1370 rb_linear_impulse( ct->rba, ra, impulse );
1371
1372 v3_muls( ct->t[j], -lambda, impulse );
1373 rb_linear_impulse( ct->rbb, rb, impulse );
1374 }
1375
1376 /* Normal */
1377 rb_rcv( ct->rba, ct->rbb, ra, rb, rv );
1378 float vn = v3_dot( rv, ct->n ),
1379 lambda = ct->normal_mass * (-vn + ct->bias);
1380
1381 float temp = ct->norm_impulse;
1382 ct->norm_impulse = vg_maxf( temp + lambda, 0.0f );
1383 lambda = ct->norm_impulse - temp;
1384
1385 v3f impulse;
1386 v3_muls( ct->n, lambda, impulse );
1387 rb_linear_impulse( ct->rba, ra, impulse );
1388
1389 v3_muls( ct->n, -lambda, impulse );
1390 rb_linear_impulse( ct->rbb, rb, impulse );
1391 }
1392 }
1393
1394 /*
1395 * -----------------------------------------------------------------------------
1396 * Constraints
1397 * -----------------------------------------------------------------------------
1398 */
1399
1400 static void rb_debug_position_constraints( rb_constr_pos *buffer, int len ){
1401 for( int i=0; i<len; i++ ){
1402 rb_constr_pos *constr = &buffer[i];
1403 rigidbody *rba = constr->rba, *rbb = constr->rbb;
1404
1405 v3f wca, wcb;
1406 m3x3_mulv( rba->to_world, constr->lca, wca );
1407 m3x3_mulv( rbb->to_world, constr->lcb, wcb );
1408
1409 v3f p0, p1;
1410 v3_add( wca, rba->co, p0 );
1411 v3_add( wcb, rbb->co, p1 );
1412 vg_line_point( p0, 0.0025f, 0xff000000 );
1413 vg_line_point( p1, 0.0025f, 0xffffffff );
1414 vg_line2( p0, p1, 0xff000000, 0xffffffff );
1415 }
1416 }
1417
1418 static void rb_presolve_swingtwist_constraints( rb_constr_swingtwist *buf,
1419 int len ){
1420 for( int i=0; i<len; i++ ){
1421 rb_constr_swingtwist *st = &buf[ i ];
1422
1423 v3f vx, vy, va, vxb, axis, center;
1424
1425 m3x3_mulv( st->rba->to_world, st->conevx, vx );
1426 m3x3_mulv( st->rbb->to_world, st->conevxb, vxb );
1427 m3x3_mulv( st->rba->to_world, st->conevy, vy );
1428 m3x3_mulv( st->rbb->to_world, st->coneva, va );
1429 m4x3_mulv( st->rba->to_world, st->view_offset, center );
1430 v3_cross( vy, vx, axis );
1431
1432 /* Constraint violated ? */
1433 float fx = v3_dot( vx, va ), /* projection world */
1434 fy = v3_dot( vy, va ),
1435 fn = v3_dot( va, axis ),
1436
1437 rx = st->conevx[3], /* elipse radii */
1438 ry = st->conevy[3],
1439
1440 lx = fx/rx, /* projection local (fn==lz) */
1441 ly = fy/ry;
1442
1443 st->tangent_violation = ((lx*lx + ly*ly) > fn*fn) || (fn <= 0.0f);
1444 if( st->tangent_violation ){
1445 /* Calculate a good position and the axis to solve on */
1446 v2f closest, tangent,
1447 p = { fx/fabsf(fn), fy/fabsf(fn) };
1448
1449 closest_point_elipse( p, (v2f){rx,ry}, closest );
1450 tangent[0] = -closest[1] / (ry*ry);
1451 tangent[1] = closest[0] / (rx*rx);
1452 v2_normalize( tangent );
1453
1454 v3f v0, v1;
1455 v3_muladds( axis, vx, closest[0], v0 );
1456 v3_muladds( v0, vy, closest[1], v0 );
1457 v3_normalize( v0 );
1458
1459 v3_muls( vx, tangent[0], v1 );
1460 v3_muladds( v1, vy, tangent[1], v1 );
1461
1462 v3_copy( v0, st->tangent_target );
1463 v3_copy( v1, st->tangent_axis );
1464
1465 /* calculate mass */
1466 v3f aIw, bIw;
1467 m3x3_mulv( st->rba->iIw, st->tangent_axis, aIw );
1468 m3x3_mulv( st->rbb->iIw, st->tangent_axis, bIw );
1469 st->tangent_mass = 1.0f / (v3_dot( st->tangent_axis, aIw ) +
1470 v3_dot( st->tangent_axis, bIw ));
1471
1472 float angle = v3_dot( va, st->tangent_target );
1473 }
1474
1475 v3f refaxis;
1476 v3_cross( vy, va, refaxis ); /* our default rotation */
1477 v3_normalize( refaxis );
1478
1479 float angle = v3_dot( refaxis, vxb );
1480 st->axis_violation = fabsf(angle) < st->conet;
1481
1482 if( st->axis_violation ){
1483 v3f dir_test;
1484 v3_cross( refaxis, vxb, dir_test );
1485
1486 if( v3_dot(dir_test, va) < 0.0f )
1487 st->axis_violation = -st->axis_violation;
1488
1489 float newang = (float)st->axis_violation * acosf(st->conet-0.0001f);
1490
1491 v3f refaxis_up;
1492 v3_cross( va, refaxis, refaxis_up );
1493 v3_muls( refaxis_up, sinf(newang), st->axis_target );
1494 v3_muladds( st->axis_target, refaxis, -cosf(newang), st->axis_target );
1495
1496 /* calculate mass */
1497 v3_copy( va, st->axis );
1498 v3f aIw, bIw;
1499 m3x3_mulv( st->rba->iIw, st->axis, aIw );
1500 m3x3_mulv( st->rbb->iIw, st->axis, bIw );
1501 st->axis_mass = 1.0f / (v3_dot( st->axis, aIw ) +
1502 v3_dot( st->axis, bIw ));
1503 }
1504 }
1505 }
1506
1507 static void rb_debug_swingtwist_constraints( rb_constr_swingtwist *buf,
1508 int len ){
1509 float size = 0.12f;
1510
1511 for( int i=0; i<len; i++ ){
1512 rb_constr_swingtwist *st = &buf[ i ];
1513
1514 v3f vx, vxb, vy, va, axis, center;
1515
1516 m3x3_mulv( st->rba->to_world, st->conevx, vx );
1517 m3x3_mulv( st->rbb->to_world, st->conevxb, vxb );
1518 m3x3_mulv( st->rba->to_world, st->conevy, vy );
1519 m3x3_mulv( st->rbb->to_world, st->coneva, va );
1520 m4x3_mulv( st->rba->to_world, st->view_offset, center );
1521 v3_cross( vy, vx, axis );
1522
1523 float rx = st->conevx[3], /* elipse radii */
1524 ry = st->conevy[3];
1525
1526 v3f p0, p1;
1527 v3_muladds( center, va, size, p1 );
1528 vg_line( center, p1, 0xffffffff );
1529 vg_line_point( p1, 0.00025f, 0xffffffff );
1530
1531 if( st->tangent_violation ){
1532 v3_muladds( center, st->tangent_target, size, p0 );
1533
1534 vg_line( center, p0, 0xff00ff00 );
1535 vg_line_point( p0, 0.00025f, 0xff00ff00 );
1536 vg_line( p1, p0, 0xff000000 );
1537 }
1538
1539 for( int x=0; x<32; x++ ){
1540 float t0 = ((float)x * (1.0f/32.0f)) * VG_TAUf,
1541 t1 = (((float)x+1.0f) * (1.0f/32.0f)) * VG_TAUf,
1542 c0 = cosf( t0 ),
1543 s0 = sinf( t0 ),
1544 c1 = cosf( t1 ),
1545 s1 = sinf( t1 );
1546
1547 v3f v0, v1;
1548 v3_muladds( axis, vx, c0*rx, v0 );
1549 v3_muladds( v0, vy, s0*ry, v0 );
1550 v3_muladds( axis, vx, c1*rx, v1 );
1551 v3_muladds( v1, vy, s1*ry, v1 );
1552
1553 v3_normalize( v0 );
1554 v3_normalize( v1 );
1555
1556 v3_muladds( center, v0, size, p0 );
1557 v3_muladds( center, v1, size, p1 );
1558
1559 u32 col0r = fabsf(c0) * 255.0f,
1560 col0g = fabsf(s0) * 255.0f,
1561 col1r = fabsf(c1) * 255.0f,
1562 col1g = fabsf(s1) * 255.0f,
1563 col = st->tangent_violation? 0xff0000ff: 0xff000000,
1564 col0 = col | (col0r<<16) | (col0g << 8),
1565 col1 = col | (col1r<<16) | (col1g << 8);
1566
1567 vg_line2( center, p0, VG__NONE, col0 );
1568 vg_line2( p0, p1, col0, col1 );
1569 }
1570
1571 /* Draw twist */
1572 v3_muladds( center, va, size, p0 );
1573 v3_muladds( p0, vxb, size, p1 );
1574
1575 vg_line( p0, p1, 0xff0000ff );
1576
1577 if( st->axis_violation ){
1578 v3_muladds( p0, st->axis_target, size*1.25f, p1 );
1579 vg_line( p0, p1, 0xffffff00 );
1580 vg_line_point( p1, 0.0025f, 0xffffff80 );
1581 }
1582
1583 v3f refaxis;
1584 v3_cross( vy, va, refaxis ); /* our default rotation */
1585 v3_normalize( refaxis );
1586 v3f refaxis_up;
1587 v3_cross( va, refaxis, refaxis_up );
1588 float newang = acosf(st->conet-0.0001f);
1589
1590 v3_muladds( p0, refaxis_up, sinf(newang)*size, p1 );
1591 v3_muladds( p1, refaxis, -cosf(newang)*size, p1 );
1592 vg_line( p0, p1, 0xff000000 );
1593
1594 v3_muladds( p0, refaxis_up, sinf(-newang)*size, p1 );
1595 v3_muladds( p1, refaxis, -cosf(-newang)*size, p1 );
1596 vg_line( p0, p1, 0xff404040 );
1597 }
1598 }
1599
1600 /*
1601 * Solve a list of positional constraints
1602 */
1603 static void rb_solve_position_constraints( rb_constr_pos *buf, int len ){
1604 for( int i=0; i<len; i++ ){
1605 rb_constr_pos *constr = &buf[i];
1606 rigidbody *rba = constr->rba, *rbb = constr->rbb;
1607
1608 v3f wa, wb;
1609 m3x3_mulv( rba->to_world, constr->lca, wa );
1610 m3x3_mulv( rbb->to_world, constr->lcb, wb );
1611
1612 m3x3f ssra, ssrat, ssrb, ssrbt;
1613
1614 m3x3_skew_symetric( ssrat, wa );
1615 m3x3_skew_symetric( ssrbt, wb );
1616 m3x3_transpose( ssrat, ssra );
1617 m3x3_transpose( ssrbt, ssrb );
1618
1619 v3f b, b_wa, b_wb, b_a, b_b;
1620 m3x3_mulv( ssra, rba->w, b_wa );
1621 m3x3_mulv( ssrb, rbb->w, b_wb );
1622 v3_add( rba->v, b_wa, b );
1623 v3_sub( b, rbb->v, b );
1624 v3_sub( b, b_wb, b );
1625 v3_muls( b, -1.0f, b );
1626
1627 m3x3f invMa, invMb;
1628 m3x3_diagonal( invMa, rba->inv_mass );
1629 m3x3_diagonal( invMb, rbb->inv_mass );
1630
1631 m3x3f ia, ib;
1632 m3x3_mul( ssra, rba->iIw, ia );
1633 m3x3_mul( ia, ssrat, ia );
1634 m3x3_mul( ssrb, rbb->iIw, ib );
1635 m3x3_mul( ib, ssrbt, ib );
1636
1637 m3x3f cma, cmb;
1638 m3x3_add( invMa, ia, cma );
1639 m3x3_add( invMb, ib, cmb );
1640
1641 m3x3f A;
1642 m3x3_add( cma, cmb, A );
1643
1644 /* Solve Ax = b ( A^-1*b = x ) */
1645 v3f impulse;
1646 m3x3f invA;
1647 m3x3_inv( A, invA );
1648 m3x3_mulv( invA, b, impulse );
1649
1650 v3f delta_va, delta_wa, delta_vb, delta_wb;
1651 m3x3f iwa, iwb;
1652 m3x3_mul( rba->iIw, ssrat, iwa );
1653 m3x3_mul( rbb->iIw, ssrbt, iwb );
1654
1655 m3x3_mulv( invMa, impulse, delta_va );
1656 m3x3_mulv( invMb, impulse, delta_vb );
1657 m3x3_mulv( iwa, impulse, delta_wa );
1658 m3x3_mulv( iwb, impulse, delta_wb );
1659
1660 v3_add( rba->v, delta_va, rba->v );
1661 v3_add( rba->w, delta_wa, rba->w );
1662 v3_sub( rbb->v, delta_vb, rbb->v );
1663 v3_sub( rbb->w, delta_wb, rbb->w );
1664 }
1665 }
1666
1667 static void rb_solve_swingtwist_constraints( rb_constr_swingtwist *buf,
1668 int len ){
1669 for( int i=0; i<len; i++ ){
1670 rb_constr_swingtwist *st = &buf[ i ];
1671
1672 if( !st->axis_violation )
1673 continue;
1674
1675 float rv = v3_dot( st->axis, st->rbb->w ) -
1676 v3_dot( st->axis, st->rba->w );
1677
1678 if( rv * (float)st->axis_violation > 0.0f )
1679 continue;
1680
1681 v3f impulse, wa, wb;
1682 v3_muls( st->axis, rv*st->axis_mass, impulse );
1683 m3x3_mulv( st->rba->iIw, impulse, wa );
1684 v3_add( st->rba->w, wa, st->rba->w );
1685
1686 v3_muls( impulse, -1.0f, impulse );
1687 m3x3_mulv( st->rbb->iIw, impulse, wb );
1688 v3_add( st->rbb->w, wb, st->rbb->w );
1689
1690 float rv2 = v3_dot( st->axis, st->rbb->w ) -
1691 v3_dot( st->axis, st->rba->w );
1692 }
1693
1694 for( int i=0; i<len; i++ ){
1695 rb_constr_swingtwist *st = &buf[ i ];
1696
1697 if( !st->tangent_violation )
1698 continue;
1699
1700 float rv = v3_dot( st->tangent_axis, st->rbb->w ) -
1701 v3_dot( st->tangent_axis, st->rba->w );
1702
1703 if( rv > 0.0f )
1704 continue;
1705
1706 v3f impulse, wa, wb;
1707 v3_muls( st->tangent_axis, rv*st->tangent_mass, impulse );
1708 m3x3_mulv( st->rba->iIw, impulse, wa );
1709 v3_add( st->rba->w, wa, st->rba->w );
1710
1711 v3_muls( impulse, -1.0f, impulse );
1712 m3x3_mulv( st->rbb->iIw, impulse, wb );
1713 v3_add( st->rbb->w, wb, st->rbb->w );
1714
1715 float rv2 = v3_dot( st->tangent_axis, st->rbb->w ) -
1716 v3_dot( st->tangent_axis, st->rba->w );
1717 }
1718 }
1719
1720 /* debugging */
1721 static void rb_postsolve_swingtwist_constraints( rb_constr_swingtwist *buf,
1722 u32 len ){
1723 for( int i=0; i<len; i++ ){
1724 rb_constr_swingtwist *st = &buf[ i ];
1725
1726 if( !st->axis_violation ){
1727 st->conv_axis = 0.0f;
1728 continue;
1729 }
1730
1731 f32 rv = v3_dot( st->axis, st->rbb->w ) -
1732 v3_dot( st->axis, st->rba->w );
1733
1734 if( rv * (f32)st->axis_violation > 0.0f )
1735 st->conv_axis = 0.0f;
1736 else
1737 st->conv_axis = rv;
1738 }
1739
1740 for( int i=0; i<len; i++ ){
1741 rb_constr_swingtwist *st = &buf[ i ];
1742
1743 if( !st->tangent_violation ){
1744 st->conv_tangent = 0.0f;
1745 continue;
1746 }
1747
1748 f32 rv = v3_dot( st->tangent_axis, st->rbb->w ) -
1749 v3_dot( st->tangent_axis, st->rba->w );
1750
1751 if( rv > 0.0f )
1752 st->conv_tangent = 0.0f;
1753 else
1754 st->conv_tangent = rv;
1755 }
1756 }
1757
1758 static void rb_solve_constr_angle( rigidbody *rba, rigidbody *rbb,
1759 v3f ra, v3f rb ){
1760 m3x3f ssra, ssrb, ssrat, ssrbt;
1761 m3x3f cma, cmb;
1762
1763 m3x3_skew_symetric( ssrat, ra );
1764 m3x3_skew_symetric( ssrbt, rb );
1765 m3x3_transpose( ssrat, ssra );
1766 m3x3_transpose( ssrbt, ssrb );
1767
1768 m3x3_mul( ssra, rba->iIw, cma );
1769 m3x3_mul( cma, ssrat, cma );
1770 m3x3_mul( ssrb, rbb->iIw, cmb );
1771 m3x3_mul( cmb, ssrbt, cmb );
1772
1773 m3x3f A, invA;
1774 m3x3_add( cma, cmb, A );
1775 m3x3_inv( A, invA );
1776
1777 v3f b_wa, b_wb, b;
1778 m3x3_mulv( ssra, rba->w, b_wa );
1779 m3x3_mulv( ssrb, rbb->w, b_wb );
1780 v3_add( b_wa, b_wb, b );
1781 v3_negate( b, b );
1782
1783 v3f impulse;
1784 m3x3_mulv( invA, b, impulse );
1785
1786 v3f delta_wa, delta_wb;
1787 m3x3f iwa, iwb;
1788 m3x3_mul( rba->iIw, ssrat, iwa );
1789 m3x3_mul( rbb->iIw, ssrbt, iwb );
1790 m3x3_mulv( iwa, impulse, delta_wa );
1791 m3x3_mulv( iwb, impulse, delta_wb );
1792 v3_add( rba->w, delta_wa, rba->w );
1793 v3_sub( rbb->w, delta_wb, rbb->w );
1794 }
1795
1796 /*
1797 * Correct position constraint drift errors
1798 * [ 0.0 <= amt <= 1.0 ]: the correction amount
1799 */
1800 static void rb_correct_position_constraints( rb_constr_pos *buf, int len,
1801 float amt ){
1802 for( int i=0; i<len; i++ ){
1803 rb_constr_pos *constr = &buf[i];
1804 rigidbody *rba = constr->rba, *rbb = constr->rbb;
1805
1806 v3f p0, p1, d;
1807 m3x3_mulv( rba->to_world, constr->lca, p0 );
1808 m3x3_mulv( rbb->to_world, constr->lcb, p1 );
1809 v3_add( rba->co, p0, p0 );
1810 v3_add( rbb->co, p1, p1 );
1811 v3_sub( p1, p0, d );
1812
1813 #if 1
1814 v3_muladds( rbb->co, d, -1.0f * amt, rbb->co );
1815 rb_update_matrices( rbb );
1816 #else
1817 f32 mt = 1.0f/(rba->inv_mass+rbb->inv_mass),
1818 a = mt * (k_phys_baumgarte/k_rb_delta);
1819
1820 v3_muladds( rba->v, d, a* rba->inv_mass, rba->v );
1821 v3_muladds( rbb->v, d, a*-rbb->inv_mass, rbb->v );
1822 #endif
1823 }
1824 }
1825
1826 static void rb_correct_swingtwist_constraints( rb_constr_swingtwist *buf,
1827 int len, float amt ){
1828 for( int i=0; i<len; i++ ){
1829 rb_constr_swingtwist *st = &buf[i];
1830
1831 if( !st->tangent_violation )
1832 continue;
1833
1834 v3f va;
1835 m3x3_mulv( st->rbb->to_world, st->coneva, va );
1836
1837 f32 angle = v3_dot( va, st->tangent_target );
1838
1839 if( fabsf(angle) < 0.9999f ){
1840 v3f axis;
1841 v3_cross( va, st->tangent_target, axis );
1842 #if 1
1843 angle = acosf(angle) * amt;
1844 v4f correction;
1845 q_axis_angle( correction, axis, angle );
1846 q_mul( correction, st->rbb->q, st->rbb->q );
1847 q_normalize( st->rbb->q );
1848 rb_update_matrices( st->rbb );
1849 #else
1850 f32 mt = 1.0f/(st->rba->inv_mass+st->rbb->inv_mass),
1851 wa = mt * acosf(angle) * (k_phys_baumgarte/k_rb_delta);
1852 //v3_muladds( st->rba->w, axis, wa*-st->rba->inv_mass, st->rba->w );
1853 v3_muladds( st->rbb->w, axis, wa* st->rbb->inv_mass, st->rbb->w );
1854 #endif
1855 }
1856 }
1857
1858 for( int i=0; i<len; i++ ){
1859 rb_constr_swingtwist *st = &buf[i];
1860
1861 if( !st->axis_violation )
1862 continue;
1863
1864 v3f vxb;
1865 m3x3_mulv( st->rbb->to_world, st->conevxb, vxb );
1866
1867 f32 angle = v3_dot( vxb, st->axis_target );
1868
1869 if( fabsf(angle) < 0.9999f ){
1870 v3f axis;
1871 v3_cross( vxb, st->axis_target, axis );
1872
1873 #if 1
1874 angle = acosf(angle) * amt;
1875 v4f correction;
1876 q_axis_angle( correction, axis, angle );
1877 q_mul( correction, st->rbb->q, st->rbb->q );
1878 q_normalize( st->rbb->q );
1879 rb_update_matrices( st->rbb );
1880 #else
1881 f32 mt = 1.0f/(st->rba->inv_mass+st->rbb->inv_mass),
1882 wa = mt * acosf(angle) * (k_phys_baumgarte/k_rb_delta);
1883 //v3_muladds( st->rba->w, axis, wa*-0.5f, st->rba->w );
1884 v3_muladds( st->rbb->w, axis, wa* st->rbb->inv_mass, st->rbb->w );
1885 #endif
1886 }
1887 }
1888 }
1889
1890 static void rb_correct_contact_constraints( rb_ct *buf, int len, float amt ){
1891 for( int i=0; i<len; i++ ){
1892 rb_ct *ct = &buf[i];
1893 rigidbody *rba = ct->rba,
1894 *rbb = ct->rbb;
1895
1896 f32 mass_total = 1.0f / (rba->inv_mass + rbb->inv_mass),
1897 d = ct->p*mass_total*amt;
1898
1899 v3_muladds( rba->co, ct->n, -d * rba->inv_mass, rba->co );
1900 v3_muladds( rbb->co, ct->n, d * rbb->inv_mass, rbb->co );
1901 }
1902 }
1903
1904
1905 /*
1906 * Effectors
1907 */
1908
1909 static void rb_effect_simple_bouyency( rigidbody *ra, v4f plane,
1910 float amt, float drag ){
1911 /* float */
1912 float depth = v3_dot( plane, ra->co ) - plane[3],
1913 lambda = vg_clampf( -depth, 0.0f, 1.0f ) * amt;
1914
1915 v3_muladds( ra->v, plane, lambda * k_rb_delta, ra->v );
1916
1917 if( depth < 0.0f )
1918 v3_muls( ra->v, 1.0f-(drag*k_rb_delta), ra->v );
1919 }
1920
1921 /* apply a spring&dampener force to match ra(worldspace) on rigidbody, to
1922 * rt(worldspace)
1923 */
1924 static void rb_effect_spring_target_vector( rigidbody *rba, v3f ra, v3f rt,
1925 float spring, float dampening,
1926 float timestep ){
1927 float d = v3_dot( rt, ra );
1928 float a = acosf( vg_clampf( d, -1.0f, 1.0f ) );
1929
1930 v3f axis;
1931 v3_cross( rt, ra, axis );
1932
1933 float Fs = -a * spring,
1934 Fd = -v3_dot( rba->w, axis ) * dampening;
1935
1936 v3_muladds( rba->w, axis, (Fs+Fd) * timestep, rba->w );
1937 }
1938
1939 #endif /* RIGIDBODY_H */