void Import::LoadGeometries (dScene& scene, GeometryCache& meshCache, const MaterialCache& materialCache) { dScene::Iterator iter (scene); for (iter.Begin(); iter; iter ++) { dScene::dTreeNode* const geometryNode = iter.GetNode(); dNodeInfo* const info = scene.GetInfoFromNode(geometryNode); if (info->IsType(dGeometryNodeInfo::GetRttiType())) { if (info->GetTypeId() == dMeshNodeInfo::GetRttiType()) { // add the vertices //TriObject* const geometry = CreateNewTriObject(); TriObject* const geometry = (TriObject*) CreateInstance (GEOMOBJECT_CLASS_ID, Class_ID(TRIOBJ_CLASS_ID, 0)); meshCache.AddMesh(geometry, geometryNode); dMeshNodeInfo* const meshInfo = (dMeshNodeInfo*) scene.GetInfoFromNode(geometryNode); NewtonMesh* const mesh = meshInfo->GetMesh(); NewtonMeshTriangulate (mesh); int vertexCount = NewtonMeshGetVertexCount(mesh); int pointCount = NewtonMeshGetPointCount(mesh); //int triangleCount = NewtonMeshGetTotalFaceCount(mesh); int triangleCount = 0; for (void* face = NewtonMeshGetFirstFace(mesh); face; face = NewtonMeshGetNextFace(mesh, face)) { if (!NewtonMeshIsFaceOpen(mesh, face)) { triangleCount += NewtonMeshGetFaceIndexCount (mesh, face) - 2; } } Mesh& maxMesh = geometry->mesh; maxMesh.setNumVerts(vertexCount); maxMesh.setNumFaces(triangleCount); maxMesh.setNumTVerts(pointCount); maxMesh.setNumTVFaces(triangleCount); int vertexStride = NewtonMeshGetVertexStrideInByte(mesh) / sizeof (dFloat64); dFloat64* const vertex = NewtonMeshGetVertexArray (mesh); for (int j = 0; j < vertexCount; j ++) { Point3 vx (vertex[vertexStride * j + 0], vertex[vertexStride * j + 1], vertex[vertexStride * j + 2]); maxMesh.setVert(j, vx); } int pointStride = NewtonMeshGetPointStrideInByte(mesh) / sizeof (dFloat64); dFloat64* const points = NewtonMeshGetUV0Array(mesh); for (int j = 0; j < pointCount; j ++) { Point3 uv (dFloat(points[j * pointStride + 0]), dFloat(points[j * pointStride + 1]), 0.0f); maxMesh.setTVert(j, uv); } int faceIndex = 0; for (void* face = NewtonMeshGetFirstFace(mesh); face; face = NewtonMeshGetNextFace(mesh, face)) { if (!NewtonMeshIsFaceOpen(mesh, face)) { int vertexInices[256]; int pointIndices[256]; int indexCount = NewtonMeshGetFaceIndexCount (mesh, face); int matId = NewtonMeshGetFaceMaterial (mesh, face); MaterialProxi material; material.m_mtl = 0; material.m_matID = 0; MaterialCache::dTreeNode* const materialNode = materialCache.Find(matId); if (materialNode) { material = materialNode->GetInfo(); } NewtonMeshGetFaceIndices (mesh, face, vertexInices); NewtonMeshGetFacePointIndices (mesh, face, pointIndices); for (int i = 2; i < indexCount; i ++) { Face* f = &maxMesh.faces[faceIndex]; TVFace* t = &maxMesh.tvFace[faceIndex]; f->v[0] = vertexInices[0]; f->v[1] = vertexInices[i - 1]; f->v[2] = vertexInices[i]; f->setEdgeVis(0, 1); f->setEdgeVis(1, 1); f->setEdgeVis(2, 1); f->setSmGroup(0); //f->setMatID((MtlID)matID); f->setMatID(material.m_matID); t->t[0] = pointIndices[0]; t->t[1] = pointIndices[i - 1]; t->t[2] = pointIndices[i]; faceIndex ++; } } } SetSmoothingGroups (maxMesh); #if 0 if (geom->m_uv1) { int texChannel = 2; // maxMesh.setNumMaps (texChannel, TRUE); maxMesh.setMapSupport (texChannel); if (maxMesh.mapSupport(texChannel)) { maxMesh.setNumMapVerts (texChannel, triangleCount * 3); maxMesh.setNumMapFaces (texChannel, triangleCount); UVVert *tv = maxMesh.mapVerts(texChannel); faceIndex = 0; TVFace *tf = maxMesh.mapFaces(texChannel); for (segmentPtr = geom->GetFirst(); segmentPtr; segmentPtr = segmentPtr->GetNext()) { const dSubMesh& segment = segmentPtr->GetInfo(); int triangleCount = segment.m_indexCount / 3; for (k = 0; k < triangleCount; k ++) { for (int m = 0; m < 3; m ++) { int index = segment.m_indexes[k * 3 + m]; UVVert v (dFloat (geom->m_uv1[index * 2 + 0]), dFloat (geom->m_uv1[index * 2 + 1]), 0.0f); tv[faceIndex * 3 + m] = v; tf[faceIndex].t[m] = faceIndex * 3 + m; } faceIndex ++; } } } } #endif } else { _ASSERTE (0); } } } }
void CBattlegroundManager::EventQueueUpdate() { deque<Player*> tempPlayerVec[2]; uint32 i,j,k; Player * plr; CBattleground * bg; list<uint32>::iterator it3, it4; //vector<Player*>::iterator it6; map<uint32, CBattleground*>::iterator iitr; Arena * arena; int32 team; m_queueLock.Acquire(); m_instanceLock.Acquire(); for(i = 0; i < BATTLEGROUND_NUM_TYPES; ++i) { for(j = 0; j < MAX_LEVEL_GROUP; ++j) { if(!m_queuedPlayers[i][j].size()) continue; tempPlayerVec[0].clear(); tempPlayerVec[1].clear(); for(it3 = m_queuedPlayers[i][j].begin(); it3 != m_queuedPlayers[i][j].end();) { it4 = it3++; plr = objmgr.GetPlayer(*it4); if(!plr || GetLevelGrouping(plr->getLevel()) != j) { m_queuedPlayers[i][j].erase(it4); continue; } // queued to a specific instance id? if(plr->m_bgQueueInstanceId != 0) { iitr = m_instances[i].find(plr->m_bgQueueInstanceId); if(iitr == m_instances[i].end()) { // queue no longer valid plr->GetSession()->SystemMessage("Your queue on battleground instance id %u is no longer valid. Reason: Instance Deleted.", plr->m_bgQueueInstanceId); plr->m_bgIsQueued = false; plr->m_bgQueueType = 0; plr->m_bgQueueInstanceId = 0; m_queuedPlayers[i][j].erase(it4); } // can we join? bg = iitr->second; if(bg->CanPlayerJoin(plr)) { bg->AddPlayer(plr, plr->GetTeam()); m_queuedPlayers[i][j].erase(it4); } } else { if(IS_ARENA(i)) tempPlayerVec[0].push_back(plr); else tempPlayerVec[plr->GetTeam()].push_back(plr); } } // try to join existing instances for(iitr = m_instances[i].begin(); iitr != m_instances[i].end(); ++iitr) { if( iitr->second->HasEnded() ) continue; if(IS_ARENA(i)) { arena = ((Arena*)iitr->second); if(arena->Rated()) continue; team = arena->GetFreeTeam(); while(team >= 0 && tempPlayerVec[0].size()) { plr = *tempPlayerVec[0].begin(); tempPlayerVec[0].pop_front(); plr->m_bgTeam=team; arena->AddPlayer(plr, team); ErasePlayerFromList(plr->GetLowGUID(), &m_queuedPlayers[i][j]); team = arena->GetFreeTeam(); } } else { bg = iitr->second; for(k = 0; k < 2; ++k) { while(tempPlayerVec[k].size() && bg->HasFreeSlots(k)) { plr = *tempPlayerVec[k].begin(); tempPlayerVec[k].pop_front(); bg->AddPlayer(plr, plr->GetTeam()); ErasePlayerFromList(plr->GetLowGUID(), &m_queuedPlayers[i][j]); } } } } if(IS_ARENA(i)) { // enough players to start a round? if(tempPlayerVec[0].size() < BGMinimumPlayers[i]) continue; if(CanCreateInstance(i,j)) { arena = ((Arena*)CreateInstance(i, j)); if ( arena == NULL ) { m_queueLock.Release(); m_instanceLock.Release(); return; } team = arena->GetFreeTeam(); while(!arena->IsFull() && tempPlayerVec[0].size() && team >= 0) { plr = *tempPlayerVec[0].begin(); tempPlayerVec[0].pop_front(); arena->AddPlayer(plr, team); team = arena->GetFreeTeam(); // remove from the main queue (painful!) ErasePlayerFromList(plr->GetLowGUID(), &m_queuedPlayers[i][j]); } } } else { #ifdef ONLY_ONE_PERSON_REQUIRED_TO_JOIN_DEBUG if(tempPlayerVec[0].size() >= 1 || tempPlayerVec[1].size() >= 1) #else if(tempPlayerVec[0].size() >= BGMinimumPlayers[i] && tempPlayerVec[1].size() >= BGMinimumPlayers[i]) #endif { if(CanCreateInstance(i,j)) { bg = CreateInstance(i,j); //ASSERT(bg); if ( bg == NULL ) { m_queueLock.Release(); m_instanceLock.Release(); return; } // push as many as possible in for(k = 0; k < 2; ++k) { while(tempPlayerVec[k].size() && bg->HasFreeSlots(k)) { plr = *tempPlayerVec[k].begin(); tempPlayerVec[k].pop_front(); bg->AddPlayer(plr, k); ErasePlayerFromList(plr->GetLowGUID(), &m_queuedPlayers[i][j]); } } } } } } } /* Handle paired arena team joining */ Group * group1, *group2; uint32 n; list<uint32>::iterator itz; for(i = BATTLEGROUND_ARENA_2V2; i < BATTLEGROUND_ARENA_5V5+1; ++i) { for(;;) { if(m_queuedGroups[i].size() < 2) /* got enough to have an arena battle ;P */ { break; } group1 = group2 = NULL; while(group1 == NULL) { n = RandomUInt((uint32)m_queuedGroups[i].size()) - 1; for(itz = m_queuedGroups[i].begin(); itz != m_queuedGroups[i].end() && n>0; ++itz) --n; if(itz == m_queuedGroups[i].end()) itz=m_queuedGroups[i].begin(); if(itz == m_queuedGroups[i].end()) { Log.Error("BattlegroundMgr", "Internal error at %s:%u", __FILE__, __LINE__); m_queueLock.Release(); m_instanceLock.Release(); return; } group1 = objmgr.GetGroupById(*itz); m_queuedGroups[i].erase(itz); } while(group2 == NULL) { n = RandomUInt((uint32)m_queuedGroups[i].size()) - 1; for(itz = m_queuedGroups[i].begin(); itz != m_queuedGroups[i].end() && n>0; ++itz) --n; if(itz == m_queuedGroups[i].end()) itz=m_queuedGroups[i].begin(); if(itz == m_queuedGroups[i].end()) { Log.Error("BattlegroundMgr", "Internal error at %s:%u", __FILE__, __LINE__); m_queueLock.Release(); m_instanceLock.Release(); return; } group2 = objmgr.GetGroupById(*itz); m_queuedGroups[i].erase(itz); } Arena * ar = ((Arena*)CreateInstance(i,LEVEL_GROUP_70)); GroupMembersSet::iterator itx; ar->rated_match=true; for(itx = group1->GetSubGroup(0)->GetGroupMembersBegin(); itx != group1->GetSubGroup(0)->GetGroupMembersEnd(); ++itx) { if((*itx)->m_loggedInPlayer) { if( ar->HasFreeSlots(0) ) ar->AddPlayer((*itx)->m_loggedInPlayer, 0); } } for(itx = group2->GetSubGroup(0)->GetGroupMembersBegin(); itx != group2->GetSubGroup(0)->GetGroupMembersEnd(); ++itx) { if((*itx)->m_loggedInPlayer) { if( ar->HasFreeSlots(1) ) ar->AddPlayer((*itx)->m_loggedInPlayer, 1); } } } } m_queueLock.Release(); m_instanceLock.Release(); }
Map* MapInstanced::GetInstance(const WorldObject* obj) { uint32 InstanceId = obj->GetInstanceId(); Map* map = NULL; if (InstanceId != 0) map = _FindMap(InstanceId); // return map for non-player objects if (map && obj->GetTypeId() != TYPEID_PLAYER) return(map); if (obj->GetTypeId() != TYPEID_PLAYER) { sLog.outDebug("MAPINSTANCED: WorldObject '%u' (Entry: %u Type: %u) is requesting instance '%u' of map '%u', instantiating", obj->GetGUIDLow(), obj->GetEntry(), obj->GetTypeId(), InstanceId, GetId()); if (InstanceId == 0) { sLog.outError("MAPINSTANCED: WorldObject '%u' (Entry: %u Type: %u) requested base map instance of map '%u', this must not happen", obj->GetGUIDLow(), obj->GetEntry(), obj->GetTypeId(), GetId()); return(this); } // short instantiate process for world object CreateInstance(InstanceId, map); return(map); } // here we do additionally verify, if the player is allowed in instance by leader // and if it has current instance bound correctly Player* player = (Player*)obj; // reset instance validation flag player->m_InstanceValid = true; BoundInstancesMap::iterator i = player->m_BoundInstances.find(GetId()); if (i != player->m_BoundInstances.end()) { // well, we have an instance bound, really, verify self or group leader if (!((player->GetGUIDLow() == i->second.second) || (player->GetGroup() && (GUID_LOPART(player->GetGroup()->GetLeaderGUID()) == i->second.second)))) { // well, we are bound to instance, but are not a leader and are not in the correct group // we must not rebind us or the instantiator (which can surely be the same) // will remain bound if accepted into group or will be unbound, if we go to homebind InstanceId = i->second.first; // restore the instance bound player->m_InstanceValid = false; // player instance is invalid if (InstanceId != 0) map = _FindMap(InstanceId);// restore the map bound } } else { // the player has no map bindings, we can proceed safely creating a new one map = NULL; } if (map) return(map); // here we go, the map is found and we are correctly bound Player* instantiator = NULL; uint32 instantiator_id = 0; bool instantiator_online = true; bool instantiator_bound = false; // we do need to scan for the instantiator, if the instance we scan for is valid, not temporary if (player->m_InstanceValid) { // either we are not bound to the instance, or we have to create new instance, do it InstanceId = 0; // determine the instantiator which designates the instance id if (player->GetGroup()) { // instantiate map for group leader (possibly got from the database) sLog.outDebug("MAPINSTANCED: Player '%s' is in group, instantiating map for group leader", player->GetName()); instantiator = objmgr.GetPlayer(player->GetGroup()->GetLeaderGUID()); if (!instantiator) { // the very special case: leader is not online, read instance map from DB instantiator_online = false; } } if (!instantiator && instantiator_online) { sLog.outDebug("MAPINSTANCED: Player '%s' is not in group, instantiating map for player", player->GetName()); instantiator = player; } // now, get the real instance id from the instantiator if (instantiator_online) { // player online, normal instantianting sLog.outDebug("MAPINSTANCED: Instantiating map for player '%s' (group leader '%s')", player->GetName(), instantiator->GetName()); instantiator_id = instantiator->GetGUIDLow(); BoundInstancesMap::iterator i = instantiator->m_BoundInstances.find(GetId()); if (i != instantiator->m_BoundInstances.end()) { // the instantiator has his instance bound InstanceId = i->second.first; // this check is to avoid the case where remote instantiator has his instance // bound to another remote instantiator (e.g. exited from group recently) // if that is the case, the instance for him will be regenerated and rebound if ((instantiator == player) || (i->second.second == instantiator_id)) { // player is instantiator or instantiator has his instance bound to himself instantiator_bound = true; } } } else { // the aforementioned "very special" case of leader being not online sLog.outDebug("MAPINSTANCED: Instantiating map for player '%s' (group leader is not online, querying DB)", player->GetName()); instantiator_id = GUID_LOPART(player->GetGroup()->GetLeaderGUID()); QueryResult* result = CharacterDatabase.PQuery("SELECT instance FROM character_instance WHERE (guid = '%u') AND (map = '%u') AND (leader = '%u')", instantiator_id, GetId(), instantiator_id); if (result) { // the instantiator has his instance bound InstanceId = result->Fetch()[0].GetUInt32(); instantiator_bound = true; delete result; } } // check, if we have to generate new instance if (!instantiator_bound || (InstanceId == 0)) { // yes, new instance id has to be generated InstanceId = MapManager::Instance().GenerateInstanceId(); } else { // find map of the designated instance and verify it map = _FindMap(InstanceId); } } // now create the instance CreateInstance(InstanceId, map); // we do need to bind instance, if the instance we use is valid, not temporary if (player->m_InstanceValid) { // bind instance to instantiator (only if needed) if (!instantiator_bound) { CharacterDatabase.BeginTransaction(); if (instantiator_online) { // player online, normal bind instantiator->m_BoundInstances[GetId()] = std::pair< uint32, uint32 >(InstanceId, instantiator_id); CharacterDatabase.PExecute("DELETE FROM character_instance WHERE (guid = '%u') AND (map = '%u')", instantiator_id, GetId()); CharacterDatabase.PExecute("INSERT INTO character_instance VALUES ('%u', '%u', '%u', '%u')", instantiator_id, GetId(), InstanceId, instantiator_id); } else { // the aforementioned "very special" case of leader being not online CharacterDatabase.PExecute("DELETE FROM character_instance WHERE (guid = '%u') AND (map = '%u')", GUID_LOPART(player->GetGroup()->GetLeaderGUID()), GetId()); CharacterDatabase.PExecute("INSERT INTO character_instance VALUES ('%u', '%u', '%u', '%u')", GUID_LOPART(player->GetGroup()->GetLeaderGUID()), GetId(), InstanceId, GUID_LOPART(player->GetGroup()->GetLeaderGUID())); } CharacterDatabase.CommitTransaction(); } // bind instance to player (avoid duplicate binding) if (instantiator != player) { CharacterDatabase.BeginTransaction(); if (instantiator_online) { player->m_BoundInstances[GetId()] = std::pair< uint32, uint32 >(InstanceId, instantiator_id); CharacterDatabase.PExecute("DELETE FROM character_instance WHERE (guid = '%u') AND (map = '%u')", player->GetGUIDLow(), GetId()); CharacterDatabase.PExecute("INSERT INTO character_instance VALUES ('%u', '%u', '%u', '%u')", player->GetGUIDLow(), GetId(), InstanceId, instantiator_id); } else { // the aforementioned "very special" case of leader being not online player->m_BoundInstances[GetId()] = std::pair< uint32, uint32 >(InstanceId, GUID_LOPART(player->GetGroup()->GetLeaderGUID())); CharacterDatabase.PExecute("DELETE FROM character_instance WHERE (guid = '%u') AND (map = '%u')", player->GetGUIDLow(), GetId()); CharacterDatabase.PExecute("INSERT INTO character_instance VALUES ('%u', '%u', '%u', '%u')", player->GetGUIDLow(), GetId(), InstanceId, GUID_LOPART(player->GetGroup()->GetLeaderGUID())); } CharacterDatabase.CommitTransaction(); } } // set instance id for instantiating player if (player->GetPet()) player->GetPet()->SetInstanceId(InstanceId); player->SetInstanceId(InstanceId); return(map); }
static inline Derived *GetInstancePointer(Args &&...args) { static Derived *instancePointer = CreateInstance(std::forward<Args>(args)...); return instancePointer; }
dgWorld::dgWorld(dgMemoryAllocator* const allocator) :dgBodyMasterList(allocator) ,dgBodyMaterialList(allocator) ,dgBodyCollisionList(allocator) ,dgSkeletonList(allocator) ,dgInverseDynamicsList(allocator) ,dgContactList(allocator) ,dgBilateralConstraintList(allocator) ,dgWorldDynamicUpdate(allocator) ,dgMutexThread("newtonMainThread", 0) ,dgWorldThreadPool(allocator) ,dgDeadBodies(allocator) ,dgDeadJoints(allocator) ,dgWorldPluginList(allocator) ,m_broadPhase(NULL) ,m_sentinelBody(NULL) ,m_pointCollision(NULL) ,m_userData(NULL) ,m_allocator (allocator) ,m_mutex() ,m_postUpdateCallback(NULL) ,m_listeners(allocator) ,m_perInstanceData(allocator) ,m_bodiesMemory (allocator, 64) ,m_jointsMemory (allocator, 64) ,m_clusterMemory (allocator, 64) ,m_solverJacobiansMemory (allocator, 64) ,m_solverRightHandSideMemory (allocator, 64) ,m_solverForceAccumulatorMemory (allocator, 64) ,m_concurrentUpdate(false) { //TestAStart(); //TestSort(); dgMutexThread* const myThread = this; SetParentThread (myThread); // avoid small memory fragmentations on initialization m_bodiesMemory.Resize(1024); m_clusterMemory.Resize(1024); m_jointsMemory.Resize(1024 * 2); m_solverJacobiansMemory.Resize(1024 * 64); m_solverRightHandSideMemory.Resize(1024 * 64); m_solverForceAccumulatorMemory.Resize(1024 * 32); m_savetimestep = dgFloat32 (0.0f); m_allocator = allocator; m_clusterUpdate = NULL; m_onCollisionInstanceDestruction = NULL; m_onCollisionInstanceCopyConstrutor = NULL; m_serializedJointCallback = NULL; m_deserializedJointCallback = NULL; m_inUpdate = 0; m_bodyGroupID = 0; m_lastExecutionTime = 0; m_defualtBodyGroupID = CreateBodyGroupID(); m_genericLRUMark = 0; m_delayDelateLock = 0; m_clusterLRU = 0; m_useParallelSolver = 0; m_solverIterations = DG_DEFAULT_SOLVER_ITERATION_COUNT; m_dynamicsLru = 0; m_numberOfSubsteps = 1; m_bodiesUniqueID = 0; m_frictiomTheshold = dgFloat32 (0.25f); m_userData = NULL; m_clusterUpdate = NULL; m_freezeAccel2 = DG_FREEZE_ACCEL2; m_freezeAlpha2 = DG_FREEZE_ACCEL2; m_freezeSpeed2 = DG_FREEZE_SPEED2; m_freezeOmega2 = DG_FREEZE_SPEED2; m_contactTolerance = DG_PRUNE_CONTACT_TOLERANCE; dgInt32 steps = 1; dgFloat32 freezeAccel2 = m_freezeAccel2; dgFloat32 freezeAlpha2 = m_freezeAlpha2; dgFloat32 freezeSpeed2 = m_freezeSpeed2; dgFloat32 freezeOmega2 = m_freezeOmega2; for (dgInt32 i = 0; i < DG_SLEEP_ENTRIES; i ++) { m_sleepTable[i].m_maxAccel = freezeAccel2; m_sleepTable[i].m_maxAlpha = freezeAlpha2; m_sleepTable[i].m_maxVeloc = freezeSpeed2; m_sleepTable[i].m_maxOmega = freezeOmega2; m_sleepTable[i].m_steps = steps; steps += 7; freezeAccel2 *= dgFloat32 (1.5f); freezeAlpha2 *= dgFloat32 (1.4f); freezeSpeed2 *= dgFloat32 (1.5f); freezeOmega2 *= dgFloat32 (1.5f); } steps += 300; m_sleepTable[DG_SLEEP_ENTRIES - 1].m_maxAccel *= dgFloat32 (100.0f); m_sleepTable[DG_SLEEP_ENTRIES - 1].m_maxAlpha *= dgFloat32 (100.0f); m_sleepTable[DG_SLEEP_ENTRIES - 1].m_maxVeloc = 0.25f; m_sleepTable[DG_SLEEP_ENTRIES - 1].m_maxOmega = 0.1f; m_sleepTable[DG_SLEEP_ENTRIES - 1].m_steps = steps; SetThreadsCount (0); m_broadPhase = new (allocator) dgBroadPhaseMixed(this); //m_broadPhase = new (allocator) dgBroadPhaseSegregated (this); //m_pointCollision = new (m_allocator) dgCollisionPoint(m_allocator); dgCollision* const pointCollison = new (m_allocator) dgCollisionPoint(m_allocator); m_pointCollision = CreateInstance(pointCollison, 0, dgGetIdentityMatrix()); pointCollison->Release(); AddSentinelBody(); // LoadPlugins(); }
already_AddRefed<nsILoadContext> CreatePrivateLoadContext() { return CreateInstance(true); }
/* - return the right instance for the object, based on its InstanceId - create the instance if it's not created already - the player is not actually added to the instance (only in InstanceMap::Add) */ Map* MapInstanced::GetInstance(const WorldObject* obj) { uint32 CurInstanceId = obj->GetInstanceId(); Map* map = NULL; if (obj->GetMapId() == GetId() && CurInstanceId != 0) { // the object wants to be put in a certain instance of this map map = _FindMap(CurInstanceId); if(!map) { // For players if the instanceId is set, it's assumed they are already in a map, // hence the map must be loaded. For Creatures, GameObjects etc the map must exist // prior to calling GetMap, they are not allowed to create maps for themselves. sLog.outError("GetInstance: object %s(%d), typeId %d, in world %d, should be in map %d,%d but that's not loaded yet.", obj->GetName(), obj->GetGUIDLow(), obj->GetTypeId(), obj->IsInWorld(), obj->GetMapId(), obj->GetInstanceId()); assert(false); } return(map); } else { // instance not specified, find an existing or create a new one if(obj->GetTypeId() != TYPEID_PLAYER) { sLog.outError("MAPINSTANCED: WorldObject '%u' (Entry: %u TypeID: %u) is in map %d,%d and requested base map instance of map %d, this must not happen", obj->GetGUIDLow(), obj->GetEntry(), obj->GetTypeId(), obj->GetMapId(), obj->GetInstanceId(), GetId()); assert(false); return NULL; } else { uint32 NewInstanceId = 0; // instanceId of the resulting map Player* player = (Player*)obj; // TODO: battlegrounds and arenas InstancePlayerBind *pBind = player->GetBoundInstance(GetId(), player->GetDifficulty()); InstanceSave *pSave = pBind ? pBind->save : NULL; // the player's permanet player bind is taken into consideration first // then the player's group bind and finally the solo bind. if(!pBind || !pBind->perm) { InstanceGroupBind *groupBind = NULL; Group *group = player->GetGroup(); // use the player's difficulty setting (it may not be the same as the group's) if(group && (groupBind = group->GetBoundInstance(GetId(), player->GetDifficulty()))) pSave = groupBind->save; } if(pSave) { // solo/perm/group NewInstanceId = pSave->GetInstanceId(); map = _FindMap(NewInstanceId); // it is possible that the save exists but the map doesn't if(!map) map = CreateInstance(NewInstanceId, pSave, pSave->GetDifficulty()); return map; } else { // if no instanceId via group members or instance saves is found // the instance will be created for the first time NewInstanceId = MapManager::Instance().GenerateInstanceId(); return CreateInstance(NewInstanceId, NULL, player->GetDifficulty()); } } } }
SSMRESULT CreateGlobalInstance(IN const OID &objectID, OUT IBase **ppvObject) { SSMRESULT res = SSM_E_NOINTERFACE; if (ppvObject == NULL) { return SSM_E_POINTER; } *ppvObject = NULL; g_mtxGlobalInstance->lock(); res = SSM_S_FALSE; if (IsEqualOID(OID_ITasker, objectID)) { if (g_globalInstance->find(OID_ITasker) == g_globalInstance->end()) { SSM_CLEANUP_ASSERT(CreateInstance(OID_ITasker, ppvObject)); } } else if (IsEqualOID(OID_IThreadPool, objectID)) { if (g_globalInstance->find(OID_IThreadPool) == g_globalInstance->end()) { SSM_CLEANUP_ASSERT(CreateInstance(OID_IThreadPool, ppvObject)); } } else if (IsEqualOID(OID_IEvaluationEngine, objectID)) { if (g_globalInstance->find(OID_IEvaluationEngine) == g_globalInstance->end()) { SSM_CLEANUP_ASSERT(CreateInstance(OID_IEvaluationEngine, ppvObject)); } } else if (IsEqualOID(OID_IPropagationEngine, objectID)) { if (g_globalInstance->find(OID_IPropagationEngine) == g_globalInstance->end()) { SSM_CLEANUP_ASSERT(CreateInstance(OID_IPropagationEngine, ppvObject)); } } else if (IsEqualOID(OID_IContextRepository, objectID)) { if (g_globalInstance->find(OID_IContextRepository) == g_globalInstance->end()) { SSM_CLEANUP_ASSERT(CreateInstance(OID_IContextRepository, ppvObject)); } } else if (IsEqualOID(OID_IContextDataReader, objectID)) { if (g_globalInstance->find(OID_IContextDataReader) == g_globalInstance->end()) { SSM_CLEANUP_ASSERT(CreateInstance(OID_IContextDataReader, ppvObject)); } } else if (IsEqualOID(OID_ISensingEngine, objectID)) { if (g_globalInstance->find(OID_ISensingEngine) == g_globalInstance->end()) { SSM_CLEANUP_ASSERT(CreateInstance(OID_ISensingEngine, ppvObject)); } } else { res = SSM_E_NOINTERFACE; } switch (res) { case SSM_S_OK: (*g_globalInstance)[objectID] = *ppvObject; break; case SSM_S_FALSE: (*g_globalInstance)[objectID]->addRef(); *ppvObject = (*g_globalInstance)[objectID]; res = SSM_S_OK; break; default: goto CLEANUP; } CLEANUP: g_mtxGlobalInstance->unlock(); return res; }
shared_ptr<GitRepository> GitRepository::Create(const CString& root) { int encoding = GetRepositoryEncodingFromRegistory(); return CreateInstance(root, encoding); }
// TODO: Resizing bool VkContext::Init(Config config) { if (!glfwInit()) { std::cout << "Unable to initialize GLFW" << std::endl; return false; } if (!CreateInstance(config.windowTitle)) { std::cout << "Unable to create Vulkan instance" << std::endl; return false; } else { std::cout << "Created Vulkan instance" << std::endl; } if (!GetPhysicalDevice()) { std::cout << "Unable to get Vulkan physical device" << std::endl; return false; } else { std::cout << "Acquired Vulkan physical device" << std::endl; } if (!CreateWindowSurface(config.windowWidth, config.windowHeight, config.windowTitle)) { std::cout << "Unable to create window surfcace for Vulkan" << std::endl; return false; } else { std::cout << "Created Vulkan window surface" << std::endl; } if (!GetQueueFamilies()) { std::cout << "Unable to get Vulkan queue families" << std::endl; return false; } else { std::cout << "Acquired queue families" << std::endl; } if (!CreateDevice()) { std::cout << "Unable to create Vulkan device" << std::endl; return false; } else { std::cout << "Created Vulkan device" << std::endl; } #ifdef VOXL_DEBUG if (!SetupValidation()) { std::cout << "Unable to setup Vulkan validation" << std::endl; return false; } else { std::cout << "Setup Vulkan validation" << std::endl; } #endif if (!CreateSemaphores()) { std::cout << "Unable to create Vulkan semaphores" << std::endl; return false; } else { std::cout << "Created Vulkan semaphores" << std::endl; } if (!CreateSwapchain(config.windowWidth, config.windowHeight)) { std::cout << "Unable to create Vulkan swapchain" << std::endl; return false; } else { std::cout << "Created Vulkan swapchain" << std::endl; } if (!CreateCommandPool()) { std::cout << "Unable to create command pool" << std::endl; return false; } else { std::cout << "Created Vulkan command pool" << std::endl; } if (!CreateCommandBuffers()) { std::cout << "Unable to create command buffers" << std::endl; return false; } else { std::cout << "Created Vulkan command buffers" << std::endl; } std::cout << "Successfully initialized Vulkan" << std::endl; return true; }
void OpenURL(GtkBrowser *pBrowser, const char *pUrl, const char *pPostData, const char *pHeader) { nsresult rv; nsCOMPtr<nsIInputStream> postDataStream; nsCOMPtr<nsIInputStream> headersStream; if (pPostData) { unsigned long nSizeData = strlen(pPostData); if (nSizeData > 0) { char szCL[64]; sprintf(szCL, "Content-Length: %lu\r\n\r\n", nSizeData); unsigned long nSizeCL = strlen(szCL); unsigned long nSize = nSizeCL + nSizeData; char *tmp = (char *) nsMemory::Alloc(nSize + 1); // byte stream owns this mem if (tmp) { memcpy(tmp, szCL, nSizeCL); memcpy(tmp + nSizeCL, pPostData, nSizeData); tmp[nSize] = '\0'; nsCOMPtr<nsIStringInputStream> stream; rv = CreateInstance("@mozilla.org/io/string-input-stream;1", NS_GET_IID(nsIStringInputStream), getter_AddRefs(stream)); if (NS_FAILED(rv) || !stream) { NS_ASSERTION(0, "cannot create PostData stream"); nsMemory::Free(tmp); return; } stream->AdoptData(tmp, nSize); postDataStream = do_QueryInterface(stream); } } } if (pHeader) { unsigned long nSize = strlen(pHeader) + 1; if (nSize > 0) { char *tmp = (char *) nsMemory::Alloc(nSize); // byteArray stream owns this mem if (tmp) { memcpy(tmp, pHeader, nSize); nsCOMPtr<nsIStringInputStream> stream; rv = CreateInstance("@mozilla.org/io/string-input-stream;1", NS_GET_IID(nsIStringInputStream), getter_AddRefs(stream)); if (NS_FAILED(rv) || !stream) { NS_ASSERTION(0, "cannot create Header stream"); nsMemory::Free(tmp); return; } stream->AdoptData(tmp, nSize); headersStream = do_QueryInterface(stream); } } } nsCOMPtr<nsIWebBrowser> webBrowser; gtk_moz_embed_get_nsIWebBrowser(GTK_MOZ_EMBED(pBrowser->mozEmbed), getter_AddRefs(webBrowser)); nsCOMPtr<nsIWebNavigation> webNavigation(do_QueryInterface(webBrowser)); if (!webNavigation) return; nsEmbedString unicodeUrl; ConvertAsciiToUtf16(pUrl, unicodeUrl); webNavigation->LoadURI(unicodeUrl.get(), // URI string nsIWebNavigation::LOAD_FLAGS_NONE, // Load flags nsnull, // Refering URI postDataStream, // Post data headersStream); // Extra headers }
HRESULT CLR_RT_HeapBlock_String::CreateInstance( CLR_RT_HeapBlock& reference, CLR_UINT32 token, CLR_RT_Assembly* assm ) { NATIVE_PROFILE_CLR_CORE(); return CreateInstance( reference, assm->GetString( CLR_DataFromTk( token ) ), assm ); }
//=============================================================================* string BAR_CSCOnlineProxy::ReadControlVersion() //=============================================================================* { BAR_TRACE(4, "read control version"); if ( ! IsLoggedIn() ) { Throw_FatalError(L"can not read control version before logged in"); } //=== instantiate opc server // BAR_TypeLib* pTlb = NULL; // IOPCServer* pIOPCServer = (IOPCServer*)CreateInstance("opc server", // IID_IOPCServer, // CLSID_OPCServer, // m_sRemoteHost, // "OPCDA", // LIBID_OPCDA, // "2", // pTlb); //=== instantiate opc server IOPCServer* pIOPCServer = (IOPCServer*) CreateInstance("opc server", IID_IOPCServer, CLSID_OPCServer, m_sRemoteHost, false, "CSC_Onl_Srv", /*LIBID_OPCDA*/LIBID_CSC_Srv_Lib, "1", m_pTlbCSCOnlSrv); //=== get status item OPCSERVERSTATUS *pStatus = NULL; HRESULT hr = pIOPCServer->GetStatus(&pStatus); if ( FAILED(hr) ) { Throw_ReadControlVersionFailed(hr); } if ( pStatus == NULL ) { Throw_FatalError(L"opc server status is null"); } WORD wMajorVersion = pStatus->wMajorVersion; WORD wMinorVersion = pStatus->wMinorVersion; ::CoTaskMemFree(pStatus); //=== build version string ostringstream ossControlVersion; ossControlVersion << (int)wMajorVersion << "." << (int)wMinorVersion; string sControlVersion = ossControlVersion.str(); //=== release opc server if ( pIOPCServer != NULL ) { pIOPCServer->Release(); } /* //=== unregister type library if ( pTlb != NULL ) { delete pTlb; } */ //=== finished BAR_TRACE1(1, "control version=%s", sControlVersion.c_str()); return sControlVersion.c_str(); }
void Import::ApplyModifiers (dScene& scene, const MaxNodeChache& maxNodeCache) { dScene::Iterator iter (scene); for (iter.Begin(); iter; iter ++) { dScene::dTreeNode* meshNode = iter.GetNode(); dNodeInfo* info = scene.GetInfoFromNode(meshNode); if (info->IsType(dGeometryNodeInfo::GetRttiType())) { dScene::dTreeNode* skinModifierNode = NULL; for (void* ptr = scene.GetFirstChild(meshNode); ptr; ptr = scene.GetNextChild(meshNode, ptr)) { dScene::dTreeNode* node = scene.GetNodeFromLink(ptr); dNodeInfo* info = scene.GetInfoFromNode(node); if (info->GetTypeId() == dGeometryNodeSkinModifierInfo::GetRttiType()) { skinModifierNode = node; break; } } if (skinModifierNode) { //create a skin modifier and add it Modifier* skinMod = (Modifier*) CreateInstance(OSM_CLASS_ID, SKIN_CLASSID); ISkinImportData* iskinImport = (ISkinImportData*) skinMod->GetInterface(I_SKINIMPORTDATA); INode* maxNode = maxNodeCache.Find(meshNode)->GetInfo(); _ASSERTE (maxNode); IDerivedObject *derob = NULL; Object* obj = maxNode->GetObjectRef(); if(obj->SuperClassID() != GEN_DERIVOB_CLASS_ID) { derob = CreateDerivedObject(obj); maxNode->SetObjectRef(derob); } else { derob = (IDerivedObject*) obj; } derob->AddModifier(skinMod); dGeometryNodeSkinModifierInfo* skinModifier = (dGeometryNodeSkinModifierInfo*) scene.GetInfoFromNode(skinModifierNode); dMatrix matrix (skinModifier->m_shapeBindMatrix); Matrix3 bindPoseMatrix; bindPoseMatrix.SetRow (0, *((Point3*) &matrix[0])); bindPoseMatrix.SetRow (1, *((Point3*) &matrix[1])); bindPoseMatrix.SetRow (2, *((Point3*) &matrix[2])); bindPoseMatrix.SetRow (3, *((Point3*) &matrix[3])); iskinImport->SetSkinTm(maxNode, bindPoseMatrix, bindPoseMatrix); int maxNodeCount = 0; INode* maxNodes[1024]; for (void* ptr = scene.GetFirstChild(skinModifierNode); ptr; ptr = scene.GetNextChild(skinModifierNode, ptr)) { dScene::dTreeNode* boneNode = scene.GetNodeFromLink(ptr); INode* skelBone = maxNodeCache.Find(boneNode)->GetInfo(); maxNodes[maxNodeCount] = skelBone; maxNodeCount ++; skelBone->SetBoneNodeOnOff(TRUE, 0); skelBone->BoneAsLine(TRUE); skelBone->ShowBone(1); if (iskinImport->AddBoneEx(skelBone, TRUE)) { dSceneNodeInfo* sceneNode = (dSceneNodeInfo*) scene.GetInfoFromNode(boneNode); dMatrix matrix (sceneNode->GetTransform()); Matrix3 bindPoseMatrix; bindPoseMatrix.SetRow (0, *((Point3*) &matrix[0])); bindPoseMatrix.SetRow (1, *((Point3*) &matrix[1])); bindPoseMatrix.SetRow (2, *((Point3*) &matrix[2])); bindPoseMatrix.SetRow (3, *((Point3*) &matrix[3])); iskinImport->SetBoneTm(skelBone, bindPoseMatrix, bindPoseMatrix); } } // must evaluate the node after adding bones maxNode->EvalWorldState(0); for (int i = 0; i < skinModifier->m_vertexCount; i ++) { Tab<float> weightList; Tab<INode*> boneNodeList; for (int j = 0; j < 4; j ++) { if (skinModifier->m_vertexWeights[i][j] > 1.0e-5f) { int boneIndex = skinModifier->m_boneWeightIndex[i].m_index[j]; INode *skelBone = maxNodes[boneIndex]; _ASSERTE (skelBone); boneNodeList.Append (1, &skelBone); weightList.Append (1, &skinModifier->m_vertexWeights[i][j]); } } iskinImport->AddWeights(maxNode, i, boneNodeList, weightList); } } } } }
dgWorld::dgWorld(dgMemoryAllocator* const allocator) :dgBodyMasterList(allocator) ,dgBodyMaterialList(allocator) ,dgBodyCollisionList(allocator) ,dgDeformableBodiesUpdate(allocator) ,dgActiveContacts(allocator) ,dgCollidingPairCollector() ,dgWorldDynamicUpdate() ,dgMutexThread("dgMutexThread", DG_MUTEX_THREAD_ID) ,dgAsyncThread("dgAsyncThread", DG_ASYNC_THREAD_ID) ,dgWorldThreadPool(allocator) ,m_broadPhase(NULL) ,m_sentinelBody(NULL) ,m_pointCollision(NULL) ,m_amp(NULL) ,m_preListener(allocator) ,m_postListener(allocator) ,m_perInstanceData(allocator) ,m_islandMemory (DG_INITIAL_ISLAND_SIZE, allocator, 64) ,m_bodiesMemory (DG_INITIAL_BODIES_SIZE, allocator, 64) ,m_jointsMemory (DG_INITIAL_JOINTS_SIZE, allocator, 64) ,m_pairMemoryBuffer (DG_INITIAL_CONTACT_SIZE, allocator, 64) ,m_solverMatrixMemory (DG_INITIAL_JACOBIAN_SIZE, allocator, 64) ,m_solverRightSideMemory (DG_INITIAL_BODIES_SIZE, allocator, 64) { dgMutexThread* const mutexThread = this; SetMatertThread (mutexThread); m_allocator = allocator; m_islandUpdate = NULL; m_getPerformanceCount = NULL; m_onCollisionInstanceDestruction = NULL; m_onCollisionInstanceCopyConstrutor = NULL; m_inUpdate = 0; m_bodyGroupID = 0; m_defualtBodyGroupID = CreateBodyGroupID(); m_genericLRUMark = 0; m_useParallelSolver = 0; //m_solverMode = 0; m_solverMode = 1; m_frictionMode = 0; m_dynamicsLru = 0; m_bodiesUniqueID = 0; m_frictiomTheshold = dgFloat32 (0.25f); m_userData = NULL; m_islandUpdate = NULL; m_freezeAccel2 = DG_FREEZE_MAG2; m_freezeAlpha2 = DG_FREEZE_MAG2; m_freezeSpeed2 = DG_FREEZE_MAG2 * dgFloat32 (0.1f); m_freezeOmega2 = DG_FREEZE_MAG2 * dgFloat32 (0.1f); m_contactTolerance = DG_REDUCE_CONTACT_TOLERANCE; dgInt32 steps = 1; dgFloat32 freezeAccel2 = m_freezeAccel2; dgFloat32 freezeAlpha2 = m_freezeAlpha2; dgFloat32 freezeSpeed2 = m_freezeSpeed2; dgFloat32 freezeOmega2 = m_freezeOmega2; for (dgInt32 i = 0; i < DG_SLEEP_ENTRIES; i ++) { m_sleepTable[i].m_maxAccel = freezeAccel2; m_sleepTable[i].m_maxAlpha = freezeAlpha2; m_sleepTable[i].m_maxVeloc = freezeSpeed2; m_sleepTable[i].m_maxOmega = freezeOmega2; m_sleepTable[i].m_steps = steps; steps += 7; freezeAccel2 *= dgFloat32 (1.5f); freezeAlpha2 *= dgFloat32 (1.4f); freezeSpeed2 *= dgFloat32 (1.5f); freezeOmega2 *= dgFloat32 (1.5f); } steps += 300; m_sleepTable[DG_SLEEP_ENTRIES - 1].m_maxAccel *= dgFloat32 (100.0f); m_sleepTable[DG_SLEEP_ENTRIES - 1].m_maxAlpha *= dgFloat32 (100.0f); m_sleepTable[DG_SLEEP_ENTRIES - 1].m_maxVeloc = 0.25f; m_sleepTable[DG_SLEEP_ENTRIES - 1].m_maxOmega = 0.1f; m_sleepTable[DG_SLEEP_ENTRIES - 1].m_steps = steps; m_hardwaredIndex = 0; SetThreadsCount (0); //dgBroadPhase::Init (); m_broadPhase = new (allocator) dgBroadPhase(this); dgCollidingPairCollector::Init (); //m_pointCollision = new (m_allocator) dgCollisionPoint(m_allocator); dgCollision* const pointCollison = new (m_allocator) dgCollisionPoint(m_allocator); m_pointCollision = CreateInstance(pointCollison, 0, dgGetIdentityMatrix()); pointCollison->Release(); AddSentinelBody(); SetPerfomanceCounter(NULL); #ifdef _NEWTON_AMP m_amp = new (GetAllocator()) dgAmpInstance(this); #endif }
bool Renderer::Init() { return CreateInstance(); }
already_AddRefed<nsILoadContext> CreateLoadContext() { return CreateInstance(false); }
void ComponentLoader::Initialize() { // run local initialization functions InitFunctionBase::RunAll(); // set up the root component m_rootComponent = FxGameComponent::Create(); AddComponent(m_rootComponent); // parse and load additional components FILE* componentCache = _pfopen(MakeRelativeCitPath(L"components.json").c_str(), _P("rb")); if (!componentCache) { FatalError("Could not find component cache storage file (components.json)."); } // read component cache file fseek(componentCache, 0, SEEK_END); int length = ftell(componentCache); fseek(componentCache, 0, SEEK_SET); char* cacheBuf = new char[length + 1]; fread(cacheBuf, 1, length, componentCache); cacheBuf[length] = '\0'; fclose(componentCache); // parse the list rapidjson::Document doc; doc.Parse(cacheBuf); delete[] cacheBuf; if (doc.HasParseError()) { FatalError("Error parsing components.json: %d", doc.GetParseError()); } // look through the list for components to load std::vector<std::string> components; for (auto it = doc.Begin(); it != doc.End(); it++) { const char* name = it->GetString(); components.push_back(name); // replace colons with dashes char* nameStr = strdup(name); char* p = nameStr; while (*p) { if (*p == ':') { *p = '-'; } p++; } fwPlatformString nameWide(nameStr); free(nameStr); AddComponent(new DllGameComponent(va(PLATFORM_LIBRARY_STRING, nameWide.c_str()))); } // load the components, but don't instance them std::vector<fwRefContainer<ComponentData>> componentDatas; for (auto& component : components) { auto comp = LoadComponent(component.c_str()); if (!comp.GetRef()) { FatalError("Could not load component %s.", component.c_str()); } componentDatas.push_back(comp); } // sort the list by dependency std::queue<fwRefContainer<ComponentData>> sortedList = SortDependencyList(componentDatas); // clear the loaded list (it'll be added afterwards in order) m_loadedComponents.clear(); while (!sortedList.empty()) { auto comp = sortedList.front(); sortedList.pop(); m_loadedComponents.push_back(comp); // create a component instance if need be if (comp->ShouldAutoInstance()) { trace("Initializing instance of %s.\n", comp->GetName().c_str()); comp->CreateInstance(std::string()); } } }
Object* TorusObject::ConvertToType(TimeValue t, Class_ID obtype) { #ifndef NO_PATCHES if (obtype == patchObjectClassID) { Interval valid = FOREVER; float radius1, radius2; int genUVs; pblock->GetValue(PB_RADIUS,t,radius1,valid); pblock->GetValue(PB_RADIUS2,t,radius2,valid); pblock->GetValue(PB_GENUVS,t,genUVs,valid); PatchObject *ob = new PatchObject(); BuildTorusPatch(t,ob->patch,radius1,radius2,genUVs, GetUsePhysicalScaleUVs()); ob->SetChannelValidity(TOPO_CHAN_NUM,valid); ob->SetChannelValidity(GEOM_CHAN_NUM,valid); ob->UnlockObject(); return ob; } #endif #ifndef NO_NURBS if (obtype == EDITABLE_SURF_CLASS_ID) { Interval valid = FOREVER; float radius, radius2, pie1, pie2; int sliceon, genUVs; pblock->GetValue(PB_RADIUS,t,radius,valid); pblock->GetValue(PB_RADIUS2,t,radius2,valid); pblock->GetValue(PB_PIESLICE1,t,pie1,valid); pblock->GetValue(PB_PIESLICE2,t,pie2,valid); pblock->GetValue(PB_SLICEON,t,sliceon,valid); pblock->GetValue(PB_GENUVS,t,genUVs,valid); Object *ob = BuildNURBSTorus(radius, radius2, sliceon, pie1, pie2, genUVs); ob->SetChannelValidity(TOPO_CHAN_NUM,valid); ob->SetChannelValidity(GEOM_CHAN_NUM,valid); ob->UnlockObject(); return ob; } #endif #ifdef DESIGN_VER if (obtype == GENERIC_AMSOLID_CLASS_ID) { Interval valid = FOREVER; float radius1, radius2, pie1, pie2; int sliceon, genUVs, sides, segs; pblock->GetValue(PB_RADIUS,t,radius1,valid); pblock->GetValue(PB_RADIUS2,t,radius2,valid); pblock->GetValue(PB_PIESLICE1,t,pie1,valid); pblock->GetValue(PB_PIESLICE2,t,pie2,valid); pblock->GetValue(PB_SLICEON,t,sliceon,valid); pblock->GetValue(PB_GENUVS,t,genUVs,valid); pblock->GetValue(PB_SIDES,t,sides,valid); pblock->GetValue(PB_SEGMENTS,t,segs,valid); int smooth; pblock->GetValue(PB_SMOOTH,t,smooth,valid); if (radius1 < 0.0f) radius1 = 0.0f; if (radius2 < 0.0f) radius2 = 0.0f; Object* solid = (Object*)CreateInstance(GEOMOBJECT_CLASS_ID, GENERIC_AMSOLID_CLASS_ID); assert(solid); if(solid) { IGeomImp* cacheptr = (IGeomImp*)(solid->GetInterface(I_GEOMIMP)); assert(cacheptr); if(cacheptr) { bool res = cacheptr->createTorus(radius1, radius2, sides, segs, smooth); solid->ReleaseInterface(I_GEOMIMP, cacheptr); if(res) return solid; else { solid->DeleteMe(); } } } return NULL; } #endif return SimpleObject::ConvertToType(t,obtype); }
bool ExtrudeMod::BuildAMSolidFromShape(TimeValue t,ModContext &mc, ObjectState * os, IGeomImp* igeom) { ShapeObject *shape = (ShapeObject *)os->obj; float amount; pblock->GetValue(PB_AMOUNT,t,amount,FOREVER); BOOL texturing; pblock->GetValue(PB_MAPPING, TimeValue(0), texturing, FOREVER); BOOL genMatIDs; pblock->GetValue(PB_GEN_MATIDS, TimeValue(0), genMatIDs, FOREVER); BOOL useShapeIDs; pblock->GetValue(PB_USE_SHAPEIDS, TimeValue(0), useShapeIDs, FOREVER); BOOL smooth; pblock->GetValue(PB_SMOOTH, TimeValue(0), smooth, FOREVER); LimitValue(amount, -1000000.0f, 1000000.0f); if(fabs(amount)<MIN_EXT) amount = MIN_EXT; // Get the basic dimension stuff float zSize = (float)fabs(amount); float baseZ = 0.0f; if(amount < 0.0f) baseZ = amount; // If the shape can convert itself to a BezierShape, have it do so! BezierShape bShape; PolyShape pShape; shape->MakePolyShape(t, pShape, PSHAPE_BUILTIN_STEPS, true); ShapeHierarchy hier; pShape.OrganizeCurves(t, &hier); // Need to flip the reversed curves in the shape! pShape.Reverse(hier.reverse); //Now add the extrusion for each polygon bool res = false;//assume the best //make a solid to hold our work Object* solid = (Object*)CreateInstance(GEOMOBJECT_CLASS_ID, GENERIC_AMSOLID_CLASS_ID); IGeomImp* workgeom = NULL; assert(solid); if(solid) { workgeom = (IGeomImp*)(solid->GetInterface(I_GEOMIMP)); assert(workgeom); } for(int i=0;i<pShape.numLines; i++) { PolyLine poly = pShape.lines[i]; if(poly.numPts) poly.pts[0].aux = poly.flags; bool localres = workgeom->createExtrusion(poly.pts, poly.numPts, amount, smooth, genMatIDs, useShapeIDs); if(localres) { //need to figure out how deeply nested this shape is //order is this value with zero meaning not nested HierarchyEntry *entry = hier.hier.FindEntry(i); assert(entry); int order = 0; while(entry && (entry->parent != (HierarchyEntry *)-1)) { entry = entry->parent; ++order; } if(order%2) igeom->operator-=(*workgeom); else igeom->operator+=(*workgeom); } res |= localres; } //do some cleanup if(workgeom) { assert(solid); solid->ReleaseInterface(I_GEOMIMP, workgeom); solid->DeleteMe(); } return res; }
NetworkID GameFactory::CreateInstance(unsigned char type, unsigned int baseID) { return CreateInstance(type, 0x00, baseID); }
void ExtrudeMod::ModifyObject(TimeValue t, ModContext &mc, ObjectState * os, INode *node) { //DebugPrint(_T("Extrude modifying object\n")); // Get our personal validity interval... Interval valid = GetValidity(t); // and intersect it with the channels we use as input (see ChannelsUsed) valid &= os->obj->ChannelValidity(t,TOPO_CHAN_NUM); valid &= os->obj->ChannelValidity(t,GEOM_CHAN_NUM); int output; pblock->GetValue(PB_OUTPUT, TimeValue(0), output, FOREVER); switch (output) { case NURBS_OUTPUT: #ifndef NO_NURBS { // Here is where all the fun stuff happens -- GenerateExtrudeSurface fills in the EM, // then we stuff the EditableSurface into the pipeline. ShapeObject *shape = (ShapeObject *)os->obj; float amount; BOOL texturing, genMatIds, useShapeIDs; pblock->GetValue(PB_MAPPING, TimeValue(0), texturing, FOREVER); pblock->GetValue(PB_GEN_MATIDS, TimeValue(0), genMatIds, FOREVER); pblock->GetValue(PB_USE_SHAPEIDS, TimeValue(0), useShapeIDs, FOREVER); int levels,capStart,capEnd,capType; pblock->GetValue(PB_SEGS,t,levels,FOREVER); if (levels<1) levels = 1; pblock->GetValue(PB_CAPSTART,t,capStart,FOREVER); pblock->GetValue(PB_CAPEND,t,capEnd,FOREVER); pblock->GetValue(PB_CAPTYPE,t,capType,FOREVER); pblock->GetValue(PB_AMOUNT,t,amount,FOREVER); LimitValue(amount, -1000000.0f, 1000000.0f); BOOL suspended = FALSE; if (theHold.Holding()) { theHold.Suspend(); suspended = TRUE; } Object *nobj = CreateNURBSExtrudeShape(ip, GetString(IDS_RB_EXTRUDE), t, shape, amount, capStart, capEnd, capType, texturing, genMatIds, useShapeIDs); if (suspended) { theHold.Resume(); } // We only set geom validity because we preserve animation on clone // and copying other cahnnels causes problems -- SCM 9/2/97 nobj->SetChannelValidity(GEOM_CHAN_NUM, valid); os->obj = nobj; break;} #endif #ifndef NO_PATCHES case PATCH_OUTPUT: { // Here is where all the fun stuff happens -- BuildPatchFromShape fills in the PatchObject's patch mesh, // then we stuff the PatchObject into the pipeline. PatchObject *pat = new PatchObject; BuildPatchFromShape(t, mc, os, pat->patch); pat->SetChannelValidity(TOPO_CHAN_NUM, valid); pat->SetChannelValidity(GEOM_CHAN_NUM, valid); pat->SetChannelValidity(TEXMAP_CHAN_NUM, valid); pat->SetChannelValidity(MTL_CHAN_NUM, valid); pat->SetChannelValidity(SELECT_CHAN_NUM, valid); pat->SetChannelValidity(SUBSEL_TYPE_CHAN_NUM, valid); pat->SetChannelValidity(DISP_ATTRIB_CHAN_NUM, valid); os->obj = pat; break;} #endif // NO_PATCHES case MESH_OUTPUT: { // Here is where all the fun stuff happens -- BuildMeshFromShape fills in the TriObject's mesh, // then we stuff the TriObj into the pipeline. TriObject *tri = CreateNewTriObject(); BuildMeshFromShape(t, mc, os, tri->GetMesh()); tri->SetChannelValidity(TOPO_CHAN_NUM, valid); tri->SetChannelValidity(GEOM_CHAN_NUM, valid); tri->SetChannelValidity(TEXMAP_CHAN_NUM, valid); tri->SetChannelValidity(MTL_CHAN_NUM, valid); tri->SetChannelValidity(SELECT_CHAN_NUM, valid); tri->SetChannelValidity(SUBSEL_TYPE_CHAN_NUM, valid); tri->SetChannelValidity(DISP_ATTRIB_CHAN_NUM, valid); os->obj = tri; break; } #ifdef XXDESIGN_VER case AMSOLID_OUTPUT: { //Create an extrusion solid using Facet Modeler Object* solid = (Object*)CreateInstance(GEOMOBJECT_CLASS_ID, GENERIC_AMSOLID_CLASS_ID); assert(solid); if(solid) { IGeomImp* cacheptr = (IGeomImp*)(solid->GetInterface(I_GEOMIMP)); assert(cacheptr); if(cacheptr) { bool res = BuildAMSolidFromShape(t, mc, os, cacheptr); solid->ReleaseInterface(I_GEOMIMP, cacheptr); if(!res) { valid.SetInstant(t); // assert(!cacheptr->isNull()); } for(int i=0; i<NUM_OBJ_CHANS;i++) solid->SetChannelValidity(i, valid); os->obj = solid; } } break; } #endif } os->obj->UnlockObject(); }
void CBattlegroundManager::EventQueueUpdate() { deque<Player*> tempPlayerVec[2]; uint32 i,j,k; Player * plr; CBattleground * bg; list<uint32>::iterator it3, it4; //vector<Player*>::iterator it6; map<uint32, CBattleground*>::iterator iitr; Arena * arena; int32 team; m_queueLock.Acquire(); m_instanceLock.Acquire(); for(i = 0; i < BATTLEGROUND_NUM_TYPES; ++i) { for(j = 0; j < MAX_LEVEL_GROUP; ++j) { if(!m_queuedPlayers[i][j].size()) continue; tempPlayerVec[0].clear(); tempPlayerVec[1].clear(); for(it3 = m_queuedPlayers[i][j].begin(); it3 != m_queuedPlayers[i][j].end();) { it4 = it3++; plr = objmgr.GetPlayer(*it4); if(!plr || GetLevelGrouping(plr->getLevel()) != j) { m_queuedPlayers[i][j].erase(it4); continue; } // queued to a specific instance id? if(plr->m_bgQueueInstanceId != 0) { iitr = m_instances[i].find(plr->m_bgQueueInstanceId); if(iitr == m_instances[i].end()) { // queue no longer valid plr->GetSession()->SystemMessage("Your queue on battleground instance id %u is no longer valid. Reason: Instance Deleted.", plr->m_bgQueueInstanceId); plr->m_bgIsQueued = false; plr->m_bgQueueType = 0; plr->m_bgQueueInstanceId = 0; m_queuedPlayers[i][j].erase(it4); } // can we join? bg = iitr->second; if(bg->CanPlayerJoin(plr)) { bg->AddPlayer(plr, plr->GetTeam()); m_queuedPlayers[i][j].erase(it4); } } else { if(IS_ARENA(i)) tempPlayerVec[0].push_back(plr); else tempPlayerVec[plr->GetTeam()].push_back(plr); } } // try to join existing instances for(iitr = m_instances[i].begin(); iitr != m_instances[i].end(); ++iitr) { if( iitr->second->HasEnded() || iitr->second->GetLevelGroup() != j) continue; if(IS_ARENA(i)) { arena = ((Arena*)iitr->second); if(arena->Rated()) continue; team = arena->GetFreeTeam(); while(team >= 0 && tempPlayerVec[0].size()) { plr = *tempPlayerVec[0].begin(); tempPlayerVec[0].pop_front(); plr->m_bgTeam=team; arena->AddPlayer(plr, team); ErasePlayerFromList(plr->GetLowGUID(), &m_queuedPlayers[i][j]); team = arena->GetFreeTeam(); } } else { bg = iitr->second; for(k = 0; k < 2; ++k) { while(tempPlayerVec[k].size() && bg->HasFreeSlots(k)) { plr = *tempPlayerVec[k].begin(); tempPlayerVec[k].pop_front(); bg->AddPlayer(plr, plr->GetTeam()); ErasePlayerFromList(plr->GetLowGUID(), &m_queuedPlayers[i][j]); } } } } if(IS_ARENA(i)) { // enough players to start a round? if(tempPlayerVec[0].size() < BGMinimumPlayers[i]) continue; if(CanCreateInstance(i,j)) { arena = ((Arena*)CreateInstance(i, j)); team = arena->GetFreeTeam(); while(!arena->IsFull() && tempPlayerVec[0].size() && team >= 0) { plr = *tempPlayerVec[0].begin(); tempPlayerVec[0].pop_front(); plr->m_bgTeam=team; arena->AddPlayer(plr, team); team = arena->GetFreeTeam(); // remove from the main queue (painful!) ErasePlayerFromList(plr->GetLowGUID(), &m_queuedPlayers[i][j]); } } } else { #ifdef ONLY_ONE_PERSON_REQUIRED_TO_JOIN_DEBUG if(tempPlayerVec[0].size() >= 1 || tempPlayerVec[1].size() >= 1) #else if(tempPlayerVec[0].size() >= BGMinimumPlayers[i] && tempPlayerVec[1].size() >= BGMinimumPlayers[i]) #endif { if(CanCreateInstance(i,j)) { bg = CreateInstance(i,j); if( bg == NULL ) { // creation failed for(k = 0; k < 2; ++k) { while(tempPlayerVec[k].size()) { plr = *tempPlayerVec[k].begin(); tempPlayerVec[k].pop_front(); ErasePlayerFromList(plr->GetLowGUID(), &m_queuedPlayers[i][j]); } } } else { // push as many as possible in for(k = 0; k < 2; ++k) { while(tempPlayerVec[k].size() && bg->HasFreeSlots(k)) { plr = *tempPlayerVec[k].begin(); tempPlayerVec[k].pop_front(); plr->m_bgTeam=k; bg->AddPlayer(plr, k); ErasePlayerFromList(plr->GetLowGUID(), &m_queuedPlayers[i][j]); } } } } } } } } /* Handle paired arena team joining */ list<uint32>::iterator itz; list<uint32>::iterator itp; for(i = BATTLEGROUND_ARENA_2V2; i < BATTLEGROUND_ARENA_5V5+1; ++i) { // We need at least this many :( if(m_queuedGroups[i].size() < 2) continue; list<uint32> removegroups; for(itz = m_queuedGroups[i].begin(); itz != m_queuedGroups[i].end(); itz++) { Group * pGroup = objmgr.GetGroupById(*itz); if(!pGroup || !pGroup->m_isqueued || !pGroup->GetLeader() || pGroup->GetLeader()->arenaTeam[i - 4] == NULL) continue; uint32 maxRange = pGroup->GetLeader()->arenaTeam[i - 4]->m_queueSearchRange; pGroup->GetLeader()->arenaTeam[i - 4]->m_queueSearchRange += 100; vector<uint32> inRangeGroups; uint32 rating = pGroup->GetLeader()->arenaTeam[i - 4]->m_stat_rating; for(itp = m_queuedGroups[i].begin(); itp != m_queuedGroups[i].end();) { Group * tGrp = objmgr.GetGroupById(*itp); if(!tGrp || !tGrp->m_isqueued || !tGrp->GetLeader() || tGrp->GetLeader()->arenaTeam[i - 4] == NULL) { itp = m_queuedGroups[i].erase(itp); continue; } ++itp; if( pGroup == tGrp ) continue; uint32 tRating = tGrp->GetLeader()->arenaTeam[i - 4]->m_stat_rating; int32 diff = (int32)tRating - (int32)rating; if(diff < 0) diff = -diff; if(diff > (int32)maxRange) continue; //Log.Notice("Debug", "EventQueueUpdate added 1 in range arena"); inRangeGroups.push_back(tGrp->GetID()); } // K, we have a giant list of groups that we could group with, hopefully! // or not, we can't go on :( if(!inRangeGroups.size()) continue; // But if we're here, we can :D uint32 r = 0; if( inRangeGroups.size() > 1 ) r = RandomUInt((uint32)inRangeGroups.size() - 1); Group * pairGroup = objmgr.GetGroupById(inRangeGroups[r]); if(!pairGroup) continue; // Now, let's create this rated Arena Match :) //Log.Notice("Debug", "EventQueueUpdate creating arena"); Arena * arena = (Arena*)CreateInstance(i, LEVEL_GROUP_70); ArenaTeam *pTeamPair[2]; if(arena) { //Log.Notice("Debug", "EventQueueUpdate arena created"); removegroups.push_back(pGroup->GetID()); removegroups.push_back(pairGroup->GetID()); pGroup->m_isqueued = false; pairGroup->m_isqueued = false; arena->rated_match = true; if( pGroup->GetLeader()->arenaTeam[i - 4] != NULL ) { arena->m_ratedTeams[0] = pGroup->GetLeader()->arenaTeam[i - 4]->m_id; pTeamPair[0] = pGroup->GetLeader()->arenaTeam[i - 4]; } else pTeamPair[0] = NULL; if( pairGroup->GetLeader()->arenaTeam[i - 4] != NULL ) { arena->m_ratedTeams[1] = pairGroup->GetLeader()->arenaTeam[i - 4]->m_id; pTeamPair[1] = pairGroup->GetLeader()->arenaTeam[i - 4]; } else pTeamPair[1] = NULL; pGroup->GetLeader()->arenaTeam[i - 4]->m_queueSearchRange = 100; pairGroup->GetLeader()->arenaTeam[i - 4]->m_queueSearchRange = 100; GroupMembersSet::iterator gitr; pGroup->Lock(); for(gitr = pGroup->GetSubGroup(0)->GetGroupMembersBegin(); gitr != pGroup->GetSubGroup(0)->GetGroupMembersEnd(); gitr++) { PlayerInfo * pi = (*gitr); if(!pi->m_loggedInPlayer) continue; //Log.Notice("Debug", "EventQueueUpdate player lewp"); pi->m_loggedInPlayer->m_bgTeam = 0; if(arena->HasFreeSlots(0)) { arena->AddPlayer(pi->m_loggedInPlayer, 0); arena->m_RatedPlayers[0].insert(pi); if( pTeamPair[0] != NULL ) { ArenaTeamMember * atm = pTeamPair[0]->GetMember(pi); if(atm) { atm->Played_ThisSeason++; atm->Played_ThisWeek++; } //Log.Notice("Debug", "EventQueueUpdate added player %s", pi->m_loggedInPlayer->GetName()); } } } pGroup->Unlock(); pairGroup->Lock(); for(gitr = pairGroup->GetSubGroup(0)->GetGroupMembersBegin(); gitr != pairGroup->GetSubGroup(0)->GetGroupMembersEnd(); gitr++) { PlayerInfo * pi = (*gitr); if(!pi->m_loggedInPlayer || pi->arenaTeam[i-4] == NULL) continue; pi->m_loggedInPlayer->m_bgTeam = 1; if(arena->HasFreeSlots(1)) { arena->AddPlayer(pi->m_loggedInPlayer, 1); arena->m_RatedPlayers[1].insert(pi); if( pTeamPair[1] != NULL ) { ArenaTeamMember * atm = pTeamPair[1]->GetMember(pi); if(atm) { atm->Played_ThisSeason++; atm->Played_ThisWeek++; } } } } pairGroup->Unlock(); } } for(itz = removegroups.begin(); itz != removegroups.end(); itz++) { m_queuedGroups[i].remove(*itz); } } m_queueLock.Release(); m_instanceLock.Release(); }
/* - return the right instance for the object, based on its InstanceId - create the instance if it's not created already - the player is not actually added to the instance (only in InstanceMap::Add) */ Map* MapInstanced::CreateInstance(const uint32 mapId, Player* player) { if (GetId() != mapId || !player) return NULL; Map* map = NULL; uint32 NewInstanceId = 0; // instanceId of the resulting map if (IsBattlegroundOrArena()) { // instantiate or find existing bg map for player // the instance id is set in battlegroundid NewInstanceId = player->GetBattlegroundId(); if (!NewInstanceId) return NULL; map = _FindMap(NewInstanceId); if (!map) if (Battleground* NewBattleground = player->GetBattleground()) map = CreateBattleground(NewInstanceId, NewBattleground); } else { InstancePlayerBind *pBind = player->GetBoundInstance(GetId(), player->GetDifficulty(IsRaid())); InstanceSave *pSave = pBind ? pBind->save : NULL; // the player's permanent player bind is taken into consideration first // then the player's group bind and finally the solo bind. if (!pBind || !pBind->perm) { InstanceGroupBind *groupBind = NULL; Group* group = player->GetGroup(); // use the player's difficulty setting (it may not be the same as the group's) if (group) { groupBind = group->GetBoundInstance(this); if (groupBind) pSave = groupBind->save; } } if (pSave) { // solo/perm/group NewInstanceId = pSave->GetInstanceId(); map = _FindMap(NewInstanceId); // it is possible that the save exists but the map doesn't if (!map) map = CreateInstance(NewInstanceId, pSave, pSave->GetDifficulty()); } else { // if no instanceId via group members or instance saves is found // the instance will be created for the first time NewInstanceId = sMapMgr->GenerateInstanceId(); Difficulty diff = player->GetGroup() ? player->GetGroup()->GetDifficulty(IsRaid()) : player->GetDifficulty(IsRaid()); map = CreateInstance(NewInstanceId, NULL, diff); } } // create transports sTransportMgr->CreateInstanceTransports(map); return map; }
// Insert COpcBrowseElement* COpcBrowseElement::Insert(const COpcString& cPath) { COpcString cName = cPath; COpcString cSubPath = OPC_EMPTY_STRING; // check if multiple levels have been specified. do { UINT uIndex = cName.Find(GetSeparator()); if (uIndex == -1) { break; } cSubPath = cName.SubStr(uIndex + GetSeparator().GetLength()); cName = cName.SubStr(0, uIndex); if (!cName.IsEmpty()) { break; } cName = cSubPath; } while (!cSubPath.IsEmpty()); // invalid path specified. if (cName.IsEmpty()) { return NULL; } // find out if node already exists. COpcBrowseElement* pNode = NULL; OPC_POS pos = m_cChildren.GetHeadPosition(); while (pos != NULL) { pNode = m_cChildren.GetNext(pos); if (pNode->m_cName == cName) { // return existing node. if (cSubPath.IsEmpty()) { return pNode; } // insert sub-path into existing node. return pNode->Insert(cSubPath); } } // create new node. pNode = CreateInstance(); pNode->m_cName = cName; OPC_ASSERT(!pNode->m_cName.IsEmpty()); COpcBrowseElement* pChild = pNode; if (!cSubPath.IsEmpty()) { pChild = pNode->Insert(cSubPath); if (pChild == NULL) { delete pNode; return NULL; } } m_cChildren.AddTail(pNode); return pChild; }
/* - return the right instance for the object, based on its InstanceId - create the instance if it's not created already - the player is not actually added to the instance (only in InstanceMap::Add) */ Map* MapInstanced::CreateInstanceForPlayer(const uint32 mapId, Player* player) { if (GetId() != mapId || !player) return NULL; Map* map = NULL; if (IsBattlegroundOrArena()) { // instantiate or find existing bg map for player // the instance id is set in battlegroundid uint32 newInstanceId = player->GetBattlegroundId(); if (!newInstanceId) return NULL; map = sMapMgr->FindMap(mapId, newInstanceId); if (!map) { Battleground* bg = player->GetBattleground(true); if (bg && bg->GetStatus() < STATUS_WAIT_LEAVE) map = CreateBattleground(newInstanceId, bg); else { player->TeleportToEntryPoint(); return NULL; } } } else { Difficulty realdiff = player->GetDifficulty(IsRaid()); uint32 destInstId = sInstanceSaveMgr->PlayerGetDestinationInstanceId(player, GetId(), realdiff); if (destInstId) { InstanceSave* pSave = sInstanceSaveMgr->GetInstanceSave(destInstId); ASSERT(pSave); // pussywizard: must exist map = FindInstanceMap(destInstId); if (!map) map = CreateInstance(destInstId, pSave, realdiff); else if ((mapId == 631 || mapId == 724) && !map->HavePlayers() && map->GetDifficulty() != realdiff) { if (player->isBeingLoaded()) // pussywizard: crashfix (assert(passengers.empty) fail in ~transport), could be added to a transport during loading from db return NULL; if (!map->AllTransportsEmpty()) map->AllTransportsRemovePassengers(); // pussywizard: gameobjects / summons (assert(passengers.empty) fail in ~transport) for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i) if (i->first == destInstId) { DestroyInstance(i); map = CreateInstance(destInstId, pSave, realdiff); break; } } } else { uint32 newInstanceId = sMapMgr->GenerateInstanceId(); ASSERT(!FindInstanceMap(newInstanceId)); // pussywizard: instance with new id can't exist Difficulty diff = player->GetGroup() ? player->GetGroup()->GetDifficulty(IsRaid()) : player->GetDifficulty(IsRaid()); map = CreateInstance(newInstanceId, NULL, diff); } } return map; }
/* - return the right instance for the object, based on its InstanceId - create the instance if it's not created already - the player is not actually added to the instance (only in InstanceMap::Add) */ Map* MapInstanced::CreateInstanceForPlayer(const uint32 mapId, Player* player) { if (GetId() != mapId || !player) return NULL; Map* map = NULL; uint32 newInstanceId = 0; // instanceId of the resulting map. if (IsBattlegroundOrArena()) { // Instantiate or find existing bg map for player. The instance id is set in battlegroundid. newInstanceId = player->GetBattlegroundId(); if (!newInstanceId) return NULL; map = sMapMgr->FindMap(mapId, newInstanceId); if (!map) { if (Battleground* bg = player->GetBattleground()) map = CreateBattleground(newInstanceId, bg); else { player->TeleportToBGEntryPoint(); return NULL; } } } else { InstancePlayerBind* pBind = player->GetBoundInstance(GetId(), player->GetDifficulty(IsRaid())); InstanceSave* pSave = pBind ? pBind->save : NULL; // The player's permanent player bind is taken into consideration first, then the player's group bind and finally the solo bind. if (!pBind || !pBind->perm) { InstanceGroupBind* groupBind = NULL; Group* group = player->GetGroup(); // Use the player's difficulty setting (it may not be the same as the group's). if (group) { groupBind = group->GetBoundInstance(this); if (groupBind) pSave = groupBind->save; } } if (pSave) { // Solo / permanent / group lock exists. newInstanceId = pSave->GetInstanceId(); map = FindInstanceMap(newInstanceId); if (IsRaid()) { if (player->IsOnDynamicDifficultyMap()) { // Dynamic Difficulty lock: create an instance that matches the difficulty the player changes to. if (player->GetDifficulty(IsRaid()) != pSave->GetDifficulty() || map && map->GetSpawnMode() != player->GetDifficulty(IsRaid())) map = CreateInstance(newInstanceId, pSave, player->GetDifficulty(IsRaid())); } else { // Shared locks: create an instance to match the current player raid difficulty, if the save and player difficulties don't match. // We must check for save difficulty going original diff -> new one, and map spawn mode going new -> original, to make sure all cases are handled. // Although Heroic 10 / 25 Man also theoretically share a cooldown, if you kill a boss on 10 / 25 Heroic you cannot enter any other Heroic size version of the raid (cannot switch). // Heroic size switching is already handled with no checks needed. The map is created on the save difficulty and you can only switch difficulty dynamically, from inside. if (pSave->GetDifficulty() == RAID_DIFFICULTY_10MAN_NORMAL || pSave->GetDifficulty() == RAID_DIFFICULTY_25MAN_NORMAL) { // Normal. The map is created on the player difficulty. if (player->GetDifficulty(IsRaid()) != pSave->GetDifficulty() || map && map->GetSpawnMode() != player->GetDifficulty(IsRaid())) map = CreateInstance(newInstanceId, pSave, player->GetDifficulty(IsRaid())); } } } // It is possible that the save exists but the map doesn't, create it. if (!map) map = CreateInstance(newInstanceId, pSave, pSave->GetDifficulty()); } else { // If no instanceId via group members or instance saves is found, the instance will be created for the first time. newInstanceId = sMapMgr->GenerateInstanceId(); Difficulty diff = player->GetGroup() ? player->GetGroup()->GetDifficulty(IsRaid()) : player->GetDifficulty(IsRaid()); map = FindInstanceMap(newInstanceId); if (!map) map = CreateInstance(newInstanceId, NULL, diff); } } return map; }
STRUCT__OBJECT__COLOR * getRGB_object(int ifcModel, STRUCT__IFC__ITEM * ifcItem) { STRUCT__OBJECT__COLOR * objectColor = 0, ** ppObjectColor = &objectColor; STRUCT__ITEM__COLOR * returnedItemColor = 0; int ifcProductRepresentationInstance = 0; #ifdef _UNICODE sdaiGetAttrBN(ifcItem->ifcID, (char *) L"Representation", sdaiINSTANCE, &ifcProductRepresentationInstance); #else sdaiGetAttrBN(ifcItem->ifcID, "Representation", sdaiINSTANCE, &ifcProductRepresentationInstance); #endif if (ifcProductRepresentationInstance != 0) { getRGB_productDefinitionShape(ifcModel, ifcProductRepresentationInstance, ppObjectColor); } if (objectColor) { bool unique = true, defaultColorIsUsed = false; STRUCT__ITEM__COLOR * itemColor = 0; DEBUG__localObjectColor = objectColor; minimizeItemColorItems(objectColor, &itemColor, &unique, &defaultColorIsUsed); if (unique) { returnedItemColor = itemColor; } else { returnedItemColor = 0; } if (defaultColorIsUsed) { // // Color not found, check if we can find colors via propertySets // STRUCT__PROPERTY__SET * propertySet = ifcItem->propertySets; while (propertySet) { #ifdef _UNICODE if (Equals(propertySet->name, L"Pset_Draughting")) { #else if (Equals(propertySet->name, "Pset_Draughting")) { #endif /// color->surface.R = 0; /// color->surface.G = 0; /// color->surface.B = 0; /// color->surface.A = 1; STRUCT__PROPERTY * _property = propertySet->properties; while (_property) { #ifdef _UNICODE if (Equals(_property->name, L"Red")) { int value = _wtoi(_property->nominalValue); #else if (Equals(_property->name, "Red")) { int value = atoi(_property->nominalValue); #endif /// color->surface.R = (double) value / 256; } #ifdef _UNICODE if (Equals(_property->name, L"Green")) { int value = _wtoi(_property->nominalValue); #else if (Equals(_property->name, "Green")) { int value = atoi(_property->nominalValue); #endif /// color->surface.G = (double) value / 256; } #ifdef _UNICODE if (Equals(_property->name, L"Blue")) { int value = _wtoi(_property->nominalValue); #else if (Equals(_property->name, "Blue")) { int value = atoi(_property->nominalValue); #endif /// color->surface.B = (double) value / 256; } _property = _property->next; } } propertySet = propertySet->next; } } } if (returnedItemColor) { ifcItem->itemColor = returnedItemColor; return 0; } else { ifcItem->itemColor = 0; return objectColor; } } void minimizeItemColorItems(STRUCT__OBJECT__COLOR * objectColor, STRUCT__ITEM__COLOR ** ppItemColor, bool * pUnique, bool * pDefaultColorIsUsed) { while (objectColor) { // // Check nested child object (i.e. Mapped Items) // if (objectColor->child) { //ASSERT(objectColor->itemColor->surface.R == -1); if (objectColor->itemColor->surface.R != -1) return; //ASSERT(objectColor->itemColor->active == false); if (objectColor->itemColor->active != false) return; deleteItemColor(objectColor->itemColor); objectColor->itemColor = 0; minimizeItemColorItems(objectColor->child, ppItemColor, pUnique, pDefaultColorIsUsed); } // // Complete Color // STRUCT__ITEM__COLOR * itemColor = objectColor->itemColor; if (itemColor) { if (itemColor->surface.R == -1) { objectColor->itemColor = defaultItemColor; deleteItemColor(itemColor); } else { if (itemColor->diffuse.R == -1) { itemColor->diffuse.R = itemColor->surface.R; itemColor->diffuse.G = itemColor->surface.G; itemColor->diffuse.B = itemColor->surface.B; itemColor->diffuse.A = itemColor->surface.A; } if (itemColor->specular.R == -1) { itemColor->specular.R = itemColor->surface.R; itemColor->specular.G = itemColor->surface.G; itemColor->specular.B = itemColor->surface.B; itemColor->specular.A = itemColor->surface.A; } } } else { //ASSERT(objectColor->child); if (objectColor->child != NULL) return; } // // Merge the same colors // itemColor = objectColor->itemColor; if (itemColor && itemColor != defaultItemColor) { bool adjusted = false; //ASSERT(itemColor->active == false); if (itemColor->active != false) return; STRUCT__ITEM__COLOR * itemColorLoop = firstItemColor; while (itemColorLoop && itemColorLoop->next) { if ( (itemColorLoop->active) && (itemColor->transparency == itemColorLoop->transparency) && (itemColor->surface.R == itemColorLoop->surface.R) && (itemColor->surface.G == itemColorLoop->surface.G) && (itemColor->surface.B == itemColorLoop->surface.B) && (itemColor->surface.A == itemColorLoop->surface.A) && (itemColor->diffuse.R == itemColorLoop->diffuse.R) && (itemColor->diffuse.G == itemColorLoop->diffuse.G) && (itemColor->diffuse.B == itemColorLoop->diffuse.B) && (itemColor->diffuse.A == itemColorLoop->diffuse.A) && (itemColor->specular.R == itemColorLoop->specular.R) && (itemColor->specular.G == itemColorLoop->specular.G) && (itemColor->specular.B == itemColorLoop->specular.B) && (itemColor->specular.A == itemColorLoop->specular.A) ) { objectColor->itemColor = itemColorLoop; deleteItemColor(itemColor); itemColorLoop = 0; adjusted = true; } else { itemColorLoop = itemColorLoop->next; } } if (adjusted) { //ASSERT(objectColor->itemColor->active); if (!objectColor->itemColor->active) return; } else { //ASSERT(objectColor->itemColor->active == false); if (objectColor->itemColor->active != false) return; objectColor->itemColor->active = true; } //ASSERT(itemColorLoop == 0 || (itemColorLoop == defaultItemColor && itemColorLoop->next == 0)); if (itemColorLoop != 0 && (itemColorLoop != defaultItemColor || itemColorLoop->next != 0)) return; } // // Assign default color in case of no color and no children // if (objectColor->itemColor == 0 && objectColor->child == 0) { objectColor->itemColor = defaultItemColor; } // // Check if unique // itemColor = objectColor->itemColor; if ((*ppItemColor)) { if ((*ppItemColor) != itemColor) { if (itemColor == 0 && objectColor->child) { } else { (*pUnique) = false; } } } else { //ASSERT((*pUnique) == true); if ((*pUnique) != true) return; (*ppItemColor) = itemColor; } if (itemColor == defaultItemColor) { (*pDefaultColorIsUsed) = true; } objectColor = objectColor->next; } } void completeItemColorItems() { STRUCT__ITEM__COLOR * itemColor = firstItemColor; while (itemColor) { //ASSERT(itemColor->active); if (!itemColor->active) return; itemColor->mtrl.Ambient.r = (float) itemColor->surface.R; itemColor->mtrl.Ambient.g = (float) itemColor->surface.G; itemColor->mtrl.Ambient.b = (float) itemColor->surface.B; itemColor->mtrl.Ambient.a = (float) itemColor->transparency; itemColor->mtrl.Diffuse.r = (float) itemColor->diffuse.R; itemColor->mtrl.Diffuse.g = (float) itemColor->diffuse.G; itemColor->mtrl.Diffuse.b = (float) itemColor->diffuse.B; itemColor->mtrl.Diffuse.a = (float) itemColor->transparency; itemColor->mtrl.Specular.r = (float) itemColor->specular.R; itemColor->mtrl.Specular.g = (float) itemColor->specular.G; itemColor->mtrl.Specular.b = (float) itemColor->specular.B; itemColor->mtrl.Specular.a = (float) itemColor->transparency; itemColor->mtrl.Emissive.r = (float) itemColor->surface.R / 2; itemColor->mtrl.Emissive.g = (float) itemColor->surface.G / 2; itemColor->mtrl.Emissive.b = (float) itemColor->surface.B / 2; itemColor->mtrl.Emissive.a = (float) itemColor->transparency / 2; itemColor->mtrl.Power = 0.5; itemColor = itemColor->next; } } __int64 owlInstanceBase; void reCreateGeometry(__int64 owlModel, __int64 owlInstance, STRUCT__IFC__ITEM ** ppIfcSubItem, STRUCT__ITEM__COLOR * itemColor, __int64 transformationOwlInstance) { __int64 noVertices = 0, noIndices = 0; SetObjectTypeProperty(transformationOwlInstance, owlObjectTypePropertyObject, &owlInstance, 1); CalculateInstance(owlInstanceBase, &noVertices, &noIndices, 0); if (noVertices && noIndices) { while ((*ppIfcSubItem)) { ppIfcSubItem = &(*ppIfcSubItem)->next; } (*ppIfcSubItem) = new STRUCT__IFC__ITEM; STRUCT__IFC__ITEM * ifcSubItem = (*ppIfcSubItem); //ifcSubItem->hideChildren = false; ifcSubItem->structType = STRUCT_TYPE_IFC_ITEM; ifcSubItem->ifcID = 0; //ifcSubItem->treeItemGeometry = 0; //ifcSubItem->treeItemProperties = 0; ifcSubItem->itemColor = itemColor; //ifcSubItem->isSub = true; ifcSubItem->parent = 0; ifcSubItem->child = 0; //ifcSubItem->subChild = 0; ifcSubItem->next = 0; ifcSubItem->globalId = 0; ifcSubItem->name = 0; //ifcSubItem->description = 0; ifcSubItem->ifcType = 0; /*ifcSubItem->indicesForFaces = 0; ifcSubItem->noPrimitivesForFaces = 0; ifcSubItem->indicesForLinesWireFrame = 0; ifcSubItem->noPrimitivesForWireFrame = 0;*/ //ifcSubItem->indexOffsetForFaces = 0; //ifcSubItem->vertexOffsetForFaces = 0; //ifcSubItem->noVertices = (int)noVertices; //ifcSubItem->vertices = new float[(int)noVertices * 6]; // <x, y, z> //int * indices = new int[(int)noIndices]; // //UpdateInstanceVertexBuffer(owlInstanceBase, ifcSubItem->vertices); //UpdateInstanceIndexBuffer(owlInstanceBase, indices); //ifcSubItem->noPrimitivesForWireFrame = 0; ////ASSERT(ifcSubItem->indicesForLinesWireFrame == 0); //if (ifcSubItem->indicesForLinesWireFrame != 0) // return; //int * indicesForLinesWireFrame = new int[2*(int)noIndices]; //ifcSubItem->noVertices = (int)noVertices; ////ASSERT(ifcSubItem->indicesForFaces == 0); //if (ifcSubItem->indicesForFaces != 0) // return; //int * indicesForFaces = new int[(int)noIndices]; //__int64 faceCnt = GetConceptualFaceCnt(owlInstanceBase); //for (__int64 j = 0; j < faceCnt; j++) { // __int64 startIndexTriangles = 0, noIndicesTrangles = 0, startIndexFacesPolygons = 0, noIndicesFacesPolygons = 0; // GetConceptualFaceEx(owlInstanceBase, j, &startIndexTriangles, &noIndicesTrangles, 0, 0, 0, 0, &startIndexFacesPolygons, &noIndicesFacesPolygons, 0, 0); // int i = 0; // while (i < noIndicesTrangles) { // indicesForFaces[ifcSubItem->noPrimitivesForFaces * 3 + i] = indices[startIndexTriangles + i]; // i++; // } // ifcSubItem->noPrimitivesForFaces += (int)noIndicesTrangles/3; // i = 0; // int lastItem = -1; // while (i < noIndicesFacesPolygons) { // if (lastItem >= 0 && indices[startIndexFacesPolygons+i] >= 0) { // indicesForLinesWireFrame[2*ifcSubItem->noPrimitivesForWireFrame + 0] = lastItem; // indicesForLinesWireFrame[2*ifcSubItem->noPrimitivesForWireFrame + 1] = indices[startIndexFacesPolygons+i]; // ifcSubItem->noPrimitivesForWireFrame++; // } // lastItem = indices[startIndexFacesPolygons+i]; // i++; // } //} //ifcSubItem->indicesForFaces = new int[3 * ifcSubItem->noPrimitivesForFaces]; //ifcSubItem->indicesForLinesWireFrame = new int[2 * ifcSubItem->noPrimitivesForWireFrame]; // //memcpy(ifcSubItem->indicesForFaces, indicesForFaces, 3 * ifcSubItem->noPrimitivesForFaces * sizeof(int)); //memcpy(ifcSubItem->indicesForLinesWireFrame, indicesForLinesWireFrame, 2 * ifcSubItem->noPrimitivesForWireFrame * sizeof(int)); } } void walkThroughGeometry__object(__int64 owlModel, __int64 owlInstance, STRUCT__IFC__ITEM ** ppIfcSubItem, STRUCT__OBJECT__COLOR ** ppObjectColor, int depth, __int64 transformationOwlInstance) { __int64 * owlInstanceExpressID = 0, expressIDCard = 0; GetDataTypeProperty(owlInstance, owlDataTypePropertyExpressID, (void **) &owlInstanceExpressID, &expressIDCard); if (expressIDCard == 1) { __int64 expressID = owlInstanceExpressID[0]; while ((*ppObjectColor) && (*ppObjectColor)->expressID != expressID) { ppObjectColor = &(*ppObjectColor)->next; } if ((*ppObjectColor)) { //ASSERT((*ppObjectColor)->expressID == expressID); if ((*ppObjectColor)->expressID != expressID) return; if ((*ppObjectColor)->child) { if (GetInstanceClass(owlInstance) == rdfClassTransformation) { __int64 * owlInstanceObject = 0, objectCard = 0; GetObjectTypeProperty(owlInstance, owlObjectTypePropertyObject, &owlInstanceObject, &objectCard); if (objectCard == 1) { __int64 * owlInstanceMatrix = 0, matrixCard = 0; GetObjectTypeProperty(owlInstance, owlObjectTypePropertyMatrix, &owlInstanceMatrix, &matrixCard); __int64 subTransformationOwlInstance = CreateInstance(rdfClassTransformation, 0); SetObjectTypeProperty(transformationOwlInstance, owlObjectTypePropertyObject, &subTransformationOwlInstance, 1); if (matrixCard == 1) { SetObjectTypeProperty(subTransformationOwlInstance, owlObjectTypePropertyMatrix, owlInstanceMatrix, 1); } else { //ASSERT(false); return; } walkThroughGeometry__object(owlModel, owlInstanceObject[0], ppIfcSubItem, &(*ppObjectColor)->child, depth+1, subTransformationOwlInstance); } else { //ASSERT(false); return; } } else if (GetInstanceClass(owlInstance) == rdfClassCollection) { STRUCT__OBJECT__COLOR ** ppObjectColorChild = &(*ppObjectColor)->child; __int64 * owlInstanceObjects = 0, objectsCard = 0; GetObjectTypeProperty(owlInstance, owlObjectTypePropertyObjects, &owlInstanceObjects, &objectsCard); int i = 0; while (i < objectsCard) { walkThroughGeometry__object(owlModel, owlInstanceObjects[i], ppIfcSubItem, ppObjectColorChild, depth+1, transformationOwlInstance); i++; } } else { //ASSERT(false); return; } } else { // // Now recreate the geometry for this object // reCreateGeometry(owlModel, owlInstance, ppIfcSubItem, (*ppObjectColor)->itemColor, transformationOwlInstance); } ppObjectColor = &(*ppObjectColor)->next; } else { ///////////////////////////// ASSERT(false); } } else { //ASSERT(depth); if (!depth) return; if (GetInstanceClass(owlInstance) == rdfClassTransformation) { __int64 * owlInstanceObject = 0, objectCard = 0; GetObjectTypeProperty(owlInstance, owlObjectTypePropertyObject, &owlInstanceObject, &objectCard); __int64 * owlInstanceMatrix = 0, matrixCard = 0; GetObjectTypeProperty(owlInstance, owlObjectTypePropertyMatrix, &owlInstanceMatrix, &matrixCard); __int64 subTransformationOwlInstance = CreateInstance(rdfClassTransformation, 0); SetObjectTypeProperty(transformationOwlInstance, owlObjectTypePropertyObject, &subTransformationOwlInstance, 1); if (matrixCard == 1) { SetObjectTypeProperty(subTransformationOwlInstance, owlObjectTypePropertyMatrix, owlInstanceMatrix, 1); } else { //ASSERT(false); return; } if (objectCard == 1) { walkThroughGeometry__object(owlModel, owlInstanceObject[0], ppIfcSubItem, ppObjectColor, depth+1, subTransformationOwlInstance); } else { //ASSERT(false); return; } } else if (GetInstanceClass(owlInstance) == rdfClassCollection) { __int64 * owlInstanceObjects = 0, objectsCard = 0; GetObjectTypeProperty(owlInstance, owlObjectTypePropertyObjects, &owlInstanceObjects, &objectsCard); int i = 0; while (i < objectsCard) { walkThroughGeometry__object(owlModel, owlInstanceObjects[i], ppIfcSubItem, ppObjectColor, depth+1, transformationOwlInstance); i++; } } else { //ASSERT(false); return; } } } void walkThroughGeometry__collection(__int64 owlModel, __int64 owlInstance, STRUCT__IFC__ITEM ** ppIfcSubItem, STRUCT__OBJECT__COLOR ** ppObjectColor, __int64 transformationOwlInstance) { if (GetInstanceClass(owlInstance) == rdfClassCollection) { __int64 * owlInstanceObjects = 0, objectsCard = 0; GetObjectTypeProperty(owlInstance, owlObjectTypePropertyObjects, &owlInstanceObjects, &objectsCard); int i = 0; while (i < objectsCard) { walkThroughGeometry__collection(owlModel, owlInstanceObjects[i], ppIfcSubItem, ppObjectColor, transformationOwlInstance); i++; } } else { walkThroughGeometry__object(owlModel, owlInstance, ppIfcSubItem, ppObjectColor, 0, transformationOwlInstance); } } void walkThroughGeometry__transformation(__int64 owlModel, __int64 owlInstance, STRUCT__IFC__ITEM ** ppIfcSubItem, STRUCT__OBJECT__COLOR ** ppObjectColor) { //ASSERT(GetInstanceClass(owlInstance) == rdfClassTransformation); if (GetInstanceClass(owlInstance) != rdfClassTransformation) return; owlInstanceBase = CreateInstance(rdfClassTransformation, 0); __int64 * owlInstanceMatrix = 0, matrixCard = 0; GetObjectTypeProperty(owlInstance, owlObjectTypePropertyMatrix, &owlInstanceMatrix, &matrixCard); if (matrixCard == 1) { SetObjectTypeProperty(owlInstanceBase, owlObjectTypePropertyMatrix, owlInstanceMatrix, 1); } else { //ASSERT(false); return; } __int64 * owlInstanceObject = 0, objectCard = 0; GetObjectTypeProperty(owlInstance, owlObjectTypePropertyObject, &owlInstanceObject, &objectCard); if (objectCard == 1) { walkThroughGeometry__collection(owlModel, owlInstanceObject[0], ppIfcSubItem, ppObjectColor, owlInstanceBase); } else { //ASSERT(false); return; } } STRUCT__IFC__ITEM * newSubGeometry(__int64 owlModel, __int64 owlInstance, STRUCT__OBJECT__COLOR * objectColor) { STRUCT__IFC__ITEM * ifcSubItem = 0; if (objectColor) { STRUCT__OBJECT__COLOR * loopObjectColor = objectColor; walkThroughGeometry__transformation(owlModel, owlInstance, &ifcSubItem, &loopObjectColor); } return ifcSubItem; }
/* - return the right instance for the object, based on its InstanceId - create the instance if it's not created already - the player is not actually added to the instance (only in InstanceMap::Add) */ Map* MapInstanced::CreateInstanceForPlayer(const uint32 mapId, Player* player) { if (GetId() != mapId || !player) return NULL; Map* map = NULL; uint32 newInstanceId = 0; // instanceId of the resulting map if (IsBattlegroundOrArena()) { // instantiate or find existing bg map for player // the instance id is set in battlegroundid newInstanceId = player->GetBattlegroundId(); if (!newInstanceId) return NULL; map = sMapMgr->FindMap(mapId, newInstanceId); if (!map) { if (Battleground* bg = player->GetBattleground()) map = CreateBattleground(newInstanceId, bg); else { player->TeleportToBGEntryPoint(); return NULL; } } } else if (!IsGarrison()) { InstancePlayerBind* pBind = player->GetBoundInstance(GetId(), player->GetDifficultyID(GetEntry())); InstanceSave* pSave = pBind ? pBind->save : NULL; // the player's permanent player bind is taken into consideration first // then the player's group bind and finally the solo bind. if (!pBind || !pBind->perm) { InstanceGroupBind* groupBind = NULL; Group* group = player->GetGroup(); // use the player's difficulty setting (it may not be the same as the group's) if (group) { groupBind = group->GetBoundInstance(this); if (groupBind) pSave = groupBind->save; } } if (pSave) { // solo/perm/group newInstanceId = pSave->GetInstanceId(); map = FindInstanceMap(newInstanceId); // it is possible that the save exists but the map doesn't if (!map) map = CreateInstance(newInstanceId, pSave, pSave->GetDifficultyID()); } else { // if no instanceId via group members or instance saves is found // the instance will be created for the first time newInstanceId = sMapMgr->GenerateInstanceId(); Difficulty diff = player->GetGroup() ? player->GetGroup()->GetDifficultyID(GetEntry()) : player->GetDifficultyID(GetEntry()); //Seems it is now possible, but I do not know if it should be allowed //ASSERT(!FindInstanceMap(NewInstanceId)); map = FindInstanceMap(newInstanceId); if (!map) map = CreateInstance(newInstanceId, NULL, diff); } } else { newInstanceId = player->GetGUID().GetCounter(); map = FindInstanceMap(newInstanceId); if (!map) map = CreateGarrison(newInstanceId, player); } return map; }
void Import::LoadGeometries (dScene& scene, GeometryCache& meshCache, const MaterialCache& materialCache) { dScene::Iterator iter (scene); for (iter.Begin(); iter; iter ++) { dScene::dTreeNode* const geometryNode = iter.GetNode(); dNodeInfo* const info = scene.GetInfoFromNode(geometryNode); if (info->IsType(dGeometryNodeInfo::GetRttiType())) { if (info->GetTypeId() == dMeshNodeInfo::GetRttiType()) { // add the vertices PolyObject* const geometry = (PolyObject*) CreateInstance (GEOMOBJECT_CLASS_ID, Class_ID(POLYOBJ_CLASS_ID, 0)); meshCache.AddMesh(geometry, geometryNode); MNMesh& maxMesh = geometry->GetMesh(); dMeshNodeInfo* const meshInfo = (dMeshNodeInfo*) scene.GetInfoFromNode(geometryNode); NewtonMesh* const mesh = meshInfo->GetMesh(); //NewtonMeshTriangulate (mesh); //NewtonMeshPolygonize (mesh); int faceCount = 0; int vertexCount = NewtonMeshGetVertexCount(mesh); for (void* face = NewtonMeshGetFirstFace(mesh); face; face = NewtonMeshGetNextFace(mesh, face)) { if (!NewtonMeshIsFaceOpen(mesh, face)) { faceCount ++; } } maxMesh.Clear(); maxMesh.setNumVerts(vertexCount); maxMesh.setNumFaces(faceCount); // add all vertex int vertexStride = NewtonMeshGetVertexStrideInByte(mesh) / sizeof (dFloat64); dFloat64* const vertex = NewtonMeshGetVertexArray (mesh); for (int j = 0; j < vertexCount; j ++) { maxMesh.P(j) = Point3 (vertex[vertexStride * j + 0], vertex[vertexStride * j + 1], vertex[vertexStride * j + 2]); } // count the number of face and make a face map int faceIndex = 0; for (void* face = NewtonMeshGetFirstFace(mesh); face; face = NewtonMeshGetNextFace(mesh, face)) { if (!NewtonMeshIsFaceOpen(mesh, face)) { int faceIndices[256]; int indexCount = NewtonMeshGetFaceIndexCount (mesh, face); int matId = NewtonMeshGetFaceMaterial (mesh, face); MaterialProxi material; material.m_mtl = 0; material.m_matID = 0; MaterialCache::dTreeNode* const materialNode = materialCache.Find(matId); if (materialNode) { material = materialNode->GetInfo(); } NewtonMeshGetFaceIndices (mesh, face, faceIndices); MNFace* const face = maxMesh.F(faceIndex); face->MakePoly(indexCount, faceIndices, NULL, NULL); face->material = material.m_matID; faceIndex ++; } } int pointCount = NewtonMeshGetPointCount(mesh); int texChannels = 2; maxMesh.SetMapNum (texChannels); maxMesh.M(texChannels - 1)->ClearFlag (MN_DEAD); maxMesh.M(texChannels - 1)->setNumFaces (faceCount); maxMesh.M(texChannels - 1)->setNumVerts (pointCount); UVVert* const tv = maxMesh.M(texChannels - 1)->v; MNMapFace* const tf = maxMesh.M(texChannels - 1)->f; // add uvs dFloat64* const uv0 = NewtonMeshGetUV0Array(mesh); int pointStride = NewtonMeshGetPointStrideInByte(mesh) / sizeof (dFloat64); for (int j = 0; j < pointCount; j ++) { tv[j] = Point3 (uv0[pointStride * j + 0], uv0[pointStride * j + 1], 0.0); } faceIndex = 0; for (void* face = NewtonMeshGetFirstFace(mesh); face; face = NewtonMeshGetNextFace(mesh, face)) { if (!NewtonMeshIsFaceOpen(mesh, face)) { int faceIndices[256]; int indexCount = NewtonMeshGetFaceIndexCount (mesh, face); NewtonMeshGetFacePointIndices (mesh, face, faceIndices); MNMapFace* const textFace = &tf[faceIndex]; textFace->MakePoly (indexCount, faceIndices); faceIndex ++; } } maxMesh.InvalidateGeomCache(); maxMesh.InvalidateTopoCache(); maxMesh.FillInMesh(); } else { _ASSERTE (0); } } } }