// MapGen bool CDataFileWriter::SaveMap(class IStorage *pStorage, CDataFileReader *pFileMap, const char *pFileName, char *pBlocksData, int BlocksDataSize) { dbg_msg("CDataFileWriter", "saving to '%s'...", pFileName); char aBuf[128]; if(!Open(pStorage, pFileName)) { dbg_msg("CDataFileWriter", "failed to open file '%s'...", pFileName); return 0; } // save version { CMapItemVersion *pItem = (CMapItemVersion *)pFileMap->FindItem(MAPITEMTYPE_VERSION, 0); AddItem(MAPITEMTYPE_VERSION, 0, sizeof(CMapItemVersion), pItem); dbg_msg("CDataFileWriter", "saving version"); } // save map info { CMapItemInfo Item = *((CMapItemInfo *)pFileMap->FindItem(MAPITEMTYPE_INFO, 0)); if(Item.m_Version == 1) { if(Item.m_Author > -1) { str_copy(aBuf, (char *)pFileMap->GetData(Item.m_Author), sizeof(aBuf)); Item.m_Author = AddData(str_length(aBuf)+1, aBuf); } if(Item.m_MapVersion > -1) { str_copy(aBuf, (char *)pFileMap->GetData(Item.m_MapVersion), sizeof(aBuf)); Item.m_MapVersion = AddData(str_length(aBuf)+1, aBuf); } if(Item.m_Credits > -1) { str_copy(aBuf, (char *)pFileMap->GetData(Item.m_Credits), sizeof(aBuf)); Item.m_Credits = AddData(str_length(aBuf)+1, aBuf); } if(Item.m_License > -1) { str_copy(aBuf, (char *)pFileMap->GetData(Item.m_License), sizeof(aBuf)); Item.m_License = AddData(str_length(aBuf)+1, aBuf); } } AddItem(MAPITEMTYPE_INFO, 0, sizeof(CMapItemInfo), &Item); dbg_msg("CDataFileWriter", "saving info"); } // save images int Start, Count; pFileMap->GetType(MAPITEMTYPE_IMAGE, &Start, &Count); for(int i = 0; i < Count; i++) { dbg_msg("CDataFileWriter", "saving image"); CMapItemImage Item = *((CMapItemImage *)pFileMap->GetItem(Start+i, 0, 0)); str_copy(aBuf, (char *)pFileMap->GetData(Item.m_ImageName), sizeof(aBuf)); Item.m_ImageName = AddData(str_length(aBuf)+1, aBuf); if(Item.m_External == 0) { const int PixelSize = Item.m_Format == CImageInfoFile::FORMAT_RGB ? 3 : 4; void *pData = pFileMap->GetData(Item.m_ImageData); Item.m_ImageData = AddData(Item.m_Width*Item.m_Height*PixelSize, pData); } AddItem(MAPITEMTYPE_IMAGE, i, sizeof(CMapItemImage), &Item); } // save layers enum { COLFLAG_SOLID=1, COLFLAG_DEATH=2, COLFLAG_NOHOOK=4, COLFLAG_RAMP_LEFT=8, COLFLAG_RAMP_RIGHT=16, COLFLAG_ROOFSLOPE_LEFT=32, COLFLAG_ROOFSLOPE_RIGHT=64, COLFLAG_DAMAGEFLUID=128, // 256 = out of range for unsigned char, ugly! it custom :D COLFLAG_MOVELEFT=129, COLFLAG_MOVERIGHT=130, COLFLAG_HANG=131, COLFLAG_PLATFORM=132, }; int LayerStart, LayerCount=0, LayerNum, GroupStart, GroupCount=0, GroupNum; pFileMap->GetType(MAPITEMTYPE_GROUP, &GroupStart, &GroupNum); pFileMap->GetType(MAPITEMTYPE_LAYER, &LayerStart, &LayerNum); for(int g = 0; g < GroupNum; g++) { CMapItemGroup *pGroup = static_cast<CMapItemGroup *>(pFileMap->GetItem(GroupStart+g, 0, 0)); for(int l = 0; l < pGroup->m_NumLayers; l++) { CMapItemLayer *pLayer = static_cast<CMapItemLayer *>(pFileMap->GetItem(LayerStart+(pGroup->m_StartLayer+l), 0, 0)); if(pLayer->m_Type == LAYERTYPE_TILES) { //dbg_msg("CDataFileWriter", "saving tile layer"); CMapItemLayerTilemap Tilemap = *(reinterpret_cast<CMapItemLayerTilemap *>(pLayer)); CTile *pTiles = (CTile *)pFileMap->GetData(Tilemap.m_Data); if (Tilemap.m_Flags&TILESLAYERFLAG_GAME) { for (int u=0; u<Tilemap.m_Width; u++) { for (int o=0; o<Tilemap.m_Height; o++) { const int tpos = o*Tilemap.m_Width+u; const int index = pTiles[tpos].m_Index; if (index <= 133) { if (index&COLFLAG_DEATH) pTiles[tpos].m_Index = TILE_DEATH; if (index&COLFLAG_SOLID) pTiles[tpos].m_Index = TILE_SOLID; if (index&COLFLAG_DAMAGEFLUID) pTiles[tpos].m_Index = TILE_DAMAGEFLUID; if (index == COLFLAG_RAMP_LEFT) pTiles[tpos].m_Index = TILE_RAMP_LEFT; if (index == COLFLAG_RAMP_RIGHT) pTiles[tpos].m_Index = TILE_RAMP_RIGHT; if (index == COLFLAG_ROOFSLOPE_LEFT) pTiles[tpos].m_Index = TILE_ROOFSLOPE_LEFT; if (index == COLFLAG_ROOFSLOPE_RIGHT) pTiles[tpos].m_Index = TILE_ROOFSLOPE_RIGHT; if (index == COLFLAG_MOVELEFT) pTiles[tpos].m_Index = TILE_MOVELEFT; if (index == COLFLAG_MOVERIGHT) pTiles[tpos].m_Index = TILE_MOVERIGHT; if (index == COLFLAG_HANG) pTiles[tpos].m_Index = TILE_HANG; if (index == COLFLAG_PLATFORM) pTiles[tpos].m_Index = TILE_PLATFORM; } } } } Tilemap.m_Data = AddData(Tilemap.m_Width*Tilemap.m_Height*sizeof(CTile), pTiles); AddItem(MAPITEMTYPE_LAYER, LayerCount++, sizeof(CMapItemLayerTilemap), &Tilemap); } else if (pLayer->m_Type == LAYERTYPE_QUADS) { dbg_msg("CDataFileWriter", "saving quad layer"); CMapItemLayerQuads QLayer = *(reinterpret_cast<CMapItemLayerQuads*>(pLayer)); CQuad *pQuads = (CQuad *)pFileMap->GetDataSwapped(QLayer.m_Data); QLayer.m_Data = AddDataSwapped(QLayer.m_NumQuads*sizeof(CQuad), pQuads); AddItem(MAPITEMTYPE_LAYER, LayerCount++, sizeof(CMapItemLayerQuads), &QLayer); } } dbg_msg("CDataFileWriter", "saving group"); AddItem(MAPITEMTYPE_GROUP, GroupCount++, sizeof(CMapItemGroup), pGroup); } // save envelopes int StartEV, NumEV; Count = 0; pFileMap->GetType(MAPITEMTYPE_ENVELOPE, &StartEV, &NumEV); for(int e = 0; e < NumEV; e++) { dbg_msg("CDataFileWriter", "saving envelope"); CMapItemEnvelope *pEnvelope = (CMapItemEnvelope*)pFileMap->GetItem(StartEV+e, 0, 0); AddItem(MAPITEMTYPE_ENVELOPE, e, sizeof(CMapItemEnvelope), pEnvelope); Count += pEnvelope->m_NumPoints; } // save points int StartEP, NumEP; pFileMap->GetType(MAPITEMTYPE_ENVPOINTS, &StartEP, &NumEP); if (NumEP) { CEnvPoint *pPoints = (CEnvPoint *)pFileMap->GetItem(StartEP, 0, 0); int TotalSizePoints = sizeof(CEnvPoint)*Count; AddItem(MAPITEMTYPE_ENVPOINTS, 0, TotalSizePoints, pPoints); } // finish the data file Finish(); dbg_msg("CDataFileWriter", "saving done"); return true; }
void CMenus::RenderGame(CUIRect MainView) { if(m_pClient->m_LocalClientID == -1) return; char aBuf[128]; const char *pNotification = 0; int TeamMod = m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team != TEAM_SPECTATORS ? -1 : 0; bool AllowSpec = true; int TimeLeft = 0; if(TeamMod+m_pClient->m_GameInfo.m_aTeamSize[TEAM_RED]+m_pClient->m_GameInfo.m_aTeamSize[TEAM_BLUE] >= m_pClient->m_ServerSettings.m_PlayerSlots) { str_format(aBuf, sizeof(aBuf), Localize("Only %d active players are allowed"), m_pClient->m_ServerSettings.m_PlayerSlots); pNotification = aBuf; } else if(m_pClient->m_ServerSettings.m_TeamLock) pNotification = Localize("Teams are locked"); else if(m_pClient->m_TeamCooldownTick+1 >= Client()->GameTick()) { TimeLeft = (m_pClient->m_TeamCooldownTick-Client()->GameTick())/Client()->GameTickSpeed()+1; str_format(aBuf, sizeof(aBuf), Localize("Teams are locked. Time to wait before changing team: %02d:%02d"), TimeLeft/60, TimeLeft%60); pNotification = aBuf; AllowSpec = false; } CUIRect Button, BottomView, Left, Middle, Right; // cut view MainView.HSplitBottom(80.0f, &MainView, &BottomView); // MainView not used for now BottomView.HSplitTop(20.f, 0, &BottomView); float Spacing = 3.0f; float ButtonWidth = (BottomView.w/6.0f)-(Spacing*5.0)/6.0f; BottomView.VSplitLeft(ButtonWidth*3.0f+Spacing*2.0f, &Left, &Middle); Middle.VSplitLeft(Spacing, 0, &Middle); Middle.VSplitLeft(ButtonWidth, &Middle, &Right); Right.VSplitRight(ButtonWidth, 0, &Right); if(!(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS)) Left.VSplitLeft(ButtonWidth, &Left, 0); // do backgrounds RenderTools()->DrawUIRect4(&Left, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); RenderTools()->DrawUIRect4(&Middle, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); RenderTools()->DrawUIRect4(&Right, vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.25f), vec4(0.0f, 0.0f, 0.0f, 0.0f), vec4(0.0f, 0.0f, 0.0f, 0.0f), CUI::CORNER_T, 5.0f); // do buttons Left.HSplitTop(25.0f, &Left, 0); Middle.HSplitTop(25.0f, &Middle, 0); Right.HSplitTop(25.0f, &Right, 0); if(pNotification != 0) { // print notice CUIRect Bar; MainView.HSplitTop(45.0f, &Bar, &MainView); RenderTools()->DrawUIRect(&Bar, vec4(0.0f, 0.0f, 0.0f, 0.25f), CUI::CORNER_B, 10.0f); Bar.HMargin(15.0f, &Bar); UI()->DoLabelScaled(&Bar, pNotification, 14.0f, 0); } // join buttons { // specator button int Team = m_pClient->m_aClients[m_pClient->m_LocalClientID].m_Team; if(pNotification && Team != TEAM_SPECTATORS) { if(TimeLeft) str_format(aBuf, sizeof(aBuf), "(%d)", TimeLeft); else str_copy(aBuf, Localize("locked"), sizeof(aBuf)); } else str_copy(aBuf, Localize(Team != TEAM_SPECTATORS ? "Spectate" : "Spactating"), sizeof(aBuf)); // Localize("Spectating"); Left.VSplitLeft(ButtonWidth, &Button, &Left); Left.VSplitLeft(Spacing, 0, &Left); static int s_SpectateButton = 0; if(DoButton_Menu(&s_SpectateButton, aBuf, Team == TEAM_SPECTATORS, &Button) && Team != TEAM_SPECTATORS && AllowSpec && !pNotification) { m_pClient->SendSwitchTeam(TEAM_SPECTATORS); SetActive(false); } // team button if(m_pClient->m_GameInfo.m_GameFlags&GAMEFLAG_TEAMS) { if(pNotification && Team != TEAM_RED) { if(TimeLeft) str_format(aBuf, sizeof(aBuf), "(%d)", TimeLeft); else str_copy(aBuf, Localize("locked"), sizeof(aBuf)); } else str_copy(aBuf, Localize(Team != TEAM_RED ? "Join red" : "Joined red"), sizeof(aBuf)); // Localize("Join red");Localize("Joined red"); Left.VSplitLeft(ButtonWidth, &Button, &Left); Left.VSplitLeft(Spacing, 0, &Left); static int s_RedButton = 0; if(DoButton_Menu(&s_RedButton, aBuf, Team == TEAM_RED, &Button, CUI::CORNER_ALL, 5.0f, 0.0f, vec4(0.975f, 0.17f, 0.17f, 0.75f), false) && Team != TEAM_RED && !pNotification) { m_pClient->SendSwitchTeam(TEAM_RED); SetActive(false); } if(pNotification && Team != TEAM_BLUE) { if(TimeLeft) str_format(aBuf, sizeof(aBuf), "(%d)", TimeLeft); else str_copy(aBuf, Localize("locked"), sizeof(aBuf)); } else str_copy(aBuf, Localize(Team != TEAM_BLUE ? "Join blue" : "Joined blue"), sizeof(aBuf)); // Localize("Join blue");Localize("Joined blue"); Left.VSplitLeft(ButtonWidth, &Button, &Left); static int s_BlueButton = 0; if(DoButton_Menu(&s_BlueButton, aBuf, Team == TEAM_BLUE, &Button, CUI::CORNER_ALL, 5.0f, 0.0f, vec4(0.17f, 0.46f, 0.975f, 0.75f), false) && Team != TEAM_BLUE && !pNotification) { m_pClient->SendSwitchTeam(TEAM_BLUE); SetActive(false); } } else { if(pNotification && Team != TEAM_RED) { if(TimeLeft) str_format(aBuf, sizeof(aBuf), "(%d)", TimeLeft); else str_copy(aBuf, Localize("locked"), sizeof(aBuf)); } else str_copy(aBuf, Localize(Team != TEAM_RED ? "Join" : "Joined"), sizeof(aBuf)); //Localize("Join");Localize("Joined"); Left.VSplitLeft(ButtonWidth, &Button, &Left); static int s_JoinButton = 0; if(DoButton_Menu(&s_JoinButton, aBuf, Team == TEAM_RED, &Button) && Team != TEAM_RED && !pNotification) { m_pClient->SendSwitchTeam(0); SetActive(false); } } } // Record button static int s_DemoButton = 0; bool Recording = DemoRecorder()->IsRecording(); if(DoButton_Menu(&s_DemoButton, Localize(Recording ? "Stop record" : "Record"), Recording, &Middle)) // Localize("Stop record");Localize("Record"); { if(!Recording) Client()->DemoRecorder_Start("demo", true); else Client()->DemoRecorder_Stop(); } // disconnect button static int s_DisconnectButton = 0; if(DoButton_Menu(&s_DisconnectButton, Localize("Disconnect"), 0, &Right)) Client()->Disconnect(); }
void CGameConsole::OnRender() { CUIRect Screen = *UI()->Screen(); float ConsoleMaxHeight = Screen.h*3/5.0f; float ConsoleHeight; float Progress = (TimeNow()-(m_StateChangeEnd-m_StateChangeDuration))/float(m_StateChangeDuration); if (Progress >= 1.0f) { if (m_ConsoleState == CONSOLE_CLOSING) m_ConsoleState = CONSOLE_CLOSED; else if (m_ConsoleState == CONSOLE_OPENING) m_ConsoleState = CONSOLE_OPEN; Progress = 1.0f; } if (m_ConsoleState == CONSOLE_OPEN && g_Config.m_ClEditor) Toggle(CONSOLETYPE_LOCAL); if (m_ConsoleState == CONSOLE_CLOSED) return; if (m_ConsoleState == CONSOLE_OPEN) Input()->MouseModeAbsolute(); float ConsoleHeightScale; if (m_ConsoleState == CONSOLE_OPENING) ConsoleHeightScale = ConsoleScaleFunc(Progress); else if (m_ConsoleState == CONSOLE_CLOSING) ConsoleHeightScale = ConsoleScaleFunc(1.0f-Progress); else //if (console_state == CONSOLE_OPEN) ConsoleHeightScale = ConsoleScaleFunc(1.0f); ConsoleHeight = ConsoleHeightScale*ConsoleMaxHeight; Graphics()->MapScreen(Screen.x, Screen.y, Screen.w, Screen.h); // do console shadow Graphics()->TextureSet(-1); Graphics()->QuadsBegin(); IGraphics::CColorVertex Array[4] = { IGraphics::CColorVertex(0, 0,0,0, 0.5f), IGraphics::CColorVertex(1, 0,0,0, 0.5f), IGraphics::CColorVertex(2, 0,0,0, 0.0f), IGraphics::CColorVertex(3, 0,0,0, 0.0f)}; Graphics()->SetColorVertex(Array, 4); IGraphics::CQuadItem QuadItem(0, ConsoleHeight, Screen.w, 10.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); // do background Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CONSOLE_BG].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(0.2f, 0.2f, 0.2f,0.9f); if(m_ConsoleType == CONSOLETYPE_REMOTE) Graphics()->SetColor(0.4f, 0.2f, 0.2f,0.9f); Graphics()->QuadsSetSubset(0,-ConsoleHeight*0.075f,Screen.w*0.075f*0.5f,0); QuadItem = IGraphics::CQuadItem(0, 0, Screen.w, ConsoleHeight); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); // do small bar shadow Graphics()->TextureSet(-1); Graphics()->QuadsBegin(); Array[0] = IGraphics::CColorVertex(0, 0,0,0, 0.0f); Array[1] = IGraphics::CColorVertex(1, 0,0,0, 0.0f); Array[2] = IGraphics::CColorVertex(2, 0,0,0, 0.25f); Array[3] = IGraphics::CColorVertex(3, 0,0,0, 0.25f); Graphics()->SetColorVertex(Array, 4); QuadItem = IGraphics::CQuadItem(0, ConsoleHeight-20, Screen.w, 10); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); // do the lower bar Graphics()->TextureSet(g_pData->m_aImages[IMAGE_CONSOLE_BAR].m_Id); Graphics()->QuadsBegin(); Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.9f); Graphics()->QuadsSetSubset(0,0.1f,Screen.w*0.015f,1-0.1f); QuadItem = IGraphics::CQuadItem(0,ConsoleHeight-10.0f,Screen.w,10.0f); Graphics()->QuadsDrawTL(&QuadItem, 1); Graphics()->QuadsEnd(); ConsoleHeight -= 22.0f; CInstance *pConsole = CurrentConsole(); { float FontSize = 10.0f; float RowHeight = FontSize*1.25f; float x = 3; float y = ConsoleHeight - RowHeight - 5.0f; CRenderInfo Info; Info.m_pSelf = this; Info.m_WantedCompletion = pConsole->m_CompletionChosen; Info.m_EnumCount = 0; Info.m_Offset = pConsole->m_CompletionRenderOffset; Info.m_Width = Screen.w; Info.m_pCurrentCmd = pConsole->m_aCompletionBuffer; TextRender()->SetCursor(&Info.m_Cursor, x+Info.m_Offset, y+RowHeight+2.0f, FontSize, TEXTFLAG_RENDER); // render prompt CTextCursor Cursor; TextRender()->SetCursor(&Cursor, x, y, FontSize, TEXTFLAG_RENDER); const char *pPrompt = "> "; if(m_ConsoleType == CONSOLETYPE_REMOTE) { if(Client()->State() == IClient::STATE_ONLINE) { if(Client()->RconAuthed()) pPrompt = "rcon> "; else pPrompt = "ENTER PASSWORD> "; } else pPrompt = "NOT CONNECTED> "; } TextRender()->TextEx(&Cursor, pPrompt, -1); x = Cursor.m_X; //hide rcon password char aInputString[512]; str_copy(aInputString, pConsole->m_Input.GetString(), sizeof(aInputString)); if(m_ConsoleType == CONSOLETYPE_REMOTE && Client()->State() == IClient::STATE_ONLINE && !Client()->RconAuthed()) { for(int i = 0; i < pConsole->m_Input.GetLength(); ++i) aInputString[i] = '*'; } // render console input (wrap line) TextRender()->SetCursor(&Cursor, x, y, FontSize, 0); Cursor.m_LineWidth = Screen.w - 10.0f - x; TextRender()->TextEx(&Cursor, aInputString, pConsole->m_Input.GetCursorOffset()); TextRender()->TextEx(&Cursor, aInputString+pConsole->m_Input.GetCursorOffset(), -1); int Lines = Cursor.m_LineCount; y -= (Lines - 1) * FontSize; TextRender()->SetCursor(&Cursor, x, y, FontSize, TEXTFLAG_RENDER); Cursor.m_LineWidth = Screen.w - 10.0f - x; TextRender()->TextEx(&Cursor, aInputString, pConsole->m_Input.GetCursorOffset()); static float MarkerOffset = TextRender()->TextWidth(0, FontSize, "|", -1)/3; CTextCursor Marker = Cursor; Marker.m_X -= MarkerOffset; Marker.m_LineWidth = -1; TextRender()->TextEx(&Marker, "|", -1); TextRender()->TextEx(&Cursor, aInputString+pConsole->m_Input.GetCursorOffset(), -1); // render possible commands if(m_ConsoleType == CONSOLETYPE_LOCAL || Client()->RconAuthed()) { if(pConsole->m_Input.GetString()[0] != 0) { m_pConsole->PossibleCommands(pConsole->m_aCompletionBuffer, pConsole->m_CompletionFlagmask, m_ConsoleType != CGameConsole::CONSOLETYPE_LOCAL && Client()->RconAuthed() && Client()->UseTempRconCommands(), PossibleCommandsRenderCallback, &Info); pConsole->m_CompletionRenderOffset = Info.m_Offset; if(Info.m_EnumCount <= 0) { if(pConsole->m_IsCommand) { char aBuf[512]; str_format(aBuf, sizeof(aBuf), "Help: %s ", pConsole->m_aCommandHelp); TextRender()->TextEx(&Info.m_Cursor, aBuf, -1); TextRender()->TextColor(0.75f, 0.75f, 0.75f, 1); str_format(aBuf, sizeof(aBuf), "Usage: %s %s", pConsole->m_aCommandName, pConsole->m_aCommandParams); TextRender()->TextEx(&Info.m_Cursor, aBuf, -1); } } } } vec3 rgb = HslToRgb(vec3(g_Config.m_ClMessageHighlightHue / 255.0f, g_Config.m_ClMessageHighlightSat / 255.0f, g_Config.m_ClMessageHighlightLht / 255.0f)); // render log (actual page, wrap lines) CInstance::CBacklogEntry *pEntry = pConsole->m_Backlog.Last(); float OffsetY = 0.0f; float LineOffset = 1.0f; for(int Page = 0; Page <= pConsole->m_BacklogActPage; ++Page, OffsetY = 0.0f) { while(pEntry) { if(pEntry->m_Highlighted) TextRender()->TextColor(rgb.r, rgb.g, rgb.b, 1); else TextRender()->TextColor(1,1,1,1); // get y offset (calculate it if we haven't yet) if(pEntry->m_YOffset < 0.0f) { TextRender()->SetCursor(&Cursor, 0.0f, 0.0f, FontSize, 0); Cursor.m_LineWidth = Screen.w-10; TextRender()->TextEx(&Cursor, pEntry->m_aText, -1); pEntry->m_YOffset = Cursor.m_Y+Cursor.m_FontSize+LineOffset; } OffsetY += pEntry->m_YOffset; // next page when lines reach the top if(y-OffsetY <= RowHeight) break; // just render output from actual backlog page (render bottom up) if(Page == pConsole->m_BacklogActPage) { TextRender()->SetCursor(&Cursor, 0.0f, y-OffsetY, FontSize, TEXTFLAG_RENDER); Cursor.m_LineWidth = Screen.w-10.0f; TextRender()->TextEx(&Cursor, pEntry->m_aText, -1); } pEntry = pConsole->m_Backlog.Prev(pEntry); // reset color TextRender()->TextColor(1,1,1,1); } // actual backlog page number is too high, render last available page (current checked one, render top down) if(!pEntry && Page < pConsole->m_BacklogActPage) { pConsole->m_BacklogActPage = Page; pEntry = pConsole->m_Backlog.First(); while(OffsetY > 0.0f && pEntry) { TextRender()->SetCursor(&Cursor, 0.0f, y-OffsetY, FontSize, TEXTFLAG_RENDER); Cursor.m_LineWidth = Screen.w-10.0f; TextRender()->TextEx(&Cursor, pEntry->m_aText, -1); OffsetY -= pEntry->m_YOffset; pEntry = pConsole->m_Backlog.Next(pEntry); } break; } } // render page char aBuf[128]; TextRender()->TextColor(1,1,1,1); str_format(aBuf, sizeof(aBuf), Localize("-Page %d-"), pConsole->m_BacklogActPage+1); TextRender()->Text(0, 10.0f, 0.0f, FontSize, aBuf, -1); // render version str_format(aBuf, sizeof(aBuf), "v%s", GAME_VERSION); float Width = TextRender()->TextWidth(0, FontSize, aBuf, -1); TextRender()->Text(0, Screen.w-Width-10.0f, 0.0f, FontSize, aBuf, -1); } }
bool gtf_next(gtf_file_t* f, gtf_row_t* r) { gtf_row_clear(r); if (f->state == STATE_EOF) return false; int last_k = -1; str_t* field = NULL; char* endptr; str_t* attr; while (true) { /* figure out what string we are reading into */ if (f->k != last_k) { last_k = f->k; switch (f->k) { case 0: field = r->seqname; break; case 1: field = r->source; break; case 2: field = r->feature; break; case 3: case 4: case 5: case 6: case 7: field = f->field1; break; default: break; } } /* read more, if needed */ if (*f->c == '\0') { gtf_file_refill(f); if (f->state == STATE_EOF) return false; continue; } if (*f->c == '\n') { /* skip blank lines */ if (f->state == STATE_FIELD && f->k == 0 && field->n == 0) { f->c++; f->col = 1; f->line++; } else if (f->state != STATE_KEY_SEEK && f->state != STATE_VALUE_END) { fail("Premature end of line.", f->line, f->col); } } /* handle the next character */ switch (f->state) { case STATE_FIELD: if (*f->c == '\t') { field->s[field->n] = '\0'; switch (f->k) { case 3: r->start = strtol(field->s, &endptr, 10); if (*endptr != '\0') { fail("Invalid start position.", f->line, f->col); } str_clear(field); break; case 4: r->end = strtol(field->s, &endptr, 10); if (*endptr != '\0') { fail("Invalid end position.", f->line, f->col); } str_clear(field); break; case 5: if (field->n == 1 && field->s[0] == '.') { r->score = 0.0; } else { r->score = strtod(field->s, &endptr); if (*endptr != '\0') { fail("Invalid score.", f->line, f->col); } } str_clear(field); break; case 6: if (field->n > 0 && field->s[0] == '+') { r->strand = strand_pos; } else if (field->n > 0 && field->s[0] == '-') { r->strand = strand_neg; } else { r->strand = strand_na; } str_clear(field); break; case 7: if (field->n == 1 && field->s[0] == '.') { r->frame = -1; } else { r->frame = strtol(field->s, &endptr, 10); if (*endptr != '\0') { fail("Invalid frame.", f->line, f->col); } } str_clear(field); break; default: break; } f->k++; if (f->k == 8) f->state = STATE_KEY_SEEK; } else { str_append(field, *f->c); } break; case STATE_KEY_SEEK: if (*f->c == '\n') { f->c++; goto gtf_next_finish; } if (isspace(*f->c)) break; f->state = STATE_KEY; if (*f->c == '"' || *f->c == '\'') { f->quote = *f->c; break; } else continue; case STATE_KEY: if ((f->quote != '\0' && *f->c == f->quote) || (f->quote == '\0' && isspace(*f->c))) { f->field1->s[f->field1->n] = '\0'; f->state = STATE_VALUE_SEEK; f->quote = '\0'; } else { str_append(f->field1, *f->c); } break; case STATE_VALUE_SEEK: if (isspace(*f->c)) break; f->state = STATE_VALUE; if (*f->c == '"' || *f->c == '\'') { f->quote = *f->c; break; } else continue; case STATE_VALUE: if ((*f->c == '\n') || (f->quote != '\0' && *f->c == f->quote) || (f->quote == '\0' && (*f->c == ';' || isspace(*f->c)))) { if (*f->c == '\n' && f->quote != '\0') { fail("Newline found before end quote.", f->line, f->col); } f->field2->s[f->field2->n] = '\0'; f->state = STATE_VALUE_END; attr = (str_t*)str_map_get(r->attributes, f->field1->s, f->field1->n); if (attr == NULL) { str_map_set(r->attributes, f->field1->s, f->field1->n, str_alloc()); attr = (str_t*)str_map_get(r->attributes, f->field1->s, f->field1->n); } str_copy((str_t*)attr, f->field2); str_clear(f->field1); str_clear(f->field2); if (f->quote != '\0') { f->quote = '\0'; break; } else continue; } else { str_append(f->field2, *f->c); break; } case STATE_VALUE_END: if (isspace(*f->c)) break; else if (*f->c == ';') { f->state = STATE_KEY_SEEK; break; } else if (*f->c == '\n') { f->c++; goto gtf_next_finish; } else { fail("Expected ';'.", f->line, f->col); } default: fputs("Inexplicable error in the gtf parser.\n", stderr); exit(1); } f->c++; f->col++; } gtf_next_finish: f->state = STATE_FIELD; f->k = 0; f->col = 1; f->line++; return true; }
int CNetServer::BanAdd(NETADDR Addr, int Seconds, const char *pReason) { int IpHash = (Addr.ip[0]+Addr.ip[1]+Addr.ip[2]+Addr.ip[3]+Addr.ip[4]+Addr.ip[5]+Addr.ip[6]+Addr.ip[7]+ Addr.ip[8]+Addr.ip[9]+Addr.ip[10]+Addr.ip[11]+Addr.ip[12]+Addr.ip[13]+Addr.ip[14]+Addr.ip[15])&0xff; int Stamp = -1; CBan *pBan; // remove the port Addr.port = 0; if(Seconds) Stamp = time_timestamp() + Seconds; // search to remove it if it already exists pBan = m_aBans[IpHash]; MACRO_LIST_FIND(pBan, m_pHashNext, net_addr_comp(&pBan->m_Info.m_Addr, &Addr) == 0); if(pBan) BanRemoveByObject(pBan); if(!m_BanPool_FirstFree) return -1; // fetch and clear the new ban pBan = m_BanPool_FirstFree; MACRO_LIST_UNLINK(pBan, m_BanPool_FirstFree, m_pPrev, m_pNext); // setup the ban info pBan->m_Info.m_Expires = Stamp; pBan->m_Info.m_Addr = Addr; str_copy(pBan->m_Info.m_Reason, pReason, sizeof(pBan->m_Info.m_Reason)); // add it to the ban hash MACRO_LIST_LINK_FIRST(pBan, m_aBans[IpHash], m_pHashPrev, m_pHashNext); // insert it into the used list { if(m_BanPool_FirstUsed) { CBan *pInsertAfter = m_BanPool_FirstUsed; MACRO_LIST_FIND(pInsertAfter, m_pNext, Stamp < pInsertAfter->m_Info.m_Expires); if(pInsertAfter && Stamp != -1) pInsertAfter = pInsertAfter->m_pPrev; else { // add to last if (m_BanPool_FirstUsed->m_Info.m_Expires == -1) pInsertAfter = 0; else { pInsertAfter = m_BanPool_FirstUsed; while(pInsertAfter->m_pNext && pInsertAfter->m_pNext->m_Info.m_Expires != -1) pInsertAfter = pInsertAfter->m_pNext; } } if(pInsertAfter) { MACRO_LIST_LINK_AFTER(pBan, pInsertAfter, m_pPrev, m_pNext); } else { MACRO_LIST_LINK_FIRST(pBan, m_BanPool_FirstUsed, m_pPrev, m_pNext); } } else { MACRO_LIST_LINK_FIRST(pBan, m_BanPool_FirstUsed, m_pPrev, m_pNext); } } // drop banned clients { char Buf[128]; NETADDR BanAddr; if(Stamp > -1) { int Mins = (Seconds + 59) / 60; if(Mins <= 1) str_format(Buf, sizeof(Buf), "You have been banned for 1 minute (%s)", pReason); else str_format(Buf, sizeof(Buf), "You have been banned for %d minutes (%s)", Mins, pReason); } else str_format(Buf, sizeof(Buf), "You have been banned for life (%s)", pReason); for(int i = 0; i < MaxClients(); i++) { BanAddr = m_aSlots[i].m_Connection.PeerAddress(); BanAddr.port = 0; if(net_addr_comp(&Addr, &BanAddr) == 0) Drop(i, Buf); } } return 0; }
int vsf_filename_passes_filter(const struct mystr* p_filename_str, const struct mystr* p_filter_str, unsigned int* iters) { /* A simple routine to match a filename against a pattern. * This routine is used instead of e.g. fnmatch(3), because we should be * reluctant to trust the latter. fnmatch(3) involves _lots_ of string * parsing and handling. There is broad potential for any given fnmatch(3) * implementation to be buggy. * * Currently supported pattern(s): * - any number of wildcards, "*" or "?" * - {,} syntax (not nested) * * Note that pattern matching is only supported within the last path * component. For example, searching for /a/b/? will work, but searching * for /a/?/c will not. */ struct mystr filter_remain_str = INIT_MYSTR; struct mystr name_remain_str = INIT_MYSTR; struct mystr temp_str = INIT_MYSTR; struct mystr brace_list_str = INIT_MYSTR; struct mystr new_filter_str = INIT_MYSTR; int ret = 0; char last_token = 0; int must_match_at_current_pos = 1; str_copy(&filter_remain_str, p_filter_str); str_copy(&name_remain_str, p_filename_str); while (!str_isempty(&filter_remain_str) && *iters < VSFTP_MATCHITERS_MAX) { static struct mystr s_match_needed_str; /* Locate next special token */ struct str_locate_result locate_result = str_locate_chars(&filter_remain_str, "*?{"); (*iters)++; /* Isolate text leading up to token (if any) - needs to be matched */ if (locate_result.found) { unsigned int indexx = locate_result.index; str_left(&filter_remain_str, &s_match_needed_str, indexx); str_mid_to_end(&filter_remain_str, &temp_str, indexx + 1); str_copy(&filter_remain_str, &temp_str); last_token = locate_result.char_found; } else { /* No more tokens. Must match remaining filter string exactly. */ str_copy(&s_match_needed_str, &filter_remain_str); str_empty(&filter_remain_str); last_token = 0; } if (!str_isempty(&s_match_needed_str)) { /* Need to match something.. could be a match which has to start at * current position, or we could allow it to start anywhere */ unsigned int indexx; locate_result = str_locate_str(&name_remain_str, &s_match_needed_str); if (!locate_result.found) { /* Fail */ goto out; } indexx = locate_result.index; if (must_match_at_current_pos && indexx > 0) { goto out; } /* Chop matched string out of remainder */ str_mid_to_end(&name_remain_str, &temp_str, indexx + str_getlen(&s_match_needed_str)); str_copy(&name_remain_str, &temp_str); } if (last_token == '?') { if (str_isempty(&name_remain_str)) { goto out; } str_right(&name_remain_str, &temp_str, str_getlen(&name_remain_str) - 1); str_copy(&name_remain_str, &temp_str); must_match_at_current_pos = 1; } else if (last_token == '{') { struct str_locate_result end_brace = str_locate_char(&filter_remain_str, '}'); must_match_at_current_pos = 1; if (end_brace.found) { str_split_char(&filter_remain_str, &temp_str, '}'); str_copy(&brace_list_str, &filter_remain_str); str_copy(&filter_remain_str, &temp_str); str_split_char(&brace_list_str, &temp_str, ','); while (!str_isempty(&brace_list_str)) { str_copy(&new_filter_str, &brace_list_str); str_append_str(&new_filter_str, &filter_remain_str); if (vsf_filename_passes_filter(&name_remain_str, &new_filter_str, iters)) { ret = 1; goto out; } str_copy(&brace_list_str, &temp_str); str_split_char(&brace_list_str, &temp_str, ','); } goto out; } else if (str_isempty(&name_remain_str) || str_get_char_at(&name_remain_str, 0) != '{') { goto out; } else { str_right(&name_remain_str, &temp_str, str_getlen(&name_remain_str) - 1); str_copy(&name_remain_str, &temp_str); } } else { must_match_at_current_pos = 0; } } /* Any incoming string left means no match unless we ended on the correct * type of wildcard. */ if (str_getlen(&name_remain_str) > 0 && last_token != '*') { goto out; } /* OK, a match */ ret = 1; if (*iters == VSFTP_MATCHITERS_MAX) { ret = 0; } out: str_free(&filter_remain_str); str_free(&name_remain_str); str_free(&temp_str); str_free(&brace_list_str); str_free(&new_filter_str); return ret; }
void FindDatadir(const char *pArgv0) { // 1) use data-dir in PWD if present if(fs_is_dir("data/mapres")) { str_copy(m_aDatadir, "data", sizeof(m_aDatadir)); return; } // 2) use compiled-in data-dir if present if(fs_is_dir(DATA_DIR "/mapres")) { str_copy(m_aDatadir, DATA_DIR, sizeof(m_aDatadir)); return; } // 3) check for usable path in argv[0] { unsigned int Pos = ~0U; for(unsigned i = 0; pArgv0[i]; i++) if(pArgv0[i] == '/' || pArgv0[i] == '\\') Pos = i; if(Pos < MAX_PATH_LENGTH) { char aBaseDir[MAX_PATH_LENGTH]; str_copy(aBaseDir, pArgv0, Pos+1); str_format(m_aDatadir, sizeof(m_aDatadir), "%s/data", aBaseDir); str_append(aBaseDir, "/data/mapres", sizeof(aBaseDir)); if(fs_is_dir(aBaseDir)) return; else m_aDatadir[0] = 0; } } #if defined(CONF_FAMILY_UNIX) // 4) check for all default locations { const char *aDirs[] = { "/usr/share/teeworlds/data", "/usr/share/games/teeworlds/data", "/usr/local/share/teeworlds/data", "/usr/local/share/games/teeworlds/data", "/usr/pkg/share/teeworlds/data", "/usr/pkg/share/games/teeworlds/data", "/opt/teeworlds/data" }; const int DirsCount = sizeof(aDirs) / sizeof(aDirs[0]); int i; for (i = 0; i < DirsCount; i++) { char aBuf[128]; str_format(aBuf, sizeof(aBuf), "%s/mapres", aDirs[i]); if(fs_is_dir(aBuf)) { str_copy(m_aDatadir, aDirs[i], sizeof(m_aDatadir)); return; } } } #endif // no data-dir found dbg_msg("storage", "warning no data directory found"); }
void IGameController::ChangeMap(const char *pToMap) { str_copy(m_aMapWish, pToMap, sizeof(m_aMapWish)); EndMatch(); }
void IGameController::CycleMap() { if(m_aMapWish[0] != 0) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "rotating map to %s", m_aMapWish); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); str_copy(g_Config.m_SvMap, m_aMapWish, sizeof(g_Config.m_SvMap)); m_aMapWish[0] = 0; m_MatchCount = 0; return; } if(!str_length(g_Config.m_SvMaprotation)) return; if(m_MatchCount < m_GameInfo.m_MatchNum-1) { if(g_Config.m_SvMatchSwap) GameServer()->SwapTeams(); return; } // handle maprotation const char *pMapRotation = g_Config.m_SvMaprotation; const char *pCurrentMap = g_Config.m_SvMap; int CurrentMapLen = str_length(pCurrentMap); const char *pNextMap = pMapRotation; while(*pNextMap) { int WordLen = 0; while(pNextMap[WordLen] && !IsSeparator(pNextMap[WordLen])) WordLen++; if(WordLen == CurrentMapLen && str_comp_num(pNextMap, pCurrentMap, CurrentMapLen) == 0) { // map found pNextMap += CurrentMapLen; while(*pNextMap && IsSeparator(*pNextMap)) pNextMap++; break; } pNextMap++; } // restart rotation if(pNextMap[0] == 0) pNextMap = pMapRotation; // cut out the next map char aBuf[512] = {0}; for(int i = 0; i < 511; i++) { aBuf[i] = pNextMap[i]; if(IsSeparator(pNextMap[i]) || pNextMap[i] == 0) { aBuf[i] = 0; break; } } // skip spaces int i = 0; while(IsSeparator(aBuf[i])) i++; m_MatchCount = 0; char aBufMsg[256]; str_format(aBufMsg, sizeof(aBufMsg), "rotating map to %s", &aBuf[i]); GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); str_copy(g_Config.m_SvMap, &aBuf[i], sizeof(g_Config.m_SvMap)); }
int vsf_sysdep_check_auth(struct mystr* p_user_str, const struct mystr* p_pass_str, const struct mystr* p_remote_host) { int retval; #ifdef PAM_USER pam_item_t item; const char* pam_user_name = 0; #endif struct pam_conv the_conv = { &pam_conv_func, 0 }; if (s_pamh != 0) { bug("vsf_sysdep_check_auth"); } str_copy(&s_pword_str, p_pass_str); retval = pam_start(tunable_pam_service_name, str_getbuf(p_user_str), &the_conv, &s_pamh); if (retval != PAM_SUCCESS) { s_pamh = 0; return 0; } #ifdef PAM_RHOST retval = pam_set_item(s_pamh, PAM_RHOST, str_getbuf(p_remote_host)); if (retval != PAM_SUCCESS) { (void) pam_end(s_pamh, retval); s_pamh = 0; return 0; } #endif #ifdef PAM_TTY retval = pam_set_item(s_pamh, PAM_TTY, "ftp"); if (retval != PAM_SUCCESS) { (void) pam_end(s_pamh, retval); s_pamh = 0; return 0; } #endif #ifdef PAM_RUSER retval = pam_set_item(s_pamh, PAM_RUSER, str_getbuf(p_user_str)); if (retval != PAM_SUCCESS) { (void) pam_end(s_pamh, retval); s_pamh = 0; return 0; } #endif retval = pam_authenticate(s_pamh, 0); if (retval != PAM_SUCCESS) { (void) pam_end(s_pamh, retval); s_pamh = 0; return 0; } #ifdef PAM_USER retval = pam_get_item(s_pamh, PAM_USER, &item); if (retval != PAM_SUCCESS) { (void) pam_end(s_pamh, retval); s_pamh = 0; return 0; } pam_user_name = item; str_alloc_text(p_user_str, pam_user_name); #endif retval = pam_acct_mgmt(s_pamh, 0); if (retval != PAM_SUCCESS) { (void) pam_end(s_pamh, retval); s_pamh = 0; return 0; } retval = pam_setcred(s_pamh, PAM_ESTABLISH_CRED); if (retval != PAM_SUCCESS) { (void) pam_end(s_pamh, retval); s_pamh = 0; return 0; } if (!tunable_session_support) { /* You're in already! */ (void) pam_end(s_pamh, retval); s_pamh = 0; return 1; } /* Must do this BEFORE opening a session for pam_limits to count us */ vsf_insert_uwtmp(p_user_str, p_remote_host); retval = pam_open_session(s_pamh, 0); if (retval != PAM_SUCCESS) { vsf_remove_uwtmp(); (void) pam_setcred(s_pamh, PAM_DELETE_CRED); (void) pam_end(s_pamh, retval); s_pamh = 0; return 0; } /* We MUST ensure the PAM session, utmp, wtmp etc. are cleaned up, however * we exit. */ vsf_sysutil_set_exit_func(vsf_auth_shutdown); /* You're in dude */ return 1; }
void vsf_sysutil_set_proctitle_prefix(const struct mystr* p_str) { str_copy(&s_proctitle_prefix_str, p_str); }
void CGameConsole::CInstance::OnInput(IInput::CEvent Event) { bool Handled = false; if(Event.m_Flags&IInput::FLAG_PRESS) { if(Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER) { if(m_Input.GetString()[0]) { if(m_Type == CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed()) { char *pEntry = m_History.Allocate(m_Input.GetLength()+1); mem_copy(pEntry, m_Input.GetString(), m_Input.GetLength()+1); } ExecuteLine(m_Input.GetString()); m_Input.Clear(); m_pHistoryEntry = 0x0; } Handled = true; } else if (Event.m_Key == KEY_UP) { if (m_pHistoryEntry) { char *pTest = m_History.Prev(m_pHistoryEntry); if (pTest) m_pHistoryEntry = pTest; } else m_pHistoryEntry = m_History.Last(); if (m_pHistoryEntry) m_Input.Set(m_pHistoryEntry); Handled = true; } else if (Event.m_Key == KEY_DOWN) { if (m_pHistoryEntry) m_pHistoryEntry = m_History.Next(m_pHistoryEntry); if (m_pHistoryEntry) m_Input.Set(m_pHistoryEntry); else m_Input.Clear(); Handled = true; } else if(Event.m_Key == KEY_TAB) { if(m_Type == CGameConsole::CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed()) { m_CompletionChosen++; m_CompletionEnumerationCount = 0; m_pGameConsole->m_pConsole->PossibleCommands(m_aCompletionBuffer, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL && m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands(), PossibleCommandsCompleteCallback, this); // handle wrapping if(m_CompletionEnumerationCount && m_CompletionChosen >= m_CompletionEnumerationCount) { m_CompletionChosen %= m_CompletionEnumerationCount; m_CompletionEnumerationCount = 0; m_pGameConsole->m_pConsole->PossibleCommands(m_aCompletionBuffer, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL && m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands(), PossibleCommandsCompleteCallback, this); } } } else if(Event.m_Key == KEY_PAGEUP) { ++m_BacklogActPage; } else if(Event.m_Key == KEY_PAGEDOWN) { --m_BacklogActPage; if(m_BacklogActPage < 0) m_BacklogActPage = 0; } } if(!Handled) m_Input.ProcessInput(Event); if(Event.m_Flags&IInput::FLAG_PRESS) { if(Event.m_Key != KEY_TAB) { m_CompletionChosen = -1; str_copy(m_aCompletionBuffer, m_Input.GetString(), sizeof(m_aCompletionBuffer)); } // find the current command { char aBuf[64] = {0}; const char *pSrc = GetString(); int i = 0; for(; i < (int)sizeof(aBuf)-1 && *pSrc && *pSrc != ' '; i++, pSrc++) aBuf[i] = *pSrc; aBuf[i] = 0; const IConsole::CCommandInfo *pCommand = m_pGameConsole->m_pConsole->GetCommandInfo(aBuf, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL && m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands()); if(pCommand) { m_IsCommand = true; str_copy(m_aCommandName, pCommand->m_pName, IConsole::TEMPCMD_NAME_LENGTH); str_copy(m_aCommandHelp, pCommand->m_pHelp, IConsole::TEMPCMD_HELP_LENGTH); str_copy(m_aCommandParams, pCommand->m_pParams, IConsole::TEMPCMD_PARAMS_LENGTH); } else m_IsCommand = false; } } }
void IGameController::CycleMap() { if(m_aMapWish[0] != 0) { dbg_msg("game", "rotating map to %s", m_aMapWish); str_copy(g_Config.m_SvMap, m_aMapWish, sizeof(g_Config.m_SvMap)); m_aMapWish[0] = 0; m_RoundCount = 0; return; } if(!str_length(g_Config.m_SvMaprotation)) return; if(m_RoundCount < g_Config.m_SvRoundsPerMap-1) return; // handle maprotation const char *pMapRotation = g_Config.m_SvMaprotation; const char *pCurrentMap = g_Config.m_SvMap; int CurrentMapLen = str_length(pCurrentMap); const char *pNextMap = pMapRotation; while(*pNextMap) { int WordLen = 0; while(pNextMap[WordLen] && !IsSeparator(pNextMap[WordLen])) WordLen++; if(WordLen == CurrentMapLen && str_comp_num(pNextMap, pCurrentMap, CurrentMapLen) == 0) { // map found pNextMap += CurrentMapLen; while(*pNextMap && IsSeparator(*pNextMap)) pNextMap++; break; } pNextMap++; } // restart rotation if(pNextMap[0] == 0) pNextMap = pMapRotation; // cut out the next map char Buf[512]; for(int i = 0; i < 512; i++) { Buf[i] = pNextMap[i]; if(IsSeparator(pNextMap[i]) || pNextMap[i] == 0) { Buf[i] = 0; break; } } // skip spaces int i = 0; while(IsSeparator(Buf[i])) i++; m_RoundCount = 0; dbg_msg("game", "rotating map to %s", &Buf[i]); str_copy(g_Config.m_SvMap, &Buf[i], sizeof(g_Config.m_SvMap)); }
bool CDataFileWriter::CreateEmptyMap(class IStorage *pStorage, const char *pFileName, int w, int h, CImageInfoFile *pTileset) { dbg_msg("CDataFileWriter", "Saving Empty MineTee Map to '%s'...", pFileName); if(!Open(pStorage, pFileName)) { dbg_msg("CDataFileWriter", "failed to open file '%s'...", pFileName); return 0; } CTile *pTiles = (CTile*)mem_alloc(sizeof(CTile)*w*h, 1); mem_zero(pTiles, sizeof(CTile)*w*h); int LayerCount = 0, GroupCount = 0; // save version { CMapItemVersion Item; Item.m_Version = 1; AddItem(MAPITEMTYPE_VERSION, 0, sizeof(Item), &Item); dbg_msg("CDataFileWriter", "saving version"); } // save map info { CMapItemInfo Item; Item.m_Version = 1; Item.m_Author = -1; Item.m_MapVersion = -1; Item.m_Credits = -1; Item.m_License = -1; AddItem(MAPITEMTYPE_INFO, 0, sizeof(Item), &Item); dbg_msg("CDataFileWriter", "saving info"); } // save images { CMapItemImage Item; Item.m_Version = CMapItemImage::CURRENT_VERSION; char aName[12]; mem_zero(aName,sizeof(aName)); str_copy(aName, "grass_main", sizeof(aName)); Item.m_ImageName = AddData(str_length(aName)+1, aName); if (pTileset && pTileset->m_pData) { Item.m_External = 0; Item.m_Format = pTileset->m_Format; Item.m_Width = pTileset->m_Width; Item.m_Height = pTileset->m_Height; const int PixelSize = pTileset->m_Format == CImageInfoFile::FORMAT_RGB ? 3 : 4; Item.m_ImageData = AddData(Item.m_Width*Item.m_Height*PixelSize, pTileset->m_pData); } else { Item.m_External = 1; Item.m_Format = 1; // RGBA Item.m_Width = 1024; Item.m_Height = 1024; Item.m_ImageData = -1; } AddItem(MAPITEMTYPE_IMAGE, 0, sizeof(Item), &Item); dbg_msg("CDataFileWriter", "saving images"); } // Background Layer { CMapItemGroup GItem; GItem.m_NumLayers = 1; GItem.m_StartLayer = 0; GItem.m_Version = CMapItemGroup::CURRENT_VERSION; GItem.m_ParallaxX = 0; GItem.m_ParallaxY = 0; GItem.m_OffsetX = 0; GItem.m_OffsetY = 0; GItem.m_UseClipping = 0; GItem.m_ClipX = 0; GItem.m_ClipY = 0; GItem.m_ClipW = 0; GItem.m_ClipH = 0; StrToInts(GItem.m_aName, sizeof(GItem.m_aName)/sizeof(int), "\0"); CMapItemLayerQuads Item; Item.m_Image = -1; Item.m_NumQuads = 1; Item.m_Version = 2; Item.m_Layer.m_Flags = 0; Item.m_Layer.m_Type = LAYERTYPE_QUADS; StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), "Quads\0"); CQuad QuadBkg; const int Width = 1000000; const int Height = 800000; QuadBkg.m_ColorEnv = -1; QuadBkg.m_ColorEnvOffset = 0; QuadBkg.m_PosEnv = -1; QuadBkg.m_PosEnvOffset = 0; QuadBkg.m_aPoints[0].x = QuadBkg.m_aPoints[2].x = -Width; QuadBkg.m_aPoints[1].x = QuadBkg.m_aPoints[3].x = Width; QuadBkg.m_aPoints[0].y = QuadBkg.m_aPoints[1].y = -Height; QuadBkg.m_aPoints[2].y = QuadBkg.m_aPoints[3].y = Height; QuadBkg.m_aPoints[4].x = QuadBkg.m_aPoints[4].y = 0; QuadBkg.m_aColors[0].r = QuadBkg.m_aColors[1].r = 94; QuadBkg.m_aColors[0].g = QuadBkg.m_aColors[1].g = 132; QuadBkg.m_aColors[0].b = QuadBkg.m_aColors[1].b = 174; QuadBkg.m_aColors[0].a = QuadBkg.m_aColors[1].a = 255; QuadBkg.m_aColors[2].r = QuadBkg.m_aColors[3].r = 204; QuadBkg.m_aColors[2].g = QuadBkg.m_aColors[3].g = 232; QuadBkg.m_aColors[2].b = QuadBkg.m_aColors[3].b = 255; QuadBkg.m_aColors[2].a = QuadBkg.m_aColors[3].a = 255; QuadBkg.m_aTexcoords[0].x = 0; QuadBkg.m_aTexcoords[0].y = 0; QuadBkg.m_aTexcoords[1].x = 1<<10; QuadBkg.m_aTexcoords[1].y = 0; QuadBkg.m_aTexcoords[2].x = 0; QuadBkg.m_aTexcoords[2].y = 1<<10; QuadBkg.m_aTexcoords[3].x = 1<<10; QuadBkg.m_aTexcoords[3].y = 1<<10; Item.m_Data = AddDataSwapped(sizeof(CQuad), &QuadBkg); AddItem(MAPITEMTYPE_LAYER, LayerCount++, sizeof(Item), &Item); AddItem(MAPITEMTYPE_GROUP, GroupCount++, sizeof(GItem), &GItem); dbg_msg("CDataFileWriter", "saving background group"); } // Game Group { CMapItemGroup GItem; GItem.m_Version = CMapItemGroup::CURRENT_VERSION; GItem.m_NumLayers = 4; GItem.m_StartLayer = 1; GItem.m_ParallaxX = 100; GItem.m_ParallaxY = 100; GItem.m_OffsetX = 0; GItem.m_OffsetY = 0; GItem.m_UseClipping = 0; GItem.m_ClipX = 0; GItem.m_ClipY = 0; GItem.m_ClipW = 0; GItem.m_ClipH = 0; StrToInts(GItem.m_aName, sizeof(GItem.m_aName)/sizeof(int), "Game\0"); CMapItemLayerTilemap Item; Item.m_Width = w; Item.m_Height = h; Item.m_Version = 3; Item.m_Color.r=Item.m_Color.g=Item.m_Color.b=Item.m_Color.a=255; Item.m_ColorEnv = -1; Item.m_ColorEnvOffset = 0; Item.m_Layer.m_Flags = 0; Item.m_Layer.m_Type = LAYERTYPE_TILES; // background StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), "background\0"); Item.m_Image = 0; Item.m_Flags = 0; Item.m_Data = AddData(w*h*sizeof(CTile), pTiles); AddItem(MAPITEMTYPE_LAYER, LayerCount++, sizeof(Item), &Item); // game StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), "Game\0"); Item.m_Image = -1; Item.m_Flags = TILESLAYERFLAG_GAME; Item.m_Data = AddData(w*h*sizeof(CTile), pTiles); AddItem(MAPITEMTYPE_LAYER, LayerCount++, sizeof(Item), &Item); // foreground StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), "foreground\0"); Item.m_Image = 0; Item.m_Flags = 0; Item.m_Data = AddData(w*h*sizeof(CTile), pTiles); AddItem(MAPITEMTYPE_LAYER, LayerCount++, sizeof(Item), &Item); AddItem(MAPITEMTYPE_GROUP, GroupCount++, sizeof(GItem), &GItem); dbg_msg("CDataFileWriter", "saving game group"); } mem_free(pTiles); // AddItem(MAPITEMTYPE_ENVPOINTS, 0, 0, 0x0); // finish the data file Finish(); dbg_msg("CDataFileWriter", "Saving Done!"); return true; }
void stress_a() { #ifdef _STRESS_DEBUG rtx_dbug_outs("Registering Stress Test A...\r\n"); #endif struct MessageEnvelope * msg_rx; struct num_message * num_msg; struct MessageEnvelope * reg_cmd = (MessageEnvelope *)request_memory_block(); reg_cmd->type = TYPE_REGISTER_CMD; str_copy((BYTE *) "%Z", (BYTE *)reg_cmd->msg); send_message(KCD_PID, reg_cmd); UINT32 num; while(1) { #ifdef _STRESS_DEBUG rtx_dbug_outs("Enter: Stress Test A - Loop 1\r\n"); #endif msg_rx = (MessageEnvelope *)receive_message(NULL); #ifdef _STRESS_DEBUG rtx_dbug_outs("Stress Test A received a message in Loop 1\r\n"); #endif if(msg_rx->msg[0] == '%' && msg_rx->msg[1] == 'Z') { #ifdef _STRESS_DEBUG rtx_dbug_outs("Stress Test A received valid message - breaking out of loop\r\n"); #endif release_memory_block((void *)msg_rx); break; } release_memory_block((void *)msg_rx); } num = 0; while(1) { #ifdef _STRESS_DEBUG rtx_dbug_outs("Enter: Stress Test A - Loop 2\r\n"); #endif num_msg = (num_message *)request_memory_block(); #ifdef _STRESS_DEBUG rtx_dbug_outs_int("Just got memory block for message num ", num); #endif num_msg->type = TYPE_COUNT_REPORT; num_msg->msg = num; send_message(STRESS_B_PID, num_msg); #ifdef _STRESS_DEBUG rtx_dbug_outs("Stress Test A sent message to Stress Test B\r\n"); #endif num = num + 1; release_processor(); #ifdef _STRESS_DEBUG rtx_dbug_outs("Stress Test A back from release processor\r\n"); #endif } }
static int def_load_bio(CONF *conf, BIO *in, long *line) { /* The macro BUFSIZE conflicts with a system macro in VxWorks */ #define CONFBUFSIZE 512 int bufnum = 0, i, ii; BUF_MEM *buff = NULL; char *s, *p, *end; int again; long eline = 0; CONF_VALUE *v = NULL, *tv; CONF_VALUE *sv = NULL; char *section = NULL, *buf; char *start, *psection, *pname; void *h = (void *)(conf->data); if ((buff = BUF_MEM_new()) == NULL) { CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_BUF_LIB); goto err; } section = strdup("default"); if (section == NULL) { CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE); goto err; } if (_CONF_new_data(conf) == 0) { CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE); goto err; } sv = _CONF_new_section(conf, section); if (sv == NULL) { CONFerr(CONF_F_DEF_LOAD_BIO, CONF_R_UNABLE_TO_CREATE_NEW_SECTION); goto err; } bufnum = 0; again = 0; for (;;) { if (!BUF_MEM_grow(buff, bufnum + CONFBUFSIZE)) { CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_BUF_LIB); goto err; } p = &(buff->data[bufnum]); *p = '\0'; BIO_gets(in, p, CONFBUFSIZE - 1); p[CONFBUFSIZE - 1] = '\0'; ii = i = strlen(p); if (i == 0 && !again) break; again = 0; while (i > 0) { if ((p[i - 1] != '\r') && (p[i - 1] != '\n')) break; else i--; } /* we removed some trailing stuff so there is a new * line on the end. */ if (ii && i == ii) again = 1; /* long line */ else { p[i] = '\0'; eline++; /* another input line */ } /* we now have a line with trailing \r\n removed */ /* i is the number of bytes */ bufnum += i; v = NULL; /* check for line continuation */ if (bufnum >= 1) { /* If we have bytes and the last char '\\' and * second last char is not '\\' */ p = &(buff->data[bufnum - 1]); if (IS_ESC(conf, p[0]) && ((bufnum <= 1) || !IS_ESC(conf, p[-1]))) { bufnum--; again = 1; } } if (again) continue; bufnum = 0; buf = buff->data; clear_comments(conf, buf); s = eat_ws(conf, buf); if (IS_EOF(conf, *s)) continue; /* blank line */ if (*s == '[') { char *ss; s++; start = eat_ws(conf, s); ss = start; again: end = eat_alpha_numeric(conf, ss); p = eat_ws(conf, end); if (*p != ']') { if (*p != '\0' && ss != p) { ss = p; goto again; } CONFerr(CONF_F_DEF_LOAD_BIO, CONF_R_MISSING_CLOSE_SQUARE_BRACKET); goto err; } *end = '\0'; if (!str_copy(conf, NULL, §ion, start)) goto err; if ((sv = _CONF_get_section(conf, section)) == NULL) sv = _CONF_new_section(conf, section); if (sv == NULL) { CONFerr(CONF_F_DEF_LOAD_BIO, CONF_R_UNABLE_TO_CREATE_NEW_SECTION); goto err; } continue; } else { pname = s; psection = NULL; end = eat_alpha_numeric(conf, s); if ((end[0] == ':') && (end[1] == ':')) { *end = '\0'; end += 2; psection = pname; pname = end; end = eat_alpha_numeric(conf, end); } p = eat_ws(conf, end); if (*p != '=') { CONFerr(CONF_F_DEF_LOAD_BIO, CONF_R_MISSING_EQUAL_SIGN); goto err; } *end = '\0'; p++; start = eat_ws(conf, p); while (!IS_EOF(conf, *p)) p++; p--; while ((p != start) && (IS_WS(conf, *p))) p--; p++; *p = '\0'; if (!(v = malloc(sizeof(CONF_VALUE)))) { CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE); goto err; } if (psection == NULL) psection = section; v->name = strdup(pname); v->value = NULL; if (v->name == NULL) { CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE); goto err; } if (!str_copy(conf, psection, &(v->value), start)) goto err; if (strcmp(psection, section) != 0) { if ((tv = _CONF_get_section(conf, psection)) == NULL) tv = _CONF_new_section(conf, psection); if (tv == NULL) { CONFerr(CONF_F_DEF_LOAD_BIO, CONF_R_UNABLE_TO_CREATE_NEW_SECTION); goto err; } } else tv = sv; if (_CONF_add_string(conf, tv, v) == 0) { CONFerr(CONF_F_DEF_LOAD_BIO, ERR_R_MALLOC_FAILURE); goto err; } v = NULL; } } if (buff != NULL) BUF_MEM_free(buff); free(section); return (1); err: if (buff != NULL) BUF_MEM_free(buff); free(section); if (line != NULL) *line = eline; ERR_asprintf_error_data("line %ld", eline); if ((h != conf->data) && (conf->data != NULL)) { CONF_free(conf->data); conf->data = NULL; } if (v != NULL) { free(v->name); free(v->value); free(v); } return (0); }
static blob_list_ty * ifeq(blob_list_ty *blp, string_list_ty *ref) { blob_ty *arg; blob_ty *bp; blob_list_ty *result; string_ty *s; string_ty *s2; char *cp; size_t j; /* * allocate the result list */ trace(("ifeq()\n{\n")); result = blob_list_alloc(); /* * make sure we were given enough arguments */ if (blp->length < 2) { arg = blp->list[0]; blob_list_append ( result, blob_alloc(str_from_c("0"), arg->file_name, arg->line_number) ); trace(("}\n")); return result; } /* * turn the list of arguments into a single string */ arg = blp->list[1]; s = str_copy(blp->list[1]->text); for (j = 2; j < blp->length; ++j) { s2 = str_format("%s %s", s->str_text, blp->list[j]->text->str_text); str_free(s); s = s2; } bp = blob_alloc(s, arg->file_name, arg->line_number); /* * rename the variables * and reform to be a single string, again. */ variable_rename(bp, result, ref, VAREN_NO_QUOQUO); blob_free(bp); s = result->length ? str_copy(result->list[0]->text) : str_from_c("0"); for (j = 1; j < result->length; ++j) { s2 = str_format("%s %s", s->str_text, result->list[j]->text->str_text); str_free(s); s = s2; } blob_list_free(result); /* * construct the result */ result = blob_list_alloc(); switch (s->str_text[0]) { case '(': /* * ifeq (xxx,yyy) */ if (s->str_length < 3) goto useless; cp = strchr(s->str_text, ','); if (cp == 0 || s->str_text[s->str_length - 1] != ')') goto useless; blob_list_append ( result, blob_alloc(str_from_c("[in"), arg->file_name, arg->line_number) ); s2 = str_n_from_c(s->str_text + 1, cp - s->str_text - 1); if (s2->str_length == 0) s2 = str_from_c("\"\""); bp = blob_alloc(s2, arg->file_name, arg->line_number); blob_list_append(result, bp); s2 = str_n_from_c(cp + 1, s->str_text + s->str_length - cp - 2); if (s2->str_length == 0) s2 = str_from_c("\"\""); bp = blob_alloc(s2, arg->file_name, arg->line_number); blob_list_append(result, bp); blob_list_append ( result, blob_alloc(str_from_c("]"), arg->file_name, arg->line_number) ); break; case '\'': case '"': /* * ifeq "xxx" "yyy" */ if (s->str_length < 5) goto useless; cp = strchr(s->str_text + 1, s->str_text[0]); if ( !cp || cp[1] != ' ' || cp[2] != s->str_text[0] || s->str_text[s->str_length - 1] != s->str_text[0] ) goto useless; blob_list_append ( result, blob_alloc(str_from_c("[in"), arg->file_name, arg->line_number) ); s2 = str_n_from_c(s->str_text + 1, cp - s->str_text - 1); if (s2->str_length == 0) s2 = str_from_c("\"\""); bp = blob_alloc(s2, arg->file_name, arg->line_number); blob_list_append(result, bp); s2 = str_n_from_c(cp + 3, s->str_text + s->str_length - cp - 4); if (s2->str_length == 0) s2 = str_from_c("\"\""); bp = blob_alloc(s2, arg->file_name, arg->line_number); blob_list_append(result, bp); blob_list_append ( result, blob_alloc(str_from_c("]"), arg->file_name, arg->line_number) ); break; default: /* * We were given some useless thing, just rename the * variables and copy it through. */ useless: bp = blob_alloc(str_copy(s), arg->file_name, arg->line_number); blob_list_append(result, bp); break; } str_free(s); trace(("}\n")); return result; }
int LOCAL_XFORM(main, the_session)(void *session) { struct vsf_session_old *old_session = (struct vsf_session_old *) stackvars_get_local("main", "the_session"); assert(old_session); struct vsf_session *new_session = (struct vsf_session *) session; /* copy control connection */ if (old_session->p_local_addr != NULL) { new_session->p_local_addr = malloc(sizeof(struct sockaddr_in)); memcpy(new_session->p_local_addr, old_session->p_local_addr, sizeof(struct sockaddr_in)); free(old_session->p_local_addr); } if (old_session->p_remote_addr != NULL) { new_session->p_remote_addr = malloc(sizeof(struct sockaddr_in)); memcpy(new_session->p_remote_addr, old_session->p_remote_addr, sizeof(struct sockaddr_in)); free(old_session->p_remote_addr); } /* copy data connection */ new_session->pasv_listen_fd = old_session->pasv_listen_fd; if (old_session->p_port_sockaddr != NULL) { new_session->p_port_sockaddr = malloc(sizeof(struct sockaddr_in)); memcpy(new_session->p_port_sockaddr, old_session->p_port_sockaddr, sizeof(struct sockaddr_in)); free(old_session->p_port_sockaddr); } new_session->data_fd = old_session->data_fd; new_session->data_progress = old_session->data_progress; new_session->bw_rate_max = old_session->bw_rate_max; new_session->bw_send_start_sec = old_session->bw_send_start_sec; new_session->bw_send_start_usec = old_session->bw_send_start_usec; /* copy login details */ new_session->is_anonymous = old_session->is_anonymous; str_copy(&(new_session->user_str), &(old_session->user_str)); str_copy(&(new_session->anon_pass_str), &(old_session->anon_pass_str)); /* copy ftp protocol state */ new_session->restart_pos = old_session->restart_pos; new_session->is_ascii = old_session->is_ascii; str_copy(&(new_session->rnfr_filename_str), &(old_session->rnfr_filename_str)); new_session->abor_received = old_session->abor_received; /* copy ftp session state */ struct mystr_list the_list = INIT_STRLIST; new_session->p_visited_dir_list = vsf_sysutil_malloc(sizeof(struct mystr_list)); *new_session->p_visited_dir_list = the_list; struct mystr_list *mystr_l = old_session->p_visited_dir_list; if (mystr_l != NULL) { int num_nodes = mystr_l->list_len; new_session->p_visited_dir_list->list_len = 0; new_session->p_visited_dir_list->alloc_len = mystr_l->alloc_len; /* save some reallocs */ new_session->p_visited_dir_list->p_nodes = (void*) 0; int i; for (i = 0; i < num_nodes; i++) { str_list_add(new_session->p_visited_dir_list, &(mystr_l->p_nodes[i].str), &(mystr_l->p_nodes[i].sort_key_str)); } } /* copy userids */ new_session->anon_ftp_uid = old_session->anon_ftp_uid; new_session->anon_upload_chown_uid; /* guest_user_uid added; main should init it properly */ /* copy cache */ str_copy(&(new_session->banned_email_str), &(old_session->banned_email_str)); str_copy(&(new_session->userlist_str), &(old_session->userlist_str)); str_copy(&(new_session->banner_str), &(old_session->banner_str)); new_session->tcp_wrapper_ok = old_session->tcp_wrapper_ok; /* copy logging related details */ /* let main + logging.c handle init of xferlog_fd and log_fd */ str_copy(&(new_session->remote_ip_str), &(old_session->remote_ip_str)); new_session->log_type = old_session->log_type; new_session->log_start_sec = old_session->log_start_sec; new_session->log_start_usec = old_session->log_start_usec; str_copy(&(new_session->log_str), &(old_session->log_str)); new_session->transfer_size = old_session->transfer_size; /* copy buffers */ str_copy(&(new_session->ftp_cmd_str), &(old_session->ftp_cmd_str)); str_copy(&(new_session->ftp_arg_str), &(old_session->ftp_arg_str)); /* copy parent<->child comms channel */ new_session->parent_fd = old_session->parent_fd; new_session->child_fd = old_session->child_fd; /* copy other details */ new_session->num_clients = old_session->num_clients; new_session->num_this_ip = old_session->num_this_ip; return 1; }
void vsf_ls_populate_dir_list(struct vsf_session* p_sess, struct mystr_list* p_list, struct mystr_list* p_subdir_list, struct vsf_sysutil_dir* p_dir, const struct mystr* p_base_dir_str, const struct mystr* p_option_str, const struct mystr* p_filter_str, int is_verbose) { struct mystr dirline_str = INIT_MYSTR; struct mystr normalised_base_dir_str = INIT_MYSTR; struct str_locate_result loc_result; int a_option; int r_option; int t_option; int F_option; int do_stat = 0; long curr_time = 0; loc_result = str_locate_char(p_option_str, 'a'); a_option = loc_result.found; loc_result = str_locate_char(p_option_str, 'r'); r_option = loc_result.found; loc_result = str_locate_char(p_option_str, 't'); t_option = loc_result.found; loc_result = str_locate_char(p_option_str, 'F'); F_option = loc_result.found; loc_result = str_locate_char(p_option_str, 'l'); if (loc_result.found) { is_verbose = 1; } /* Invert "reverse" arg for "-t", the time sorting */ if (t_option) { r_option = !r_option; } if (is_verbose || t_option || F_option || p_subdir_list != 0) { do_stat = 1; } /* If the filter starts with a . then implicitly enable -a */ if (!str_isempty(p_filter_str) && str_get_char_at(p_filter_str, 0) == '.') { a_option = 1; } /* "Normalise" the incoming base directory string by making sure it * ends in a '/' if it is nonempty */ if (!str_equal_text(p_base_dir_str, ".")) { str_copy(&normalised_base_dir_str, p_base_dir_str); } if (!str_isempty(&normalised_base_dir_str)) { unsigned int len = str_getlen(&normalised_base_dir_str); if (str_get_char_at(&normalised_base_dir_str, len - 1) != '/') { str_append_char(&normalised_base_dir_str, '/'); } } /* If we're going to need to do time comparisions, cache the local time */ if (is_verbose) { curr_time = vsf_sysutil_get_time_sec(); } while (1) { static struct mystr s_next_filename_str; static struct mystr s_next_path_and_filename_str; static struct vsf_sysutil_statbuf* s_p_statbuf; str_next_dirent(&s_next_filename_str, p_dir); if (str_isempty(&s_next_filename_str)) { break; } /* Padavan */ if (!asus_check_file_visible(p_sess, &s_next_filename_str)) continue; { unsigned int len = str_getlen(&s_next_filename_str); if (len > 0 && str_get_char_at(&s_next_filename_str, 0) == '.') { if (!a_option && !tunable_force_dot_files) { continue; } if (!a_option && ((len == 2 && str_get_char_at(&s_next_filename_str, 1) == '.') || len == 1)) { continue; } } } /* Don't show hidden directory entries */ if (!vsf_access_check_file_visible(&s_next_filename_str)) { continue; } /* If we have an ls option which is a filter, apply it */ if (!str_isempty(p_filter_str)) { unsigned int iters = 0; if (!vsf_filename_passes_filter(&s_next_filename_str, p_filter_str, &iters)) { continue; } } /* Calculate the full path (relative to CWD) for lstat() and * output purposes */ str_copy(&s_next_path_and_filename_str, &normalised_base_dir_str); str_append_str(&s_next_path_and_filename_str, &s_next_filename_str); if (do_stat) { /* lstat() the file. Of course there's a race condition - the * directory entry may have gone away whilst we read it, so * ignore failure to stat */ int retval = str_lstat(&s_next_path_and_filename_str, &s_p_statbuf); if (vsf_sysutil_retval_is_error(retval)) { continue; } } if (is_verbose) { static struct mystr s_final_file_str; /* If it's a damn symlink, we need to append the target */ str_copy(&s_final_file_str, &s_next_filename_str); if (vsf_sysutil_statbuf_is_symlink(s_p_statbuf)) { static struct mystr s_temp_str; int retval = str_readlink(&s_temp_str, &s_next_path_and_filename_str); if (retval == 0 && !str_isempty(&s_temp_str)) { str_append_text(&s_final_file_str, " -> "); str_append_str(&s_final_file_str, &s_temp_str); } } if (F_option && vsf_sysutil_statbuf_is_dir(s_p_statbuf)) { str_append_char(&s_final_file_str, '/'); } build_dir_line(&dirline_str, &s_final_file_str, s_p_statbuf, curr_time); } else { /* Just emit the filenames - note, we prepend the directory for NLST * but not for LIST */ str_copy(&dirline_str, &s_next_path_and_filename_str); if (F_option) { if (vsf_sysutil_statbuf_is_dir(s_p_statbuf)) { str_append_char(&dirline_str, '/'); } else if (vsf_sysutil_statbuf_is_symlink(s_p_statbuf)) { str_append_char(&dirline_str, '@'); } } str_append_text(&dirline_str, "\r\n"); } /* Add filename into our sorted list - sorting by filename or time. Also, * if we are required to, maintain a distinct list of direct * subdirectories. */ { static struct mystr s_temp_str; const struct mystr* p_sort_str = 0; const struct mystr* p_sort_subdir_str = 0; if (!t_option) { p_sort_str = &s_next_filename_str; } else { str_alloc_text(&s_temp_str, vsf_sysutil_statbuf_get_sortkey_mtime(s_p_statbuf)); p_sort_str = &s_temp_str; p_sort_subdir_str = &s_temp_str; } str_list_add(p_list, &dirline_str, p_sort_str); if (p_subdir_list != 0 && vsf_sysutil_statbuf_is_dir(s_p_statbuf)) { str_list_add(p_subdir_list, &s_next_filename_str, p_sort_subdir_str); } } } /* END: while(1) */ str_list_sort(p_list, r_option); if (p_subdir_list != 0) { str_list_sort(p_subdir_list, r_option); } str_free(&dirline_str); str_free(&normalised_base_dir_str); }
void CChat::AddLine(int ClientID, int Team, const char *pLine) { if(ClientID != -1 && (m_pClient->m_aClients[ClientID].m_aName[0] == '\0' || // unknown client m_pClient->m_aClients[ClientID].m_ChatIgnore)) return; bool Highlighted = false; char *p = const_cast<char*>(pLine); while(*p) { pLine = p; // find line seperator and strip multiline while(*p) { if(*p++ == '\n') { *(p-1) = 0; break; } } m_CurrentLine = (m_CurrentLine+1)%MAX_LINES; m_aLines[m_CurrentLine].m_Time = time_get(); m_aLines[m_CurrentLine].m_YOffset[0] = -1.0f; m_aLines[m_CurrentLine].m_YOffset[1] = -1.0f; m_aLines[m_CurrentLine].m_ClientID = ClientID; m_aLines[m_CurrentLine].m_Team = Team; m_aLines[m_CurrentLine].m_NameColor = -2; m_aLines[m_CurrentLine].m_Highlighted = str_find_nocase(pLine, m_pClient->m_aClients[m_pClient->m_Snap.m_LocalClientID].m_aName) != 0; if(m_aLines[m_CurrentLine].m_Highlighted) Highlighted = true; if(ClientID == -1) // server message { str_copy(m_aLines[m_CurrentLine].m_aName, "*** ", sizeof(m_aLines[m_CurrentLine].m_aName)); str_format(m_aLines[m_CurrentLine].m_aText, sizeof(m_aLines[m_CurrentLine].m_aText), "%s", pLine); } else { if(m_pClient->m_aClients[ClientID].m_Team == TEAM_SPECTATORS) m_aLines[m_CurrentLine].m_NameColor = TEAM_SPECTATORS; if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) { if(m_pClient->m_aClients[ClientID].m_Team == TEAM_RED) m_aLines[m_CurrentLine].m_NameColor = TEAM_RED; else if(m_pClient->m_aClients[ClientID].m_Team == TEAM_BLUE) m_aLines[m_CurrentLine].m_NameColor = TEAM_BLUE; } str_copy(m_aLines[m_CurrentLine].m_aName, m_pClient->m_aClients[ClientID].m_aName, sizeof(m_aLines[m_CurrentLine].m_aName)); str_format(m_aLines[m_CurrentLine].m_aText, sizeof(m_aLines[m_CurrentLine].m_aText), ": %s", pLine); } char aBuf[1024]; str_format(aBuf, sizeof(aBuf), "%s%s", m_aLines[m_CurrentLine].m_aName, m_aLines[m_CurrentLine].m_aText); Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "chat", aBuf); } // play sound if(ClientID == -1) m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_SERVER, 0, vec2(0,0)); else if(Highlighted) m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_HIGHLIGHT, 0, vec2(0.0f, 0.0f)); else m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_CLIENT, 0, vec2(0,0)); }
void CGameClient::OnNewSnapshot() { m_NewTick = true; // clear out the invalid pointers mem_zero(&g_GameClient.m_Snap, sizeof(g_GameClient.m_Snap)); m_Snap.m_LocalClientID = -1; // secure snapshot { int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT); for(int Index = 0; Index < Num; Index++) { IClient::CSnapItem Item; void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, Index, &Item); if(m_NetObjHandler.ValidateObj(Item.m_Type, pData, Item.m_DataSize) != 0) { if(g_Config.m_Debug) { char aBuf[256]; str_format(aBuf, sizeof(aBuf), "invalidated index=%d type=%d (%s) size=%d id=%d", Index, Item.m_Type, m_NetObjHandler.GetObjName(Item.m_Type), Item.m_DataSize, Item.m_ID); Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf); } Client()->SnapInvalidateItem(IClient::SNAP_CURRENT, Index); } } } ProcessEvents(); if(g_Config.m_DbgStress) { if((Client()->GameTick()%100) == 0) { char aMessage[64]; int MsgLen = rand()%(sizeof(aMessage)-1); for(int i = 0; i < MsgLen; i++) aMessage[i] = 'a'+(rand()%('z'-'a')); aMessage[MsgLen] = 0; CNetMsg_Cl_Say Msg; Msg.m_Team = rand()&1; Msg.m_pMessage = aMessage; Client()->SendPackMsg(&Msg, MSGFLAG_VITAL); } } // go trough all the items in the snapshot and gather the info we want { m_Snap.m_aTeamSize[TEAM_RED] = m_Snap.m_aTeamSize[TEAM_BLUE] = 0; int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT); for(int i = 0; i < Num; i++) { IClient::CSnapItem Item; const void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, i, &Item); if(Item.m_Type == NETOBJTYPE_CLIENTINFO) { const CNetObj_ClientInfo *pInfo = (const CNetObj_ClientInfo *)pData; int ClientID = Item.m_ID; CClientData *pClient = &m_aClients[ClientID]; IntsToStr(&pInfo->m_Name0, 4, pClient->m_aName); IntsToStr(&pInfo->m_Clan0, 3, pClient->m_aClan); pClient->m_Country = pInfo->m_Country; for(int p = 0; p < NUM_SKINPARTS; p++) { IntsToStr(pInfo->m_aaSkinPartNames[p], 6, pClient->m_aaSkinPartNames[p]); pClient->m_aUseCustomColors[p] = pInfo->m_aUseCustomColors[p]; pClient->m_aSkinPartColors[p] = pInfo->m_aSkinPartColors[p]; } pClient->m_SkinInfo.m_Size = 64; for(int p = 0; p < NUM_SKINPARTS; p++) { if(pClient->m_aaSkinPartNames[p][0] == 'x' && pClient->m_aaSkinPartNames[p][1] == '_') str_copy(pClient->m_aaSkinPartNames[p], "default", 24); pClient->m_SkinPartIDs[p] = m_pSkins->FindSkinPart(p, pClient->m_aaSkinPartNames[p]); if(pClient->m_SkinPartIDs[p] < 0) { pClient->m_SkinPartIDs[p] = m_pSkins->Find("default"); if(pClient->m_SkinPartIDs[p] < 0) pClient->m_SkinPartIDs[p] = 0; } const CSkins::CSkinPart *pSkinPart = m_pSkins->GetSkinPart(p, pClient->m_SkinPartIDs[p]); if(pClient->m_aUseCustomColors[p]) { pClient->m_SkinInfo.m_aTextures[p] = pSkinPart->m_ColorTexture; pClient->m_SkinInfo.m_aColors[p] = m_pSkins->GetColorV4(pClient->m_aSkinPartColors[p], p==SKINPART_TATTOO); } else { pClient->m_SkinInfo.m_aTextures[p] = pSkinPart->m_OrgTexture; pClient->m_SkinInfo.m_aColors[p] = vec4(1.0f, 1.0f, 1.0f, 1.0f); } } pClient->UpdateRenderInfo(); } else if(Item.m_Type == NETOBJTYPE_PLAYERINFO) { const CNetObj_PlayerInfo *pInfo = (const CNetObj_PlayerInfo *)pData; m_aClients[pInfo->m_ClientID].m_Team = pInfo->m_Team; m_aClients[pInfo->m_ClientID].m_Active = true; m_Snap.m_paPlayerInfos[pInfo->m_ClientID] = pInfo; m_Snap.m_NumPlayers++; if(pInfo->m_Local) { m_Snap.m_LocalClientID = Item.m_ID; m_Snap.m_pLocalInfo = pInfo; if(pInfo->m_Team == TEAM_SPECTATORS) { m_Snap.m_SpecInfo.m_Active = true; m_Snap.m_SpecInfo.m_SpectatorID = SPEC_FREEVIEW; } } // calculate team-balance if(pInfo->m_Team != TEAM_SPECTATORS) m_Snap.m_aTeamSize[pInfo->m_Team]++; } else if(Item.m_Type == NETOBJTYPE_CHARACTER) { const void *pOld = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_CHARACTER, Item.m_ID); m_Snap.m_aCharacters[Item.m_ID].m_Cur = *((const CNetObj_Character *)pData); // clamp ammo count for non ninja weapon if(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_Weapon != WEAPON_NINJA) m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_AmmoCount = clamp(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_AmmoCount, 0, 10); if(pOld) { m_Snap.m_aCharacters[Item.m_ID].m_Active = true; m_Snap.m_aCharacters[Item.m_ID].m_Prev = *((const CNetObj_Character *)pOld); if(m_Snap.m_aCharacters[Item.m_ID].m_Prev.m_Tick) Evolve(&m_Snap.m_aCharacters[Item.m_ID].m_Prev, Client()->PrevGameTick()); if(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_Tick) Evolve(&m_Snap.m_aCharacters[Item.m_ID].m_Cur, Client()->GameTick()); } } else if(Item.m_Type == NETOBJTYPE_SPECTATORINFO) { m_Snap.m_pSpectatorInfo = (const CNetObj_SpectatorInfo *)pData; m_Snap.m_pPrevSpectatorInfo = (const CNetObj_SpectatorInfo *)Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_SPECTATORINFO, Item.m_ID); m_Snap.m_SpecInfo.m_Active = true; m_Snap.m_SpecInfo.m_SpectatorID = m_Snap.m_pSpectatorInfo->m_SpectatorID; } else if(Item.m_Type == NETOBJTYPE_GAMEINFO) { static bool s_GameOver = 0; m_Snap.m_pGameInfoObj = (const CNetObj_GameInfo *)pData; if(!s_GameOver && m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER) OnGameOver(); else if(s_GameOver && !(m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)) OnStartGame(); s_GameOver = m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER; } else if(Item.m_Type == NETOBJTYPE_GAMEDATA) { m_Snap.m_pGameDataObj = (const CNetObj_GameData *)pData; m_Snap.m_GameDataSnapID = Item.m_ID; } else if(Item.m_Type == NETOBJTYPE_FLAG) m_Snap.m_paFlags[Item.m_ID%2] = (const CNetObj_Flag *)pData; } } // setup local pointers if(m_Snap.m_LocalClientID >= 0) { CSnapState::CCharacterInfo *c = &m_Snap.m_aCharacters[m_Snap.m_LocalClientID]; if(c->m_Active) { m_Snap.m_pLocalCharacter = &c->m_Cur; m_Snap.m_pLocalPrevCharacter = &c->m_Prev; m_LocalCharacterPos = vec2(m_Snap.m_pLocalCharacter->m_X, m_Snap.m_pLocalCharacter->m_Y); } else if(Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_CHARACTER, m_Snap.m_LocalClientID)) { // player died m_pControls->OnPlayerDeath(); } } else { m_Snap.m_SpecInfo.m_Active = true; if(Client()->State() == IClient::STATE_DEMOPLAYBACK && DemoPlayer()->GetDemoType() == IDemoPlayer::DEMOTYPE_SERVER && m_DemoSpecID != SPEC_FREEVIEW && m_Snap.m_aCharacters[m_DemoSpecID].m_Active) m_Snap.m_SpecInfo.m_SpectatorID = m_DemoSpecID; else m_Snap.m_SpecInfo.m_SpectatorID = SPEC_FREEVIEW; } // clear out unneeded client data for(int i = 0; i < MAX_CLIENTS; ++i) { if(!m_Snap.m_paPlayerInfos[i] && m_aClients[i].m_Active) m_aClients[i].Reset(); } // update friend state for(int i = 0; i < MAX_CLIENTS; ++i) { if(i == m_Snap.m_LocalClientID || !m_Snap.m_paPlayerInfos[i] || !Friends()->IsFriend(m_aClients[i].m_aName, m_aClients[i].m_aClan, true)) m_aClients[i].m_Friend = false; else m_aClients[i].m_Friend = true; } // sort player infos by score mem_copy(m_Snap.m_paInfoByScore, m_Snap.m_paPlayerInfos, sizeof(m_Snap.m_paInfoByScore)); for(int k = 0; k < MAX_CLIENTS-1; k++) // ffs, bubblesort { for(int i = 0; i < MAX_CLIENTS-k-1; i++) { if(m_Snap.m_paInfoByScore[i+1] && (!m_Snap.m_paInfoByScore[i] || m_Snap.m_paInfoByScore[i]->m_Score < m_Snap.m_paInfoByScore[i+1]->m_Score)) { const CNetObj_PlayerInfo *pTmp = m_Snap.m_paInfoByScore[i]; m_Snap.m_paInfoByScore[i] = m_Snap.m_paInfoByScore[i+1]; m_Snap.m_paInfoByScore[i+1] = pTmp; } } } // sort player infos by team int Teams[3] = { TEAM_RED, TEAM_BLUE, TEAM_SPECTATORS }; int Index = 0; for(int Team = 0; Team < 3; ++Team) { for(int i = 0; i < MAX_CLIENTS && Index < MAX_CLIENTS; ++i) { if(m_Snap.m_paPlayerInfos[i] && m_Snap.m_paPlayerInfos[i]->m_Team == Teams[Team]) m_Snap.m_paInfoByTeam[Index++] = m_Snap.m_paPlayerInfos[i]; } } CTuningParams StandardTuning; CServerInfo CurrentServerInfo; Client()->GetServerInfo(&CurrentServerInfo); if(CurrentServerInfo.m_aGameType[0] != '0') { if(str_comp(CurrentServerInfo.m_aGameType, "DM") != 0 && str_comp(CurrentServerInfo.m_aGameType, "TDM") != 0 && str_comp(CurrentServerInfo.m_aGameType, "CTF") != 0 && str_comp(CurrentServerInfo.m_aGameType, "LMS") != 0 && str_comp(CurrentServerInfo.m_aGameType, "SUR") != 0) m_ServerMode = SERVERMODE_MOD; else if(mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) == 0) m_ServerMode = SERVERMODE_PURE; else m_ServerMode = SERVERMODE_PUREMOD; } // add tuning to demo if(DemoRecorder()->IsRecording() && mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) != 0) { CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS); int *pParams = (int *)&m_Tuning; for(unsigned i = 0; i < sizeof(m_Tuning)/sizeof(int); i++) Msg.AddInt(pParams[i]); Client()->SendMsg(&Msg, MSGFLAG_RECORD|MSGFLAG_NOSEND); } }
bool CChat::OnInput(IInput::CEvent Event) { if(m_Mode == MODE_NONE) return false; if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_ESCAPE) { m_Mode = MODE_NONE; m_pClient->OnRelease(); } else if(Event.m_Flags&IInput::FLAG_PRESS && (Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER)) { if(m_Input.GetString()[0]) { Say(m_Mode == MODE_ALL ? 0 : 1, m_Input.GetString()); char *pEntry = m_History.Allocate(m_Input.GetLength()+1); mem_copy(pEntry, m_Input.GetString(), m_Input.GetLength()+1); } m_pHistoryEntry = 0x0; m_Mode = MODE_NONE; m_pClient->OnRelease(); } if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_TAB) { // fill the completion buffer if(m_CompletionChosen < 0) { const char *pCursor = m_Input.GetString()+m_Input.GetCursorOffset(); for(int Count = 0; Count < m_Input.GetCursorOffset() && *(pCursor-1) != ' '; --pCursor, ++Count); m_PlaceholderOffset = pCursor-m_Input.GetString(); for(m_PlaceholderLength = 0; *pCursor && *pCursor != ' '; ++pCursor) ++m_PlaceholderLength; str_copy(m_aCompletionBuffer, m_Input.GetString()+m_PlaceholderOffset, min(static_cast<int>(sizeof(m_aCompletionBuffer)), m_PlaceholderLength+1)); } // find next possible name const char *pCompletionString = 0; m_CompletionChosen = (m_CompletionChosen+1)%MAX_CLIENTS; for(int i = 0; i < MAX_CLIENTS; ++i) { int Index = (m_CompletionChosen+i)%MAX_CLIENTS; if(!m_pClient->m_Snap.m_paPlayerInfos[Index]) continue; if(str_find_nocase(m_pClient->m_aClients[Index].m_aName, m_aCompletionBuffer)) { pCompletionString = m_pClient->m_aClients[Index].m_aName; m_CompletionChosen = Index; break; } } // insert the name if(pCompletionString) { char aBuf[256]; str_copy(aBuf, m_Input.GetString(), min(static_cast<int>(sizeof(aBuf)), m_PlaceholderOffset+1)); str_append(aBuf, pCompletionString, sizeof(aBuf)); str_append(aBuf, m_Input.GetString()+m_PlaceholderOffset+m_PlaceholderLength, sizeof(aBuf)); m_PlaceholderLength = str_length(pCompletionString); m_OldChatStringLength = m_Input.GetLength(); m_Input.Set(aBuf); m_Input.SetCursorOffset(m_PlaceholderOffset+m_PlaceholderLength); m_InputUpdate = true; } } else { // reset name completion process if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key != KEY_TAB) m_CompletionChosen = -1; m_OldChatStringLength = m_Input.GetLength(); m_Input.ProcessInput(Event); m_InputUpdate = true; } if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_UP) { if (m_pHistoryEntry) { char *pTest = m_History.Prev(m_pHistoryEntry); if (pTest) m_pHistoryEntry = pTest; } else m_pHistoryEntry = m_History.Last(); if (m_pHistoryEntry) { unsigned int Len = str_length(m_pHistoryEntry); if (Len < sizeof(m_Input) - 1) // TODO: WTF? m_Input.Set(m_pHistoryEntry); } } else if (Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_DOWN) { if (m_pHistoryEntry) m_pHistoryEntry = m_History.Next(m_pHistoryEntry); if (m_pHistoryEntry) { unsigned int Len = str_length(m_pHistoryEntry); if (Len < sizeof(m_Input) - 1) // TODO: WTF? m_Input.Set(m_pHistoryEntry); } else m_Input.Clear(); } return true; }
int main( int argc, char** argv ) { char cmd[ 2048 ]; BoronApp app( argc, argv ); UThread* ut; UBuffer rstr; int fileN = 0; int ret = 0; { UEnvParameters param; ut = boron_makeEnv( boron_envParam(¶m) ); } if( ! ut ) { printf( "boron_makeEnv failed\n" ); return -1; } ur_freezeEnv( ut ); boron_initQt( ut ); if( argc > 1 ) { int i; char* arg; for( i = 1; i < argc; ++i ) { arg = argv[i]; if( arg[0] == '-' ) { switch( arg[1] ) { case 's': //ur_disable( env, UR_ENV_SECURE ); break; case 'h': usage( argv[0] ); return 0; } } else { fileN = i; break; } } } ur_strInit( &rstr, UR_ENC_UTF8, 0 ); #ifdef _WIN32 { WORD wsver; WSADATA wsdata; wsver = MAKEWORD( 2, 2 ); WSAStartup( wsver, &wsdata ); } #endif if( fileN ) { char* pos; pos = cmd; cmd[ sizeof(cmd) - 1 ] = -1; // Create args block for any command line parameters. if( (argc - fileN) > 1 ) { int i; pos = str_copy( pos, "args: [" ); for( i = fileN + 1; i < argc; ++i ) { *pos++ = '"'; pos = str_copy( pos, argv[i] ); *pos++ = '"'; *pos++ = ' '; } *pos++ = ']'; } else { pos = str_copy( pos, "args: none " ); } pos = str_copy( pos, "do load {" ); pos = str_copy( pos, argv[fileN] ); *pos++ = '}'; assert( cmd[ sizeof(cmd) - 1 ] == -1 && "cmd buffer overflow" ); if( ! boron_evalUtf8( ut, cmd, pos - cmd ) ) { UCell* ex = ur_exception( ut ); if( ur_is(ex, UT_ERROR) ) { OPEN_CONSOLE reportError( ut, ex, &rstr ); goto prompt; } else if( ur_is(ex, UT_WORD) ) { switch( ur_atom(ex) ) { case UR_ATOM_QUIT: goto quit; case UR_ATOM_HALT: goto prompt; break; } } } } else { OPEN_CONSOLE printf( APPNAME " %s (%s)\n", UR_VERSION_STR, __DATE__ ); prompt: while( 1 ) { printf( ")> " ); fflush( stdout ); /* Required on Windows. */ fgets( cmd, sizeof(cmd), stdin ); #if 0 { char* cp = cmd; while( *cp != '\n' ) printf( " %d", (int) *cp++ ); printf( "\n" ); } #endif if( cmd[0] == ESC ) { // Up 27 91 65 // Down 27 91 66 printf( "\n" ); } else if( cmd[0] != '\n' ) { #if 0 if( cmd[0] == 'q' ) goto quit; #endif UCell* val = boron_evalUtf8( ut, cmd, -1 ); if( val ) { if( ur_is(val, UT_UNSET) || ur_is(val, UT_CONTEXT) ) goto prompt; rstr.used = 0; ur_toStr( ut, val, &rstr, 0 ); if( rstr.ptr.c ) { ur_strTermNull( &rstr ); if( rstr.used > PRINT_MAX ) { char* cp = str_copy( rstr.ptr.c + PRINT_MAX - 4, "..." ); *cp = '\0'; } printf( "== %s\n", rstr.ptr.c ); } } else { UCell* ex = ur_exception( ut ); if( ur_is(ex, UT_ERROR) ) { reportError( ut, ex, &rstr ); } else if( ur_is(ex, UT_WORD) ) { switch( ur_atom(ex) ) { case UR_ATOM_QUIT: goto quit; case UR_ATOM_HALT: printf( "**halt\n" ); break; default: printf( "**unhandled excepetion %s\n", ur_atomCStr(ut,ur_atom(ex)) ); break; } } boron_reset( ut ); } } } } quit: ur_strFree( &rstr ); boron_freeQt(); boron_freeEnv( ut ); #ifdef _WIN32 WSACleanup(); #endif return ret; }
static int transfer_dir_internal(struct vsf_session* p_sess, int is_control, struct vsf_sysutil_dir* p_dir, const struct mystr* p_base_dir_str, const struct mystr* p_option_str, const struct mystr* p_filter_str, int is_verbose) { struct mystr_list dir_list = INIT_STRLIST; struct mystr_list subdir_list = INIT_STRLIST; struct mystr dir_prefix_str = INIT_MYSTR; struct mystr_list* p_subdir_list = 0; struct str_locate_result loc_result = str_locate_char(p_option_str, 'R'); int failed = 0; enum EVSFRWTarget target = kVSFRWData; if (is_control) { target = kVSFRWControl; } if (loc_result.found && tunable_ls_recurse_enable) { p_subdir_list = &subdir_list; } vsf_ls_populate_dir_list(p_sess, &dir_list, p_subdir_list, p_dir, p_base_dir_str, p_option_str, p_filter_str, is_verbose); if (p_subdir_list) { int retval; str_copy(&dir_prefix_str, p_base_dir_str); str_append_text(&dir_prefix_str, ":\r\n"); retval = ftp_write_str(p_sess, &dir_prefix_str, target); if (retval != 0) { failed = 1; } } if (!failed) { failed = write_dir_list(p_sess, &dir_list, target); } /* Recurse into the subdirectories if required... */ if (!failed) { struct mystr sub_str = INIT_MYSTR; unsigned int num_subdirs = str_list_get_length(&subdir_list); unsigned int subdir_index; for (subdir_index = 0; subdir_index < num_subdirs; subdir_index++) { int retval; struct vsf_sysutil_dir* p_subdir; const struct mystr* p_subdir_str = str_list_get_pstr(&subdir_list, subdir_index); if (str_equal_text(p_subdir_str, ".") || str_equal_text(p_subdir_str, "..")) { continue; } str_copy(&sub_str, p_base_dir_str); str_append_char(&sub_str, '/'); str_append_str(&sub_str, p_subdir_str); p_subdir = str_opendir(&sub_str); if (p_subdir == 0) { /* Unreadable, gone missing, etc. - no matter */ continue; } str_alloc_text(&dir_prefix_str, "\r\n"); retval = ftp_write_str(p_sess, &dir_prefix_str, target); if (retval != 0) { failed = 1; vsf_sysutil_closedir(p_subdir); break; } retval = transfer_dir_internal(p_sess, is_control, p_subdir, &sub_str, p_option_str, p_filter_str, is_verbose); vsf_sysutil_closedir(p_subdir); if (retval != 0) { failed = 1; break; } } str_free(&sub_str); } str_list_free(&dir_list); str_list_free(&subdir_list); str_free(&dir_prefix_str); if (!failed) { return 0; } else { return -1; } }
int TextInput( int x, int y, const char *prompt, int maxlen, int fieldlen, VString *strres, void (*handlekey)( int key, VString &s, int &pos ) ) { int res = 0; int insert = 1; VString str = *strres; VString tmp; int ch; ScrollPos scroll; scroll.set_min_max( 0, str_len( str ) ); scroll.set_pagesize( fieldlen ); scroll.go( str_len(str) ); int show = 1; int firsthit = 1; int opage = -1; con_cshow(); while(1) { if (opage != scroll.page()) show = 1; if (show) { str_copy( tmp, str, scroll.page(), scroll.pagesize() ); str_pad( tmp, -scroll.pagesize() ); tmp = " " + tmp + " "; if ( scroll.page() > 0 ) str_set_ch( tmp, 0, '<' ); if ( scroll.page()+scroll.pagesize() < str_len(str) ) str_set_ch( tmp, str_len(tmp)-1, '>' ); con_out(x, y, tmp, firsthit ? EditStrFH : EditStrBF ); show = 0; opage = scroll.page(); } con_xy( x + scroll.pos() - scroll.page() + 1 , y ); ch = con_getch(); if( ch >= 32 && ch <= 255 && ch != KEY_BACKSPACE && str_len(str) < maxlen - 1 ) { if (firsthit) { str = ""; scroll.go(0); firsthit = 0; } if (!insert) str_del( str, scroll.pos(), 1 ); str_ins_ch( str, scroll.pos(), ch ); scroll.set_min_max( 0, str_len( str ) ); scroll.go( scroll.pos() ); scroll.down(); show = 1; }; if (firsthit) { show = 1; firsthit = 0; } if( ch == 27 ) { res = 0; break; } else if( ch == 13 ) { *strres = str; res = 1; break; } else if( ch == KEY_CTRL_U ) { scroll.go(0); str = ""; show = 1; } else if( (ch == KEY_BACKSPACE || ch == 8 ) && (scroll.pos() > 0) ) { scroll.up(); str_del( str, scroll.pos(), 1 ); show = 1; } else if ( ch == KEY_IC ) insert = !insert; else if ( ch == KEY_LEFT ) scroll.up(); else if ( ch == KEY_RIGHT ) scroll.down(); else /* if ( ch == KEY_PPAGE ) scroll.ppage(); else if ( ch == KEY_NPAGE ) scroll.npage(); else */ if ( ch == KEY_HOME || ch == KEY_CTRL_A ) scroll.go(0); else if ( ch == KEY_END || ch == KEY_CTRL_E ) scroll.go(str_len(str)); else if ( ( ch == KEY_DC || ch == KEY_CTRL_D ) && scroll.pos() < str_len(str) ) { str_del( str, scroll.pos(), 1 ); show = 1; } else if ( handlekey ) { int npos = scroll.pos(); handlekey( ch, str, npos ); scroll.set_min_max( 0, str_len( str ) ); scroll.go( scroll.pos() ); if (scroll.pos() != npos) scroll.go( npos ); show = 1; } scroll.set_min_max( 0, str_len( str ) ); scroll.go( scroll.pos() ); } con_chide(); return res; }
void CLua::Eval(const char *pCode) { char *pBuf = new char[str_length(pCode) + 1]; str_copy(pBuf, pCode, str_length(pCode) + 1); m_lpEvalBuffer.add(pBuf); }
int CSkins::SkinScan(const char *pName, int IsDir, int DirType, void *pUser) { CSkins *pSelf = (CSkins *)pUser; int l = str_length(pName); if(l < 4 || IsDir || str_comp(pName+l-4, ".png") != 0) return 0; char aBuf[512]; str_format(aBuf, sizeof(aBuf), "skins/%s", pName); CImageInfo Info; if(!pSelf->Graphics()->LoadPNG(&Info, aBuf, DirType)) { str_format(aBuf, sizeof(aBuf), "failed to load skin from %s", pName); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "game", aBuf); return 0; } CSkin Skin; Skin.m_OrgTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0); int BodySize = 96; // body size unsigned char *d = (unsigned char *)Info.m_pData; int Pitch = Info.m_Width*4; // dig out blood color { int aColors[3] = {0}; for(int y = 0; y < BodySize; y++) for(int x = 0; x < BodySize; x++) { if(d[y*Pitch+x*4+3] > 128) { aColors[0] += d[y*Pitch+x*4+0]; aColors[1] += d[y*Pitch+x*4+1]; aColors[2] += d[y*Pitch+x*4+2]; } } Skin.m_BloodColor = normalize(vec3(aColors[0], aColors[1], aColors[2])); } // create colorless version int Step = Info.m_Format == CImageInfo::FORMAT_RGBA ? 4 : 3; // make the texture gray scale for(int i = 0; i < Info.m_Width*Info.m_Height; i++) { int v = (d[i*Step]+d[i*Step+1]+d[i*Step+2])/3; d[i*Step] = v; d[i*Step+1] = v; d[i*Step+2] = v; } int Freq[256] = {0}; int OrgWeight = 0; int NewWeight = 192; // find most common frequence for(int y = 0; y < BodySize; y++) for(int x = 0; x < BodySize; x++) { if(d[y*Pitch+x*4+3] > 128) Freq[d[y*Pitch+x*4]]++; } for(int i = 1; i < 256; i++) { if(Freq[OrgWeight] < Freq[i]) OrgWeight = i; } // reorder int InvOrgWeight = 255-OrgWeight; int InvNewWeight = 255-NewWeight; for(int y = 0; y < BodySize; y++) for(int x = 0; x < BodySize; x++) { int v = d[y*Pitch+x*4]; if(v <= OrgWeight) v = (int)(((v/(float)OrgWeight) * NewWeight)); else v = (int)(((v-OrgWeight)/(float)InvOrgWeight)*InvNewWeight + NewWeight); d[y*Pitch+x*4] = v; d[y*Pitch+x*4+1] = v; d[y*Pitch+x*4+2] = v; } Skin.m_ColorTexture = pSelf->Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0); mem_free(Info.m_pData); // set skin data str_copy(Skin.m_aName, pName, min((int)sizeof(Skin.m_aName),l-3)); if(g_Config.m_Debug) { str_format(aBuf, sizeof(aBuf), "load skin %s", Skin.m_aName); pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "game", aBuf); } pSelf->m_aSkins.add(Skin); return 0; }
void stress_c() { #ifdef _STRESS_DEBUG rtx_dbug_outs("Initializing: Stress Test C\r\n"); #endif msgq_head = NULL; msgq_tail = NULL; struct num_message * msg_rx; struct num_message * msg_wake; struct MessageEnvelope * proc_c; struct num_message * hibernate; while(1) { #ifdef _STRESS_DEBUG rtx_dbug_outs("Enter: Stress Test C\r\n"); #endif if(msgq_head == NULL) { // receive message msg_rx = (num_message *)receive_message(NULL); #ifdef _STRESS_DEBUG rtx_dbug_outs("Stress Test C received a message\r\n"); #endif } else { // dequeue first message from local message queue msg_rx = msgq_head->env; msgq_head = msgq_head->next; if(msgq_head == NULL) { msgq_tail = NULL; } #ifdef _STRESS_DEBUG rtx_dbug_outs("Stress Test C dequeued a message\r\n"); #endif } UINT32 type = msg_rx->type; UINT32 msg_data = msg_rx->msg; release_memory_block((void *)msg_rx); if(type == TYPE_COUNT_REPORT) { #ifdef _STRESS_DEBUG rtx_dbug_outs_int("Stress Test C got message ", msg_rx->msg); #endif if(msg_data%20 == 0) { proc_c = (MessageEnvelope *)request_memory_block(); str_copy((BYTE *) "Process C\r\n", (BYTE *)proc_c->msg); send_message(CRT_PID, proc_c); #ifdef _STRESS_DEBUG rtx_dbug_outs("Stress Test C sent a message to CRT\r\n"); #endif // hibernate for 10 seconds hibernate = (num_message *)request_memory_block(); hibernate->type = TYPE_WAKEUP10; delayed_send(STRESS_C_PID, hibernate, 10000); while(1) { msg_wake = (num_message *)receive_message(NULL); if(msg_wake->type == TYPE_WAKEUP10) { break; } else { // enqueue the message into local queue enqueue_local_msg(msg_wake); } } } } release_memory_block((void *)hibernate); release_processor(); } }
void CGameConsole::CInstance::OnInput(IInput::CEvent Event) { bool Handled = false; if(m_pGameConsole->Input()->KeyIsPressed(KEY_LCTRL) && m_pGameConsole->Input()->KeyPress(KEY_V)) { const char *Text = m_pGameConsole->Input()->GetClipboardText(); if(Text) { char Line[256]; int i, Begin = 0; for(i = 0; i < str_length(Text); i++) { if(Text[i] == '\n') { if(i == Begin) { Begin++; continue; } int max = min(i - Begin + 1, (int)sizeof(Line)); str_copy(Line, Text + Begin, max); Begin = i+1; ExecuteLine(Line); } } int max = min(i - Begin + 1, (int)sizeof(Line)); str_copy(Line, Text + Begin, max); Begin = i+1; m_Input.Add(Line); } } if(m_pGameConsole->Input()->KeyIsPressed(KEY_LCTRL) && m_pGameConsole->Input()->KeyPress(KEY_C)) { m_pGameConsole->Input()->SetClipboardText(m_Input.GetString()); } if(Event.m_Flags&IInput::FLAG_PRESS) { if(Event.m_Key == KEY_RETURN || Event.m_Key == KEY_KP_ENTER) { if(m_Input.GetString()[0]) { if(m_Type == CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed()) { char *pEntry = m_History.Allocate(m_Input.GetLength()+1); mem_copy(pEntry, m_Input.GetString(), m_Input.GetLength()+1); } ExecuteLine(m_Input.GetString()); m_Input.Clear(); m_pHistoryEntry = 0x0; } Handled = true; } else if (Event.m_Key == KEY_UP) { if (m_pHistoryEntry) { char *pTest = m_History.Prev(m_pHistoryEntry); if (pTest) m_pHistoryEntry = pTest; } else m_pHistoryEntry = m_History.Last(); if (m_pHistoryEntry) m_Input.Set(m_pHistoryEntry); Handled = true; } else if (Event.m_Key == KEY_DOWN) { if (m_pHistoryEntry) m_pHistoryEntry = m_History.Next(m_pHistoryEntry); if (m_pHistoryEntry) m_Input.Set(m_pHistoryEntry); else m_Input.Clear(); Handled = true; } else if(Event.m_Key == KEY_TAB) { if(m_Type == CGameConsole::CONSOLETYPE_LOCAL || m_pGameConsole->Client()->RconAuthed()) { if(m_ReverseTAB) m_CompletionChosen--; else m_CompletionChosen++; m_CompletionEnumerationCount = 0; m_pGameConsole->m_pConsole->PossibleCommands(m_aCompletionBuffer, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL && m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands(), PossibleCommandsCompleteCallback, this); // handle wrapping if(m_CompletionEnumerationCount && (m_CompletionChosen >= m_CompletionEnumerationCount || m_CompletionChosen <0)) { m_CompletionChosen= (m_CompletionChosen + m_CompletionEnumerationCount) % m_CompletionEnumerationCount; m_CompletionEnumerationCount = 0; m_pGameConsole->m_pConsole->PossibleCommands(m_aCompletionBuffer, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL && m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands(), PossibleCommandsCompleteCallback, this); } } } else if(Event.m_Key == KEY_PAGEUP) { ++m_BacklogActPage; } else if(Event.m_Key == KEY_PAGEDOWN) { --m_BacklogActPage; if(m_BacklogActPage < 0) m_BacklogActPage = 0; } else if(Event.m_Key == KEY_LSHIFT) { m_ReverseTAB = true; Handled = true; } } if(Event.m_Flags&IInput::FLAG_RELEASE && Event.m_Key == KEY_LSHIFT) { m_ReverseTAB = false; Handled = true; } if(!Handled) m_Input.ProcessInput(Event); if(Event.m_Flags & (IInput::FLAG_PRESS|IInput::FLAG_TEXT)) { if((Event.m_Key != KEY_TAB) && (Event.m_Key != KEY_LSHIFT)) { m_CompletionChosen = -1; str_copy(m_aCompletionBuffer, m_Input.GetString(), sizeof(m_aCompletionBuffer)); } // find the current command { char aBuf[64] = {0}; const char *pSrc = GetString(); int i = 0; for(; i < (int)sizeof(aBuf)-1 && *pSrc && *pSrc != ' '; i++, pSrc++) aBuf[i] = *pSrc; aBuf[i] = 0; const IConsole::CCommandInfo *pCommand = m_pGameConsole->m_pConsole->GetCommandInfo(aBuf, m_CompletionFlagmask, m_Type != CGameConsole::CONSOLETYPE_LOCAL && m_pGameConsole->Client()->RconAuthed() && m_pGameConsole->Client()->UseTempRconCommands()); if(pCommand) { m_IsCommand = true; str_copy(m_aCommandName, pCommand->m_pName, IConsole::TEMPCMD_NAME_LENGTH); str_copy(m_aCommandHelp, pCommand->m_pHelp, IConsole::TEMPCMD_HELP_LENGTH); str_copy(m_aCommandParams, pCommand->m_pParams, IConsole::TEMPCMD_PARAMS_LENGTH); } else m_IsCommand = false; } } }
bool CLineInput::Manipulate(IInput::CEvent e, char *pStr, int StrMaxSize, int *pStrLenPtr, int *pCursorPosPtr) { int CursorPos = *pCursorPosPtr; int Len = *pStrLenPtr; bool Changes = false; if(CursorPos > Len) CursorPos = Len; int Code = e.m_Unicode; int k = e.m_Key; // 127 is produced on Mac OS X and corresponds to the delete key if (!(Code >= 0 && Code < 32) && Code != 127) { char Tmp[8]; int CharSize = str_utf8_encode(Tmp, Code); if (Len < StrMaxSize - CharSize && CursorPos < StrMaxSize - CharSize) { mem_move(pStr + CursorPos + CharSize, pStr + CursorPos, Len-CursorPos+1); // +1 == null term for(int i = 0; i < CharSize; i++) pStr[CursorPos+i] = Tmp[i]; CursorPos += CharSize; Len += CharSize; Changes = true; } } if(e.m_Flags&IInput::FLAG_PRESS) { // backspace, ctrl+backspace, ctrl+w if ((k == KEY_BACKSPACE || (k == KEY_w && e.GetKeyMods()&(KEYMOD_LCTRL|KEYMOD_RCTRL))) && CursorPos > 0) { int NewCursorPos; if(e.GetKeyMods()&(KEYMOD_LCTRL|KEYMOD_RCTRL)) NewCursorPos = str_skip_word_backward(pStr, CursorPos); else NewCursorPos = str_utf8_rewind(pStr, CursorPos); int CharSize = CursorPos-NewCursorPos; mem_move(pStr+NewCursorPos, pStr+CursorPos, Len - NewCursorPos - CharSize + 1); // +1 == null term CursorPos = NewCursorPos; Len -= CharSize; Changes = true; } // ctrl+u else if(k == KEY_u && e.GetKeyMods()&(KEYMOD_LCTRL|KEYMOD_RCTRL)) { mem_move(pStr, pStr+CursorPos, Len - CursorPos + 1); // +1 == null term Len -= CursorPos; CursorPos = 0; Changes = true; } else if (k == KEY_DELETE && CursorPos < Len) { int p = str_utf8_forward(pStr, CursorPos); int CharSize = p-CursorPos; mem_move(pStr + CursorPos, pStr + CursorPos + CharSize, Len - CursorPos - CharSize + 1); // +1 == null term Len -= CharSize; Changes = true; } else if (k == KEY_LEFT && CursorPos > 0) { if(e.GetKeyMods()&(KEYMOD_LCTRL|KEYMOD_RCTRL)) CursorPos = str_skip_word_backward(pStr, CursorPos); else CursorPos = str_utf8_rewind(pStr, CursorPos); } else if (k == KEY_RIGHT && CursorPos < Len) { if(e.GetKeyMods()&(KEYMOD_LCTRL|KEYMOD_RCTRL)) CursorPos = str_skip_word_forward(pStr, CursorPos); else CursorPos = str_utf8_forward(pStr, CursorPos); } else if (k == KEY_HOME) CursorPos = 0; else if (k == KEY_END) CursorPos = Len; // ctrl+v -- paste else if(k == KEY_v && e.GetKeyMods()&(KEYMOD_LCTRL|KEYMOD_RCTRL)) { char aBuf[MAX_SIZE]; str_copy(aBuf, pStr + CursorPos, sizeof(aBuf)); int size = get_clipboard_data(pStr + CursorPos, MAX_SIZE - CursorPos); if(size >= 0 && size < MAX_SIZE - CursorPos) // success { CursorPos += size; Len += size; str_copy(pStr + CursorPos, aBuf, MAX_SIZE - CursorPos); } Changes = true; } } *pCursorPosPtr = CursorPos; *pStrLenPtr = Len; return Changes; }