UserRayHitCollectorDemo::UserRayHitCollectorDemo(hkDemoEnvironment* env) : hkDefaultPhysicsDemo(env), m_time(0.0f) { // // Setup the camera. // { hkVector4 from(-8.0f, 25.0f, 20.0f); hkVector4 to (0.0f, 0.0f, 0.0f); hkVector4 up (0.0f, 1.0f, 0.0f); setupDefaultCameras(env, from, to, up); } // // Create the world. // { hkpWorldCinfo info; info.setBroadPhaseWorldSize( 100.0f ); m_world = new hkpWorld(info); m_world->lock(); setupGraphics(); } // // Create a row of colored rigid bodies // { hkVector4 halfExtents(.5f, .5f, .5f ); hkpShape* shape = new hkpBoxShape( halfExtents , 0 ); int colors[4] = { hkColor::RED, hkColor::GREEN, hkColor::BLUE, hkColor::YELLOW }; for (int i = 0; i < 4; i++ ) { hkpRigidBodyCinfo ci; ci.m_motionType = hkpMotion::MOTION_FIXED; ci.m_shape = shape; ci.m_collisionFilterInfo = hkpGroupFilter::calcFilterInfo(i+1); ci.m_position.set( i * 3.0f, 0.f, 0.0f); hkpRigidBody* body = new hkpRigidBody( ci ); body->addProperty( COLOR_PROPERTY_ID, colors[i] ); m_world->addEntity(body); body->removeReference(); // show the objects in nice transparent colors colors[i] &= ~hkColor::rgbFromChars( 0, 0, 0 ); colors[i] |= hkColor::rgbFromChars( 0, 0, 0, 120 ); HK_SET_OBJECT_COLOR((hkUlong)body->getCollidable(), colors[i]); } shape->removeReference(); } m_world->unlock(); }
//---------------------------------------------------------------------------------------------------------------------- // This virtual function is called once before the first call to paintGL() or resizeGL(), //and then once whenever the widget has been assigned a new QGLContext. // This function should set up any required OpenGL context rendering flags, defining VBOs etc. //---------------------------------------------------------------------------------------------------------------------- void GLWindow::initializeGL() { // enable depth testing for drawing glEnable(GL_DEPTH_TEST); // we need to initialise the NGL lib, under windows and linux we also need to // initialise GLEW, under windows this needs to be done in the app as well // as the lib hence the WIN32 define ngl::NGLInit *Init = ngl::NGLInit::instance(); #ifdef WIN32 glewInit(); // need a local glew init as well as lib one for windows #endif Init->initGlew(); //---------------------------------------------------------------------------------------------------------------------- //Initialize the deferred renderer g_renderer->initScene(); //---------------------------------------------------------------------------------------------------------------------- // now to load the shader and set the values // grab an instance of shader manager ngl::ShaderLib *shader=ngl::ShaderLib::instance(); // we are creating a shader called Phong shader->createShaderProgram("Phong"); // now we are going to create empty shaders for Frag and Vert shader->attachShader("PhongVertex",ngl::VERTEX); shader->attachShader("PhongFragment",ngl::FRAGMENT); // attach the source shader->loadShaderSource("PhongVertex","shaders/Phong.vs"); shader->loadShaderSource("PhongFragment","shaders/Phong.fs"); // compile the shaders shader->compileShader("PhongVertex"); shader->compileShader("PhongFragment"); // add them to the program shader->attachShaderToProgram("Phong","PhongVertex"); shader->attachShaderToProgram("Phong","PhongFragment"); // now we have associated this data we can link the shader shader->linkProgramObject("Phong"); // and make it active ready to load values (*shader)["Phong"]->use(); //shader->setShaderParam1i("Normalize",1); // Now we will create a basic Camera from the graphics library // This is a static camera so it only needs to be set once // First create Values for the camera position ngl::Vec3 from(0,2,6); ngl::Vec3 to(0,0,0); ngl::Vec3 up(0,1,0); // now load to our new camera m_cam= new ngl::Camera(from,to,up,ngl::PERSPECTIVE); // set the shape using FOV 45 Aspect Ratio based on Width and Height // The final two are near and far clipping planes of 0.5 and 10 m_cam->setShape(45,(float)16.0/9.0,0.0001,350,ngl::PERSPECTIVE); shader->setShaderParam3f("viewerPos",m_cam->getEye().m_x,m_cam->getEye().m_y,m_cam->getEye().m_z); ngl::Material m(ngl::GOLD); // load our material values to the shader into the structure material (see Vertex shader) m.loadToShader("material"); //---------------------------------------------------------------------------------------------------------------------- // Saving our camera location in order to do all the light calculations g_renderer->setCameraLocation(m_cam); //---------------------------------------------------------------------------------------------------------------------- // SSAO shader for generation g_renderer->loadDeferredShader(0, LIGHT, "SSAOShader", "shaders/SSAOVertex.glsl", "shaders/SSAOFragment.glsl"); //---------------------------------------------------------------------------------------------------------------------- // Load the geometry + light information from the config file g_renderer->loadFromInitFile(); //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- // Sampler for SSAO Is always loaded. ngl::Texture t("SSAO/sample.jpg"); t.setMultiTexture(10); t.setTextureGL(); glGenerateMipmapEXT(GL_TEXTURE_2D); //---------------------------------------------------------------------------------------------------------------------- }
PhantomEventsDemo::PhantomEventsDemo( hkDemoEnvironment* env ) : hkDefaultPhysicsDemo(env, DEMO_FLAGS_NO_SERIALIZE) { // // Setup the camera // { hkVector4 from(13.0f, 10.0f, 13.0f); hkVector4 to (0.0f, 0.0f, 0.0f); hkVector4 up (0.0f, 1.0f, 0.0f); setupDefaultCameras( env, from, to, up ); } // // Create the world // { hkpWorldCinfo info; info.setupSolverInfo(hkpWorldCinfo::SOLVER_TYPE_4ITERS_MEDIUM); info.setBroadPhaseWorldSize( 100.0f ); info.m_enableDeactivation = false; m_world = new hkpWorld( info ); m_world->lock(); setupGraphics(); } // // Register the collision agents // { hkpAgentRegisterUtil::registerAllAgents( m_world->getCollisionDispatcher() ); } // In this demo we have three different objects; the wall, the sphere and a phantom volume. Both the wall, which is simply a box, // and the sphere are created in the usual manner using a hkpRigidBodyCinfo 'blueprint' and are added to the world. // // Create the wall box // { hkpRigidBodyCinfo info; hkVector4 fixedBoxSize( 0.5f, 5.0f , 5.0f ); hkpBoxShape* fixedBoxShape = new hkpBoxShape( fixedBoxSize , 0 ); info.m_shape = fixedBoxShape; info.m_motionType = hkpMotion::MOTION_FIXED; info.m_position.set(-2.0f, 0.0f ,0.0f); // Add some bounce. info.m_restitution = 0.9f; // Create fixed box hkpRigidBody* floor = new hkpRigidBody(info); m_world->addEntity(floor); floor->removeReference(); fixedBoxShape->removeReference(); } // // Create a moving sphere // { hkReal radius = 0.5f; hkpConvexShape* sphereShape = new hkpSphereShape(radius); // To illustrate using the shape, create a rigid body. hkpRigidBodyCinfo sphereInfo; sphereInfo.m_shape = sphereShape; sphereInfo.m_position.set(2.0f, 0.0f, 0.0f); sphereInfo.m_restitution = 0.9f; sphereInfo.m_motionType = hkpMotion::MOTION_SPHERE_INERTIA; // If we need to compute mass properties, we'll do this using the hkpInertiaTensorComputer. if (sphereInfo.m_motionType != hkpMotion::MOTION_FIXED) { sphereInfo.m_mass = 10.0f; hkpMassProperties massProperties; hkpInertiaTensorComputer::computeSphereVolumeMassProperties(radius, sphereInfo.m_mass, massProperties); sphereInfo.m_inertiaTensor = massProperties.m_inertiaTensor; sphereInfo.m_centerOfMass = massProperties.m_centerOfMass; sphereInfo.m_mass = massProperties.m_mass; } // Create a rigid body (using the template above) hkpRigidBody* sphereRigidBody = new hkpRigidBody(sphereInfo); // Remove reference since the body now "owns" the Shape sphereShape->removeReference(); // Finally add body so we can see it, and remove reference since the world now "owns" it. m_world->addEntity(sphereRigidBody); sphereRigidBody->removeReference(); } // Given below is the construction code for the phantom volume: // // Create a PHANTOM floor // { hkpRigidBodyCinfo boxInfo; hkVector4 boxSize( 4.0f, 1.5f , 2.0f ); hkpShape* boxShape = new hkpBoxShape( boxSize , 0 ); boxInfo.m_motionType = hkpMotion::MOTION_FIXED; boxInfo.m_position.set(2.0f, -4.0f, 0.0f); MyPhantomShape* myPhantomShape = new MyPhantomShape(); hkpBvShape* bvShape = new hkpBvShape( boxShape, myPhantomShape ); boxShape->removeReference(); myPhantomShape->removeReference(); boxInfo.m_shape = bvShape; hkpRigidBody* boxRigidBody = new hkpRigidBody( boxInfo ); bvShape->removeReference(); m_world->addEntity( boxRigidBody ); // the color can only be changed after the entity has been added to the world HK_SET_OBJECT_COLOR((hkUlong)boxRigidBody->getCollidable(), hkColor::rgbFromChars(255, 255, 255, 50)); boxRigidBody->removeReference(); } // The phantom volume is created using a hkpBvShape using a hkpBoxShape as the bounding volume and a // hkpPhantomCallbackShape as the child shape. The volume is set to be fixed in space and coloured with a slight alpha blend. // // Once the simulation starts the ball drops into the phantom volume, upon notification of this event we colour the ball // RED and wait for an exit event. As soon as this event is raised we colour the ball GREEN and apply an impulse upwards // back towards the wall and the simulation repeats. m_world->unlock(); }
RuntimeBindingDemo::RuntimeBindingDemo( hkDemoEnvironment* env ) : hkDefaultAnimationDemo(env) { // // Setup the camera // { hkVector4 from( 0, -2.5f, 0.0f ); hkVector4 to ( 0,0,0 ); hkVector4 up ( 0,0,1 ); setupDefaultCameras( env, from, to, up ); } m_loader = new hkLoader(); // Get the rig { hkString assetFile = hkAssetManagementUtil::getFilePath("Resources/Animation/HavokGirl/hkRig.hkx"); hkRootLevelContainer* container = m_loader->load( assetFile.cString() ); HK_ASSERT2(0x27343437, container != HK_NULL , "Could not load asset"); hkaAnimationContainer* ac = reinterpret_cast<hkaAnimationContainer*>( container->findObjectByType( hkaAnimationContainerClass.getName() )); HK_ASSERT2(0x27343435, ac && (ac->m_numSkeletons > 0), "No skeleton loaded"); m_skeleton = ac->m_skeletons[0]; } // Get the animation { hkString assetFile = hkAssetManagementUtil::getFilePath("Resources/Animation/HavokGirl/hkIdle.hkx"); hkRootLevelContainer* container = m_loader->load( assetFile.cString() ); HK_ASSERT2(0x27343437, container != HK_NULL , "Could not load asset"); hkaAnimationContainer* ac = reinterpret_cast<hkaAnimationContainer*>( container->findObjectByType( hkaAnimationContainerClass.getName() )); HK_ASSERT2(0x27343435, ac && (ac->m_numAnimations > 0 ), "No animation loaded"); m_animation = ac->m_animations[0]; } // Create a binding by matching names { // Inititalize the binding m_runtimeBinding = new hkaAnimationBinding(); m_runtimeBinding->m_animation = m_animation; m_runtimeBinding->m_blendHint = hkaAnimationBinding::NORMAL; m_runtimeBinding->m_numTransformTrackToBoneIndices = m_animation->m_numberOfTransformTracks; m_runtimeBinding->m_transformTrackToBoneIndices = hkAllocateChunk<hkInt16>( m_runtimeBinding->m_numTransformTrackToBoneIndices, HK_MEMORY_CLASS_DEMO ); // USe the binding utility to construct the track to bone map HK_ON_DEBUG(hkResult res =) hkaSkeletonUtils::bindByName( *m_skeleton, *m_animation, bindingCompare, *m_runtimeBinding); HK_ASSERT2( 0x65e45e32, res == HK_SUCCESS, "Runtime binding failed"); } // Create the skeleton m_skeletonInstance = new hkaAnimatedSkeleton( m_skeleton ); // If the weight on any bone drops below this then it is filled with the T-Pose m_skeletonInstance->setReferencePoseWeightThreshold(0.1f); // Create a control { m_control = new hkaDefaultAnimationControl( m_runtimeBinding ); m_control->setMasterWeight( 1.0f ); m_control->setPlaybackSpeed( 1.0f ); m_skeletonInstance->addAnimationControl( m_control ); m_control->removeReference(); } // make a world so that we can auto create a display world to hold the skin setupGraphics( ); }
void InterpreterRuntime::SignatureHandlerGenerator::pass_object() { const Address src(from(), -offset() * wordSize); #ifdef _WIN64 switch (_num_args) { case 0: assert(offset() == 0, "argument register 1 can only be (non-null) receiver"); __ leaq(rarg1, src); _num_args++; break; case 1: __ leaq(rax, src); __ xorl(rarg2, rarg2); __ cmpq(src, 0); __ cmovq(Assembler::notEqual, rarg2, rax); _num_args++; break; case 2: __ leaq(rax, src); __ xorl(rarg3, rarg3); __ cmpq(src, 0); __ cmovq(Assembler::notEqual, rarg3, rax); _num_args++; break; default: __ leaq(rax, src); __ xorl(temp(), temp()); __ cmpq(src, 0); __ cmovq(Assembler::notEqual, temp(), rax); __ movq(Address(to(), _stack_offset), temp()); _stack_offset += wordSize; break; } #else switch (_num_int_args) { case 0: assert(offset() == 0, "argument register 1 can only be (non-null) receiver"); __ leaq(rarg1, src); _num_int_args++; break; case 1: __ leaq(rax, src); __ xorl(rarg2, rarg2); __ cmpq(src, 0); __ cmovq(Assembler::notEqual, rarg2, rax); _num_int_args++; break; case 2: __ leaq(rax, src); __ xorl(rarg3, rarg3); __ cmpq(src, 0); __ cmovq(Assembler::notEqual, rarg3, rax); _num_int_args++; break; case 3: __ leaq(rax, src); __ xorl(rarg4, rarg4); __ cmpq(src, 0); __ cmovq(Assembler::notEqual, rarg4, rax); _num_int_args++; break; case 4: __ leaq(rax, src); __ xorl(rarg5, rarg5); __ cmpq(src, 0); __ cmovq(Assembler::notEqual, rarg5, rax); _num_int_args++; break; default: __ leaq(rax, src); __ xorl(temp(), temp()); __ cmpq(src, 0); __ cmovq(Assembler::notEqual, temp(), rax); __ movq(Address(to(), _stack_offset), temp()); _stack_offset += wordSize; break; } #endif }
IDBFactory* WorkerGlobalScopeIndexedDatabase::indexedDB(ScriptExecutionContext* context) { return from(context)->indexedDB(); }
void debugLine(idVec3 &color, float x, float y, float z, float x2, float y2, float z2) { idVec3 from(x, y, z); idVec3 to(x2, y2, z2); //D_DebugLine(color, from, to); }
uint8_t socket_active_status(sock_handle_t socket) { bool open = from(socket).is_open(); return open ? SOCKET_STATUS_ACTIVE : SOCKET_STATUS_INACTIVE; }
sock_result_t socket_close(sock_handle_t sock) { auto& handle = from(sock); handle.close(); return 0; }
virtual bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) { if( replSetBlind ) { if (theReplSet) { errmsg = str::stream() << theReplSet->selfFullName() << " is blind"; } return false; } MONGO_FAIL_POINT_BLOCK(rsDelayHeartbeatResponse, delay) { const BSONObj& data = delay.getData(); sleepsecs(data["delay"].numberInt()); } /* we don't call ReplSetCommand::check() here because heartbeat checks many things that are pre-initialization. */ if( !replSet ) { errmsg = "not running with --replSet"; return false; } /* we want to keep heartbeat connections open when relinquishing primary. tag them here. */ { AbstractMessagingPort *mp = cc().port(); if( mp ) mp->tag |= ScopedConn::keepOpen; } if( cmdObj["pv"].Int() != 1 ) { errmsg = "incompatible replset protocol version"; return false; } { string s = string(cmdObj.getStringField("replSetHeartbeat")); if (replSettings.ourSetName() != s) { errmsg = "repl set names do not match"; log() << "replSet set names do not match, our cmdline: " << replSettings.replSet << rsLog; log() << "replSet s: " << s << rsLog; result.append("mismatch", true); return false; } } result.append("rs", true); if( cmdObj["checkEmpty"].trueValue() ) { result.append("hasData", replHasDatabases()); } if( (theReplSet == 0) || (theReplSet->startupStatus == ReplSetImpl::LOADINGCONFIG) ) { string from( cmdObj.getStringField("from") ); if( !from.empty() ) { scoped_lock lck( replSettings.discoveredSeeds_mx ); replSettings.discoveredSeeds.insert(from); } result.append("hbmsg", "still initializing"); return true; } if( theReplSet->name() != cmdObj.getStringField("replSetHeartbeat") ) { errmsg = "repl set names do not match (2)"; result.append("mismatch", true); return false; } result.append("set", theReplSet->name()); MemberState currentState = theReplSet->state(); result.append("state", currentState.s); if (currentState == MemberState::RS_PRIMARY) { result.appendDate("electionTime", theReplSet->getElectionTime().asDate()); } result.append("e", theReplSet->iAmElectable()); result.append("hbmsg", theReplSet->hbmsg()); result.append("time", (long long) time(0)); result.appendDate("opTime", theReplSet->lastOpTimeWritten.asDate()); const Member *syncTarget = replset::BackgroundSync::get()->getSyncTarget(); if (syncTarget) { result.append("syncingTo", syncTarget->fullName()); } int v = theReplSet->config().version; result.append("v", v); if( v > cmdObj["v"].Int() ) result << "config" << theReplSet->config().asBson(); Member* from = NULL; if (cmdObj.hasField("fromId")) { if (v == cmdObj["v"].Int()) { from = theReplSet->getMutableMember(cmdObj["fromId"].Int()); } } if (!from) { from = theReplSet->findByName(cmdObj.getStringField("from")); if (!from) { return true; } } // if we thought that this node is down, let it know if (!from->hbinfo().up()) { result.append("stateDisagreement", true); } // note that we got a heartbeat from this node theReplSet->mgr->send(boost::bind(&ReplSet::msgUpdateHBRecv, theReplSet, from->hbinfo().id(), time(0))); return true; }
XYZColour::XYZColour (Colour const& sRGB) { *this = from (sRGB); }
void QXmppMessage::toXml(QXmlStreamWriter *xmlWriter) const { xmlWriter->writeStartElement("message"); helperToXmlAddAttribute(xmlWriter, "xml:lang", lang()); helperToXmlAddAttribute(xmlWriter, "id", id()); helperToXmlAddAttribute(xmlWriter, "to", to()); helperToXmlAddAttribute(xmlWriter, "from", from()); helperToXmlAddAttribute(xmlWriter, "type", message_types[d->type]); if (!d->subject.isEmpty()) helperToXmlAddTextElement(xmlWriter, "subject", d->subject); if (!d->body.isEmpty()) helperToXmlAddTextElement(xmlWriter, "body", d->body); if (!d->thread.isEmpty()) helperToXmlAddTextElement(xmlWriter, "thread", d->thread); error().toXml(xmlWriter); // chat states if (d->state > None && d->state <= Paused) { xmlWriter->writeStartElement(chat_states[d->state]); xmlWriter->writeAttribute("xmlns", ns_chat_states); xmlWriter->writeEndElement(); } // XEP-0071: XHTML-IM if (!d->xhtml.isEmpty()) { xmlWriter->writeStartElement("html"); xmlWriter->writeAttribute("xmlns", ns_xhtml_im); xmlWriter->writeStartElement("body"); xmlWriter->writeAttribute("xmlns", ns_xhtml); xmlWriter->writeCharacters(""); xmlWriter->device()->write(d->xhtml.toUtf8()); xmlWriter->writeEndElement(); xmlWriter->writeEndElement(); } // time stamp if (d->stamp.isValid()) { QDateTime utcStamp = d->stamp.toUTC(); if (d->stampType == DelayedDelivery) { // XEP-0203: Delayed Delivery xmlWriter->writeStartElement("delay"); xmlWriter->writeAttribute("xmlns", ns_delayed_delivery); helperToXmlAddAttribute(xmlWriter, "stamp", QXmppUtils::datetimeToString(utcStamp)); xmlWriter->writeEndElement(); } else { // XEP-0091: Legacy Delayed Delivery xmlWriter->writeStartElement("x"); xmlWriter->writeAttribute("xmlns", ns_legacy_delayed_delivery); helperToXmlAddAttribute(xmlWriter, "stamp", utcStamp.toString("yyyyMMddThh:mm:ss")); xmlWriter->writeEndElement(); } } // XEP-0184: Message Delivery Receipts if (!d->receiptId.isEmpty()) { xmlWriter->writeStartElement("received"); xmlWriter->writeAttribute("xmlns", ns_message_receipts); xmlWriter->writeAttribute("id", d->receiptId); xmlWriter->writeEndElement(); } if (d->receiptRequested) { xmlWriter->writeStartElement("request"); xmlWriter->writeAttribute("xmlns", ns_message_receipts); xmlWriter->writeEndElement(); } // XEP-0224: Attention if (d->attentionRequested) { xmlWriter->writeStartElement("attention"); xmlWriter->writeAttribute("xmlns", ns_attention); xmlWriter->writeEndElement(); } // XEP-0249: Direct MUC Invitations if (!d->mucInvitationJid.isEmpty()) { xmlWriter->writeStartElement("x"); xmlWriter->writeAttribute("xmlns", ns_conference); xmlWriter->writeAttribute("jid", d->mucInvitationJid); if (!d->mucInvitationPassword.isEmpty()) xmlWriter->writeAttribute("password", d->mucInvitationPassword); if (!d->mucInvitationReason.isEmpty()) xmlWriter->writeAttribute("reason", d->mucInvitationReason); xmlWriter->writeEndElement(); } // other extensions QXmppStanza::extensionsToXml(xmlWriter); xmlWriter->writeEndElement(); }
// static void OriginTrialContext::addTokens(ExecutionContext* host, const Vector<String>* tokens) { if (!tokens || tokens->isEmpty()) return; from(host)->addTokens(*tokens); }
void CSkypeProto::OnChatEvent(const JSONNode &node) { //std::string clientMsgId = node["clientmessageid"].as_string(); //std::string skypeEditedId = node["skypeeditedid"].as_string(); std::string fromLink = node["from"].as_string(); CMStringA from(ContactUrlToName(fromLink.c_str())); time_t timestamp = IsoToUnixTime(node["composetime"].as_string().c_str()); std::string content = node["content"].as_string(); int emoteOffset = node["skypeemoteoffset"].as_int(); std::string conversationLink = node["conversationLink"].as_string(); CMStringA chatname(ChatUrlToName(conversationLink.c_str())); CMString topic(node["threadtopic"].as_mstring()); if (FindChatRoom(chatname) == NULL) SendRequest(new GetChatInfoRequest(m_szRegToken, chatname, m_szServer), &CSkypeProto::OnGetChatInfo, topic.Detach()); std::string messageType = node["messagetype"].as_string(); if (!mir_strcmpi(messageType.c_str(), "Text") || !mir_strcmpi(messageType.c_str(), "RichText")) { AddMessageToChat(_A2T(chatname), _A2T(from), content.c_str(), emoteOffset != NULL, emoteOffset, timestamp); } else if (!mir_strcmpi(messageType.c_str(), "ThreadActivity/AddMember")) { ptrA xinitiator, xtarget, initiator; //content = <addmember><eventtime>1429186229164</eventtime><initiator>8:initiator</initiator><target>8:user</target></addmember> HXML xml = xmlParseString(ptrT(mir_a2t(content.c_str())), 0, _T("addmember")); if (xml == NULL) return; for (int i = 0; i < xmlGetChildCount(xml); i++) { HXML xmlNode = xmlGetNthChild(xml, L"target", i); if (xmlNode == NULL) break; xtarget = mir_t2a(xmlGetText(xmlNode)); CMStringA target = ParseUrl(xtarget, "8:"); AddChatContact(_A2T(chatname), target, target, L"User"); } xmlDestroyNode(xml); } else if (!mir_strcmpi(messageType.c_str(), "ThreadActivity/DeleteMember")) { ptrA xinitiator, xtarget; //content = <addmember><eventtime>1429186229164</eventtime><initiator>8:initiator</initiator><target>8:user</target></addmember> HXML xml = xmlParseString(ptrT(mir_a2t(content.c_str())), 0, _T("deletemember")); if (xml != NULL) { HXML xmlNode = xmlGetChildByPath(xml, _T("initiator"), 0); xinitiator = node != NULL ? mir_t2a(xmlGetText(xmlNode)) : NULL; xmlNode = xmlGetChildByPath(xml, _T("target"), 0); xtarget = xmlNode != NULL ? mir_t2a(xmlGetText(xmlNode)) : NULL; xmlDestroyNode(xml); } if (xtarget == NULL) return; CMStringA target = ParseUrl(xtarget, "8:"); CMStringA initiator = ParseUrl(xinitiator, "8:"); RemoveChatContact(_A2T(chatname), target, target, true, initiator); } else if (!mir_strcmpi(messageType.c_str(), "ThreadActivity/TopicUpdate")) { //content=<topicupdate><eventtime>1429532702130</eventtime><initiator>8:user</initiator><value>test topic</value></topicupdate> ptrA xinitiator, value; HXML xml = xmlParseString(ptrT(mir_a2t(content.c_str())), 0, _T("topicupdate")); if (xml != NULL) { HXML xmlNode = xmlGetChildByPath(xml, _T("initiator"), 0); xinitiator = xmlNode != NULL ? mir_t2a(xmlGetText(xmlNode)) : NULL; xmlNode = xmlGetChildByPath(xml, _T("value"), 0); value = xmlNode != NULL ? mir_t2a(xmlGetText(xmlNode)) : NULL; xmlDestroyNode(xml); } CMStringA initiator = ParseUrl(xinitiator, "8:"); RenameChat(chatname, value); ChangeChatTopic(chatname, value, initiator); } else if (!mir_strcmpi(messageType.c_str(), "ThreadActivity/RoleUpdate")) { //content=<roleupdate><eventtime>1429551258363</eventtime><initiator>8:user</initiator><target><id>8:user1</id><role>admin</role></target></roleupdate> ptrA xinitiator, xId, xRole; HXML xml = xmlParseString(ptrT(mir_a2t(content.c_str())), 0, _T("roleupdate")); if (xml != NULL) { HXML xmlNode = xmlGetChildByPath(xml, _T("initiator"), 0); xinitiator = xmlNode != NULL ? mir_t2a(xmlGetText(xmlNode)) : NULL; xmlNode = xmlGetChildByPath(xml, _T("target"), 0); if (xmlNode != NULL) { HXML xmlId = xmlGetChildByPath(xmlNode, _T("id"), 0); HXML xmlRole = xmlGetChildByPath(xmlNode, _T("role"), 0); xId = xmlId != NULL ? mir_t2a(xmlGetText(xmlId)) : NULL; xRole = xmlRole != NULL ? mir_t2a(xmlGetText(xmlRole)) : NULL; } xmlDestroyNode(xml); CMStringA initiator = ParseUrl(xinitiator, "8:"); CMStringA id = ParseUrl(xId, "8:"); GCDEST gcd = { m_szModuleName, _A2T(chatname), !mir_strcmpi(xRole, "Admin") ? GC_EVENT_ADDSTATUS : GC_EVENT_REMOVESTATUS }; GCEVENT gce = { sizeof(gce), &gcd }; ptrT tszId(mir_a2t(id)); ptrT tszRole(mir_a2t(xRole)); ptrT tszInitiator(mir_a2t(initiator)); gce.pDest = &gcd; gce.dwFlags = GCEF_ADDTOLOG; gce.ptszNick = tszId; gce.ptszUID = tszId; gce.ptszText = tszInitiator; gce.time = time(NULL); gce.bIsMe = IsMe(id); gce.ptszStatus = TranslateT("Admin"); CallServiceSync(MS_GC_EVENT, 0, (LPARAM)&gce); } } }
NGLDraw::NGLDraw() { m_rotate=false; // mouse rotation values set to 0 m_spinXFace=0; m_spinYFace=0; glClearColor(0.4f, 0.4f, 0.4f, 1.0f); // Grey Background // enable depth testing for drawing glEnable(GL_DEPTH_TEST); // now to load the shader and set the values // grab an instance of shader manager ngl::ShaderLib *shader=ngl::ShaderLib::instance(); // we are creating a shader called Phong shader->createShaderProgram("Phong"); // now we are going to create empty shaders for Frag and Vert shader->attachShader("PhongVertex",ngl::ShaderType::VERTEX); shader->attachShader("PhongFragment",ngl::ShaderType::FRAGMENT); // attach the source shader->loadShaderSource("PhongVertex","shaders/PhongVertex.glsl"); shader->loadShaderSource("PhongFragment","shaders/PhongFragment.glsl"); // compile the shaders shader->compileShader("PhongVertex"); shader->compileShader("PhongFragment"); // add them to the program shader->attachShaderToProgram("Phong","PhongVertex"); shader->attachShaderToProgram("Phong","PhongFragment"); // now bind the shader attributes for most NGL primitives we use the following // layout attribute 0 is the vertex data (x,y,z) shader->bindAttribute("Phong",0,"inVert"); // attribute 1 is the UV data u,v (if present) shader->bindAttribute("Phong",1,"inUV"); // attribute 2 are the normals x,y,z shader->bindAttribute("Phong",2,"inNormal"); // now we have associated this data we can link the shader shader->linkProgramObject("Phong"); // and make it active ready to load values (*shader)["Phong"]->use(); // the shader will use the currently active material and light0 so set them ngl::Material m(ngl::STDMAT::GOLD); // load our material values to the shader into the structure material (see Vertex shader) m.loadToShader("material"); // Now we will create a basic Camera from the graphics library // This is a static camera so it only needs to be set once // First create Values for the camera position ngl::Vec3 from(0,1,1); ngl::Vec3 to(0,0,0); ngl::Vec3 up(0,1,0); // now load to our new camera m_cam.set(from,to,up); // set the shape using FOV 45 Aspect Ratio based on Width and Height // The final two are near and far clipping planes of 0.5 and 10 m_cam.setShape(45,(float)720.0/576.0,0.05,350); shader->setShaderParam3f("viewerPos",m_cam.getEye().m_x,m_cam.getEye().m_y,m_cam.getEye().m_z); // now create our light this is done after the camera so we can pass the // transpose of the projection matrix to the light to do correct eye space // transformations ngl::Mat4 iv=m_cam.getViewMatrix(); iv.transpose(); ngl::Light light(ngl::Vec3(-2,5,2),ngl::Colour(1,1,1,1),ngl::Colour(1,1,1,1),ngl::LightModes::POINTLIGHT ); light.setTransform(iv); // load these values to the shader as well light.loadToShader("light"); }
uint8_t socket_handle_valid(sock_handle_t handle) { return is_valid(from(handle)); }
VehicleApiDemo::VehicleApiDemo(hkDemoEnvironment* env) : hkDefaultPhysicsDemo(env) { m_tag = 0; ///[driverInput] /// Initially controller is set to 0,0 i.e. neither turning left/right or forward/backward, /// so vehicle is not accelerating or turning. /// m_inputXPosition = 0.0f; m_inputYPosition = 0.0f; ///> { hkVector4 from(0.0f, 0.0f, 10.0f); hkVector4 to(0.0f, 0.0f, 0.0f); hkVector4 up(0.0f, 1.0f, 0.0f); setupDefaultCameras( env, from, to, up ); } // // Create the world. // { hkpWorldCinfo info; info.m_collisionTolerance = 0.1f; info.m_gravity.set(0.0f, -9.8f, 0.0f); info.setBroadPhaseWorldSize(1000.0f) ; info.setupSolverInfo(hkpWorldCinfo::SOLVER_TYPE_4ITERS_MEDIUM); m_world = new hkpWorld( info ); m_world->lock(); // Register all agents. hkpAgentRegisterUtil::registerAllAgents(m_world->getCollisionDispatcher()); // Graphics. setupGraphics(); } ///[buildLandscape] /// Build the landscape to drive on and add it to m_world. The landscape is simply five /// boxes, one for the ground and four for the walls. /// buildLandscape(); ///> /// /// Create the chassis /// hkpConvexVerticesShape* chassisShape = VehicleApiUtils::createCarChassisShape(); hkpRigidBody* chassisRigidBody; { hkpRigidBodyCinfo chassisInfo; // NB: The inertia value is reset by the vehicle SDK. However we give it a // reasonable value so that the hkpRigidBody does not assert on construction. See // VehicleSetup for the yaw, pitch and roll values used by hkVehicle. chassisInfo.m_mass = 750.0f; chassisInfo.m_shape = chassisShape; chassisInfo.m_friction = 0.4f; // The chassis MUST have m_motionType hkpMotion::MOTION_BOX_INERTIA to correctly simulate // vehicle roll, pitch and yaw. chassisInfo.m_motionType = hkpMotion::MOTION_BOX_INERTIA; chassisInfo.m_position.set(0.0f, 1.0f, 0.0f); hkpInertiaTensorComputer::setShapeVolumeMassProperties(chassisInfo.m_shape, chassisInfo.m_mass, chassisInfo); chassisRigidBody = new hkpRigidBody(chassisInfo); // No longer need reference to shape as the hkpRigidBody holds one. chassisShape->removeReference(); m_world->addEntity(chassisRigidBody); } ///> /// In this example, the chassis is added to the Vehicle Kit in the createVehicle() method. /// createVehicle( chassisRigidBody ); chassisRigidBody->removeReference(); ///> ///[buildVehicleCamera] /// This camera follows the vehicle when it moves. /// { VehicleApiUtils::createCamera( m_camera ); } ///> createDisplayWheels(); m_world->unlock(); }
void HistoryConfig::copy() { int cur = cmbStyle->currentItem(); if ((cur < 0) || (!m_styles.size())) return; QString name = m_styles[cur].name; QString newName; QRegExp re("\\.[0-9]+$"); unsigned next = 0; for (vector<StyleDef>::iterator it = m_styles.begin(); it != m_styles.end(); ++it){ QString nn = (*it).name; int n = nn.find(re); if (n < 0) continue; nn = nn.mid(n + 1); next = QMAX(next, nn.toUInt()); } int nn = name.find(re); if (nn >= 0){ newName = name.left(nn); }else{ newName = name; } newName += "."; newName += QString::number(next + 1); string n; n = STYLES; n += QFile::encodeName(name); n += EXT; if (m_styles[cur].bCustom){ n = user_file(n.c_str()); }else{ n = app_file(n.c_str()); } QFile from(QFile::decodeName(n.c_str())); if (!from.open(IO_ReadOnly)){ log(L_WARN, "Can't open %s", n.c_str()); return; } n = STYLES; n += QFile::encodeName(newName); n += EXT; n = user_file(n.c_str()); QFile to(QFile::decodeName((n + BACKUP_SUFFIX).c_str())); if (!to.open(IO_WriteOnly | IO_Truncate)){ log(L_WARN, "Cam't create %s", n.c_str()); return; } string s; s.append(from.size(), '\x00'); from.readBlock((char*)(s.c_str()), from.size()); to.writeBlock(s.c_str(), s.length()); from.close(); const int status = to.status(); #if QT_VERSION >= 0x030200 const QString errorMessage = to.errorString(); #else const QString errorMessage = "write file fail"; #endif to.close(); if (status != IO_Ok) { log(L_ERROR, "IO error during writting to file %s : %s", (const char*)to.name().local8Bit(), (const char*)errorMessage.local8Bit()); return; } // rename to normal file QFileInfo fileInfo(to.name()); QString desiredFileName = fileInfo.fileName(); desiredFileName = desiredFileName.left(desiredFileName.length() - strlen(BACKUP_SUFFIX)); #ifdef WIN32 fileInfo.dir().remove(desiredFileName); #endif if (!fileInfo.dir().rename(fileInfo.fileName(), desiredFileName)) { log(L_ERROR, "Can't rename file %s to %s", (const char*)fileInfo.fileName().local8Bit(), (const char*)desiredFileName.local8Bit()); return; } s = ""; StyleDef d; d.name = newName; d.bCustom = true; m_styles.push_back(d); fillCombo(QFile::encodeName(newName)); }
void ASParNewGeneration::resize_spaces(size_t requested_eden_size, size_t requested_survivor_size) { assert(UseAdaptiveSizePolicy, "sanity check"); assert(requested_eden_size > 0 && requested_survivor_size > 0, "just checking"); CollectedHeap* heap = Universe::heap(); assert(heap->kind() == CollectedHeap::GenCollectedHeap, "Sanity"); // We require eden and to space to be empty if ((!eden()->is_empty()) || (!to()->is_empty())) { return; } size_t cur_eden_size = eden()->capacity(); if (PrintAdaptiveSizePolicy && Verbose) { gclog_or_tty->print_cr("ASParNew::resize_spaces(requested_eden_size: " SIZE_FORMAT ", requested_survivor_size: " SIZE_FORMAT ")", requested_eden_size, requested_survivor_size); gclog_or_tty->print_cr(" eden: [" PTR_FORMAT ".." PTR_FORMAT ") " SIZE_FORMAT, eden()->bottom(), eden()->end(), pointer_delta(eden()->end(), eden()->bottom(), sizeof(char))); gclog_or_tty->print_cr(" from: [" PTR_FORMAT ".." PTR_FORMAT ") " SIZE_FORMAT, from()->bottom(), from()->end(), pointer_delta(from()->end(), from()->bottom(), sizeof(char))); gclog_or_tty->print_cr(" to: [" PTR_FORMAT ".." PTR_FORMAT ") " SIZE_FORMAT, to()->bottom(), to()->end(), pointer_delta( to()->end(), to()->bottom(), sizeof(char))); } // There's nothing to do if the new sizes are the same as the current if (requested_survivor_size == to()->capacity() && requested_survivor_size == from()->capacity() && requested_eden_size == eden()->capacity()) { if (PrintAdaptiveSizePolicy && Verbose) { gclog_or_tty->print_cr(" capacities are the right sizes, returning"); } return; } char* eden_start = (char*)eden()->bottom(); char* eden_end = (char*)eden()->end(); char* from_start = (char*)from()->bottom(); char* from_end = (char*)from()->end(); char* to_start = (char*)to()->bottom(); char* to_end = (char*)to()->end(); const size_t alignment = os::vm_page_size(); const bool maintain_minimum = (requested_eden_size + 2 * requested_survivor_size) <= min_gen_size(); // Check whether from space is below to space if (from_start < to_start) { // Eden, from, to if (PrintAdaptiveSizePolicy && Verbose) { gclog_or_tty->print_cr(" Eden, from, to:"); } // Set eden // "requested_eden_size" is a goal for the size of eden // and may not be attainable. "eden_size" below is // calculated based on the location of from-space and // the goal for the size of eden. from-space is // fixed in place because it contains live data. // The calculation is done this way to avoid 32bit // overflow (i.e., eden_start + requested_eden_size // may too large for representation in 32bits). size_t eden_size; if (maintain_minimum) { // Only make eden larger than the requested size if // the minimum size of the generation has to be maintained. // This could be done in general but policy at a higher // level is determining a requested size for eden and that // should be honored unless there is a fundamental reason. eden_size = pointer_delta(from_start, eden_start, sizeof(char)); } else { eden_size = MIN2(requested_eden_size, pointer_delta(from_start, eden_start, sizeof(char))); } eden_size = align_size_down(eden_size, alignment); eden_end = eden_start + eden_size; assert(eden_end >= eden_start, "addition overflowed") // To may resize into from space as long as it is clear of live data. // From space must remain page aligned, though, so we need to do some // extra calculations. // First calculate an optimal to-space to_end = (char*)virtual_space()->high(); to_start = (char*)pointer_delta(to_end, (char*)requested_survivor_size, sizeof(char)); // Does the optimal to-space overlap from-space? if (to_start < (char*)from()->end()) { // Calculate the minimum offset possible for from_end size_t from_size = pointer_delta(from()->top(), from_start, sizeof(char)); // Should we be in this method if from_space is empty? Why not the set_space method? FIX ME! if (from_size == 0) { from_size = alignment; } else { from_size = align_size_up(from_size, alignment); } from_end = from_start + from_size; assert(from_end > from_start, "addition overflow or from_size problem"); guarantee(from_end <= (char*)from()->end(), "from_end moved to the right"); // Now update to_start with the new from_end to_start = MAX2(from_end, to_start); } else { // If shrinking, move to-space down to abut the end of from-space // so that shrinking will move to-space down. If not shrinking // to-space is moving up to allow for growth on the next expansion. if (requested_eden_size <= cur_eden_size) { to_start = from_end; if (to_start + requested_survivor_size > to_start) { to_end = to_start + requested_survivor_size; } } // else leave to_end pointing to the high end of the virtual space. } guarantee(to_start != to_end, "to space is zero sized"); if (PrintAdaptiveSizePolicy && Verbose) { gclog_or_tty->print_cr(" [eden_start .. eden_end): " "[" PTR_FORMAT " .. " PTR_FORMAT ") " SIZE_FORMAT, eden_start, eden_end, pointer_delta(eden_end, eden_start, sizeof(char))); gclog_or_tty->print_cr(" [from_start .. from_end): " "[" PTR_FORMAT " .. " PTR_FORMAT ") " SIZE_FORMAT, from_start, from_end, pointer_delta(from_end, from_start, sizeof(char))); gclog_or_tty->print_cr(" [ to_start .. to_end): " "[" PTR_FORMAT " .. " PTR_FORMAT ") " SIZE_FORMAT, to_start, to_end, pointer_delta( to_end, to_start, sizeof(char))); } } else { // Eden, to, from if (PrintAdaptiveSizePolicy && Verbose) { gclog_or_tty->print_cr(" Eden, to, from:"); } // Calculate the to-space boundaries based on // the start of from-space. to_end = from_start; to_start = (char*)pointer_delta(from_start, (char*)requested_survivor_size, sizeof(char)); // Calculate the ideal eden boundaries. // eden_end is already at the bottom of the generation assert(eden_start == virtual_space()->low(), "Eden is not starting at the low end of the virtual space"); if (eden_start + requested_eden_size >= eden_start) { eden_end = eden_start + requested_eden_size; } else { eden_end = to_start; } // Does eden intrude into to-space? to-space // gets priority but eden is not allowed to shrink // to 0. if (eden_end > to_start) { eden_end = to_start; } // Don't let eden shrink down to 0 or less. eden_end = MAX2(eden_end, eden_start + alignment); assert(eden_start + alignment >= eden_start, "Overflow"); size_t eden_size; if (maintain_minimum) { // Use all the space available. eden_end = MAX2(eden_end, to_start); eden_size = pointer_delta(eden_end, eden_start, sizeof(char)); eden_size = MIN2(eden_size, cur_eden_size); } else { eden_size = pointer_delta(eden_end, eden_start, sizeof(char)); } eden_size = align_size_down(eden_size, alignment); assert(maintain_minimum || eden_size <= requested_eden_size, "Eden size is too large"); assert(eden_size >= alignment, "Eden size is too small"); eden_end = eden_start + eden_size; // Move to-space down to eden. if (requested_eden_size < cur_eden_size) { to_start = eden_end; if (to_start + requested_survivor_size > to_start) { to_end = MIN2(from_start, to_start + requested_survivor_size); } else { to_end = from_start; } } // eden_end may have moved so again make sure // the to-space and eden don't overlap. to_start = MAX2(eden_end, to_start); // from-space size_t from_used = from()->used(); if (requested_survivor_size > from_used) { if (from_start + requested_survivor_size >= from_start) { from_end = from_start + requested_survivor_size; } if (from_end > virtual_space()->high()) { from_end = virtual_space()->high(); } } assert(to_start >= eden_end, "to-space should be above eden"); if (PrintAdaptiveSizePolicy && Verbose) { gclog_or_tty->print_cr(" [eden_start .. eden_end): " "[" PTR_FORMAT " .. " PTR_FORMAT ") " SIZE_FORMAT, eden_start, eden_end, pointer_delta(eden_end, eden_start, sizeof(char))); gclog_or_tty->print_cr(" [ to_start .. to_end): " "[" PTR_FORMAT " .. " PTR_FORMAT ") " SIZE_FORMAT, to_start, to_end, pointer_delta( to_end, to_start, sizeof(char))); gclog_or_tty->print_cr(" [from_start .. from_end): " "[" PTR_FORMAT " .. " PTR_FORMAT ") " SIZE_FORMAT, from_start, from_end, pointer_delta(from_end, from_start, sizeof(char))); } } guarantee((HeapWord*)from_start <= from()->bottom(), "from start moved to the right"); guarantee((HeapWord*)from_end >= from()->top(), "from end moved into live data"); assert(is_object_aligned((intptr_t)eden_start), "checking alignment"); assert(is_object_aligned((intptr_t)from_start), "checking alignment"); assert(is_object_aligned((intptr_t)to_start), "checking alignment"); MemRegion edenMR((HeapWord*)eden_start, (HeapWord*)eden_end); MemRegion toMR ((HeapWord*)to_start, (HeapWord*)to_end); MemRegion fromMR((HeapWord*)from_start, (HeapWord*)from_end); // Let's make sure the call to initialize doesn't reset "top"! HeapWord* old_from_top = from()->top(); // For PrintAdaptiveSizePolicy block below size_t old_from = from()->capacity(); size_t old_to = to()->capacity(); // If not clearing the spaces, do some checking to verify that // the spaces are already mangled. // Must check mangling before the spaces are reshaped. Otherwise, // the bottom or end of one space may have moved into another // a failure of the check may not correctly indicate which space // is not properly mangled. if (ZapUnusedHeapArea) { HeapWord* limit = (HeapWord*) virtual_space()->high(); eden()->check_mangled_unused_area(limit); from()->check_mangled_unused_area(limit); to()->check_mangled_unused_area(limit); } // The call to initialize NULL's the next compaction space eden()->initialize(edenMR, SpaceDecorator::Clear, SpaceDecorator::DontMangle); eden()->set_next_compaction_space(from()); to()->initialize(toMR , SpaceDecorator::Clear, SpaceDecorator::DontMangle); from()->initialize(fromMR, SpaceDecorator::DontClear, SpaceDecorator::DontMangle); assert(from()->top() == old_from_top, "from top changed!"); if (PrintAdaptiveSizePolicy) { GenCollectedHeap* gch = GenCollectedHeap::heap(); assert(gch->kind() == CollectedHeap::GenCollectedHeap, "Sanity"); gclog_or_tty->print("AdaptiveSizePolicy::survivor space sizes: " "collection: %d " "(" SIZE_FORMAT ", " SIZE_FORMAT ") -> " "(" SIZE_FORMAT ", " SIZE_FORMAT ") ", gch->total_collections(), old_from, old_to, from()->capacity(), to()->capacity()); gclog_or_tty->cr(); } }
void HalftonePreviewView::preview(float gamma, float min, Halftone::DitherType ditherType, bool color) { const color_space kColorSpace = B_RGB32; const float right = Bounds().Width(); const float bottom = Bounds().Height(); BRect rect(0, 0, right, bottom); BBitmap testImage(rect, kColorSpace, true); BBitmap preview(rect, kColorSpace); BView view(rect, "", B_FOLLOW_ALL, B_WILL_DRAW); // create test image testImage.Lock(); testImage.AddChild(&view); // color bars const int height = Bounds().IntegerHeight()+1; const int width = Bounds().IntegerWidth()+1; const int delta = height / 4; const float red_bottom = delta - 1; const float green_bottom = red_bottom + delta; const float blue_bottom = green_bottom + delta; const float gray_bottom = height - 1; for (int x = 0; x <= right; x ++) { uchar value = x * 255 / width; BPoint from(x, 0); BPoint to(x, red_bottom); // red view.SetHighColor(255, value, value); view.StrokeLine(from, to); // green from.y = to.y+1; to.y = green_bottom; view.SetHighColor(value, 255, value); view.StrokeLine(from, to); // blue from.y = to.y+1; to.y = blue_bottom; view.SetHighColor(value, value, 255); view.StrokeLine(from, to); // gray from.y = to.y+1; to.y = gray_bottom; view.SetHighColor(value, value, value); view.StrokeLine(from, to); } view.Sync(); testImage.RemoveChild(&view); testImage.Unlock(); // create preview image Halftone halftone(kColorSpace, gamma, min, ditherType); halftone.setBlackValue(Halftone::kLowValueMeansBlack); const int widthBytes = (width + 7) / 8; // byte boundary uchar* buffer = new uchar[widthBytes]; const uchar* src = (uchar*)testImage.Bits(); uchar* dstRow = (uchar*)preview.Bits(); const int numPlanes = color ? 3 : 1; if (color) { halftone.setPlanes(Halftone::kPlaneRGB1); } for (int y = 0; y < height; y ++) { for (int plane = 0; plane < numPlanes; plane ++) { // halftone the preview image halftone.dither(buffer, src, 0, y, width); // convert the plane(s) to RGB32 ColorRGB32Little* dst = (ColorRGB32Little*)dstRow; const uchar* bitmap = buffer; for (int x = 0; x < width; x ++, dst ++) { const int bit = 7 - (x % 8); const bool isSet = (*bitmap & (1 << bit)) != 0; uchar value = isSet ? 255 : 0; if (color) { switch (plane) { case 0: dst->red = value; break; case 1: dst->green = value; break; case 2: dst->blue = value; break; } } else { dst->red = dst->green = dst->blue = value; } if (bit == 0) { bitmap ++; } } } // next row src += testImage.BytesPerRow(); dstRow += preview.BytesPerRow(); } delete[] buffer; SetViewBitmap(&preview); Invalidate(); }
nsresult HttpBaseChannel::ApplyContentConversions() { if (!mResponseHead) return NS_OK; LOG(("HttpBaseChannel::ApplyContentConversions [this=%p]\n", this)); if (!mApplyConversion) { LOG(("not applying conversion per mApplyConversion\n")); return NS_OK; } nsCAutoString contentEncoding; char *cePtr, *val; nsresult rv; rv = mResponseHead->GetHeader(nsHttp::Content_Encoding, contentEncoding); if (NS_FAILED(rv) || contentEncoding.IsEmpty()) return NS_OK; // The encodings are listed in the order they were applied // (see rfc 2616 section 14.11), so they need to removed in reverse // order. This is accomplished because the converter chain ends up // being a stack with the last converter created being the first one // to accept the raw network data. cePtr = contentEncoding.BeginWriting(); PRUint32 count = 0; while ((val = nsCRT::strtok(cePtr, HTTP_LWS ",", &cePtr))) { if (++count > 16) { // That's ridiculous. We only understand 2 different ones :) // but for compatibility with old code, we will just carry on without // removing the encodings LOG(("Too many Content-Encodings. Ignoring remainder.\n")); break; } if (gHttpHandler->IsAcceptableEncoding(val)) { nsCOMPtr<nsIStreamConverterService> serv; rv = gHttpHandler->GetStreamConverterService(getter_AddRefs(serv)); // we won't fail to load the page just because we couldn't load the // stream converter service.. carry on.. if (NS_FAILED(rv)) { if (val) LOG(("Unknown content encoding '%s', ignoring\n", val)); continue; } nsCOMPtr<nsIStreamListener> converter; nsCAutoString from(val); ToLowerCase(from); rv = serv->AsyncConvertData(from.get(), "uncompressed", mListener, mListenerContext, getter_AddRefs(converter)); if (NS_FAILED(rv)) { LOG(("Unexpected failure of AsyncConvertData %s\n", val)); return rv; } LOG(("converter removed '%s' content-encoding\n", val)); mListener = converter; } else { if (val) LOG(("Unknown content encoding '%s', ignoring\n", val)); } } return NS_OK; }
TriSampledHeightFieldDemo::TriSampledHeightFieldDemo(hkDemoEnvironment* env) : hkDefaultPhysicsDemo(env, DEMO_FLAGS_NO_SERIALIZE) { // Disable face culling setGraphicsState(HKG_ENABLED_CULLFACE, false); // Setup a camera in the right place to see our demo. { hkVector4 from( -3.7f, 5, 17.6f ); hkVector4 to (-1.5f, 1, 1.1f ); hkVector4 up ( 0.0f, 1.0f, 0.0f); setupDefaultCameras(env, from, to, up); } { hkpWorldCinfo info; info.setBroadPhaseWorldSize( 100.0f ); info.m_collisionTolerance = 0.03f; m_world = new hkpWorld(info); m_world->lock(); setupGraphics(); } hkpAgentRegisterUtil::registerAllAgents( m_world->getCollisionDispatcher() ); // // Create two movable rigid bodies to fall on the two heightfields. // { hkVector4 halfExtents(1.f, .25f, 1.f ); hkpShape* shape = new hkpBoxShape( halfExtents , 0 ); for (int i = 0; i < 2; i++ ) { hkpRigidBodyCinfo ci; ci.m_motionType = hkpMotion::MOTION_SPHERE_INERTIA; ci.m_shape = shape; ci.m_mass = 4.f; hkpMassProperties m; hkpInertiaTensorComputer::computeShapeVolumeMassProperties(shape,4, m); ci.m_inertiaTensor = m.m_inertiaTensor; ci.m_position.set( hkReal(i * 7) - 5 , 4, 3 ); hkpRigidBody* body = new hkpRigidBody( ci ); m_world->addEntity(body); body->removeReference(); } shape->removeReference(); } { // Create our heightfield hkpSampledHeightFieldBaseCinfo ci; ci.m_xRes = 7; ci.m_zRes = 7; SimpleSampledHeightFieldShape* heightFieldShape = new SimpleSampledHeightFieldShape( ci ); { // // Create the first fixed rigid body, using the standard heightfield as the shape // hkpRigidBodyCinfo rci; rci.m_motionType = hkpMotion::MOTION_FIXED; rci.m_position.set(-8, 0, 0); rci.m_shape = heightFieldShape; rci.m_friction = 0.2f; hkpRigidBody* bodyA = new hkpRigidBody( rci ); m_world->addEntity(bodyA); bodyA->removeReference(); // // Create the second fixed rigid body, using the triSampledHeightfield // // Wrap the heightfield in a hkpTriSampledHeightFieldCollection: hkpTriSampledHeightFieldCollection* collection = new hkpTriSampledHeightFieldCollection( heightFieldShape ); // Now wrap the hkpTriSampledHeightFieldCollection in a hkpTriSampledHeightFieldBvTreeShape hkpTriSampledHeightFieldBvTreeShape* bvTree = new hkpTriSampledHeightFieldBvTreeShape( collection ); // Finally, assign the new hkpTriSampledHeightFieldBvTreeShape to be the rigid body's shape rci.m_shape = bvTree; rci.m_position.set(-1,0,0); hkpRigidBody* bodyB = new hkpRigidBody( rci ); m_world->addEntity(bodyB); bodyB->removeReference(); heightFieldShape->removeReference(); collection->removeReference(); bvTree->removeReference(); } hkString left("Standard heightfield."); m_env->m_textDisplay->outputText3D(left, -7, -.2f, 7, 0xffffffff, 2000); hkString right("Triangle heightfield."); m_env->m_textDisplay->outputText3D(right, -1, -.2f, 7, 0xffffffff, 2000); } m_world->unlock(); }
OptimizedWorldRaycastDemo::OptimizedWorldRaycastDemo(hkDemoEnvironment* env) : hkDefaultPhysicsDemo(env) { { m_numRigidBodies = int(m_env->m_cpuMhz); m_numBroadphaseMarkers = 64; m_rayLength = 5; m_worldSizeX = 2.0f * hkMath::sqrt(hkReal(m_env->m_cpuMhz)); m_worldSizeY = 3; m_worldSizeZ = m_worldSizeX; } // // Setup the camera. // { hkVector4 from(30.0f, 8.0f, 25.0f); hkVector4 to ( 4.0f, 0.0f, -3.0f); hkVector4 up ( 0.0f, 1.0f, 0.0f); setupDefaultCameras(env, from, to, up); // Demo is slow graphicaly as it without shadows forceShadowState(false); } // // Create the world. // { hkpWorldCinfo info; // Set gravity to zero so body floats. info.m_gravity.setZero4(); // make the world big enough to hold all our objects // make y larger so that our raycasts stay within the world aabb info.m_broadPhaseWorldAabb.m_max.set( m_worldSizeX + 10, 10*m_worldSizeY + 10, m_worldSizeZ + 10 ); info.m_broadPhaseWorldAabb.m_min.setNeg4( info.m_broadPhaseWorldAabb.m_max ); // Subdivide the broadphase space into equal sections along the x-axis // NOTE: Disabling this until the marker crash issue is fixed. //info.m_broadPhaseNumMarkers = m_numBroadphaseMarkers; m_world = new hkpWorld(info); m_world->lock(); setupGraphics(); } // register all agents(however, we put all objects into the some group, // so no collision will be detected hkpAgentRegisterUtil::registerAllAgents( m_world->getCollisionDispatcher() ); // Add a collision filter to the world to allow the bodies interpenetrate { hkpGroupFilter* filter = new hkpGroupFilter(); filter->disableCollisionsBetween( hkpGroupFilterSetup::LAYER_DEBRIS, hkpGroupFilterSetup::LAYER_DEBRIS ); m_world->setCollisionFilter( filter ); filter->removeReference(); } // // Set the simulation time to 0 // m_time = 0; // // Create our phantom at our origin. // This is a bad hack, we should really create our phantom at it's final position, // but let's keep the demo simple. // If you actually create many phantoms all at the origin, you get a massive CPU spike // as every phantom will collide with every other phantom. // { hkAabb aabb; aabb.m_min.setZero4(); aabb.m_max.setZero4(); m_phantom = new hkpAabbPhantom( aabb ); m_world->addPhantom( m_phantom ); m_phantomUseCache = new hkpAabbPhantom( aabb ); m_world->addPhantom( m_phantomUseCache ); } // // Create some bodies (reuse the ShapeRaycastApi demo) // createBodies(); m_world->unlock(); }
void AsyncCopy::Run(void* data) { START_KROLL_THREAD; Logger* logger = Logger::Get("Filesystem.AsyncCopy"); AsyncCopy* ac = static_cast<AsyncCopy*>(data); std::vector<std::string>::iterator iter = ac->files.begin(); Poco::Path to(ac->destination); Poco::File tof(to.toString()); logger->Debug("Job started: dest=%s, count=%i", ac->destination.c_str(), ac->files.size()); if (!tof.exists()) { tof.createDirectory(); } int c = 0; while (!ac->stopped && iter!=ac->files.end()) { std::string file = (*iter++); c++; logger->Debug("File: path=%s, count=%i\n", file.c_str(), c); try { Poco::Path from(file); Poco::File f(file); if (f.isDirectory()) { ac->Copy(from,to); } else { Poco::Path dest(to,from.getFileName()); ac->Copy(from,dest); } logger->Debug("File copied"); SharedValue value = Value::NewString(file); ValueList args; args.push_back(value); args.push_back(Value::NewInt(c)); args.push_back(Value::NewInt(ac->files.size())); ac->host->InvokeMethodOnMainThread(ac->callback, args, false); logger->Debug("Callback executed"); } catch (ValueException &ex) { SharedString ss = ex.DisplayString(); logger->Error(std::string("Error: ") + *ss + " for file: " + file); } catch (Poco::Exception &ex) { logger->Error(std::string("Error: ") + ex.displayText() + " for file: " + file); } catch (std::exception &ex) { logger->Error(std::string("Error: ") + ex.what() + " for file: " + file); } catch (...) { logger->Error(std::string("Unknown error during copy: ") + file); } } ac->Set("running",Value::NewBool(false)); ac->stopped = true; logger->Debug(std::string("Job finished")); END_KROLL_THREAD; }
SYNCED_COMMAND_HANDLER_FUNCTION(recruit, child, use_undo, show, error_handler) { int current_team_num = resources::controller->current_side(); team ¤t_team = resources::gameboard->teams()[current_team_num - 1]; map_location loc(child, resources::gamedata); map_location from(child.child_or_empty("from"), resources::gamedata); // Validate "from". if ( !from.valid() ) { // This will be the case for AI recruits in replays saved // before 1.11.2, so it is not more severe than a warning. // EDIT: we borke compability with 1.11.2 anyway so we should give an error. error_handler("Missing leader location for recruitment.\n", false); } else if ( resources::units->find(from) == resources::units->end() ) { // Sync problem? std::stringstream errbuf; errbuf << "Recruiting leader not found at " << from << ".\n"; error_handler(errbuf.str(), false); } // Get the unit_type ID. std::string type_id = child["type"]; if ( type_id.empty() ) { error_handler("Recruitment is missing a unit type.", true); return false; } const unit_type *u_type = unit_types.find(type_id); if (!u_type) { std::stringstream errbuf; errbuf << "Recruiting illegal unit: '" << type_id << "'.\n"; error_handler(errbuf.str(), true); return false; } const std::string res = actions::find_recruit_location(current_team_num, loc, from, type_id); if(!res.empty()) { std::stringstream errbuf; errbuf << "cannot recruit unit: " << res << "\n"; error_handler(errbuf.str(), true); return false; //we are already oos because the unit wasn't created, no need to keep the bookkeeping right... } const int beginning_gold = current_team.gold(); if ( u_type->cost() > beginning_gold ) { std::stringstream errbuf; errbuf << "unit '" << type_id << "' is too expensive to recruit: " << u_type->cost() << "/" << beginning_gold << "\n"; error_handler(errbuf.str(), false); } actions::recruit_unit(*u_type, current_team_num, loc, from, show, use_undo); LOG_REPLAY << "recruit: team=" << current_team_num << " '" << type_id << "' at (" << loc << ") cost=" << u_type->cost() << " from gold=" << beginning_gold << ' ' << "-> " << current_team.gold() << "\n"; return true; }
PoweredRagdollDemo::PoweredRagdollDemo(hkDemoEnvironment* env) : hkDefaultPhysicsDemo(env) { m_time = 0.0f; // // Setup the camera // { hkVector4 from(5.0f, 2.0f, 5.0f); hkVector4 to(0.0f, 0.0f, 0.0f); hkVector4 up(0.0f, 1.0f, 0.0f); setupDefaultCameras( env, from, to, up ); } // // Create the world // { hkpWorldCinfo info; info.setupSolverInfo(hkpWorldCinfo::SOLVER_TYPE_8ITERS_MEDIUM); info.m_enableDeactivation = false; m_world = new hkpWorld( info ); m_world->lock(); // // Create constraint viewer // m_debugViewerNames.pushBack( hkpConstraintViewer::getName() ); hkpConstraintViewer::m_scale = 1.0f; setupGraphics(); // Register the single agent required (a hkpBoxBoxAgent) hkpAgentRegisterUtil::registerAllAgents( m_world->getCollisionDispatcher() ); } // // Create vectors to be used for setup // hkVector4 pivot(0.0f, 0.0f, 0.0f); hkVector4 halfSize(1.0f, 0.25f, 0.5f); // // Create Box Shape // hkpBoxShape* boxShape; { boxShape = new hkpBoxShape( halfSize , 0 ); } // // Create fixed rigid body // hkpRigidBody* fixedBody; { hkpRigidBodyCinfo info; info.m_position.set(-halfSize(0) - 1.0f, 0.0f, 0.0f); info.m_shape = boxShape; info.m_motionType = hkpMotion::MOTION_FIXED; fixedBody = new hkpRigidBody(info); m_world->addEntity(fixedBody); fixedBody->removeReference(); } // // Create movable rigid body // hkpRigidBody* moveableBody; { hkpRigidBodyCinfo info; info.m_position.set(halfSize(0) + 1.0f, 0.0f, 0.0f); info.m_shape = boxShape; // Compute the box inertia tensor hkpMassProperties massProperties; info.m_mass = 10.0f; hkpInertiaTensorComputer::computeBoxVolumeMassProperties(halfSize, info.m_mass, massProperties); info.m_inertiaTensor = massProperties.m_inertiaTensor; info.m_centerOfMass = massProperties.m_centerOfMass; info.m_motionType = hkpMotion::MOTION_BOX_INERTIA; moveableBody = new hkpRigidBody(info); m_world->addEntity(moveableBody); moveableBody->removeReference(); } // // Cleanup shape references // boxShape->removeReference(); boxShape = HK_NULL; // // CREATE POWERED RAGDOLL CONSTRAINT // { hkReal planeMin = HK_REAL_PI * -0.2f; hkReal planeMax = HK_REAL_PI * 0.1f; hkReal twistMin = HK_REAL_PI * -0.1f; hkReal twistMax = HK_REAL_PI * 0.4f; hkReal coneMin = HK_REAL_PI * 0.3f; hkpRagdollConstraintData* rdc = new hkpRagdollConstraintData(); rdc->setConeAngularLimit(coneMin); rdc->setPlaneMinAngularLimit(planeMin); rdc->setPlaneMaxAngularLimit(planeMax); rdc->setTwistMinAngularLimit(twistMin); rdc->setTwistMaxAngularLimit(twistMax); hkVector4 twistAxis(1.0f, 0.0f, 0.0f); hkVector4 planeAxis(0.0f, 1.0f, 0.0f); pivot.set(0.0f, 0.0f, 0.0f); rdc->setInWorldSpace(moveableBody->getTransform(), fixedBody->getTransform(), pivot, twistAxis, planeAxis); // // Create and add the constraint // hkpConstraintInstance* constraint = new hkpConstraintInstance(moveableBody, fixedBody, rdc ); m_world->addConstraint(constraint); hkpPositionConstraintMotor* motor = new hkpPositionConstraintMotor( 0 ); motor->m_tau = 0.6f; motor->m_maxForce = 1000.0f; motor->m_constantRecoveryVelocity = 0.1f; rdc->setTwistMotor( motor ); rdc->setConeMotor( motor ); rdc->setPlaneMotor( motor ); rdc->setMotorsActive(constraint, true); motor->removeReference(); hkRotation bRa; bRa.setTranspose( fixedBody->getTransform().getRotation() ); bRa.mul( moveableBody->getTransform().getRotation() ); rdc->setTargetRelativeOrientationOfBodies( bRa ); m_constraintData = rdc; constraint->removeReference(); } // // So that we can actually see the motor in action, rotate the constrained body slightly. // When simulation starts it will then by driven to the target position (frame). // { hkQuaternion rot; hkVector4 axis( 1.0f, 0.0f, 0.0f ); axis.normalize3(); rot.setAxisAngle( axis, 0.4f ); moveableBody->setRotation( rot ); } m_world->unlock(); }
int main(int argc, char ** argv) { boost::program_options::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("decompress,d", "decompress") ("block-size,b", boost::program_options::value<unsigned>()->default_value(DBMS_DEFAULT_BUFFER_SIZE), "compress in blocks of specified size") ("hc", "use LZ4HC instead of LZ4") ("zstd", "use ZSTD instead of LZ4") ("stat", "print block statistics of compressed data") ; boost::program_options::variables_map options; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), options); if (options.count("help")) { std::cout << "Usage: " << argv[0] << " [options] < in > out" << std::endl; std::cout << desc << std::endl; return 1; } try { bool decompress = options.count("decompress"); bool use_lz4hc = options.count("hc"); bool use_zstd = options.count("zstd"); bool stat_mode = options.count("stat"); unsigned block_size = options["block-size"].as<unsigned>(); DB::CompressionMethod method = DB::CompressionMethod::LZ4; if (use_lz4hc) method = DB::CompressionMethod::LZ4HC; else if (use_zstd) method = DB::CompressionMethod::ZSTD; DB::ReadBufferFromFileDescriptor rb(STDIN_FILENO); DB::WriteBufferFromFileDescriptor wb(STDOUT_FILENO); if (stat_mode) { /// Output statistic for compressed file. stat(rb, wb); } else if (decompress) { /// Decompression DB::CompressedReadBuffer from(rb); DB::copyData(from, wb); } else { /// Compression DB::CompressedWriteBuffer to(wb, method, block_size); DB::copyData(rb, to); } } catch (...) { std::cerr << DB::getCurrentExceptionMessage(true); return DB::getCurrentExceptionCode(); } return 0; }
NativePackfileLoadDemo::NativePackfileLoadDemo( hkDemoEnvironment* env) : hkDefaultPhysicsDemo(env) { // Disable warning: 'm_contactRestingVelocity not set, setting it to REAL_MAX, so that the new collision restitution code will be disabled' hkError::getInstance().setEnabled(0xf03243ed, false); hkError::getInstance().setEnabled(0x9fe65234, false); // Setup the camera { hkVector4 from(31, 31, 14); hkVector4 to(2.5f, -2, -.3f); hkVector4 up(0, 0, 1); setupDefaultCameras( env, from, to, up ); } hkString path("Resources/Common/Api/Serialize/SimpleLoad"); hkString fileName; NativePackfileLoadDemo_getBinaryFileName(fileName); hkRootLevelContainer* container = HK_NULL; { // read entire file into local buffer hkArray<char> buf; loadEntireFileIntoBuffer( hkString(path+fileName).cString(), buf ); #if defined(PACKFILE_LOAD_WITH_VERSIONING) updatePackfileDataVersion( buf ); #endif // Now we have native packfile data in the 'buf' variable. // extract only valuable data, stripping out all extras, such as headers and fixups tables // and load it into m_dataBuffer int bufferSize = hkNativePackfileUtils::getRequiredBufferSize( buf.begin(), buf.getSize() ); m_dataBuffer.reserveExactly(bufferSize); // Load the buffer and get the top level object in the file in one step container = static_cast<hkRootLevelContainer*>(hkNativePackfileUtils::load(buf.begin(), buf.getSize(), m_dataBuffer.begin(), m_dataBuffer.getCapacity())); } HK_ASSERT2(0xa6451543, container != HK_NULL, "Could not load root level obejct" ); hkpPhysicsData* physicsData = static_cast<hkpPhysicsData*>( container->findObjectByType( hkpPhysicsDataClass.getName() ) ); HK_ASSERT2(0xa6451544, physicsData != HK_NULL, "Could not find physics data in root level object" ); HK_ASSERT2(0xa6451535, physicsData->getWorldCinfo() != HK_NULL, "No physics cinfo in loaded file - cannot create a hkpWorld" ); // Create a world and add the physics systems to it m_world = new hkpWorld( *physicsData->getWorldCinfo() ); m_world->lock(); // Register all collision agents hkpAgentRegisterUtil::registerAllAgents( m_world->getCollisionDispatcher() ); // Add all the physics systems to the world for ( int i = 0; i < physicsData->getPhysicsSystems().getSize(); ++i ) { m_world->addPhysicsSystem( physicsData->getPhysicsSystems()[i] ); } // Setup graphics - this creates graphics objects for all rigid bodies and phantoms in the world setupGraphics(); m_world->unlock(); }
void Projectile::Render(Graphics::Renderer *renderer, const vector3d &viewCoords, const matrix4x4d &viewTransform) { vector3d _from = viewTransform * GetInterpolatedPosition(); vector3d _to = viewTransform * (GetInterpolatedPosition() + m_dirVel); vector3d _dir = _to - _from; vector3f from(&_from.x); vector3f dir = vector3f(_dir).Normalized(); vector3f v1, v2; matrix4x4f m = matrix4x4f::Identity(); v1.x = dir.y; v1.y = dir.z; v1.z = dir.x; v2 = v1.Cross(dir).Normalized(); v1 = v2.Cross(dir); m[0] = v1.x; m[4] = v2.x; m[8] = dir.x; m[1] = v1.y; m[5] = v2.y; m[9] = dir.y; m[2] = v1.z; m[6] = v2.z; m[10] = dir.z; m[12] = from.x; m[13] = from.y; m[14] = from.z; renderer->SetBlendMode(Graphics::BLEND_ALPHA_ONE); renderer->SetDepthWrite(false); glPushMatrix(); glMultMatrixf(&m[0]); // increase visible size based on distance from camera, z is always negative // allows them to be smaller while maintaining visibility for game play const float dist_scale = float(viewCoords.z / -500); const float length = Equip::lasers[m_type].length + dist_scale; const float width = Equip::lasers[m_type].width + dist_scale; glScalef(width, width, length); Color color = Equip::lasers[m_type].color; // fade them out as they age so they don't suddenly disappear // this matches the damage fall-off calculation const float base_alpha = sqrt(1.0f - m_age/Equip::lasers[m_type].lifespan); // fade out side quads when viewing nearly edge on vector3f view_dir = vector3f(viewCoords).Normalized(); color.a = base_alpha * (1.f - powf(fabs(dir.Dot(view_dir)), length)); if (color.a > 0.01f) { m_sideMat.diffuse = color; renderer->DrawTriangles(m_sideVerts.Get(), &m_sideMat); } // fade out glow quads when viewing nearly edge on // these and the side quads fade at different rates // so that they aren't both at the same alpha as that looks strange color.a = base_alpha * powf(fabs(dir.Dot(view_dir)), width); if (color.a > 0.01f) { m_glowMat.diffuse = color; renderer->DrawTriangles(m_glowVerts.Get(), &m_glowMat); } glPopMatrix(); renderer->SetBlendMode(Graphics::BLEND_SOLID); renderer->SetDepthWrite(true); }
BenchmarkSuiteDemo::BenchmarkSuiteDemo(hkDemoEnvironment* env) : hkDefaultPhysicsDemo(env) { const BenchmarkSuiteVariant& variant = g_variants[m_variantId]; // Disable warnings: hkError::getInstance().setEnabled(0x7dd65995, false); //'The system has requested a heap allocation on stack overflow.' hkError::getInstance().setEnabled(0xaf55adde, false); //'No runtime block of size 637136 currently available. Allocating new block from unmanaged memory.' // // Setup the camera // { hkVector4 from(55.0f, 50.0f, 55.0f); hkVector4 to ( 0.0f, 0.0f, 0.0f); hkVector4 up ( 0.0f, 1.0f, 0.0f); setupDefaultCameras(env, from, to, up, 0.1f, 20000.0f); } // // Create the world // { hkpWorldCinfo worldInfo; { worldInfo.m_gravity.set(-0.0f, -9.81f, -0.0f); worldInfo.setBroadPhaseWorldSize(500.0f); worldInfo.setupSolverInfo( hkpWorldCinfo::SOLVER_TYPE_4ITERS_MEDIUM ); if (variant.m_type == TYPE_3000_BODY_PILE) { worldInfo.m_enableSimulationIslands = false; } worldInfo.m_enableDeactivation = false; } m_world = new hkpWorld(worldInfo); m_world->lock(); // Register ALL agents (though some may not be necessary) hkpAgentRegisterUtil::registerAllAgents(m_world->getCollisionDispatcher()); setupGraphics(); // enable instancing (if present on platform). Call this after setup graphics (as it makes the local viewers..) hkpShapeDisplayViewer* shapeViewer = (hkpShapeDisplayViewer*)getLocalViewerByName( hkpShapeDisplayViewer::getName() ); if (shapeViewer) { shapeViewer->setInstancingEnabled( true ); } } // // Setup the camera // { hkVector4 from(15.0f, 15.0f, 15.0f); hkVector4 to (0.0f, 0.0f, 0.0f); hkVector4 up (0.0f, 1.0f, 0.0f); setupDefaultCameras( env, from, to, up ); } switch (variant.m_type) { case TYPE_10x10x1_ON_BOX: { CreateGroundPlane( m_world ); CreateStack(m_world, 10); break; } case TYPE_5x5x5_ON_BOX: { CreateGroundPlane(m_world); for (int q = -3; q <= 2; q++ ) { CreateStack(m_world,5, q * 10.0f); } break; } case TYPE_300_BODY_PILE: { CreateGroundPlane(m_world); CreateFall(m_world, 5); break; } case TYPE_OBJECTS_ON_MOPP_SMALL: { CreatePhysicsTerrain(m_world, 16, 1.0f); CreateFlatCubeGrid(m_world,8); break; } case TYPE_LIST_PILE_SMALL: { int side = 16; CreatePhysicsTerrain(m_world, side, 1.0f); CreateListGrid(m_world, hkReal(side), 3, 3); break; } case TYPE_30x30x1_ON_BOX: { CreateGroundPlane( m_world ); CreateStack(m_world, 30); break; } case TYPE_20x20x5_ON_BOX: { CreateGroundPlane(m_world); for (int q = -3; q <= 2; q++ ) { CreateStack(m_world,20, q * 10.0f); } break; } case TYPE_12x12x10_ON_BOX: { CreateGroundPlane(m_world); for (int q = -5; q <= 4; q++ ) { CreateStack(m_world,12, q * 2.5f); } break; } case TYPE_3000_BODY_PILE: { CreateGroundPlane(m_world); CreateFall(m_world, 50); break; } case TYPE_OBJECTS_ON_MOPP_LARGE: { CreatePhysicsTerrain(m_world, 64, 1.0f); CreateFlatCubeGrid(m_world,30); break; } case TYPE_LIST_PILE_LARGE: { int side = 16; CreatePhysicsTerrain(m_world, side, 1.0f); CreateListGrid(m_world, hkReal(side), 5, 5); break; } default: { CreateGroundPlane(m_world); CreateStack(m_world, 20); break; } } // // Some values // m_world->unlock(); }