void initScene () { pln1= makePlain(0.0, 1.0, 0.0, imageWidth/2.0); pln1->m = makeMaterial(0.40,0.35,0.42,0.0, 0.7,1.0,1.0, 0.6, 0.0); printf("Plain %.1fx + %.1fy + %.1fz + %.1f = 0\n",pln1->A,pln1->B,pln1->C,pln1->D); sph0 = makeSphere(-2.5, -imageWidth/2.0+2.6, -6.0, 1.4); sph0->m = makeMaterial(1.0,1.0,1.0,0.0, 1.0,1.0,1.0, 0.95, 0.0 ); printf("Sphere at (%.2f,%.2f,%.2f) radius %.2f\n",sph0->c->x,sph0->c->y,sph0->c->z,sph0->r); sph2 = makeSphere(2.0, -imageWidth/2.0+0.6, -4.4, 0.65); sph2->m = makeMaterial(1.0,0.75,0.0,0.0, 0.25,1.0,1.0, 0.60, 0.0); printf("Sphere at (%.2f,%.2f,%.2f) radius %.2f\n",sph2->c->x,sph2->c->y,sph2->c->z,sph2->r); cyl0 = makeCylinder(0.0, -imageWidth/2.0+1.70, -4.3, 0.8, 0.35, 0.22); cyl0->m = makeMaterial(0.7,0.7,0.7,0.0, 0.2,1.0,1.0, 0.0,0.0); printf("Cylinder at (%.2f,%.2f,%.2f) a=%.2f, b=%.2f\n",cyl0->c->x,cyl0->c->y,cyl0->c->z,cyl0->a,cyl0->b); sph1 = makeSphere(0.0, -imageWidth/2.0+1.54, -3.40, 0.38); sph1->m = makeMaterial(0.75,0.2,0.15,0.3, 0.4,1.0,1.0, 0.0,0.0); printf("Sphere at (%.2f,%.2f,%.2f) radius %.2f\n",sph1->c->x,sph1->c->y,sph1->c->z,sph1->r); hyp0 = makeHyperbol(0.0, -imageWidth/2.0+0.59 , -4.0, 1.2, 0.25,0.34,0.25); hyp0->m = makeMaterial(1.0,0.8,0.2,0.0, 0.5,1.0,1.0, 0.4,0.0); printf("Hyperboloid at (%.2f,%.2f,%.2f) a=%.2f, b=%.2f, c=%.2f\n",hyp0->center->x,hyp0->center->y,hyp0->center->z,hyp0->a,hyp0->b,hyp0->c); }
TopoDS_Shape CreateEllipsoid::executeCreation() const { try { gp_Pnt pnt(axis.Location()); gp_Dir dir(axis.Direction()); gp_Ax2 ax2(pnt, dir); BRepPrimAPI_MakeSphere makeSphere(ax2, radius2, angle/180.0f*Standard_PI); float scale = radius1 / radius2; gp_Dir xDir = ax2.XDirection(); gp_Dir yDir = ax2.YDirection(); gp_GTrsf mat; mat.SetValue(1, 1, xDir.X()); mat.SetValue(2, 1, xDir.Y()); mat.SetValue(3, 1, xDir.Z()); mat.SetValue(1, 2, yDir.X()); mat.SetValue(2, 2, yDir.Y()); mat.SetValue(3, 2, yDir.Z()); mat.SetValue(1, 3, dir.X()*scale); mat.SetValue(2, 3, dir.Y()*scale); mat.SetValue(3, 3, dir.Z()*scale); BRepBuilderAPI_GTransform trs(makeSphere.Shape(), mat); return trs.Shape(); } catch(const StdFail_NotDone& ex) { throw Common::Exception(QObject::tr("Create ellipsoid error")); } }
void create3DObjects(void) { // Make Object Nodes NodeRefPtr ExampleTorusGeo = makeTorus(90, 270, 16, 16); NodeRefPtr ExampleConeGeo = makeCone(150, 50, 16, true, true); NodeRefPtr ExampleSphereGeo = makeSphere(4, 100); NodeRefPtr ExampleBoxGeo = makeBox(100, 100, 100, 1, 1, 1); // AssignTextures dynamic_cast<Geometry*>(ExampleConeGeo->getCore())->setMaterial(createBlueMaterial()); dynamic_cast<Geometry*>(ExampleSphereGeo->getCore())->setMaterial(createRedMaterial()); dynamic_cast<Geometry*>(ExampleBoxGeo->getCore())->setMaterial(createGreenMaterial()); // Preform transformations on them Matrix mat; // On Torus mat.setTranslate(0.0,100.0,-200.0); TransformRefPtr TorusTranCore = Transform::create(); TorusTranCore->setMatrix(mat); ExampleTorus = Node::create(); ExampleTorus->setCore(TorusTranCore); ExampleTorus->addChild(ExampleTorusGeo); // On Sphere mat.setTranslate(250.0,0.0,0.0); TransformRefPtr SphereTranCore = Transform::create(); SphereTranCore->setMatrix(mat); ExampleSphere = Node::create(); ExampleSphere->setCore(SphereTranCore); ExampleSphere->addChild(ExampleSphereGeo); // On Cone mat.setTranslate(0.0,0.0,-250.0); TransformRefPtr ConeTranCore = Transform::create(); ConeTranCore->setMatrix(mat); ExampleCone = Node::create(); ExampleCone->setCore(ConeTranCore); ExampleCone->addChild(ExampleConeGeo); // On Box mat.setTranslate(250.0,250.0,0.0); TransformRefPtr ExampleBoxTranCore = Transform::create(); ExampleBoxTranCore->setMatrix(mat); ExampleBox = Node::create(); ExampleBox->setCore(ExampleBoxTranCore); ExampleBox->addChild(ExampleBoxGeo); }
static NodePtr makePerturbedUniform (UInt16 numSubdiv, Real32 radius, Real32 rate = 0.1f) { static Real32 factor = 1.1f; NodePtr sphereNode = makeSphere(numSubdiv, radius); GeometryPtr sphere = GeometryPtr::dcast(sphereNode->getCore()); GeoPositionsPtr points = sphere->getPositions(); beginEditCP(points); for (UInt32 i=0; i<points->size(); ++i) { Real32 random = (rand()/Real32(RAND_MAX)); if (random <= rate) { points->setValue(factor*points->getValue(i), i); } } endEditCP(points); NodePtr node = Node::create(); beginEditCP(node); node->setCore(Transform::create()); node->addChild(sphereNode); endEditCP(node); return node; }
void Munition::init() { _physics.setPosition(3,1.01,-3); _physics.setAngularVelocity(1000); _physics.setLinearVelocity(25); makeSphere(); makeMunitionModel(); makeMaterial(); }
virtual void started(const DialogEventPtr e) { if(DialogPtr::dcast(e->getSource()) == BDialogChildB) { NodePtr s = makeSphere(1,2); beginEditCP(scene, Node::ChildrenFieldMask); while(scene->getNChildren() > 0) { scene->subChild(scene->getNChildren()-1); } scene->addChild(s); endEditCP(scene, Node::ChildrenFieldMask); } if(DialogPtr::dcast(e->getSource()) == BDialogChildA) { NodePtr s = makeBox(3,3,3,2,2,2); beginEditCP(scene, Node::ChildrenFieldMask); while(scene->getNChildren() > 0) { scene->subChild(scene->getNChildren()-1); } scene->addChild(s); endEditCP(scene, Node::ChildrenFieldMask); } if(DialogPtr::dcast(e->getSource()) == ADialogChildA) { beginEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask); MainInternalWindowBackground->setColor(Color4f(0.0,0.0,1.0,0.5)); endEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask); } if(DialogPtr::dcast(e->getSource()) == ADialogChildB) { beginEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask); MainInternalWindowBackground->setColor(Color4f(1.0,0.0,0.0,0.5)); endEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask); } if(DialogPtr::dcast(e->getSource()) == End1 || DialogPtr::dcast(e->getSource()) == End2 || DialogPtr::dcast(e->getSource()) == End3 || DialogPtr::dcast(e->getSource()) == End4 ) { TutorialWindowEventProducer->closeWindow(); } if(DialogPtr::dcast(e->getSource()) == Restart1 || DialogPtr::dcast(e->getSource()) == Restart2 || DialogPtr::dcast(e->getSource()) == Restart3 || DialogPtr::dcast(e->getSource()) == Restart4) { beginEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask); MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5)); endEditCP(MainInternalWindowBackground, ColorLayer::ColorFieldMask); NodePtr s = makeTorus(.5, 2, 16, 16); beginEditCP(scene, Node::ChildrenFieldMask); while(scene->getNChildren() > 0) { scene->subChild(scene->getNChildren()-1); } scene->addChild(s); endEditCP(scene, Node::ChildrenFieldMask); } }
static void initSphere() { int ibLen, vbLen; getSphereVbIbLen(20, 10, vbLen, ibLen); // Temporary storage for sphere Geometry vector<VertexPNTBX> vtx(vbLen); vector<unsigned short> idx(ibLen); makeSphere(1, 20, 10, vtx.begin(), idx.begin()); g_sphere.reset(new SimpleIndexedGeometryPNTBX(&vtx[0], &idx[0], vtx.size(), idx.size())); }
////////////////////////////////////////////////////////////////////////// //! build a sphere ////////////////////////////////////////////////////////////////////////// void buildSphere(void) { Real32 Radius(frand()*1.5+0.2); Matrix m; //create OpenSG mesh GeometryPtr sphere; NodePtr sphereNode = makeSphere(2, Radius); sphere = GeometryPtr::dcast(sphereNode->getCore()); SimpleMaterialPtr sphere_mat = SimpleMaterial::create(); beginEditCP(sphere_mat); sphere_mat->setAmbient(Color3f(0.0,0.0,0.0)); sphere_mat->setDiffuse(Color3f(0.0,0.0,1.0)); endEditCP(sphere_mat); beginEditCP(sphere, Geometry::MaterialFieldMask); sphere->setMaterial(sphere_mat); endEditCP(sphere); TransformPtr sphereTrans; NodePtr sphereTransNode = makeCoredNode<Transform>(&sphereTrans); m.setIdentity(); Real32 randX = frand()*10.0-5.0; Real32 randY = frand()*10.0-5.0; m.setTranslate(randX, randY, 10.0); beginEditCP(sphereTrans, Transform::MatrixFieldMask); sphereTrans->setMatrix(m); endEditCP(sphereTrans); //create ODE data PhysicsBodyPtr sphereBody = PhysicsBody::create(physicsWorld); beginEditCP(sphereBody, PhysicsBody::PositionFieldMask | PhysicsBody::AngularDampingFieldMask); sphereBody->setPosition(Vec3f(randX, randY, 10.0)); sphereBody->setAngularDamping(0.0001); endEditCP(sphereBody, PhysicsBody::PositionFieldMask | PhysicsBody::AngularDampingFieldMask); sphereBody->setSphereMass(0.4,Radius); PhysicsSphereGeomPtr sphereGeom = PhysicsSphereGeom::create(); beginEditCP(sphereGeom, PhysicsSphereGeom::BodyFieldMask | PhysicsSphereGeom::SpaceFieldMask | PhysicsSphereGeom::RadiusFieldMask | PhysicsSphereGeom::CategoryBitsFieldMask); sphereGeom->setBody(sphereBody); sphereGeom->setSpace(physicsSpace); sphereGeom->setRadius(Radius); sphereGeom->setCategoryBits(SphereCategory); endEditCP(sphereGeom, PhysicsSphereGeom::BodyFieldMask | PhysicsSphereGeom::SpaceFieldMask | PhysicsSphereGeom::RadiusFieldMask | PhysicsSphereGeom::CategoryBitsFieldMask); //add attachments beginEditCP(sphereNode, Node::AttachmentsFieldMask); sphereNode->addAttachment(sphereGeom); endEditCP(sphereNode); beginEditCP(sphereTransNode, Node::AttachmentsFieldMask | Node::ChildrenFieldMask); sphereTransNode->addAttachment(sphereBody); sphereTransNode->addChild(sphereNode); endEditCP(sphereTransNode); //add to SceneGraph beginEditCP(spaceGroupNode, Node::ChildrenFieldMask); spaceGroupNode->addChild(sphereTransNode); endEditCP(spaceGroupNode); }
int main() { float c[] = { 23, 45, 67}; float r = 32; Sphere ball = makeSphere(c, r); //creates an instance of sphere from the return value of makeSphere printf("center %f %f %f radius %f", ball.center[0], ball.center[1], ball.center[2], ball.radius); return 0; }
vector<Particle::id_t> DemFuncs::SpherePack_toSimulation_fast(const shared_ptr<SpherePack>& sp, const Scene* scene, const DemField* dem, const shared_ptr<Material>& mat, int mask, Real color){ vector<Particle::id_t> ret; ret.reserve(sp->pack.size()); if(sp->cellSize!=Vector3r::Zero()) throw std::runtime_error("PBC not supported."); for(const auto& s: sp->pack){ if(s.clumpId>=0) throw std::runtime_error("Clumps not supported."); shared_ptr<Particle> p=makeSphere(s.r,mat); p->shape->nodes[0]->pos=s.c; p->shape->color=(!isnan(color)?color:Mathr::UnitRandom()); p->mask=mask; ret.push_back(dem->particles->insert(p)); } return ret; }
TopoDS_Shape CreateSphere::executeCreation() const { try { gp_Ax2 ax2(axis.Location(), axis.Direction()); BRepPrimAPI_MakeSphere makeSphere(ax2, radius, angle/180.0f*Standard_PI); return makeSphere.Shape(); } catch(const StdFail_NotDone& ex) { throw Common::Exception(QObject::tr("Create sphere error")); } }
void Tetrahedron::initVBO(int threadId) { glm::dvec3 makeOriginAsCentroid (0.0, -0.1875, 0.05); // looks messy, I know // modifies the cylinder and sphere GPUMeshes //-------------------first cylinder------------------------- pointA = -makeOriginAsCentroid + glm::dvec3(0.2, -0.3, 0.2)*1.25; //a pointB = -makeOriginAsCentroid + glm::dvec3(-0.2, -0.3, 0.2)*1.25; //b pointC = -makeOriginAsCentroid + glm::dvec3(0.0, -0.3, -0.2)*1.25; //c pointD = -makeOriginAsCentroid + glm::dvec3(0.0, 0.15, 0.0)*1.25; //d makeCylinder(pointA, pointB); //-------------------second cylinder------------------------- makeCylinder(pointA, pointC); //-------------------third cylinder------------------------- makeCylinder(pointB, pointC); //-------------------fourth cylinder------------------------- makeCylinder(pointA, pointD); //-------------------fifth cylinder------------------------- makeCylinder(pointB, pointD); //-------------------sixth cylinder------------------------- makeCylinder(pointC, pointD); //-------------------alignment guide cylinder------------------------- makeCylinder(glm::dvec3(-guideCylinderLength, 0.0, 0.0), glm::dvec3(guideCylinderLength, 0.0, 0.0), guideCylinderRadius); // centered at origin //initialize cylinderMesh Object after all the cylinder points are push into mesh cylinderMesh.reset(new GPUMesh(GL_STATIC_DRAW, sizeof(GPUMesh::Vertex)*cylinderData.size(), sizeof(int)*cylinderIndices.size(), 0, cylinderData,sizeof(int)*cylinderIndices.size(), &cylinderIndices[0])); //make one sphere then translate it glm::dvec3 center = glm::dvec3(0.0,0.0,0.0); makeSphere(center); //initialize sphereMesh Object after all the sphere points are push into mesh sphereMesh.reset(new GPUMesh(GL_STATIC_DRAW, sizeof(GPUMesh::Vertex)*sphereData.size(), sizeof(int)*sphereIndices.size(), 0, sphereData,sizeof(int)*sphereIndices.size(), &sphereIndices[0])); }
////////////////////////////////////////////////////////////////////////// //! build a sphere ////////////////////////////////////////////////////////////////////////// void buildSphere(void) { Real32 Radius((Real32)(rand()%2)*0.5+0.5); Matrix m; //create OpenSG mesh GeometryRefPtr sphere; NodeRefPtr sphereNode = makeSphere(2, Radius); sphere = dynamic_cast<Geometry*>(sphereNode->getCore()); SimpleMaterialRefPtr sphere_mat = SimpleMaterial::create(); sphere_mat->setAmbient(Color3f(0.0,0.0,0.0)); sphere_mat->setDiffuse(Color3f(0.0,0.0,1.0)); sphere->setMaterial(sphere_mat); TransformRefPtr sphereTrans; NodeRefPtr sphereTransNode = makeCoredNode<Transform>(&sphereTrans); m.setIdentity(); Real32 randX = (Real32)(rand()%10)-5.0; Real32 randY = (Real32)(rand()%10)-5.0; m.setTranslate(randX, randY, 10.0); sphereTrans->setMatrix(m); //create ODE data PhysicsBodyRefPtr sphereBody = PhysicsBody::create(physicsWorld); sphereBody->setPosition(Vec3f(randX, randY, 10.0)); sphereBody->setAngularDamping(0.0001); sphereBody->setSphereMass(1.0,Radius); PhysicsSphereGeomRefPtr sphereGeom = PhysicsSphereGeom::create(); sphereGeom->setBody(sphereBody); sphereGeom->setSpace(physicsSpace); sphereGeom->setRadius(Radius); //add attachments sphereNode->addAttachment(sphereGeom); sphereTransNode->addAttachment(sphereBody); sphereTransNode->addChild(sphereNode); //add to SceneGraph spaceGroupNode->addChild(sphereTransNode); commitChanges(); }
ShellRenderer::ShellRenderer() : sphere(makeSphere((size_t) gameSystem->getFloat("shellDensity"))) { // set up vertex buffers glGenBuffers(1, &(vertexBuffers["vertices"])); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffers["vertices"]); GLfloat* vertDataBufferArray = new GLfloat[sphere.faceGroups[""].size() * 30]; // 3 vertices + 3 normals + 4 colors * 3 faces // insert the vertex attribute data for(size_t i = 0; i < sphere.faceGroups[""].size(); ++i) { for(size_t p = 0; p < 3; ++p) { vertDataBufferArray[i * 30 + p * 10 + 0] = sphere.vertices[sphere.faceGroups[""][i].vertices[p]].x; vertDataBufferArray[i * 30 + p * 10 + 1] = sphere.vertices[sphere.faceGroups[""][i].vertices[p]].y; vertDataBufferArray[i * 30 + p * 10 + 2] = sphere.vertices[sphere.faceGroups[""][i].vertices[p]].z; vertDataBufferArray[i * 30 + p * 10 + 3] = sphere.vertices[sphere.faceGroups[""][i].normals[p]].x; vertDataBufferArray[i * 30 + p * 10 + 4] = sphere.vertices[sphere.faceGroups[""][i].normals[p]].y; vertDataBufferArray[i * 30 + p * 10 + 5] = sphere.vertices[sphere.faceGroups[""][i].normals[p]].z; vertDataBufferArray[i * 30 + p * 10 + 6] = 1.0f; vertDataBufferArray[i * 30 + p * 10 + 7] = 1.0f; vertDataBufferArray[i * 30 + p * 10 + 8] = 1.0f; vertDataBufferArray[i * 30 + p * 10 + 9] = 1.0f; } } glBufferData(GL_ARRAY_BUFFER, sphere.faceGroups[""].size() * 30 * sizeof(GLfloat), vertDataBufferArray, GL_STATIC_DRAW); delete[] vertDataBufferArray; glGenBuffers(1, &(vertexBuffers["elements"])); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexBuffers["elements"]); GLuint* vertElementBufferArray = new GLuint[sphere.faceGroups[""].size() * 3]; for(size_t i = 0; i < sphere.faceGroups[""].size() * 3; ++i) { vertElementBufferArray[i] = i; } glBufferData(GL_ELEMENT_ARRAY_BUFFER, sphere.faceGroups[""].size() * 3 * sizeof(GLuint), vertElementBufferArray, GL_STATIC_DRAW); delete[] vertElementBufferArray; }
NodeTransitPtr createSphere(void) { // Make Object Nodes NodeRecPtr ExampleSphereGeo = makeSphere(4, 100); MaterialRecPtr RedMaterial = createMaterial(Color4f(1.0f,0.0f,0.0f,1.0f)); dynamic_cast<Geometry*>(ExampleSphereGeo->getCore())->setMaterial(RedMaterial); Matrix mat; mat.setTranslate(250.0,0.0,0.0); TransformRecPtr SphereTranCore = Transform::create(); SphereTranCore->setMatrix(mat); NodeRecPtr ExampleSphere = Node::create(); ExampleSphere->setCore(SphereTranCore); ExampleSphere->addChild(ExampleSphereGeo); ExampleSphere->setTravMask(0); return NodeTransitPtr(ExampleSphere); }
static NodePtr makePerturbedAll (UInt16 numSubdiv, Real32 radius, Real32 stdDeviation = 0.1f) { NodePtr sphereNode = makeSphere(numSubdiv, radius); GeometryPtr sphere = GeometryPtr::dcast(sphereNode->getCore()); GeoPositionsPtr points = sphere->getPositions(); beginEditCP(points); for (UInt32 i=0; i<points->size(); ++i) { Real32 factor = 1.0f + stdDeviation * (rand()/Real32(RAND_MAX) - 0.5f); points->setValue(factor*points->getValue(i), i); } endEditCP(points); NodePtr node = Node::create(); beginEditCP(node); node->setCore(Transform::create()); node->addChild(sphereNode); endEditCP(node); return node; }
NodePtr createScenegraph(){ SimpleMaterialPtr simpleMaterial = SimpleMaterial::create(); beginEditCP (simpleMaterial, SimpleMaterial::DiffuseFieldMask | SimpleMaterial::AmbientFieldMask | SimpleMaterial::TransparencyFieldMask); simpleMaterial->setDiffuse(Color3f(1,0,0)); simpleMaterial->setAmbient(Color3f(0.2, 0.2, 0.2)); simpleMaterial->setTransparency(0.5); endEditCP (simpleMaterial, SimpleMaterial::DiffuseFieldMask | SimpleMaterial::AmbientFieldMask | SimpleMaterial::TransparencyFieldMask); NodePtr simpleMaterialNode = Node::create(); NodePtr sphere = makeSphere(2,6); MaterialGroupPtr mg = MaterialGroup::create(); beginEditCP(mg); mg->setMaterial(simpleMaterial); endEditCP(mg); beginEditCP(simpleMaterialNode); simpleMaterialNode->setCore(mg); simpleMaterialNode->addChild(sphere); endEditCP(simpleMaterialNode); NodePtr root = Node::create(); beginEditCP(root); root->setCore(Group::create()); root->addChild(simpleMaterialNode); endEditCP(root); return root; }
virtual void segmentActivated(const CaptionEventPtr e) { if(segUpdate == 6) { NodePtr s = makeSphere(1,2); beginEditCP(scene, Node::ChildrenFieldMask); while(scene->getNChildren() > 0) { scene->subChild(scene->getNChildren()-1); } scene->addChild(s); endEditCP(scene, Node::ChildrenFieldMask); } if(segUpdate == 9) { NodePtr s = makeBox(3,3,3,2,2,2); beginEditCP(scene, Node::ChildrenFieldMask); while(scene->getNChildren() > 0) { scene->subChild(scene->getNChildren()-1); } scene->addChild(s); endEditCP(scene, Node::ChildrenFieldMask); } if(segUpdate == 11) { beginEditCP(scene, Node::ChildrenFieldMask); while(scene->getNChildren() > 0) { scene->subChild(scene->getNChildren()-1); } endEditCP(scene, Node::ChildrenFieldMask); } ++segUpdate; std::cout<<"Segment Activated"<<std::endl; }
// main function int main() { // REFACTOR TO BELOW FUNCTION //=========================== // // create variable of type Sphere with name 'ball' // Sphere ball; // // // set values within typedef struct // // place center of sphere in 3D space // // access fields with '.' // ball.center[0] = 24; // ball.center[1] = 32; // ball.center[2] = 45; // // ball.radius = 67; float c[] = { 23, 45, 67 }; float r = 32; Sphere ball = makeSphere(c, r); printf("center %f %f %f radius %f\n", ball.center[0], ball.center[1], ball.center[2], ball.radius); return 0; }
/* * Analyze spherical points in the given object and convert them to vectors and * normals for faster drawing */ int VertBufManager::analyzeSpheres(Iobj *obj, int obNum, float zscale, int xybin, float scrnScale, int quality, int fillType, int useFillColor, int thickenCont, int checkTime) { RGBTmap colors; pair<RGBTmap::iterator,bool> mapret; RGBTmap::iterator mapit; RGBTindices rInd; DrawProps defProps, contProps; b3dUInt32 contRGBT; VertBufData *vbd = obj->vertBufSphere; Icont *cont; int handleFlags, nonVboFlags = 0, numRemnant, fullState, skip, numVerts, co, pt; int colorType, cumFanInd, cumQuadInd, surfState, contState, stepRes; float drawsize; int numDefSphVert, numDefSphQuad, numDefSphFan, numTriples,indVert, indQuad, indFan; int indQuadDef, indFanDef, irem, match; if (fillType > 0) handleFlags = (useFillColor ? CHANGED_FCOLOR : CHANGED_COLOR) | CHANGED_TRANS; else { handleFlags = CHANGED_COLOR | CHANGED_TRANS; nonVboFlags = CHANGED_3DWIDTH; } colorType = useFillColor ? GEN_STORE_FCOLOR : GEN_STORE_COLOR; istoreDefaultDrawProps(obj, &defProps); // Check if there is a current VBO and it is all still valid // TODO: handle finegrain AND size changes //packRGBT(defProps, useFillColor, contRGBT); if (vbd && vbd->vbObj && fillType == vbd->fillType && vbd->useFillColor == useFillColor && quality == vbd->quality && obj->pdrawsize == vbd->pdrawsize && checkTime == vbd->checkTime && fabs((double)(scrnScale - vbd->scrnScale)) < 1.e-4 && fabs((double)(zscale - vbd->zscale)) < 1.e-4 && (fillType != 0 || thickenCont == vbd->thickenCont)) { match = 1; if (fillType == 0 && thickenCont) match = checkSelectedAreRemnants(vbd, obNum); if (match && !Imodv->standalone && obNum == Imodv->imod->cindex.object && vbd->checksum != imodObjectChecksum(obj, obNum)) match = 0; if (match) return -1; } numRemnant = 0; cumQuadInd = 0; cumFanInd = 0; numVerts = 0; for (co = 0; co < obj->contsize; co++) { cont = &obj->cont[co]; setOrClearFlags(&cont->flags, ICONT_TEMPUSE, 0); if (!imodvCheckContourDraw(cont, co, checkTime)) continue; fullState = istoreContSurfDrawProps(obj->store, &defProps, &contProps, co, cont->surf, &contState, &surfState); // Skip a gap without counting it; count one to be excluded or that can't be handled if (contProps.gap) continue; skip = 0; if ((fullState & nonVboFlags) || (thickenCont && imodvCheckThickerContour(co))) skip = 1; // Check for point changes that would need to be handled if (!skip && cont->store) { if (istoreCountItems(cont->store, colorType, 1) || istoreCountItems(cont->store, GEN_STORE_TRANS, 1)) skip = 1; if (!skip && fillType <= 0 && istoreCountItems(cont->store, GEN_STORE_3DWIDTH, 1)) skip = 1; } if (skip) { setOrClearFlags(&cont->flags, ICONT_TEMPUSE, 1); numRemnant++; continue; } // Loop on the points and determine number of vertices and indices needed for each // Since we don't skip point drawing, this doesn't need store changes checked rInd.numInds = 0; rInd.numFanInds = 0; for (pt = 0; pt < cont->psize; pt++) { // Only draw zero-size points with scattered point objects drawsize = imodPointGetSize(obj, cont, pt) / xybin; if (!iobjScat(obj->flags) && !drawsize) continue; stepRes = sphereResForSize(drawsize); numVerts += sphereCounts(2 * stepRes, stepRes, fillType, rInd.numInds, rInd.numFanInds); // For a special contour, add to list of RGBT values with the counts if it // is not on the list; if it is already on the list increment its count; if (fullState & handleFlags) { rInd.firstElement = co; packRGBT(&contProps, useFillColor, contRGBT); mapret = colors.insert(pair<b3dUInt32,RGBTindices>(contRGBT, rInd)); if (mapret.second == false) { mapret.first->second.numInds += rInd.numInds; mapret.first->second.numFanInds += rInd.numFanInds; } } else { cumQuadInd += rInd.numInds; cumFanInd += rInd.numFanInds; } } } if (!numVerts) { vbCleanupSphereVBD(obj); return 2; } // Get parameters for default sphere drawsize = obj->pdrawsize / xybin; stepRes = sphereResForSize(drawsize); numDefSphVert = sphereCounts(2 * stepRes, stepRes, fillType, numDefSphQuad, numDefSphFan); imodTrace('b', "numverts %d cumfan %d cumquad %d def vert %d quad %d fan %d rem %d", numVerts, cumFanInd, cumQuadInd, numDefSphVert,numDefSphQuad, numDefSphFan, numRemnant); vbd = allocateVBDIfNeeded(&obj->vertBufSphere); if (!vbd || drawsize < 0) { vbCleanupSphereVBD(obj); return 1; } vbd->numFanIndDefault = cumFanInd; vbd->numRemnant = numRemnant; // Now allocate whatever pieces are needed in VBD // Add up the special set sizes and re-initialize the counts to be starting indexes if (allocateSpecialSets(vbd, colors.size(), cumQuadInd, 1) || processMap(vbd, &colors, cumQuadInd, 1, cumFanInd)) { vbCleanupSphereVBD(obj); return 1; } vbd->fanIndStart = cumQuadInd; // Now allocate temps plus default sphere numTriples = (1 + (fillType > 0 ? 1 : 0)) * numVerts; if (allocateTempVerts(numTriples) || allocateTempInds(cumFanInd) || allocateDefaultSphere(numDefSphVert, numDefSphQuad + numDefSphFan, fillType)) { vbCleanupSphereVBD(obj); return 1; } if (genAndBindBuffers(vbd, numTriples, cumFanInd)) { vbCleanupSphereVBD(obj); return 1; } // Build the default sphere indVert = 0; indQuad = 0; indFan = numDefSphQuad; makeSphere(drawsize, 2 * stepRes, stepRes, mDefSphVerts, mDefSphInds, indVert, indQuad, indFan, fillType, 0., 0., 0.); imodTrace('b', "numtriples %d cumquad %d cumfan %d after def vert %d quad %d fan %d", numTriples, cumQuadInd, cumFanInd, indVert, indQuad, indFan); /*for (pt = 0; pt < indFan; pt++) { imodPrintStderr(" %d", mDefSphInds[pt]); if ((pt + 1) % 16 == 0 || pt == indFan - 1) imodPrintStderr("\n"); } */ // Set the identifiers of this vb data vbd->zscale = zscale; vbd->fillType = fillType; vbd->useFillColor = useFillColor; packRGBT(&defProps, useFillColor, vbd->defaultRGBT); vbd->checkTime = checkTime; vbd->scrnScale = scrnScale; vbd->quality = quality; vbd->pdrawsize = obj->pdrawsize; vbd->thickenCont = thickenCont; vbd->checksum = imodObjectChecksum(obj, obNum); // Process contours and points in them indVert = 0; indQuadDef = 0; indFanDef = cumQuadInd; irem = 0; for (co = 0; co < obj->contsize; co++) { cont = &obj->cont[co]; if (!imodvCheckContourDraw(cont, co, checkTime)) continue; fullState = istoreContSurfDrawProps(obj->store, &defProps, &contProps, co, cont->surf, &contState, &surfState); if (contProps.gap) continue; // Add marked contours to the remnant list if (cont->flags & ICONT_TEMPUSE) { setOrClearFlags(&cont->flags, ICONT_TEMPUSE, 0); vbd->remnantIndList[irem++] = co; continue; } // Set the starting indices for the contour's quads and fans if (fullState & handleFlags) { packRGBT(&contProps, useFillColor, contRGBT); mapit = colors.find(contRGBT); indQuad = mapit->second.numInds; indFan = mapit->second.numFanInds; } else { indQuad = indQuadDef; indFan = indFanDef; } // Loop on the points and make sohere or copy the default for (pt = 0; pt < cont->psize; pt++) { drawsize = imodPointGetSize(obj, cont, pt); if (!iobjScat(obj->flags) && !drawsize) continue; if (drawsize == obj->pdrawsize) { copyDefaultSphere(mDefSphVerts, mDefSphInds, numDefSphVert, numDefSphQuad, numDefSphFan, fillType, mVerts, mInds, indVert, indQuad, indFan, cont->pts[pt].x, cont->pts[pt].y, cont->pts[pt].z * zscale); } else { drawsize /= xybin; stepRes = sphereResForSize(drawsize); makeSphere(drawsize, 2 * stepRes, stepRes, mVerts, mInds, indVert, indQuad, indFan, fillType, cont->pts[pt].x, cont->pts[pt].y, cont->pts[pt].z * zscale); } } // Save the new indices back where they came from if (fullState & handleFlags) { mapit->second.numInds = indQuad; mapit->second.numFanInds = indFan; } else { indQuadDef = indQuad; indFanDef = indFan; } } imodTrace('b', "cumfan %d after load vert %d quad %d fan %d irem %d", cumFanInd, indVert, indQuad, indFan, irem); /* for (pt = 0; pt < cumFanInd; pt++) { imodPrintStderr(" %d", mInds[pt]); if ((pt + 1) % 16 == 0 || pt == cumFanInd - 1) imodPrintStderr("\n"); } */ // Transfer to GL b3dBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, cumFanInd * sizeof(GLuint), mInds); b3dBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); b3dBufferSubData(GL_ARRAY_BUFFER, 0, numTriples * 3 * sizeof(GLfloat), mVerts); b3dBindBuffer(GL_ARRAY_BUFFER, 0); return 0; }
gmi_model* MeshAdaptPUMIDrvr::createSphereInBox(double* boxDim,double*sphereCenter, double radius) { sphereRadius = radius; boxLength = boxDim[0]; boxWidth = boxDim[1]; boxHeight = boxDim[2]; xyz_offset[0] = sphereCenter[0]; xyz_offset[1] = sphereCenter[1]; xyz_offset[2] = sphereCenter[2]; lion_set_verbosity(1); //create the analytic model gmi_model* model = gmi_make_analytic(); //add the sphere makeSphere(model); //add the box makeBox(model); //apf::writeVtkFiles("initialInitial",m); setParameterization(model,m); m->verify(); //apf::Field* size_initial = apf::createLagrangeField(m,"size_initial",apf::SCALAR,1); size_iso = apf::createLagrangeField(m,"proteus_size",apf::SCALAR,1); apf::MeshIterator* it = m->begin(0); apf::MeshEntity* ent; while( (ent = m->iterate(it)) ) { apf::Vector3 pt; m->getPoint(ent,0,pt); if(sqrt( (pt[0]-xyz_offset[0])*(pt[0]-xyz_offset[0])+ (pt[1]-xyz_offset[1])*(pt[1]-xyz_offset[1]) + (pt[2]-xyz_offset[2])*(pt[2]-xyz_offset[2])) < sphereRadius*1.5) apf::setScalar(size_iso,ent,0,hmin); else apf::setScalar(size_iso,ent,0,hmax); } m->end(it); gradeMesh(); ma::Input* in = ma::configure(m,size_iso); in->maximumIterations = 10; in->shouldSnap = true; in->shouldTransferParametric = true; in->shouldFixShape = true; in->debugFolder="./debug_fine"; ma::adaptVerbose(in,false); m->verify(); //apf::writeVtkFiles("initialAdapt",m); freeField(size_iso); size_iso = apf::createLagrangeField(m,"proteus_size",apf::SCALAR,1); it = m->begin(0); while( (ent = m->iterate(it)) ) { apf::Vector3 pt; m->getPoint(ent,0,pt); if(sqrt( (pt[0]-xyz_offset[0])*(pt[0]-xyz_offset[0])+ (pt[1]-xyz_offset[1])*(pt[1]-xyz_offset[1]) + (pt[2]-xyz_offset[2])*(pt[2]-xyz_offset[2])) < sphereRadius*1.5) apf::setScalar(size_iso,ent,0,hmin); else apf::setScalar(size_iso,ent,0,hmax); } m->end(it); gradeMesh(); in = ma::configure(m,size_iso); in->maximumIterations = 10; in->shouldSnap = true; in->shouldTransferParametric = true; in->shouldFixShape = true; in->debugFolder="./debug_fine"; ma::adaptVerbose(in,false); m->verify(); //apf::writeVtkFiles("initialAdapt2",m); freeField(size_iso); return model; }
void makeDefaultShape (){ makeSphere(1, 32, 32); }
NodePtr createScenegraph(){ //create sun, planet & moon geometry GeometryPtr sun = makeSphereGeo(3, 6); NodePtr planet = makeSphere(3, 3); NodePtr moon = makeSphere(2,1); //the root node will be the sun NodePtr root = Node::create(); beginEditCP(root, Node::CoreFieldMask); root->setCore(sun); endEditCP(root, Node::CoreFieldMask); NodePtr planetTransformNode = Node::create(); NodePtr moonTransformNode = Node::create(); // these were declared globally planetTransform = Transform::create(); moonTransform = Transform::create(); // Now we need to fill it with live // We want to have the planet some distance away from the sun, // but initial with no rotation. The same aplies to the moon Matrix m,n; m.setIdentity(); n.setIdentity(); m.setTranslate(20,0,0); n.setTranslate(8,0,0); beginEditCP(planetTransform, Transform::MatrixFieldMask); planetTransform->setMatrix(m); endEditCP(planetTransform, Transform::MatrixFieldMask); beginEditCP(moonTransform, Transform::MatrixFieldMask); moonTransform->setMatrix(n); endEditCP(moonTransform, Transform::MatrixFieldMask); //Insert the cores into the apropiate nodes and add the geometry beginEditCP(planetTransformNode, Node::CoreFieldMask | Node::ChildrenFieldMask); planetTransformNode->setCore(planetTransform); planetTransformNode->addChild(planet); endEditCP(planetTransformNode, Node::CoreFieldMask | Node::ChildrenFieldMask); beginEditCP(moonTransformNode, Node::CoreFieldMask | Node::ChildrenFieldMask); moonTransformNode->setCore(moonTransform); moonTransformNode->addChild(moon); endEditCP(moonTransformNode, Node::CoreFieldMask | Node::ChildrenFieldMask); //add the planet to the sun beginEditCP(root, Node::ChildrenFieldMask); root->addChild(planetTransformNode); endEditCP(root, Node::ChildrenFieldMask); //add the moon to the planet beginEditCP(planet, Node::ChildrenFieldMask); planet->addChild(moonTransformNode); endEditCP(planet, Node::ChildrenFieldMask); //now we are done return root; }
NodeTransitPtr RotateManipulator::makeHandleGeo() { return makeSphere(2, 0.2f); }
int main(int argc, char **argv) { // OSG init osgInit(argc,argv); // Set up Window TutorialWindow = createNativeWindow(); TutorialWindow->initWindow(); TutorialWindow->setDisplayCallback(display); TutorialWindow->setReshapeCallback(reshape); TutorialKeyListener TheKeyListener; TutorialWindow->addKeyListener(&TheKeyListener); TutorialMouseListener TheTutorialMouseListener; TutorialMouseMotionListener TheTutorialMouseMotionListener; TutorialWindow->addMouseListener(&TheTutorialMouseListener); TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener); // Create the SimpleSceneManager helper mgr = new SimpleSceneManager; // Tell the Manager what to manage mgr->setWindow(TutorialWindow); //Particle System ParticleSystemRefPtr ExampleParticleSystem = OSG::ParticleSystem::create(); ExampleParticleSystem->attachUpdateListener(TutorialWindow); PointParticleSystemDrawerRefPtr ExamplePointParticleSystemDrawer = OSG::PointParticleSystemDrawer::create(); //NodeRefPtr ParticlePrototypeNode = makeTorus(1.0,4.0,16,16); //NodeRefPtr CollisionNode = makeBox(5.0,5.0,5.0,1,1,1);//makeSphere(4,10.0f); NodeRefPtr CollisionNode = makeSphere(2,4.0f); //Particle System Material PointChunkRefPtr PSPointChunk = PointChunk::create(); PSPointChunk->setSize(5.0f); PSPointChunk->setSmooth(true); BlendChunkRefPtr PSBlendChunk = BlendChunk::create(); PSBlendChunk->setSrcFactor(GL_SRC_ALPHA); PSBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA); MaterialChunkRefPtr PSMaterialChunkChunk = MaterialChunk::create(); PSMaterialChunkChunk->setAmbient(Color4f(1.0f,0.0f,0.0f,1.0f)); PSMaterialChunkChunk->setDiffuse(Color4f(1.0f,0.0f,0.0f,1.0f)); PSMaterialChunkChunk->setSpecular(Color4f(1.0f,0.0f,0.0f,1.0f)); PSMaterialChunkChunk->setColorMaterial(GL_NONE); //PSMaterialChunkChunk->setLit(false); ChunkMaterialRefPtr PSMaterial = ChunkMaterial::create(); PSMaterial->addChunk(PSPointChunk); PSMaterial->addChunk(PSMaterialChunkChunk); PSMaterial->addChunk(PSBlendChunk); ParticleSystemCoreRefPtr ParticleNodeCore = OSG::ParticleSystemCore::create(); ParticleNodeCore->setSystem(ExampleParticleSystem); ParticleNodeCore->setDrawer(ExamplePointParticleSystemDrawer); ParticleNodeCore->setMaterial(PSMaterial); NodeRefPtr ParticleNode = OSG::Node::create(); ParticleNode->setCore(ParticleNodeCore); //Generator //Attach the function objects to the Generator RateParticleGeneratorRefPtr ExampleGenerator= RateParticleGenerator::create(); ExampleGenerator->setPositionDistribution(createPositionDistribution()); ExampleGenerator->setLifespanDistribution(createLifespanDistribution()); ExampleGenerator->setGenerationRate(20.0); ExampleGenerator->setVelocityDistribution(createVelocityDistribution()); //Geometry Collision Affector GeometryCollisionParticleSystemAffectorRefPtr ExampleGeometryCollisionParticleSystemAffector = GeometryCollisionParticleSystemAffector::create(); ExampleGeometryCollisionParticleSystemAffector->setCollisionNode(CollisionNode); TutorialParticleCollisionListener TheCollisionListener; ExampleGeometryCollisionParticleSystemAffector->addParticleGeometryCollisionListener(&TheCollisionListener); ExampleParticleSystem->pushToSystemAffectors(ExampleGeometryCollisionParticleSystemAffector); ExampleParticleSystem->pushToGenerators(ExampleGenerator); // Make Main Scene Node and add the Torus NodeRefPtr scene = OSG::Node::create(); scene->setCore(OSG::Group::create()); scene->addChild(ParticleNode); scene->addChild(CollisionNode); mgr->setRoot(scene); // Show the whole Scene mgr->showAll(); //Open Window Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f); Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5); TutorialWindow->openWindow(WinPos, WinSize, "13CollisionGeometry"); //Enter main Loop TutorialWindow->mainLoop(); osgExit(); return 0; }
NodePtr createScenegraph(){ // the scene must be created here NodePtr n = makeSphere(2,2); return n; }
void Manipulator::onCreate(const Manipulator* source) { Inherited::onCreate(source); SimpleMaterialUnrecPtr pMat; // SimpleMaterial *simpleMat; Geometry *geo; setExternalUpdateHandler(NULL); // add a name attachment NameUnrecPtr nameN = Name::create(); nameN->editFieldPtr()->setValue("XManipulator"); addAttachment(nameN); // make the axis lines NodeUnrecPtr pNode = makeCoordAxis(getLength()[0], 2.0, false); setAxisLinesN(pNode); // make the red x-axis transform and handle pNode = Node::create(); setTransXNode(pNode); OSG::ComponentTransformUnrecPtr transHandleXC = ComponentTransform::create(); pNode = makeHandleGeo(); setHandleXNode(pNode); pMat = SimpleMaterial::create(); setMaterialX (pMat ); getTransXNode()->setCore (transHandleXC ); getTransXNode()->addChild(getHandleXNode()); transHandleXC->setTranslation(Vec3f(getLength()[0], 0, 0) ); transHandleXC->setRotation (Quaternion(Vec3f(0, 0, 1), osgDegree2Rad(-90))); pMat->setDiffuse(Color3f(1, 0, 0)); pMat->setLit (true ); geo = dynamic_cast<Geometry *>(getHandleXNode()->getCore()); geo->setMaterial(pMat); // // make the green y-axis transform and handle pNode = Node::create(); setTransYNode(pNode); OSG::ComponentTransformUnrecPtr transHandleYC = ComponentTransform::create(); pNode = makeHandleGeo(); setHandleYNode(pNode); pMat = SimpleMaterial::create(); setMaterialY(pMat); getTransYNode()->setCore (transHandleYC ); getTransYNode()->addChild(getHandleYNode()); transHandleYC->setTranslation(Vec3f(0, getLength()[1], 0) ); // transHandleYC->setRotation ( Quaternion(Vec3f(0, 0, 1), osgDegree2Rad(-90))); pMat->setDiffuse(Color3f(0, 1, 0)); pMat->setLit (true ); geo = dynamic_cast<Geometry *>(getHandleYNode()->getCore()); geo->setMaterial(pMat); // // make the blue z-axis transform and handle pNode = Node::create(); setTransZNode(pNode); OSG::ComponentTransformUnrecPtr transHandleZC = ComponentTransform::create(); pNode = makeHandleGeo(); setHandleZNode(pNode); pMat = SimpleMaterial::create(); setMaterialZ (pMat); getTransZNode()->setCore (transHandleZC ); getTransZNode()->addChild(getHandleZNode()); transHandleZC->setTranslation(Vec3f(0, 0, getLength()[2]) ); transHandleZC->setRotation (Quaternion(Vec3f(1, 0, 0), osgDegree2Rad(90))); pMat->setDiffuse(Color3f(0, 0, 1)); pMat->setLit (true ); geo = dynamic_cast<Geometry *>(getHandleZNode()->getCore()); geo->setMaterial(pMat); // // make the yellow pivot transform and handle pNode = Node::create(); setPivotNode(pNode); OSG::ComponentTransformUnrecPtr transHandlePivotC = ComponentTransform::create(); pNode = makeSphere(2, 0.05f); setHandlePNode(pNode); pMat = SimpleMaterial::create(); setMaterialPivot (pMat); getPivotNode()->setCore (transHandlePivotC ); getPivotNode()->addChild(getHandlePNode()); transHandlePivotC->setTranslation(Vec3f(0, 0, 0)); pMat->setDiffuse(Color3f(1, 1, 0)); pMat->setLit (true ); geo = dynamic_cast<Geometry *>(getHandlePNode()->getCore()); geo->setMaterial(pMat); if (!getEnablePivot()) { getPivotNode()->setTravMask(0x0); } commitChanges(); }
// The MAIN function, from here we start the application and run the game loop int main() { //////////////////////////////////////// BULLET /////////////////////////////////////////////////////////////////////////////////////////////////////////// // create the world parameters btBroadphaseInterface * broadphase = new btDbvtBroadphase(); btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration(); btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration); btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver; btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); dynamicsWorld->setGravity(btVector3(0., GRAVITY, 0)); // Set up the sides btRigidBody* sides [6]; sides[0] = makeSide(dynamicsWorld, btVector3(0, 1, 0), btVector3(0, 0, 0)); sides[1] = makeSide(dynamicsWorld, btVector3(1, 0, 0), btVector3(-20, 0, 0)); sides[2] = makeSide(dynamicsWorld, btVector3(-1, 0, 0), btVector3(20, 0, 0)); sides[3] = makeSide(dynamicsWorld, btVector3(0, -1, 0), btVector3(0, 40, 0)); sides[4] = makeSide(dynamicsWorld, btVector3(0, 0, -1), btVector3(0, 0, 20)); sides[5] = makeSide(dynamicsWorld, btVector3(0, 0, 1), btVector3(0, 0, -20)); btRigidBody* sphere1 = makeSphere(dynamicsWorld, 1, 1, btVector3(0, 40, 0)); btRigidBody* sphere2 = makeSphere(dynamicsWorld, 1, 1, btVector3(0, 40, 0)); btRigidBody* cube = makeSphere(dynamicsWorld, 1, 1, btVector3(0, 35, 0)); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // start glfw and glew with default settings bool test = start_gl(); assert(test); // Build and compile our shader program Shader sphereShader("shaders/shader.vs", "shaders/shader.frag"); Shader cubeShader("shaders/shader.vs", "shaders/lamp.frag"); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// GLuint container_VAO, container_VBO, container_EBO; GLfloat verts[] = { -0.5f, -0.5f, 0.5f, // A 0 -0.5f, -0.5f, -0.5f, // B 1 0.5f, -0.5f, -0.5f, // C 2 0.5f, -0.5f, 0.5f, // D 3 -0.5f, 0.5f, 0.5f, // E 4 -0.5f, 0.5f, -0.5f, // F 5 0.5f, 0.5f, -0.5f, // G 6 0.5f, 0.5f, 0.5f // H 7 }; GLuint idx[] = { 0, 1, 2, 3, 0, 4, 7, 3, 2, 6, 7, 6, 5, 4, 5, 1, 0, }; std::vector<GLfloat> container_verts = std::vector<GLfloat>(verts, verts + sizeof verts / sizeof verts[0]); std::vector<GLint> container_idx = std::vector<GLint>(idx, idx + sizeof idx / sizeof idx[0]); /////// Sphere vertices, normals and indices generation ////////////////////////////////////////// std::vector<GLfloat> sphere_verts; std::vector<GLint> sphere_idx; generateSphere( &sphere_verts, &sphere_idx, stacks, slices, radius); ///////////////// DECLARATIONS //////////////////////// GLuint sphere_VBO, sphere_VAO, sphere_EBO; ///////////////// GET VAO READY //////////////////////// GLuint aLoc[3] = {0, 1, 2}; GLint size[3] = {3, 3, 2}; GLsizei vStride[3] = {8 * sizeof(GLfloat), 8 * sizeof(GLfloat), 8 * sizeof(GLfloat)}; const void* vOffset[3] = {(GLvoid*)0, (GLvoid*)(3 * sizeof(GLfloat)), (GLvoid*)(6 * sizeof(GLfloat))}; prepareVAO(&sphere_VAO, &sphere_VBO, &sphere_EBO, sphere_verts, sphere_idx, 2, aLoc, size, vStride, vOffset); aLoc[0] = 0; size[0] = 3; vStride[0] = 3 * sizeof(GLfloat); vOffset[0] = (GLvoid*)0; prepareVAO(&container_VAO, &container_VBO, &container_EBO, container_verts, container_idx, 1, aLoc, size, vStride, vOffset); ///////////////// The positions for the spheres in q4 //////////////////////// // where the cubes will appear in the world space glm::vec3 cubePositions[] = { glm::vec3(1.5f, 0.0f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f) }; ///////////////// Uniform variables for MVP in VS //////////////////////// GLint modelLoc = glGetUniformLocation(sphereShader.Program, "model"); GLint viewLoc = glGetUniformLocation(sphereShader.Program, "view"); GLint projLoc = glGetUniformLocation(sphereShader.Program, "projection"); // uniforms for lighting GLint objectColorLoc = glGetUniformLocation(sphereShader.Program, "objectColor"); GLint lightColorLoc = glGetUniformLocation(sphereShader.Program, "lightColor"); GLint lightPosLoc = glGetUniformLocation(sphereShader.Program, "lightPos"); GLint viewPosLoc = glGetUniformLocation(sphereShader.Program, "viewPos"); ofstream myfile; myfile.open ("velocity.log"); btTransform trans; // Main loop while (!glfwWindowShouldClose(window)) { GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check if any events have been activated (key pressed, mouse moved) glfwPollEvents(); do_movement(); // Clear the color buffer glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); drawSphere(&cubeShader, &container_VAO, &sphereShader, &sphere_VAO, (GLint)sphere_idx.size(), 17, &objectColorLoc, &lightColorLoc, &lightPosLoc, &viewPosLoc, 2, cubePositions, &modelLoc, &viewLoc, &projLoc, dynamicsWorld, sphere1, sphere2, cube); sphere1->getMotionState()->getWorldTransform(trans); myfile << trans.getOrigin().getX() << " " << trans.getOrigin().getY() << " " << trans.getOrigin().getZ() << ":"; sphere2->getMotionState()->getWorldTransform(trans); myfile << trans.getOrigin().getX() << " " << trans.getOrigin().getY() << " " << trans.getOrigin().getZ() << ":"; cube->getMotionState()->getWorldTransform(trans); myfile << trans.getOrigin().getX() << " " << trans.getOrigin().getY() << " " << trans.getOrigin().getZ() << "\n"; // Swap the screen buffers glfwSwapBuffers(window); } // Deallocate glDeleteVertexArrays(1, &sphere_VAO); glDeleteBuffers(1, &sphere_VBO); glDeleteBuffers(1, &sphere_EBO); // Terminate GLFW glfwDestroyWindow(window); glfwTerminate(); myfile.close(); for(int i=0; i<6; i++){ dynamicsWorld->removeRigidBody(sides[i]); delete sides[i]->getMotionState(); delete sides[i]; } delete dynamicsWorld; delete solver; delete dispatcher; delete collisionConfiguration; delete broadphase; return EXIT_SUCCESS; }
// Initialize WIN32 & OpenSG and set up the scene int main(int argc, char **argv) { // OSG init osgInit(argc,argv); { // Set up Window WindowEventProducerRecPtr TutorialWindow = createNativeWindow(); TutorialWindow->initWindow(); // Create the SimpleSceneManager helper SimpleSceneManager sceneManager; TutorialWindow->setDisplayCallback(boost::bind(display, &sceneManager)); TutorialWindow->setReshapeCallback(boost::bind(reshape, _1, &sceneManager)); // Tell the Manager what to manage sceneManager.setWindow(TutorialWindow); //Attach to events TutorialWindow->connectMousePressed(boost::bind(mousePressed, _1, &sceneManager)); TutorialWindow->connectMouseReleased(boost::bind(mouseReleased, _1, &sceneManager)); TutorialWindow->connectMouseDragged(boost::bind(mouseDragged, _1, &sceneManager)); TutorialWindow->connectMouseWheelMoved(boost::bind(mouseWheelMoved, _1, &sceneManager)); //Sound Emitter Node SoundEmitterRecPtr TheEmitter = SoundEmitter::create(); TheEmitter->attachUpdateProducer(TutorialWindow); NodeUnrecPtr TheEmitterNode = Node::create(); TheEmitterNode->setCore(TheEmitter); //Sphere Transformation Node Matrix Translate; Translate.setTranslate(0.0,0.0,-5.0); Matrix Rotation; Rotation.setRotate(Quaternion(Vec3f(0.0,1.0,0.0), 0.0)); Matrix Total(Translate); Total.mult(Rotation); TransformRecPtr TheSphereTransform = Transform::create(); TheSphereTransform->setMatrix(Total); NodeUnrecPtr SphereTransformNode = Node::create(); SphereTransformNode->setCore(TheSphereTransform); SphereTransformNode->addChild(makeSphere(2, 1.0)); SphereTransformNode->addChild(TheEmitterNode); // create the scene NodeUnrecPtr scene = Node::create(); scene->setCore(Group::create()); scene->addChild(SphereTransformNode); // tell the manager what to manage sceneManager.setRoot (scene); CameraUnrecPtr TheCamera = sceneManager.getCamera(); TheCamera->setNear(0.1); TheCamera->setFar(100.0); //Initialize the Sound Manager SoundManager::the()->attachUpdateProducer(TutorialWindow); SoundManager::the()->setCamera(sceneManager.getCamera()); SoundRecPtr PopSound = SoundManager::the()->createSound(); PopSound->setFile(BoostPath("./Data/pop.wav")); PopSound->setVolume(1.0); PopSound->setStreaming(false); PopSound->setLooping(-1); PopSound->setEnable3D(true); PopSound->connectSoundPlayed (boost::bind(handleSoundPlayed, _1)); PopSound->connectSoundStopped (boost::bind(handleSoundStopped, _1)); PopSound->connectSoundPaused (boost::bind(handleSoundPaused, _1)); PopSound->connectSoundUnpaused(boost::bind(handleSoundUnpaused, _1)); PopSound->connectSoundLooped (boost::bind(handleSoundLooped, _1)); //Attach this sound to the emitter node TheEmitter->setSound(PopSound); TutorialWindow->connectKeyTyped(boost::bind(keyTyped, _1, TheEmitter.get())); TutorialWindow->connectUpdate(boost::bind(handleUpdate, _1, TheSphereTransform.get())); //Create the Documentation SimpleScreenDoc TheSimpleScreenDoc(&sceneManager, TutorialWindow); Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f); Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5); TutorialWindow->openWindow(WinPos, WinSize, "02 Sound3D Window"); //Enter main loop TutorialWindow->mainLoop(); } osgExit(); return 0; }
int main(int argc, char **argv) { // OSG init osgInit(argc,argv); // Set up Window TutorialWindow = createNativeWindow(); TutorialWindow->initWindow(); TutorialWindow->setDisplayCallback(display); TutorialWindow->setReshapeCallback(reshape); TutorialKeyListener TheKeyListener; TutorialWindow->addKeyListener(&TheKeyListener); NodeRefPtr Root(NULL); if(argc == 2) { Root = SceneFileHandler::the()->read(argv[1]); } if(Root == NULL) { // Make Torus Node (creates Torus in background of Root) NodeRefPtr TorusGeometryNode = makeTorus(.5, 2, 16, 16); setName(TorusGeometryNode, std::string("Torus")); NodeRefPtr TorusNode = Node::create(); TorusNode->setCore(OSG::Transform::create()); TorusNode->addChild(TorusGeometryNode); setName(TorusNode, std::string("Torus Transform")); NodeRefPtr SphereGeometryNode = makeSphere(2,1.0f); setName(SphereGeometryNode, std::string("Sphere")); NodeRefPtr BoxGeometryNode = makeBox(1.0,1.0,1.0,1,1,1); setName(BoxGeometryNode, std::string("Box")); // Make Main Scene Node and add the Torus Root = OSG::Node::create(); Root->setCore(OSG::Group::create()); Root->addChild(TorusNode); Root->addChild(SphereGeometryNode); Root->addChild(BoxGeometryNode); setName(Root, std::string("Root")); } // Create the Graphics GraphicsRefPtr TutorialGraphics = OSG::Graphics2D::create(); // Initialize the LookAndFeelManager to enable default settings LookAndFeelManager::the()->getLookAndFeel()->init(); //Tree Model TheTreeModel = SceneGraphTreeModel::create(); TheTreeModel->setRoot(Root); //TheFileSystemTreeModel = FileSystemTreeModel::create(); //TheFileSystemTreeModel->setRoot(BoostPath("C:\\")); //TheFileSystemTreeModel->setRoot(BoostPath("/")); //Create the Tree TheTree = Tree::create(); TheTree->setPreferredSize(Vec2f(100, 500)); TheTree->setModel(TheTreeModel); //TheTree->setModel(TheFileSystemTreeModel); TutorialTreeSelectionListener TheTutorialTreeSelectionListener; TheTree->getSelectionModel()->addTreeSelectionListener(&TheTutorialTreeSelectionListener); // Create a ScrollPanel for easier viewing of the List (see 27ScrollPanel) BorderLayoutConstraintsRefPtr SceneTreeConstraints = OSG::BorderLayoutConstraints::create(); SceneTreeConstraints->setRegion(BorderLayoutConstraints::BORDER_WEST); ScrollPanelRefPtr ExampleScrollPanel = ScrollPanel::create(); ExampleScrollPanel->setPreferredSize(Vec2f(350,300)); ExampleScrollPanel->setConstraints(SceneTreeConstraints); //ExampleScrollPanel->setHorizontalResizePolicy(ScrollPanel::RESIZE_TO_VIEW); //ExampleScrollPanel->setVerticalResizePolicy(ScrollPanel::RESIZE_TO_VIEW); ExampleScrollPanel->setViewComponent(TheTree); //Details Panel Labels LabelRefPtr NodeNameLabel = Label::create(); NodeNameLabel->setText("Name"); NodeNameLabel->setPreferredSize(Vec2f(100.0f, 20.0f)); NodeNameValueLabel = Label::create(); NodeNameValueLabel->setPreferredSize(Vec2f(300.0f, 20.0f)); LabelRefPtr NodeCoreTypeLabel = Label::create(); NodeCoreTypeLabel->setText("Core Type"); NodeCoreTypeLabel->setPreferredSize(Vec2f(100.0f, 20.0f)); NodeCoreTypeValueLabel = Label::create(); NodeCoreTypeValueLabel->setPreferredSize(Vec2f(300.0f, 20.0f)); LabelRefPtr NodeMinLabel = Label::create(); NodeMinLabel->setText("Min"); NodeMinLabel->setPreferredSize(Vec2f(100.0f, 20.0f)); NodeMinValueLabel = Label::create(); NodeMinValueLabel->setPreferredSize(Vec2f(300.0f, 20.0f)); LabelRefPtr NodeMaxLabel = Label::create(); NodeMaxLabel->setText("Max"); NodeMaxLabel->setPreferredSize(Vec2f(100.0f, 20.0f)); NodeMaxValueLabel = Label::create(); NodeMaxValueLabel->setPreferredSize(Vec2f(300.0f, 20.0f)); LabelRefPtr NodeCenterLabel = Label::create(); NodeCenterLabel->setText("Center"); NodeCenterLabel->setPreferredSize(Vec2f(100.0f, 20.0f)); NodeCenterValueLabel = Label::create(); NodeCenterValueLabel->setPreferredSize(Vec2f(300.0f, 20.0f)); LabelRefPtr NodeTriCountLabel = Label::create(); NodeTriCountLabel->setText("TriCount"); NodeTriCountLabel->setPreferredSize(Vec2f(100.0f, 20.0f)); NodeTriCountValueLabel = Label::create(); NodeTriCountValueLabel->setPreferredSize(Vec2f(300.0f, 20.0f)); LabelRefPtr NodeTravMaskLabel = Label::create(); NodeTravMaskLabel->setText("Traversal Mask"); NodeTravMaskLabel->setPreferredSize(Vec2f(100.0f, 20.0f)); NodeTravMaskValueLabel = Label::create(); NodeTravMaskValueLabel->setPreferredSize(Vec2f(300.0f, 20.0f)); LabelRefPtr NodeOcclusionMaskLabel = Label::create(); NodeOcclusionMaskLabel->setText("Occlusion Mask"); NodeOcclusionMaskLabel->setPreferredSize(Vec2f(100.0f, 20.0f)); NodeOcclusionMaskValueLabel = Label::create(); NodeOcclusionMaskValueLabel->setPreferredSize(Vec2f(300.0f, 20.0f)); LabelRefPtr NodeActiveLabel = Label::create(); NodeActiveLabel->setText("Active"); NodeActiveLabel->setPreferredSize(Vec2f(100.0f, 20.0f)); NodeActiveValueLabel = Label::create(); NodeActiveValueLabel->setPreferredSize(Vec2f(300.0f, 20.0f)); //Details Panel BorderLayoutConstraintsRefPtr NodeDetailPanelConstraints = OSG::BorderLayoutConstraints::create(); NodeDetailPanelConstraints->setRegion(BorderLayoutConstraints::BORDER_SOUTH); GridLayoutRefPtr NodeDetailPanelLayout = OSG::GridLayout::create(); NodeDetailPanelLayout->setRows(9); NodeDetailPanelLayout->setColumns(2); NodeDetailPanelLayout->setHorizontalGap(2); NodeDetailPanelLayout->setVerticalGap(2); PanelRefPtr NodeDetailPanel = Panel::create(); NodeDetailPanel->setConstraints(NodeDetailPanelConstraints); NodeDetailPanel->setPreferredSize(Vec2f(100.0f, 200.0f)); NodeDetailPanel->setLayout(NodeDetailPanelLayout); NodeDetailPanel->pushToChildren(NodeNameLabel); NodeDetailPanel->pushToChildren(NodeNameValueLabel); NodeDetailPanel->pushToChildren(NodeCoreTypeLabel); NodeDetailPanel->pushToChildren(NodeCoreTypeValueLabel); NodeDetailPanel->pushToChildren(NodeMinLabel); NodeDetailPanel->pushToChildren(NodeMinValueLabel); NodeDetailPanel->pushToChildren(NodeMaxLabel); NodeDetailPanel->pushToChildren(NodeMaxValueLabel); NodeDetailPanel->pushToChildren(NodeCenterLabel); NodeDetailPanel->pushToChildren(NodeCenterValueLabel); NodeDetailPanel->pushToChildren(NodeTriCountLabel); NodeDetailPanel->pushToChildren(NodeTriCountValueLabel); NodeDetailPanel->pushToChildren(NodeTravMaskLabel); NodeDetailPanel->pushToChildren(NodeTravMaskValueLabel); NodeDetailPanel->pushToChildren(NodeOcclusionMaskLabel); NodeDetailPanel->pushToChildren(NodeOcclusionMaskValueLabel); NodeDetailPanel->pushToChildren(NodeActiveLabel); NodeDetailPanel->pushToChildren(NodeActiveValueLabel); // Create The Main InternalWindow // Create Background to be used with the Main InternalWindow ColorLayerRefPtr MainInternalWindowBackground = OSG::ColorLayer::create(); MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5)); LayoutRefPtr MainInternalWindowLayout = OSG::BorderLayout::create(); InternalWindowRefPtr MainInternalWindow = OSG::InternalWindow::create(); MainInternalWindow->pushToChildren(ExampleScrollPanel); MainInternalWindow->pushToChildren(NodeDetailPanel); MainInternalWindow->setLayout(MainInternalWindowLayout); MainInternalWindow->setBackgrounds(NULL); MainInternalWindow->setBorders(NULL); MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.0f,0.5f)); MainInternalWindow->setScalingInDrawingSurface(Vec2f(1.0,1.0)); MainInternalWindow->setDrawTitlebar(false); MainInternalWindow->setResizable(false); // Create the Drawing Surface UIDrawingSurfaceRefPtr TutorialDrawingSurface = UIDrawingSurface::create(); TutorialDrawingSurface->setGraphics(TutorialGraphics); TutorialDrawingSurface->setEventProducer(TutorialWindow); TutorialDrawingSurface->openWindow(MainInternalWindow); // Create the UI Foreground Object UIForegroundRefPtr TutorialUIForeground = OSG::UIForeground::create(); TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface); // Create the SimpleSceneManager helper mgr = new SimpleSceneManager; // Tell the Manager what to manage mgr->setWindow(TutorialWindow); mgr->setRoot(Root); // Add the UI Foreground Object to the Scene ViewportRefPtr TutorialViewport = mgr->getWindow()->getPort(0); TutorialViewport->addForeground(TutorialUIForeground); // Show the whole Scene mgr->showAll(); //Open Window Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f); Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5); TutorialWindow->openWindow(WinPos, WinSize, "52SceneGraphTree"); //Enter main Loop TutorialWindow->mainLoop(); osgExit(); return 0; }