iImage * pawsImageDrawable::GetImage() { if (image) return image; csRef<iVFS> vfs = csQueryRegistry<iVFS>(PawsManager::GetSingleton().GetObjectRegistry()); csRef<iImageIO> imageLoader = csQueryRegistry<iImageIO >( PawsManager::GetSingleton().GetObjectRegistry()); csRef<iDataBuffer> buf(vfs->ReadFile(imageFileLocation, false)); if (!buf || !buf->GetSize()) { Error2("Could not open image: '%s'", imageFileLocation.GetData()); return 0; } image = imageLoader->Load(buf, CS_IMGFMT_ANY | CS_IMGFMT_ALPHA); if (!image) { Error2( "Could not load image: '%s'", imageFileLocation.GetData()); return 0; } image->SetName(imageFileLocation); return image; }
unsigned int psEffectManager::RenderEffect(const csString & effectName, iSector * sector, const csVector3 & pos, iMeshWrapper * attachTarget, const csVector3 & up, const unsigned int uniqueIDOverride, const float* scale) { #ifndef DONT_DO_EFFECTS // check if it's a single effect psEffect * currEffect = FindEffect(effectName); if (currEffect != 0) { currEffect = currEffect->Clone(); if (scale != NULL) { if (!currEffect->SetFrameParamScalings(scale)) { Error2("Received scale factor for effect %s that don't use param scaling",effectName.GetDataSafe()); } } unsigned int uniqueID = currEffect->Render(sector, pos, 0, attachTarget, up.Unit(), uniqueIDOverride); actualEffects.Put(uniqueID, currEffect); return uniqueID; } Error2("Failed to find effect with name: %s",effectName.GetDataSafe()); #endif return 0; }
csRef<iDocumentNode> PawsManager::ParseWidgetFile( const char* widgetFile ) { csRef<iDocument> doc; const char* error; csRef<iDataBuffer> buff = vfs->ReadFile(widgetFile); if (buff == NULL) { Error2("Could not find file: %s", widgetFile); return NULL; } doc=xml->CreateDocument(); error=doc->Parse(buff); if ( error ) { Error3("Parse error in %s: %s", widgetFile, error); return NULL; } csRef<iDocumentNode> root; if((root=doc->GetRoot())) { csRef<iDocumentNode> widgetNode = root->GetNode("widget_description"); if (!widgetNode) Error2("File %s has no <widget_description> tag", widgetFile); return widgetNode; } else { Error2("Bad XML document in %s", widgetFile); return NULL; } }
static int Read_Dump(BYTE *buf, DWORD size) { int num, ahex; ZeroMemory(buf, size); //Обнулили буфер на случай группового нуля char *NewAdr = strchr(Adr, '\0'); if(NewAdr > AdrEnd || NewAdr == NULL) return -1; //Данные кончились и Больше нет ни одной полной строки Adr = NewAdr + 1; DWORD nn = 0; for(int n=1, hex=0; ; n++,hex+=128) //До конца файла { NewAdr = strchr(Adr, '\0'); if(NewAdr > AdrEnd || NewAdr == NULL) return -1; //Данные кончились и Больше нет ни одной полной строки if(lstrcmp(Adr, "All bytes == 0\r") == 0) return 0; //Абсолютно везде нули sscanf(Adr, "%d: %x:", &num, &ahex); if(n != num && ahex != hex) return Error2("Нарушение порядка следования строк.", "Эмулятор."); Adr += 14; for(int j=1; j<=128; j++) { if(strncmp(Adr, "(0)", 3) == 0) return 0; //Далее все нули DWORD OneB; sscanf(Adr, "%x", &OneB); *(buf + nn) = BYTE(OneB); nn++; if(nn > size) return Error2("Переполнение буфера.", "Эмулятор."); Adr += 3; if((j % 8) == 0) Adr++; } Adr = NewAdr + 1; if(nn == size) return 0; } }
void QuestionManager::HandleQuestionResponse(MsgEntry *me,Client *client) { psQuestionResponseMsg msg(me); if (!msg.valid) { psserver->SendSystemError(me->clientnum, "Invalid QuestionResponse Message."); Error2("Failed to parse psQuestionResponseMsg from client %u.",me->clientnum); return; } // Find the question that we got response to PendingQuestion *question = questions.Get(msg.questionID, NULL); if (!question) { Error2("Received psQuestionResponseMsg from client %u that was not questioned.",me->clientnum); return; } if (question->event) { question->event->valid = false; // This keeps the cancellation timeout from firing. } question->HandleAnswer(msg.answer); questions.DeleteAll(msg.questionID); // Question is no longer pending. delete question; }
/* perform actions that are common to all NAMED group addresses: checking if the entry exists, parsing options, ev.removing old filesystem entry or setting early owners and permissions. It applies options of PH_EARLY and PH_PREOPEN. If the path exists, its st_mode field is returned. After this sub you may proceed with open() or whatever... */ int _xioopen_named_early(int argc, const char *argv[], xiofile_t *xfd, int groups, bool *exists, struct opt *opts) { const char *path = argv[1]; unsigned int iogroups = 0; #if HAVE_STAT64 struct stat64 statbuf; #else struct stat statbuf; #endif /* !HAVE_STAT64 */ bool opt_unlink_early = false; if (argc != 2) { Error2("%s: wrong number of parameters (%d instead of 1)", argv[0]?argv[0]:"<named>", argc); } statbuf.st_mode = 0; /* find the appropriate groupbits */ if ( #if HAVE_STAT64 Stat64(path, &statbuf) < 0 #else Stat(path, &statbuf) < 0 #endif /* !HAVE_STAT64 */ ) { if (errno != ENOENT) { Error2("stat(\"%s\"): %s", path, strerror(errno)); return STAT_RETRYLATER; } iogroups = GROUP_REG; *exists = false; } else { iogroups = _groupbits(statbuf.st_mode); *exists = true; } if (applyopts_single(&xfd->stream, opts, PH_INIT) < 0) return -1; applyopts(-1, opts, PH_INIT); retropt_bool(opts, OPT_UNLINK_EARLY, &opt_unlink_early); if (*exists && opt_unlink_early) { Info1("\"%s\" already exists; removing it", path); if (Unlink(path) < 0) { Error2("unlink(\"%s\"): %s", path, strerror(errno)); *exists = true; } else { *exists = false; } } applyopts(-1, opts, PH_EARLY); applyopts_named(path, opts, PH_EARLY); if (*exists) { applyopts_named(path, opts, PH_PREOPEN); } else { dropopts(opts, PH_PREOPEN); } return statbuf.st_mode; }
static int xioopen_rawip_recv(int argc, const char *argv[], struct opt *opts, int xioflags, xiofile_t *xfd, unsigned groups, int pf, int socktype, int dummy3) { const char *protname = argv[1]; char *garbage; bool needbind = false; union sockaddr_union us; socklen_t uslen = sizeof(us); int ipproto; int result; if (argc != 2) { Error2("%s: wrong number of parameters (%d instead of 1)", argv[0], argc-1); return STAT_NORETRY; } if ((ipproto = strtoul(protname, &garbage, 0)) >= 256) { Error2("xioopen_rawip_recv(\"%s\",,): protocol number exceeds 255 (%u)", protname, ipproto); return STAT_NORETRY; } else if (*garbage) { Warn1("xioopen_rawip_recv(\"%s\",,): trailing garbage in protocol specification", protname); /*return STAT_NORETRY;*/ } retropt_socket_pf(opts, &pf); if (pf == PF_UNSPEC) { #if WITH_IP4 && WITH_IP6 pf = xioopts.default_ip=='6'?PF_INET6:PF_INET; #elif WITH_IP6 pf = PF_INET6; #else pf = PF_INET; #endif } if (retropt_bind(opts, pf, socktype, ipproto, &/*us.soa*/xfd->stream.para.socket.la.soa, &uslen, 1, xfd->stream.para.socket.ip.res_opts[0], xfd->stream.para.socket.ip.res_opts[1]) == STAT_OK) { needbind = true; } else { /* pf is required during xioread checks */ xfd->stream.para.socket.la.soa.sa_family = pf; } xfd->stream.dtype = XIODATA_RECV_SKIPIP; result = _xioopen_dgram_recv(&xfd->stream, xioflags, needbind?&/*us.soa*/xfd->stream.para.socket.la.soa:NULL, uslen, opts, pf, socktype, ipproto, E_ERROR); _xio_openlate(&xfd->stream, opts); return result; }
int xioparsenetwork_ip4(const char *rangename, struct xiorange *range) { struct hostent *maskaddr; struct in_addr *netaddr_in = &range->netaddr.ip4.sin_addr; struct in_addr *netmask_in = &range->netmask.ip4.sin_addr; char *rangename1; /* a copy of rangename with writing allowed */ char *delimpos; /* absolute address of delimiter */ unsigned int bits; /* netmask bits */ if ((rangename1 = strdup(rangename)) == NULL) { Error1("strdup(\"%s\"): out of memory", rangename); return STAT_RETRYLATER; } if (delimpos = strchr(rangename1, '/')) { char *endptr; bits = strtoul(delimpos+1, &endptr, 10); if (! ((*(delimpos+1) != '\0') && (*endptr == '\0'))) { Error1("not a valid netmask in \"%s\"", rangename); bits = 32; /* most secure selection */ } else if (bits > 32) { Error1("netmask \"%s\" is too large", rangename); bits = 32; } if (bits <= 0) { netmask_in->s_addr = 0; } else { netmask_in->s_addr = htonl((0xffffffff << (32-bits))); } } else if (delimpos = strchr(rangename1, ':')) { if ((maskaddr = Gethostbyname(delimpos+1)) == NULL) { /* note: cast is req on AIX: */ Error2("gethostbyname(\"%s\"): %s", delimpos+1, h_errno == NETDB_INTERNAL ? strerror(errno) : (char *)hstrerror(h_errno)); return STAT_NORETRY; } netmask_in->s_addr = *(uint32_t *)maskaddr->h_addr_list[0]; } else { Error1("xioparsenetwork_ip4(\"%s\",,): missing netmask delimiter", rangename); free(rangename1); return STAT_NORETRY; } { struct hostent *nameaddr; *delimpos = 0; if ((nameaddr = Gethostbyname(rangename1)) == NULL) { /* note: cast is req on AIX: */ Error2("gethostbyname(\"%s\"): %s", rangename1, h_errno == NETDB_INTERNAL ? strerror(errno) : (char *)hstrerror(h_errno)); free(rangename1); return STAT_NORETRY; } netaddr_in->s_addr = *(uint32_t *)nameaddr->h_addr_list[0]; } free(rangename1); return STAT_OK; }
bool pawsTextureManager::LoadImageList( const char* listName ) { printf("Texture Manager parsing %s\n", listName); csRef<iDataBuffer> buff = vfs->ReadFile( listName ); if ( !buff || !buff->GetSize() ) { return false; } csRef<iDocument> doc = xml->CreateDocument(); const char* error = doc->Parse( buff ); if ( error ) { Error3("Error %s in %s", error, listName); return false; } csRef<iDocumentNode> root = doc->GetRoot(); if (!root) { Error2("XML error in %s", listName); return false; } csRef<iDocumentNode> topNode = root->GetNode("image_list"); if(!topNode) { Error2("Missing tag <image_list> in %s", listName); return false; } csRef<iDocumentNodeIterator> iter = topNode->GetNodes(); while ( iter->HasNext() ) { csRef<iDocumentNode> node = iter->Next(); if ( node->GetType() != CS_NODE_ELEMENT ) continue; if (elementList.Contains(node->GetAttributeValue("resource"))) continue; csRef<iPawsImage> element; if (!strcmp(node->GetValue(), "image")) element.AttachNew(new pawsImageDrawable(node)); else if (!strcmp(node->GetValue(), "frame")) element.AttachNew(new pawsFrameDrawable(node)); else Error2("Illegal node name in imagelist.xml: %s", node->GetValue() ); if(element.IsValid()) AddPawsImage(element); } return true; }
/* applies to fd all options belonging to phase */ int applyopts_named(const char *filename, struct opt *opts, unsigned int phase) { struct opt *opt; if (!opts) return 0; opt = opts; while (opt->desc != ODESC_END) { if (opt->desc == ODESC_DONE || opt->desc->phase != phase && phase != PH_ALL || !(opt->desc->group & GROUP_NAMED)) { ++opt; continue; } switch (opt->desc->optcode) { case OPT_GROUP_EARLY: case OPT_GROUP: if (Chown(filename, -1, opt->value.u_gidt) < 0) { Error3("chown(\"%s\", -1, "F_gid"): %s", filename, opt->value.u_gidt, strerror(errno)); } break; case OPT_USER_EARLY: case OPT_USER: if (Chown(filename, opt->value.u_uidt, -1) < 0) { Error3("chown(\"%s\", "F_uid", -1): %s", filename, opt->value.u_uidt, strerror(errno)); } break; case OPT_PERM_EARLY: case OPT_PERM: if (Chmod(filename, opt->value.u_modet) < 0) { Error3("chmod(\"%s\", "F_mode"): %s", filename, opt->value.u_modet, strerror(errno)); } break; case OPT_UNLINK_EARLY: case OPT_UNLINK: case OPT_UNLINK_LATE: if (Unlink(filename) < 0) { if (errno == ENOENT) { Warn2("unlink(\"%s\"): %s", filename, strerror(errno)); } else { Error2("unlink(\"%s\"): %s", filename, strerror(errno)); } } break; case OPT_UMASK: if (Umask(opt->value.u_modet) < 0) { /* linux docu says it always succeeds, but who believes it? */ Error2("umask("F_mode"): %s", opt->value.u_modet, strerror(errno)); } break; default: Error1("applyopts_named(): option \"%s\" not implemented", opt->desc->defname); break; } opt->desc = ODESC_DONE; ++opt; } return 0; }
csRef<iSndSysData> PawsManager::LoadSound(const char *filename,const char *registeredname) { PawsSoundHandle *pawssndhandle; // If a registered name is not provided, the filename is used as the registered name if (registeredname==NULL) registeredname=filename; // Filename must always be specified if (filename==NULL) return NULL; // Search for the same sound already loaded int name_hash=csHashCompute(registeredname); { csHash<PawsSoundHandle *>::Iterator sounditerator = sounds.GetIterator(name_hash); while (sounditerator.HasNext()) { pawssndhandle = sounditerator.Next(); if (pawssndhandle->name.Compare(registeredname)) return pawssndhandle->snddata; } } // If there is no sound loader or vfs, sound loading cannot not be performed // This is checked after the registered name check since RegisterSound could add sounds created // by some other method. if (!vfs.IsValid() || !soundloader.IsValid()) return NULL; // Load the file data csRef<iDataBuffer> soundbuf = vfs->ReadFile(filename); if (!soundbuf) { Error2("Error while reading file '%s'", filename); return NULL; } // Read it into a sound buffer csRef<iSndSysData> sounddata = soundloader->LoadSound (soundbuf); if (!sounddata) { Error2("Cannot create sound data from file '%s'", filename); return NULL; } // Create a paws handle to relate the name to the iSndData and add it to our paws managed list pawssndhandle = new PawsSoundHandle(registeredname,sounddata); if (pawssndhandle) sounds.Put(name_hash,pawssndhandle); // Return the iSndSysHandle return csPtr<iSndSysData>( sounddata ); }
int FindHDD_LG_Emul(void) //Поиск диска из рекордера LG эмулятором { #if !defined EMULATOR_HDD_AND_COPY //Режим эмулятора с эмуляцией копирования EnableWindow(hCopy, FALSE); #endif if(Load_Dump() < 0) return -1; //Загрузка дампа SEC_0 Sec0; // if(FindStr("Sector 0") < 0) return -1; // if(Read_Dump((BYTE*)&Sec0, 512) < 0) return -1; if(Read_Sec_Emul(0, (BYTE*)&Sec0) < 0) return -1; //Чтение сектора по номеру эмулятором #if defined OUT_TEST Add_SpecSpis("Find HDD from LG emulator"); #endif SEC_63 Sec63; if(FindStr("Sector 63") < 0) return -1; if(Read_Dump((BYTE*)&Sec63, 512) < 0) return -1; if(strncmp(Sec63.Met, "LGEINC ", 8) != 0 || strncmp(Sec63.Name, "VOLUMELABE FAT32 ", 19) != 0) return Error2("Содержимое сектора 63 не соответствует требованиям.", "Эмулятор."); #if defined OUT_TEST Add_SpecSpis("HDD from LG found"); Add_SpecSpis("Sector 63"); View_HEX_Any((BYTE *)&Sec63, 512); #endif if(Sec63.nf != 1 || Sec63.F8 != 0xF8 || Sec63.SecPerCl != sClSec) return Error1((Lan+19)->msg); //return Error1("Найден жесткий диск только частично похожий на то, что он из рекордера LG."); Start_SecFAT1 = 63 + Sec63.numRezSec; //Позиция начала таблицы FAT Start_SecDir1 = Start_SecFAT1 + Sec63.nSecDir; //Позиция начала первого каталога num_SecFAT1 = Sec63.numSecFAT; //Число секторов в FAT Size_FAT1 = num_SecFAT1 * sSecB; //Число байт в FAT // maxZapFAT1 = sSecB / 4 * num_SecFAT1; //Число записей в FAT (по 4 байта) maxZapFAT1 = Sec63.numSecPart / sClSec; //Максимальное число записей в FAT (по 4 байта) SEC_63 Sec64; if(FindStr("Sector 64") < 0) return -1; if(Read_Dump((BYTE*)&Sec64, 512) < 0) return -1; #if defined OUT_TEST Add_SpecSpis("Sector 64"); View_HEX_Any((BYTE *)&Sec64, 512); #endif if(strncmp(Sec64.Met, "LGEINC ", 8) != 0 || strncmp(Sec64.Name, "VOLUMELABE FAT32 ", 19) != 0) return Error2("Содержимое сектора 64 не соответствует требованиям.", "Эмулятор."); Start_SecDir2 = Sec63.numSecPart + 63 + Sec64.numRezSec + Sec64.nSecDir; //Номер сектора начала каталога во втором разделе num_SecFAT2 = Sec64.numSecFAT; //Число секторов в FAT Size_FAT2 = num_SecFAT2 * sSecB; //Число байт в FAT maxZapFAT2 = sSecB / 4 * num_SecFAT2; //Число записей в FAT (по 4 байта) Start_SecFAT2 = Start_SecFAT1 + Sec0.numClP1; //Позиция начала таблицы FAT2 return 0; }
void pawsBuddyWindow::LoadAliases(const csString & charName) { aliases.DeleteAll(); csRef<iDocument> doc; csRef<iDocumentNode> root; csString fileName = ALIASES_FILE_PREFIX + charName + ".xml"; fileName.FindReplace(" ", "_"); if (!psengine->GetVFS()->Exists(fileName)) return; doc = ParseFile(psengine->GetObjectRegistry(), fileName); if (doc == NULL) { Error2("Failed to parse file %s", fileName.GetData()); return; } root = doc->GetRoot(); if (root == NULL) { Error2("%s has no XML root", fileName.GetData()); return; } csRef<iDocumentNode> aliasesNode = root->GetNode("aliases"); if (aliasesNode == NULL) { Error2("%s has no <aliases> tag", fileName.GetData()); return; } csRef<iDocumentNodeIterator> nodes = aliasesNode->GetNodes(); while (nodes->HasNext()) { csRef<iDocumentNode> alias = nodes->Next(); if (strcmp(alias->GetValue(), "alias")) continue; // Check for duplicate aliases if (!IsUniqueAlias(alias->GetAttributeValue("alias"))) { Error2("Ignoring duplicate alias '%s'", alias->GetAttributeValue("alias")); continue; } aliases.PutUnique(alias->GetAttributeValue("name"), alias->GetAttributeValue("alias")); } }
bool psShadowManager::Load(const char * filename) { csRef<iDocument> doc; csRef<iDocumentNode> root; csRef<iVFS> vfs; csRef<iDocumentSystem> xml; const char* error; vfs = psengine->GetVFS(); assert(vfs); csRef<iDataBuffer> buff = vfs->ReadFile(filename); if (buff == NULL) { return false; } xml = psengine->GetXMLParser (); doc = xml->CreateDocument(); assert(doc); error = doc->Parse( buff ); if ( error ) { Error3("Parse error in %s: %s", filename, error); return false; } if (doc == NULL) return false; root = doc->GetRoot(); if (root == NULL) { Error2("No root in XML %s", filename); return false; } csRef<iDocumentNode> shadowsNode = root->GetNode("shadows"); if (!shadowsNode) { Error2("No shadows node in %s", filename); return false; } if ((csString) shadowsNode->GetAttributeValue("enabled") == "false") DisableShadows(); else EnableShadows(); return true; }
void Autoexec::LoadCommands(const char * fileName) { csRef<iVFS> vfs = csQueryRegistry<iVFS > ( PawsManager::GetSingleton().GetObjectRegistry()); csRef<iDocumentSystem> xml = psengine->GetXMLParser (); csRef<iDocumentNode> root, autoexecNode, optionsNode; csRef<iDocument> doc = xml->CreateDocument(); csRef<iDataBuffer> buf (vfs->ReadFile (fileName)); if (!buf || !buf->GetSize ()) { return ; } const char* error = doc->Parse( buf ); if ( error ) { Error2("Error loading shortcut window commands: %s\n", error); return ; } root = doc->GetRoot(); if (root == NULL) { Error2("%s has no XML root", fileName); } autoexecNode = root->GetNode(AUTOEXECROOTNODE); if (autoexecNode == NULL) { Error2("%s has no <autoexec> tag", fileName); } optionsNode = autoexecNode->GetNode(AUTOEXECOPTIONSNODE); if (optionsNode != NULL) { enabled = optionsNode->GetAttributeValueAsBool("enable", false); } else { Error2("%s has no <options> tag", fileName); } csRef<iDocumentNodeIterator> oNodes = autoexecNode->GetNodes(AUTOEXECCOMMANDSNODE); while (oNodes->HasNext()) { csRef<iDocumentNode> commands = oNodes->Next(); csString charname = commands->GetAttributeValue("charname"); csString cmds = commands->GetAttributeValue("execute"); addCommand(charname, cmds); } }
void SpawnManager::RepopulateItems(psSectorInfo *sectorinfo) { csArray<psItem*> items; // Load list from database if (!cacheManager->LoadWorldItems(sectorinfo, items)) { Error1("Failed to load world items."); return; } // Now create entities and meshes, etc. for each one int spawned = 0; for (size_t i = 0; i < items.GetSize(); i++) { psItem *item = items[i]; CS_ASSERT(item); // load items not in containers if (item->GetContainerID() == 0) { //if create item returns false, then no spawn occurs if (entityManager->CreateItem( item, (item->GetFlags() & PSITEM_FLAG_TRANSIENT) ? true : false)) { // printf("Created item %d: %s\n", item->GetUID(), item->GetName() ); // item->Save(false); item->SetLoaded(); spawned++; } else { printf("Creating item '%s' (%i) failed.\n", item->GetName(), item->GetUID()); delete item; // note that the dead item is still in the array } } // load items in containers else if (item->GetContainerID()) { gemItem *citem = entityManager->GetGEM()->FindItemEntity(item->GetContainerID()); gemContainer *container = dynamic_cast<gemContainer*> (citem); if (container) { if (!container->AddToContainer(item,NULL,item->GetLocInParent())) { Error2("Cannot add item into container slot %i.\n",item->GetLocInParent()); delete item; } item->SetLoaded(); } else { Error3("Container with id %d not found, specified in item %d.", item->GetContainerID(), item->GetUID() ); delete item; } } } Debug2(LOG_SPAWN,0,"Spawned %d items.\n",spawned); }
void ChatManager::SendAudioFile(Client *client, const char *voiceFileHash) { if (!voiceFileHash || voiceFileHash[0]==0) return; csRef<iDataBuffer> buffer; csString timestamp,voiceFile; // printf("Checking cache for audio file '%s'.\n", voiceFileHash); // Check cache for file csRef<iDataBuffer> cache; for (size_t i=0; i < audioFileCache.GetSize(); i++) { // printf("Cached item %d: '%s'\n", i, audioFileCache[i]->key.GetDataSafe() ); if (audioFileCache[i]->alternate == voiceFileHash) // found { // printf("Found in cache. Moving to front.\n"); buffer = audioFileCache[i]->data; timestamp = audioFileCache[i]->alternate; voiceFile = audioFileCache[i]->key; int sequence = client->GetOrderedMessageChannel(MSGTYPE_CACHEFILE)->IncrementSequenceNumber(); psCachedFileMessage msg(client->GetClientNum(),sequence, timestamp, buffer); msg.SendMessage(); // printf("Cached file message sent to client with buffer attached, seq=%d.\n",sequence); return; } } Error2("Client requested file hash that does not exist. (%s)", voiceFileHash); }
const csVector3 SpawnRange::PickPos() { if (type == 'A') { return csVector3(x1 + randomgen->Get() * (x2 - x1), y1 + randomgen->Get() * (y2 - y1), z1 + randomgen->Get() * (z2 - z1)); } else if (type == 'L')// type 'L' means spawn along line segment with an offset determined by radius (Line swept circle) { float d = randomgen->Get(); csVector3 pos = csVector3(x1 + d * (x2 - x1), y1 + d * (y2 - y1), z1 + d * (z2 - z1)); return PickWithRadius(pos, radius); } else if (type == 'C') // type 'C' means spawn within a circle centered at the first set of co-ordinates { return PickWithRadius(csVector3(x1, y1, z1), radius); } else { Error2("Unknown spawn range %c!", type); } return csVector3(0.0, 0.0, 0.0); }
void psClientDR::HandleDeadReckon( MsgEntry* me ) { psDRMessage drmsg(me,0,msgstrings,psengine->GetEngine() ); GEMClientActor* gemActor = (GEMClientActor*)celclient->FindObject( drmsg.entityid ); if (!gemActor) { csTicks currenttime = csGetTicks(); if (currenttime - lastquery > 750) { lastquery = currenttime; } Error2("Got DR message for unknown entity %s.", ShowID(drmsg.entityid)); return; } if (!msgstrings) { Error1("msgstrings not received, cannot handle DR"); return; } // Ignore any updates to the main player...psForcePositionMessage handles that. if (gemActor == celclient->GetMainPlayer()) { psengine->GetModeHandler()->SetModeSounds(drmsg.mode); return; } // Set data for this actor gemActor->SetDRData(drmsg); }
unsigned int psEffectManager::RenderEffect(const csString & effectName, const csVector3 & offset, iMeshWrapper * attachPos, iMeshWrapper * attachTarget, const csVector3 & up, const unsigned int uniqueIDOverride, bool rotateWithMesh, const float* scale) { #ifndef DONT_DO_EFFECTS if (!attachPos) return 0; // check if it's a single effect psEffect * currEffect = FindEffect(effectName); if (currEffect != 0) { currEffect = currEffect->Clone(); if (scale != NULL) { if (!currEffect->SetFrameParamScalings(scale)) { Error2("Received scale factor for effect %s that don't use param scaling",effectName.GetDataSafe()); } } const unsigned int uniqueID = currEffect->Render(attachPos->GetMovable()->GetSectors(), offset, attachPos, attachTarget, up.Unit(), uniqueIDOverride, rotateWithMesh); actualEffects.Put(uniqueID, currEffect); return uniqueID; } #endif return 0; }
void pawsWritingWindow::OnStringEntered(const char* /*name*/, int /*param*/, const char* value) { const unsigned int MAX_BOOK_FILE_SIZE = 60000; csString fileName; csRef<iVFS> vfs = psengine->GetVFS(); if (!value) return; fileName.Format("/planeshift/userdata/books/%s", value); Error2("%s", fileName.GetData()); if (!vfs->Exists(fileName)) { psSystemMessage msg(0, MSG_ERROR, "File not found!" ); msg.FireEvent(); return; } csRef<iDataBuffer> data = vfs->ReadFile(fileName); if (data->GetSize() > MAX_BOOK_FILE_SIZE) { psSystemMessage msg(0, MSG_ERROR, "File too big, data trimmed to %d chars.", MAX_BOOK_FILE_SIZE ); msg.FireEvent(); } csString book(data->GetData(), csMin(data->GetSize(), (size_t)MAX_BOOK_FILE_SIZE)); book.ReplaceAll("\r\n", "\n"); lefttext->SetText(book, true); psSystemMessage msg(0, MSG_ACK, "Book Loaded Successfully!" ); msg.FireEvent(); }
bool Behavior::ResumeScript(NPC *npc,EventManager *eventmgr) { if (current_step < sequence.GetSize()) { npc->Printf(3, "Resuming behavior %s at step %d - %s.", name.GetData(),current_step,sequence[current_step]->GetName()); if (sequence[current_step]->CompleteOperation(npc,eventmgr)) { npc->Printf(2,"Completed step %d - %s of behavior %s", current_step,sequence[current_step]->GetName(),name.GetData()); current_step++; return RunScript(npc, eventmgr, false); } else { return false; // This behavior isn't done yet } } else { Error2("No script operation to resume for behavior '%s'",GetName()); return true; } }
pawsWidget * PawsManager::LoadWidget(iDocumentNode *widgetNode ) { pawsWidget * widget; csString factory; if ( strcmp( widgetNode->GetValue(), "widget" ) == 0 ) // old syntax is <widget factory="bla"....> factory = widgetNode->GetAttributeValue( "factory" ); else factory = widgetNode->GetValue(); // new syntax is using factory name as tag name directly: <pawsChatWindow ....> if ( factory.Length() == 0 ) { Error1("Could not read factory from XML node. Error in XML"); return NULL; } widget = CreateWidget( factory ); if ( !widget ) { Error2( "Failed to create widget %s", factory.GetData() ); return NULL; } if (!widget->Load(widgetNode)) { Error3("Widget %s failed to load %s", widget->GetName(), factory.GetData() ); delete widget; return NULL; } return widget; }
void SpawnManager::LoadSpawnRanges(SpawnRule *rule) { Result result(db->Select("select npc_spawn_ranges.id,x1,y1,z1,x2,y2,z2,radius,name,range_type_code" " from npc_spawn_ranges, sectors " " where npc_spawn_ranges.sector_id = sectors.id" " and npc_spawn_rule_id=%d", rule->GetID() )); if (!result.IsValid() ) { Error2("Could not load NPC spawn ranges due to database error: %s\n", db->GetLastError()); return; } for (unsigned int i=0; i<result.Count(); i++) { SpawnRange *r = new SpawnRange; r->Initialize( result[i].GetInt("id"), rule->GetID(), result[i]["range_type_code"], result[i].GetFloat("x1"), result[i].GetFloat("y1"), result[i].GetFloat("z1"), result[i].GetFloat("x2"), result[i].GetFloat("y2"), result[i].GetFloat("z2"), result[i].GetFloat("radius"), result[i]["name"]); rule->AddRange(r); } }
bool ZoneHandler::LoadZoneInfo() { iVFS* vfs = psengine->GetVFS(); if(!vfs) return false; csRef<iDocument> doc = psengine->GetXMLParser()->CreateDocument(); csRef<iFile> file = vfs->Open("/planeshift/data/zoneinfo.xml", VFS_FILE_READ); if(!file) return false; const char* error = doc->Parse(file); if(error) { Error2("Error Loading Zone Data: %s\n", error); return false; } csRef<iDocumentNodeIterator> zoneIter = doc->GetRoot()->GetNode("zonelist")->GetNodes("zone"); while(zoneIter->HasNext()) { csRef<iDocumentNode> zoneNode = zoneIter->Next(); ZoneLoadInfo* zone = new ZoneLoadInfo(zoneNode); zonelist.Put(zone->inSector, zone); } return true; }
bool pawsStyles::LoadStyles(const csString &fileName) { csRef<iVFS> vfs = csQueryRegistry<iVFS > (objectReg); assert(vfs); csRef<iDataBuffer> buff = vfs->ReadFile(fileName); if(buff == NULL) { Error2("Could not find file: %s", fileName.GetData()); return false; } csRef<iDocumentSystem> xml; xml.AttachNew(new csTinyDocumentSystem); assert(xml); csRef<iDocument> doc = xml->CreateDocument(); assert(doc); const char* error = doc->Parse(buff); if(error) { Error3("Parse error in %s: %s", fileName.GetData(), error); return false; } csRef<iDocumentNode> root = doc->GetRoot(); if(root == NULL) return false; csRef<iDocumentNode> topNode = root->GetNode("styles"); if(topNode == NULL) { Error2("Missing <styles> tag in %s", fileName.GetData()); return false; } csRef<iDocumentNodeIterator> iter = topNode->GetNodes("style"); while(iter->HasNext()) { csRef<iDocumentNode> styleNode = iter->Next(); csString name = styleNode->GetAttributeValue("name"); if(styles.In(csString(name))) { // This is not an error anymore. Custom skins can and should supercede standard styles. //Error2("Warning: PAWS style '%s' defined more than once", name.GetData()); } else styles.Put(csString(name), styleNode); } InheritStyles(); return true; }
void HandleAnswer(const csString & answer) { PendingQuestion::HandleAnswer(answer); if ( dynamic_cast<psItem*>(item) == NULL ) { Error2("Item held in PendingLootPrompt with id %u has been lost",id); return; } gemActor* looter = gemSupervisor->FindPlayerEntity(looterID); gemActor* roller = gemSupervisor->FindPlayerEntity(rollerID); gemActor* getter = (answer == "yes") ? looter : roller ; // If the getter left the world, default to the other player if (!getter /*|| !getter->InGroup()*/ ) { getter = (answer == "yes") ? roller : looter ; // If the other player also vanished, get rid of the item and be done with it... if (!getter /*|| !getter->InGroup()*/ ) { cacheManager->RemoveInstance(item); return; } } // Create the loot message csString lootmsg; lootmsg.Format("%s was %s a %s by roll winner %s", lootername.GetData(), (getter == looter) ? "allowed to loot" : "stopped from looting", item->GetName(), rollername.GetData() ); // Attempt to give to getter bool dropped = getter->GetCharacterData()->Inventory().AddOrDrop(item); if (!dropped) lootmsg.Append(", but can't hold anymore"); // Send out the loot message psSystemMessage loot(getter->GetClientID(), MSG_LOOT, lootmsg.GetData() ); getter->SendGroupMessage(loot.msg); psLootEvent evt( looteeID, looteename, getter->GetCharacterData()->GetPID(), lootername, item->GetUID(), item->GetName(), item->GetStackCount(), (int)item->GetCurrentStats()->GetQuality(), 0 ); evt.FireEvent(); }
pawsScriptStatement::pawsScriptStatement(const char *scriptText) : env(&PawsManager::GetSingleton().ExtraScriptVars()) { script = MathScript::Create("pawsScript", scriptText); if(!script) { Error2("pawsScript: failed to parse script: %s", scriptText); } }
void cGameModel::CreateBuilding(int type,int xPosi, int yPosi, int owner) { cBuilding* newBuilding; buildingLayout lay; for(int i=0;i<buildingSpecifications.BuildingSizeX[type];i++) { for(int j=0;j<buildingSpecifications.BuildingSizeY[type];j++) { lay.layoutSetting[i][j] = buildingSpecifications.BuildingLayoutStorgage[type][i][j]; } } Error2("BuildingSizeX[type] ",buildingSpecifications.BuildingSizeX[type]); Error2("BuildingSizeY[type] ",buildingSpecifications.BuildingSizeY[type]); newBuilding = new cBuilding(type, owner, buildingSpecifications.BuildingSizeX[type], buildingSpecifications.BuildingSizeY[type]); newBuilding->initBuilding(&MapObj, xPosi, yPosi, lay); }
double psOptions::GetProperty(MathEnvironment* /*env*/, const char* ptr) { if (configFile->KeyExists(ptr)) return (double)configFile->GetFloat(ptr); Error2("psOptions::GetProperty(%s) failed\n", ptr); return 0.0; }