-
Notifications
You must be signed in to change notification settings - Fork 1
/
PhysWorld.cpp
882 lines (735 loc) · 24.3 KB
/
PhysWorld.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
#include "StdAfx.h"
#include "PhysWorld.h"
#include "JSConvert.h"
#include "JSVector.h"
#include "JSRotation.h"
#include "JSConstraint.h"
namespace Sarona
{
// Event used to call JavaScript code (used by setTimeout)
class JSTimeoutEvent : public TimedEventReceiver::Event
{
private:
PhysWorld * m_owner;
v8::Persistent<v8::Value> m_function;
public:
JSTimeoutEvent(PhysWorld* owner, v8::Handle<v8::Value> val)
: m_owner(owner)
{
m_function = v8::Persistent<v8::Value>::New(val);
}
~JSTimeoutEvent()
{
m_function.Dispose();
}
void operator()()
{
// Time to do our thing
m_owner->CallFunction(m_function);
}
};
PhysWorld::PhysWorld(IrrlichtDevice * dev)
: BaseWorld<PhysWorld, PhysObject>(dev)
, m_constraintCounter(0)
{
m_timer.reset(new TimedEventReceiver);
// ZCom_setUpstreamLimit(30000, 30000);
this->beginReplicationSetup(0);
this->endReplicationSetup();
this->setEventInterceptor(this);
this->registerNodeUnique(TypeRegistry::m_commId, eZCom_RoleAuthority, this);
}
PhysWorld::~PhysWorld(void)
{
// Remove ground plane
if(m_ground)
m_dynamicsWorld->removeRigidBody(get_pointer(m_ground));
m_ground.reset();
// Remove constraints
while(!m_constraints.empty())
{
delete m_constraints.begin()->second;
m_constraints.erase(m_constraints.begin());
}
m_objects.clear(); // Objects must die before the phys engine dies...
}
void PhysWorld::Bind(int port, bool local)
{
// Bind
bool result = this->ZCom_initSockets(!local, port, port);
if (!result)
{
throw std::runtime_error("Unable to create ZCom socket!");
}
}
void PhysWorld::Start()
{
m_thread = boost::thread(&PhysWorld::Loop, this);
}
void PhysWorld::Shutdown()
{
m_thread.interrupt();
}
void PhysWorld::Wait()
{
m_thread.join();
}
void PhysWorld::KillZombies()
{
// Remove objects scheduled for deletion
for(int i = 0; i < (int)m_objects.size(); i++)
{
PhysObject& obj = m_objects[i];
if(obj.isZombie())
{
m_objects.erase(m_objects.begin() + i);
i--;
}
}
}
void PhysWorld::UpdateNodes()
{
// Send node status updates
for(int i = 0; i < (int)m_objects.size(); i++)
{
PhysObject& obj = m_objects[i];
obj.sendUpdate();
}
}
void PhysWorld::CreateV8Context()
{
// Get rid of any existing contexts..
m_jscontext.Dispose();
v8::Locker locker;
v8::HandleScope handle_scope;
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
global->SetInternalFieldCount(2);
v8::Handle<v8::ObjectTemplate> scene = v8::ObjectTemplate::New();
scene->SetInternalFieldCount(1);
// Static functions
global->Set(v8::String::New("print"), v8::FunctionTemplate::New(PhysWorld::JSPrint));
global->Set(v8::String::New("setTimeout"), v8::FunctionTemplate::New(PhysWorld::JSSetTimeout));
global->Set(v8::String::New("createObject"), v8::FunctionTemplate::New(PhysWorld::JSCreateObject));
global->Set(v8::String::New("createConstraint"),v8::FunctionTemplate::New(PhysWorld::JSCreateConstraint));
// Scene Object
global->Set(v8::String::New("scene"), scene);
// Init context
m_jscontext = v8::Context::New(NULL, global);
v8::Context::Scope scope(m_jscontext);
v8::Handle<v8::External> myself = v8::External::New(this);
v8::Handle<v8::Object>::Cast(v8::Context::GetCurrent()->Global()->GetPrototype())->SetInternalField(0, myself);
v8::Handle<v8::Object> global_obj = v8::Context::GetCurrent()->Global();
JSObject::SetupClass(global_obj);
JSVector::SetupClass(global_obj);
JSRotation::SetupClass(global_obj);
Client::JSHandle::SetupClass(global_obj);
JSConstraint::SetupClass(global_obj);
}
void PhysWorld::CreateBulletContext()
{
m_broadphase.reset(new btDbvtBroadphase());
m_collisionConfiguration.reset(new btDefaultCollisionConfiguration());
m_dispatcher.reset(new btCollisionDispatcher(get_pointer(m_collisionConfiguration)));
m_solver.reset(new btSequentialImpulseConstraintSolver);
m_dynamicsWorld.reset(new btDiscreteDynamicsWorld(
get_pointer(m_dispatcher),
get_pointer(m_broadphase),
get_pointer(m_solver),
get_pointer(m_collisionConfiguration)
));
m_dynamicsWorld->setGravity(btVector3(0,0,-9.80665f));
}
// Constraint management
PhysWorld::ConstraintID PhysWorld::AddConstraint(btTypedConstraint* constraint)
{
m_constraints[++m_constraintCounter] = constraint;
m_dynamicsWorld->addConstraint(constraint);
return m_constraintCounter;
}
btTypedConstraint* PhysWorld::GetConstraint(ConstraintID id)
{
std::map<ConstraintID, btTypedConstraint*>::iterator iter = m_constraints.find(id);
if(iter == m_constraints.end())
return NULL;
return iter->second;
}
void PhysWorld::DropConstraint(ConstraintID id)
{
std::map<ConstraintID, btTypedConstraint*>::iterator iter = m_constraints.find(id);
if(iter == m_constraints.end())
return;
delete iter->second;
m_constraints.erase(iter);
}
Client* PhysWorld::GetClientById(const ZCom_ConnID& id)
{
ptr_vector<Client>::iterator iter = m_clients.begin();
while(iter != m_clients.end())
{
if(iter->m_connection_id == id)
return &*iter;
iter++;
}
return NULL;
}
void PhysWorld::AnnounceGameStart()
{
m_gamerunning = true;
// Send gamerunning event to all players
ZCom_BitStream stream;
Protocol::GameStartNotify notify;
notify.write(stream);
ptr_vector<Client>::iterator iter = m_clients.begin();
while(iter != m_clients.end())
{
this->sendEventDirect(eZCom_ReliableOrdered, stream.Duplicate(), iter->m_connection_id);
iter++;
}
}
void PhysWorld::RunSceneJS()
{
v8::Locker locker;
v8::HandleScope handle_scope;
v8::Context::Scope scope(m_jscontext);
// Create scene.players object now that we know how many players there are
v8::Handle<v8::Value> scenevariant = v8::Context::GetCurrent()->Global()->Get(v8::String::New("scene"));
if(!scenevariant->IsObject())
return; // shouldn't happen unless someone did something nasty in the code
v8::Handle<v8::Object> obj = scenevariant->ToObject();
v8::Handle<v8::Array> players = v8::Array::New();
for( unsigned i = 0 ; i < m_clients.size(); i++)
{
// Instantiate new instance of Client::JSHandle via JS:
typedef v8::juice::cw::ClassWrap<Client::JSHandle> CW;
v8::Handle<v8::Object> jobj = CW::Instance().NewInstance(0, NULL);
// Get ref to the native type & implant the weak ref to PhysWorld-owned Client class
Client::JSHandle *handle = CW::ToNative::Value(jobj);
handle->initialize(&m_clients[i]);
players->Set(i, jobj);
}
obj->Set(v8::String::New("players"), players);
// Call 'level_start' defined in script
v8::Handle<v8::Value> result = CallFunction(v8::String::New("level_start();"));
if(result.IsEmpty())
{
// Call failed...
std::cout << "Call failed!" << std::endl;
}
}
void PhysWorld::Loop()
{
boost::this_thread::disable_interruption disable;
// Wait until enough players have joined...
while(true)
{
if(boost::this_thread::interruption_requested())
return;
// Step network code
this->ZCom_processInput();
this->ZCom_processOutput();
boost::this_thread::sleep(boost::posix_time::milliseconds(50));
if(!m_gamerunning && m_clients.size() > 0)
{
// Wait for enough confirmations to start the game
unsigned confirmations = 0;
ptr_vector<Client>::iterator iter = m_clients.begin();
while(iter != m_clients.end())
{
if(iter->m_level_confirmed)
confirmations++;
iter++;
}
if(confirmations == m_clients.size())
{
// We're ready to go! Game begin!
AnnounceGameStart();
// Process events for 1 second and start self.
boost::posix_time::ptime begin = boost::posix_time::microsec_clock::local_time();
while(true)
{
this->ZCom_processInput();
this->ZCom_processOutput();
boost::this_thread::sleep(boost::posix_time::milliseconds(50));
boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration timewaited = boost::posix_time::time_period(begin, now).length();
if(timewaited > boost::posix_time::seconds(1))
break;
}
break;
}
}
}
std::cout << "Game starting!" << std::endl;
this->ZCom_processInput();
this->ZCom_processOutput();
// Start physics
CreateBulletContext();
this->ZCom_processInput();
this->ZCom_processOutput();
// Load level, initialize components
CreateV8Context();
this->ZCom_processInput();
this->ZCom_processOutput();
// Execute scripts
LoadLevel(true); // also load scripts
this->ZCom_processInput();
this->ZCom_processOutput();
// Create Player objects in Javascript and run level_start()
RunSceneJS();
this->ZCom_processInput();
this->ZCom_processOutput();
//CreateCube(btVector3(0,0,10), 5)->setMass(1);
//CreateCube(btVector3(-4.5,-4.5,16), 5)->setMass(100);
// CreatePlane(btVector3(0,0,0), btVector3(0,0,1));
// Create ground
btCollisionShape* shape = new btStaticPlaneShape(btVector3(0,0,1), 0);
btRigidBody::btRigidBodyConstructionInfo CI(0,NULL,shape,btVector3(0,0,0));
m_ground.reset(new btRigidBody(CI));
m_dynamicsWorld->addRigidBody(get_pointer(m_ground));
unsigned long long frame = 0;
unsigned long long framecounter = 0;
// Set our delta time and time stamp
const int targetFPS = 50;
double frametime = 0;
double totalframetime = 1.0/targetFPS;
SimpleTimer timer;
while(true)
{
if(boost::this_thread::interruption_requested())
break;
// Simulate physics
// m_dynamicsWorld->stepSimulation(btScalar(1.0/targetFPS), 5);
m_dynamicsWorld->stepSimulation(totalframetime, 20);
// Remove dead objects from simulation
KillZombies();
// Send node status updates (mesh, texture, scale, etc. slow-changing params)
UpdateNodes();
// Step network code
this->ZCom_processInput();
this->ZCom_processOutput();
//this->ZCom_processReplicators(zU32(1000.0/targetFPS));
// Advance the timer, calling timed callbacks
m_timer->TimeStep(totalframetime);
framecounter++;
frame++;
double elapsed = timer.elapsed();
if(elapsed >= 1.0)
{
timer.restart();
double lastsleep = 1.0/targetFPS-frametime;
frametime = elapsed / framecounter;
totalframetime = frametime;
frametime -= lastsleep;
std::cout << m_objects.size() << " objects. Server FPS: " << framecounter << " frametime " << frametime << ", " << totalframetime << std::endl;
framecounter = 0;
}
// Limit fps by sleeping?
double tosleep = 1.0/targetFPS-frametime;
if(tosleep > 0)
{
boost::this_thread::sleep(boost::posix_time::microseconds(1000000.0*tosleep));
}
else
{
//std::cout << "Time dilatation..." << std::endl;
}
}
}
PhysObject* PhysWorld::CreateObject(const btVector3& position, const btQuaternion& rotation)
{
// Creates bare object in the dynamics simulation context
PhysObject* obj = new PhysObject(this, get_pointer(m_dynamicsWorld), btTransform(rotation, position));
m_objects.push_back(obj);
return obj;
}
v8::Handle<v8::Value> PhysWorld::CreateObject(const v8::Arguments& arg)
{
using namespace extractor;
if(arg.Length() != 1 || !arg[0]->IsObject())
return v8::ThrowException(v8::String::New("Invalid arguments"));
v8::Handle<v8::Object> obj = arg[0]->ToObject();
// Creates object in JS context
std::string mesh;
std::string body;
std::string texture;
double mass(0);
btVector3 bodyScale(1,1,1), meshScale(1,1,1);
btVector3 position(0,0,0);
btQuaternion rotation(btVector3(0,1,0), 0.0);
std::map<std::string, v8::Handle<v8::Value> > params;
try
{
emap(obj)
("body", body, 0) // default body = cube
("mesh", mesh, 0) // default mesh = cube
("position", position, REQUIRED)
("rotation", rotation, 0)
("texture", texture, 0)
("mass", mass, 0)
("bodyScale", bodyScale, 0)
("meshScale", meshScale, 0);
// in case the user provided a scalar instead of vector in bodyScale or meshScale, convert them here
double scalar_meshScale;
double scalar_bodyScale;
if(emap(obj)("meshScale",scalar_meshScale)){
meshScale = btVector3(scalar_meshScale,scalar_meshScale,scalar_meshScale);
}
if(emap(obj)("bodyScale",scalar_bodyScale)){
bodyScale = btVector3(scalar_bodyScale,scalar_bodyScale,scalar_bodyScale);
}
}
catch(...)
{
return v8::ThrowException(v8::String::New("'position' not specified in createObject"));
}
// std::cout << "tex " << texture << " mesh " << mesh << std::endl;
// Success! Create the object
v8::Local<v8::External> external = v8::Local<v8::External>::Cast(
v8::Handle<v8::Object>::Cast(v8::Context::GetCurrent()->Global()->GetPrototype())
->GetInternalField(0));
PhysWorld* world = static_cast<PhysWorld*>(external->Value());
PhysObject * object = world->CreateObject(position, rotation);
typedef v8::juice::cw::ClassWrap<JSObject> CW;
v8::Handle<v8::Object> jobj = CW::Instance().NewInstance(0, NULL);
// Get ref to the native type & implant the weak ref to PhysWorld-owned Client class
JSObject *handle = CW::ToNative::Value(jobj);
handle -> initialize(object->getNetworkId());
object -> setBody(body);
object -> setMesh(mesh);
object -> setMass(mass);
object -> setTexture(texture);
object -> setMeshScale(meshScale);
object -> setBodyScale(bodyScale);
return jobj;
}
v8::Handle<v8::Value> PhysWorld::CreateConstraint(const v8::Arguments& arg)
{
using namespace extractor;
if(arg.Length() != 1 || !arg[0]->IsObject())
return v8::ThrowException(v8::String::New("Invalid arguments"));
try
{
v8::Handle<v8::Object> obj = arg[0]->ToObject();
std::string type;
try
{
emap(obj)("type", type, REQUIRED);
}
catch(...)
{
return v8::ThrowException(v8::String::New("Constraint type not specified in createConstraint"));
}
if(type == "hinge")
{
vector<v8::Handle<v8::Value> > objects;
btVector3 position;
btVector3 axis;
emap(obj)
("objects", objects, REQUIRED)
("position", position, REQUIRED)
("axis", axis, REQUIRED);
if(objects.size() != 2 || !objects[0]->IsObject() || !objects[1]->IsObject())
{
return v8::ThrowException(v8::String::New("Two objects must be passed to createConstraint"));
}
JSObject* obj1 = v8::juice::cw::ClassWrap<JSObject>::ToNative::Value(objects[0]->ToObject());
JSObject* obj2 = v8::juice::cw::ClassWrap<JSObject>::ToNative::Value(objects[1]->ToObject());
if(!obj1 || !obj2)
return v8::ThrowException(v8::String::New("Invalid object handle"));
PhysObject * obj1phys = obj1->getObject();
PhysObject * obj2phys = obj2->getObject();
if(!obj1phys || !obj2phys || !obj1phys->m_rigidbody || !obj2phys->m_rigidbody)
return v8::ThrowException(v8::String::New("Invalid object handle"));
const btTransform& obj1pos = obj1phys->m_rigidbody->getWorldTransform();
const btTransform& obj2pos = obj2phys->m_rigidbody->getWorldTransform();
btVector3 rot1 = axis.rotate(obj1pos.getRotation().getAxis(), -obj1pos.getRotation().getAngle());
btVector3 rot2 = axis.rotate(obj2pos.getRotation().getAxis(), -obj2pos.getRotation().getAngle());
btHingeConstraint * c = new btHingeConstraint(
*get_pointer(obj1phys->m_rigidbody),
*get_pointer(obj2phys->m_rigidbody),
position-obj1pos.getOrigin(),
position-obj2pos.getOrigin(),
rot1,
rot2
);
typedef v8::juice::cw::ClassWrap<JSConstraint> CW;
v8::Handle<v8::Object> jobj = CW::Instance().NewInstance(0, NULL);
JSConstraint *handle = CW::ToNative::Value(jobj);
handle -> m_constraint = AddConstraint(c);
return jobj;
}
else
{
return v8::ThrowException(v8::String::New("Unknown constraint type passed to createConstraint"));
}
}
catch(...)
{
return v8::ThrowException(v8::String::New("Invalid or missing argument"));
}
return v8::Undefined();
}
v8::Handle<v8::Value> PhysWorld::SetTimeout(const v8::Arguments& args)
{
// First param: timeout in milliseconds
// Second param: function to be called
if(args.Length() != 2)return v8::Undefined();
double milliseconds = v8::juice::convert::CastFromJS<double>(args[0]);
v8::Handle<v8::Value> function = args[1];
shared_ptr<JSTimeoutEvent> e = make_shared<JSTimeoutEvent>(this, function);
m_timer->Schedule(milliseconds / 1000.0, e);
return v8::Undefined();
}
btCollisionShape* PhysWorld::getShape(const string& shape, btVector3 scale, bool isStatic)
{
// check for primitives
if(shape == "cube")
{
return new btBoxShape(scale/2);
}
if(shape == "cylinder")
{
return new btCylinderShapeZ(scale/2);
}
// is the shape cached?
string cachename = shape;
cachename += isStatic ? "s" : "d";
if(m_shapecache.find(cachename) != m_shapecache.end())
{
ShapeData & data = m_shapecache[cachename];
if(isStatic)
{
// A weak ref
// create a facade for the scaled object
// The cast is safe as all static objects are created as btBvhTriangleMeshShapes
ShapeData & scaled_model = m_shapecache[cachename+"f"];
scaled_model.shape = new btScaledBvhTriangleMeshShape(reinterpret_cast<btBvhTriangleMeshShape*>(data.shape), scale);
return scaled_model.shape;
}
return data.shape;
}
// load body from file using irrlicht
scene::IAnimatedMesh * irrmesh = NULL;
if(!(irrmesh = m_device->getSceneManager()->getMesh(shape.c_str())))
{
// loading failed.. return a basic cube
return getShape("cube", scale, isStatic);
}
// Create index
ShapeData & data = m_shapecache[cachename];
data.mesh_interface = new btTriangleMesh();
// Deal some rotation to the mesh since our coordinate system has Z axis up
/*core::matrix4 rotmatrix;
rotmatrix.setRotationDegrees(core::vector3df(90,0,0));
for(unsigned i = 0; i < irrmesh->getMeshBufferCount(); i++)
{
irr::scene::IMeshBuffer * meshbuffer = irrmesh->getMeshBuffer(i);
m_device->getSceneManager()->getMeshManipulator()->transform(meshbuffer, rotmatrix);
}*/
const btScalar static_scale = 1.0;
for(unsigned i = 0; i < irrmesh->getMeshBufferCount(); i++)
{
irr::scene::IMeshBuffer * meshbuffer = irrmesh->getMeshBuffer(i);
if(meshbuffer->getVertexType() == video::EVT_STANDARD)
{
irr::video::S3DVertex * vertices = reinterpret_cast<video::S3DVertex*>(meshbuffer->getVertices());
u16* indices = meshbuffer->getIndices();
int vertexcount = meshbuffer->getVertexCount();
for(unsigned a = 0 ; a < meshbuffer->getIndexCount(); a += 3)
{
btVector3 triangle[3];
for (int k=0;k<3;k++)
{
//three verts per triangle
int index = indices[a+k];
if (index > vertexcount) continue;
//convert to btVector3
core::vector3df& pos = vertices[index].Pos;
triangle[k] = btVector3(pos.X, pos.Y, pos.Z) * static_scale;
}
data.mesh_interface->addTriangle(triangle[0], triangle[1], triangle[2]);
}
}
else if(meshbuffer->getVertexType() == irr::video::EVT_2TCOORDS)
{
// Same but for S3DVertex2TCoords data
irr::video::S3DVertex * vertices = reinterpret_cast<video::S3DVertex*>(meshbuffer->getVertices());
u16* indices = meshbuffer->getIndices();
int vertexcount = meshbuffer->getVertexCount();
for(unsigned a = 0 ; a < meshbuffer -> getIndexCount(); a += 3)
{
btVector3 triangle[3];
for (int k=0;k<3;k++)
{
s32 index = indices[a+k];
if (index > vertexcount) continue;
core::vector3df pos = vertices[index].Pos * static_scale;
triangle[k] = btVector3(pos.X, pos.Y, pos.Z);
}
data.mesh_interface->addTriangle(triangle[0], triangle[1], triangle[2]);
}
}
}
if(isStatic)
{
// Static shapes can be concave
// Here we store a reference to the actual mesh in the cache and return a lightweight scaled facade
data.shape = new btBvhTriangleMeshShape(data.mesh_interface, true, true);
// ensure the facade is cached too
ShapeData & scaled_model = m_shapecache[cachename+"f"];
scaled_model.shape = new btScaledBvhTriangleMeshShape(reinterpret_cast<btBvhTriangleMeshShape*>(data.shape), scale);
return scaled_model.shape;
}
else
{
// At the moment dynamic shapes must be convex
// that is until we implement convex decomposition here
// TODO: convex decomposition..
data.shape = new btConvexTriangleMeshShape(data.mesh_interface);
}
return data.shape;
}
bool PhysWorld::ZCom_cbConnectionRequest(ZCom_ConnID _id, ZCom_BitStream &_request, ZCom_BitStream &_reply)
{
// Allow incoming connection when game is not running (we're in lobby)
return !m_gamerunning;
}
void PhysWorld::ZCom_cbConnectionSpawned( ZCom_ConnID _id )
{
ZCom_requestDownstreamLimit(_id, (zU16)50, (zU16)65535);
//ZCom_simulateLoss(_id, 0.5);
}
void PhysWorld::ZCom_cbConnectionClosed( ZCom_ConnID _id, eZCom_CloseReason _reason, ZCom_BitStream &_reasondata )
{
// Mark client disconnected
Client *c = GetClientById(_id);
if(c)
{
c->m_disconnected = true;
}
}
void PhysWorld::ZCom_cbConnectResult( ZCom_ConnID _id, eZCom_ConnectResult _result, ZCom_BitStream &_reply )
{
}
void PhysWorld::ZCom_cbDataReceived( ZCom_ConnID _id, ZCom_BitStream &_data )
{
}
bool PhysWorld::ZCom_cbZoidRequest( ZCom_ConnID _id, zU8 _requested_level, ZCom_BitStream &_reason )
{
if (_requested_level == 1)
{
// Add new client
Client * c = new Client(this);
c->m_connection_id = _id;
c->m_disconnected = false ; // They're active
m_clients.push_back(c);
return true;
}
else
return false;
}
void PhysWorld::ZCom_cbZoidResult( ZCom_ConnID _id, eZCom_ZoidResult _result, zU8 _new_level, ZCom_BitStream &_reason )
{
// Send LevelSelect to new clients
ZCom_BitStream* stream = new ZCom_BitStream;
Protocol::LevelSelect select;
select.name = m_levelname;
select.write(*stream);
this->sendEventDirect(eZCom_ReliableOrdered, stream, _id);
}
void PhysWorld::ZCom_cbNodeRequest_Dynamic( ZCom_ConnID _id, ZCom_ClassID _requested_class, ZCom_BitStream *_announcedata,
eZCom_NodeRole _role, ZCom_NodeID _net_id )
{
}
void PhysWorld::ZCom_cbNodeRequest_Tag( ZCom_ConnID _id, ZCom_ClassID _requested_class, ZCom_BitStream *_announcedata,
eZCom_NodeRole _role, zU32 _tag )
{
}
bool PhysWorld::ZCom_cbDiscoverRequest( const ZCom_Address &_addr, ZCom_BitStream &_request,
ZCom_BitStream &_reply )
{
return false;
}
void PhysWorld::ZCom_cbDiscovered( const ZCom_Address & _addr, ZCom_BitStream &_reply )
{
}
// Node events
bool PhysWorld::recUserEvent(ZCom_Node *_node, ZCom_ConnID _from,
eZCom_NodeRole _remoterole, ZCom_BitStream &_data,
zU32 _estimated_time_sent)
{
// Check event type:
unsigned int Id = _data.getInt(16);
if(Id == Protocol::KeyPressEvent::Id)
{
Protocol::KeyPressEvent event;
event.read(_data);
Client * c = GetClientById(_from);
if(c)
{
// Calling an event requires a scope :p
if(m_jscontext.IsEmpty())
return false;
v8::Locker locker;
v8::HandleScope handle_scope;
v8::Context::Scope scope(m_jscontext);
c->CallEvent(event.press?"keydown":"keyup", keycode2string(event.keycode));
}
// std::cout << "KeyPress: " << event.press << " " << event.keycode << std::endl;
}
else if(Id == Protocol::LevelConfirm::Id)
{
Protocol::LevelConfirm confirm;
confirm.read(_data);
// Level was confirmed available by client!
// Mark them ready.
Client* c = GetClientById(_from);
if(c)
{
c->m_level_confirmed = true;
}
}
else
{
std::cerr << "FATAL: Unhandled world message with id: " << Id << std::endl;
}
return false;
}
bool PhysWorld::recInit(ZCom_Node *_node, ZCom_ConnID _from,
eZCom_NodeRole _remoterole)
{
return false;
}
bool PhysWorld::recSyncRequest(ZCom_Node *_node, ZCom_ConnID _from,
eZCom_NodeRole _remoterole)
{
return false;
}
bool PhysWorld::recRemoved(ZCom_Node *_node, ZCom_ConnID _from,
eZCom_NodeRole _remoterole)
{
return false;
}
bool PhysWorld::recFileIncoming(ZCom_Node *_node, ZCom_ConnID _from,
eZCom_NodeRole _remoterole, ZCom_FileTransID _fid,
ZCom_BitStream &_request)
{
return false;
}
bool PhysWorld::recFileData(ZCom_Node *_node, ZCom_ConnID _from,
eZCom_NodeRole _remoterole, ZCom_FileTransID _fid)
{
return false;
}
bool PhysWorld::recFileAborted(ZCom_Node *_node, ZCom_ConnID _from,
eZCom_NodeRole _remoterole, ZCom_FileTransID _fid)
{
return false;
}
bool PhysWorld::recFileComplete(ZCom_Node *_node, ZCom_ConnID _from,
eZCom_NodeRole _remoterole, ZCom_FileTransID _fid)
{
return false;
}
// Client object member functions:
}