Example #1
0
bool CTaksiConfig::ReadIniFile()
{
	// Read an INI file in standard INI file format.
	// Returns true if successful.

	TCHAR szIniFileName[_MAX_PATH];
	Str_MakeFilePath( szIniFileName, COUNTOF(szIniFileName), 
		sg_Shared.m_szIniDir, _T(TAKSI_INI_FILE) );

#ifdef _UNICODE
	// convert from UNICODE. fopen() is multibyte only.
	FILE* pFile = NULL;	ASSERT(0);
#else
	FILE* pFile = fopen(szIniFileName, _T("rt"));
#endif
	if (pFile == NULL) 
	{
		// ASSUME constructor has already set this to all defaults.
		return false;
	}

	LOG_MSG(( "Reading INI file '%s'" LOG_CR, szIniFileName ));

	CIniObject* pObj = NULL;
	while (true)
	{
		char szBuffer[_MAX_PATH*2];
		fgets(szBuffer, sizeof(szBuffer)-1, pFile);
		if (feof(pFile))
			break;

		// skip/trim comments
		char* pszComment = strstr(szBuffer, ";");
		if (pszComment != NULL) 
			pszComment[0] = '\0';

		// parse the line
		char* pszName = Str_SkipSpace(szBuffer);	// skip leading spaces.
		if ( *pszName == '\0' )
			continue;

		if ( *pszName == '[' )
		{
			if ( ! strnicmp( pszName, "[" TAKSI_SECTION "]", 7 ))
			{
				pObj = this;
			}
			else if ( ! strnicmp( pszName, "[" TAKSI_CUSTOM_SECTION " ", sizeof(TAKSI_CUSTOM_SECTION)+1 ))
			{
				TCHAR szSection[ _MAX_PATH ];
#ifdef _UNICODE
				ASSERT(0);
#else
				strncpy( szSection, pszName+sizeof(TAKSI_CUSTOM_SECTION)+1, sizeof(szSection));
#endif
				TCHAR* pszEnd = _tcschr(szSection, ']');
				if (pszEnd)
					*pszEnd = '\0';
				pObj = CustomConfig_Lookup(szSection,true);
			}
			else
			{
				pObj = NULL;
				LOG_MSG(("INI Bad Section %s" LOG_CR, pszName ));
			}
			continue;
		}

		if ( pObj == NULL )	// skip
			continue;

		char* pszEq = strstr(pszName, "=");
		if (pszEq == NULL) 
			continue;
		pszEq[0] = '\0';

		char* pszValue = Str_SkipSpace( pszEq + 1 );	// skip leading spaces.

		if ( ! pObj->PropSetName( pszName, pszValue ))
		{
			LOG_MSG(("INI Bad Prop %s" LOG_CR, pszName ));
		}
	}

	fclose(pFile);
	FixCaptureDir();
	return true;
}
Example #2
0
void ConfigIO :: loadParam (const char *param)
{
  char line [10240];
  char paramName [10240];
  strncpy_s (line, param, sizeof (line));

  char *div = strchr (line, '=');

  for (size_t f = 0; f < parameters.size (); f ++)
      {
        strcpy_s (paramName, parameters [f].name);
        trimWhiteSpace (paramName);
        if (strnicmp (paramName, line, strlen (paramName)) == 0)
           {
             if (parameters [f].type == INT) *parameters [f].pInt = atoi (div + 1);
             if (parameters [f].type == UNSIGNED) *parameters [f].pUnsigned = atoi (div + 1);
             if (parameters [f].type == BOOL) {
				 std::string boolValue = std::string(div+1);
				 if (boolValue.compare("true") == 0)
					 *parameters [f].pBool = true;
				 else if (boolValue.compare("false") == 0)
					 *parameters [f].pBool = false;
				 else
				 {
					 *parameters [f].pBool = !! atoi (div + 1);
				 }

			 }
             if (parameters [f].type == DOUBLE) *parameters [f].pDouble = atof (div + 1);
             if (parameters [f].type == STRING)
                {
//                  if (div [1] != '"') continue;
//                  if (strchr (div + 2, '"') == NULL) continue;
//                  *strchr (div + 2, '"') = '\0';
//                  *parameters [f].pString = div + 2;
                  if (div [1] == '"')
                     {
                       if (strchr (div + 2, '"') == NULL) continue;
                       *strchr (div + 2, '"') = '\0';
                       *parameters [f].pString = div + 2;
                     }
                  else if (div [1] == '\'')
                     {
                       if (strchr (div + 2, '\'') == NULL) continue;
                       *strchr (div + 2, '\'') = '\0';
                       *parameters [f].pString = div + 2;
                     }
                  else 
                     {  
//                        for (char *p = div + 2; *p != '\0'; p ++)  // already trimmed
//                             if (isspace (*p)) *p = '\0';
                       *parameters [f].pString = div + 1;
                     }
                }
             if (parameters [f].type == ENUM)
             {
                if (strtol(div+1, (char **)NULL, 10)==0)
                {
                   // it is not a number
                   if (parameters [f].enum_map->is_valuename(div+1))
                      *parameters [f].pInt = parameters [f].enum_map->get_value(div+1);
                   else
                      printf("Warning: Invalid enum value name '%s' of '%s', leaving default value.\n",
                             div+1, parameters [f].name); // leave default value_type
                } else
                   *parameters [f].pInt = atoi (div + 1);
             }
           }
      }

  for (size_t f = 0; f < checks.size (); f ++)
      {
        strcpy_s (paramName, checks [f].name);
        trimWhiteSpace (paramName);
        if (strnicmp (paramName, line, strlen (paramName)) == 0)
           {
             if (checks [f].type == INT)
                {
                  int v = atoi (div + 1);
                  if (checks [f].vInt != v) cerr << "Config-file parameter " << paramName << " (" << v << ") does not match to compile time value " << checks [f].vInt << endl;
                  assert (checks [f].vInt == v);
                }
             if (checks [f].type == UNSIGNED)
                {
                  unsigned v = atoi (div + 1);
                  if (checks [f].vUnsigned != v) cerr << "Config-file parameter " << paramName << " (" << v << ") does not match to compile time value " << checks [f].vUnsigned << endl;
                  assert (checks [f].vUnsigned == v);
                }
             if (checks [f].type == BOOL)
                {
                  bool v = !! atoi (div + 1);
                  if (checks [f].vBool != v) cerr << "Config-file parameter " << paramName << " (" << v << ") does not match to compile time value " << checks [f].vBool << endl;
                  assert (checks [f].vBool == v);
                }
             if (checks [f].type == DOUBLE)
                {
                  double v = atof (div + 1);
                  if (checks [f].vDouble != v) cerr << "Config-file parameter " << paramName << " (" << v << ") does not match to compile time value " << checks [f].vDouble << endl;
                  assert (checks [f].vDouble == v);
                }
           }
      }
}
bool CItemStone::r_GetRef( LPCTSTR & pszKey, CScriptObj * & pRef )
{
	ADDTOCALLSTACK("CItemStone::r_GetRef");
	if ( !strnicmp("member.", pszKey, 7) )
	{
		pszKey = pszKey + 7;
		if ( !pszKey[0] )
			return false;

		int nNumber = Exp_GetVal(pszKey);
		SKIP_SEPARATORS(pszKey);

		CStoneMember * pMember = STATIC_CAST <CStoneMember *>(GetHead());

		for ( int i = 0; pMember != NULL; pMember = pMember->GetNext() )
		{
			if ( !pMember->GetLinkUID().IsChar() ) 
				continue;

			if ( nNumber == i )
			{
				pRef = pMember; 
				return true;
			}

			i++;
		}
	}
	else if ( !strnicmp("memberfromuid.", pszKey, 14) )
	{
		pszKey = pszKey + 14;
		if ( !pszKey[0] )
			return false;

		CGrayUID pMemberUid = static_cast<DWORD>(Exp_GetVal(pszKey));
		SKIP_SEPARATORS(pszKey);

		CChar * pMemberChar = pMemberUid.CharFind();
		if ( pMemberChar )
		{
			CStoneMember * pMemberGuild = GetMember( pMemberChar );
			if ( pMemberGuild )
			{
				pRef = pMemberGuild; 
				return true;
			}
		}
	}
	else if ( !strnicmp("guild.", pszKey, 6) )
	{
		pszKey = pszKey + 6;
		if ( !pszKey[0] )
			return false;

		int nNumber = Exp_GetVal(pszKey);
		SKIP_SEPARATORS(pszKey);

		CStoneMember * pMember = STATIC_CAST <CStoneMember *>(GetHead());

		for ( int i = 0; pMember != NULL; pMember = pMember->GetNext() )
		{
			if ( pMember->GetLinkUID().IsChar() ) 
				continue;

			if ( nNumber == i )
			{
				pRef = pMember;
				return true;
			}

			i++;
		}
	}
	else if ( !strnicmp("guildfromuid.", pszKey, 13) )
	{
		pszKey = pszKey + 13;
		if ( !pszKey[0] )
			return false;

		CGrayUID pGuildUid = static_cast<DWORD>(Exp_GetVal(pszKey));
		SKIP_SEPARATORS(pszKey);

		CItem * pMemberGuild = pGuildUid.ItemFind();
		if ( pMemberGuild )
		{
			CStoneMember * pGuild = GetMember( pMemberGuild );
			if ( pGuild )
			{
				pRef = pGuild; 
				return true;
			}
		}
	}

	return CItem::r_GetRef( pszKey, pRef );
}
Example #4
0
//---------------------------------------------------------------------------
void __fastcall TChangeSPWForm::cxButton1Click(TObject *Sender)
{
	String Oldpwstr = TEOldPassword->Text;
	String Newpwstr1 = TENewPassword1->Text;
	String Newpwstr2 = TENewPassword2->Text;

	if("" != Oldpwstr)
	{
		if(("" != Newpwstr1)&&("" != Newpwstr2))
		{
			if(Newpwstr1 == Newpwstr2)
			{
				ADOQuery1->Close();
				ADOQuery1->SQL->Clear();
				ADOQuery1->SQL->Add("Select * from XTSET");
				ADOQuery1->Open();
		  //		String tmpstr = ADOQuery1->FieldByName("CARDMM")->AsString;
				//ShowMessage(tmpstr);

				unsigned int cmplen = 12;
				if(!strnicmp(DECSuperPassword, Oldpwstr.t_str(), 12))//tmpstr == Oldpwstr)
				{
					if(Newpwstr1 == Newpwstr2)
					{
						if(12 == Newpwstr1.Length())
						{
							char CDPW[8];
							char Enchar[9];
							ZeroMemory(CDPW, 8);
							ZeroMemory(Enchar, 9);

							String tmppwstr = Newpwstr1;
							for(int i = 0; i < 6; i++)
							{
								int tmpint = StrToInt("0x"+tmppwstr.SubString(i*2+1, 2));
								IntToUChar(tmpint, &CDPW[i]);
							}
							EncrptyCardMMProc(0, CDPW, Enchar);

							memcpy(SuperPasword, CDPW, 6);
							memcpy(DECSuperPassword, tmppwstr.t_str(), 12);

							char Inbasechar[16];
							ZeroMemory(Inbasechar, 16);
							for(int t = 0; t<8; t++)
							{
								char tmp;
								tmp = Enchar[t]>>4;
								tmp = tmp&0x0f;
					 //			itoa(tmp, &Inbasechar[t*2], 16);
					 			if(tmp >= 10)
									Inbasechar[t*2] = tmp+55;
								if(tmp <10)
									Inbasechar[t*2] = tmp+48;
								tmp = Enchar[t]&0x0f;
					 //			itoa(tmp, &Inbasechar[t*2+1], 16);
					 			if(tmp >= 10)
									Inbasechar[t*2+1] = tmp+55;
								if(tmp <10)
									Inbasechar[t*2+1] = tmp+48;
							}

							String stortstr = Inbasechar;
							ADOQuery1->Edit();
							ADOQuery1->FieldByName("SuperPW")->AsAnsiString = Inbasechar;
							ADOQuery1->Post();

				   /*			String tmpCARDPassword = ADOQuery1->FieldByName("CARDMM")->AsAnsiString;
							for(int i = 0; i<6; i++)
							{
								int tmpint = StrToInt("0x"+tmpCARDPassword.SubString(i*2+1, 2));
								IntToUChar(tmpint, &CARDPassword[i]);
							}        */

							MessageBox(this->Handle, "³¬¼¶ÃÜÂëÐ޸ijɹ¦£¡", "³É¹¦", MB_OK|MB_ICONEXCLAMATION);
							this->Close();
						}
						else
							MessageBox(this->Handle, "³¬¼¶ÃÜÂë±ØÐëΪ12λ", "´íÎó", MB_OK|MB_ICONERROR);
					}
					else
						MessageBox(this->Handle, "ÇëÊäÈëÁ½´ÎÏàͬµÄÐÂÃÜÂ룡", "´íÎó", MB_OK|MB_ICONERROR);
				}
Example #5
0
void    scr_if( void )
{
    ifcb            *   cb;             // if stack ptr

    condcode        cct1;
    condcode        cct2;
    condcode        ccrelop;
    termcb          t1;                 // first argument
    termcb          t2;                 // second argument
    relop           relation;           // the relation between t1 and t2
    logop           logical;            // if more than 1 condition
    bool            ifcond;             // current condition
    bool            totalcondition;     // resultant condition
    bool            firstcondition;     // first comparison .if

    scan_err = false;

    firstcondition = true;              // first 2 terms to compare
    garginit();                         // find end of control word

    cb = input_cbs->if_cb;              // get .if control block
    cb->if_flags[cb->if_level].ifcwif = false;  // reset cwif switch

    for( ;; ) {                         // evaluate if conditions

        cct1    = gargterm( &t1 );      // get term 1
        ccrelop = gargrelop( &relation );   // get relation operator
        cct2    = gargterm( &t2 );      // get term 2

        if( (cct1 == no) || (cct2 == no) ) {
            scan_err = true;
            err_count++;
            g_err( err_if_term );
            g_info_inp_pos();
            show_include_stack();
            return;
        }
        if( ccrelop != pos ) {
            scan_err = true;
            err_count++;
            g_err( err_if_relop );
            g_info_inp_pos();
            show_include_stack();
            return;
        }

        // terms and operator ok now compare
        ifcond = ifcompare( &t1, relation, &t2 );
        mem_free( t1.term_string );     // don't need the strings anymore
        mem_free( t2.term_string );
        if( firstcondition ) {
            firstcondition = false;
            if( cb->if_level < MAX_IF_LEVEL ) {
                cb->if_level++;
                memset( &cb->if_flags[cb->if_level], '\0',
                        sizeof( cb->if_flags[cb->if_level] ) );
                cb->if_flags[cb->if_level].iflast = true;
                cb->if_flags[cb->if_level].ifcwte = false;  // no .th .el yet
                cb->if_flags[cb->if_level].iftrue = false;  // cond not yet true
                cb->if_flags[cb->if_level].iffalse = false; // cond not yet false
            } else {
                scan_err = true;
                g_err( err_if_nesting );
                g_info_inp_pos();
                show_include_stack();
                err_count++;
                return;
            }
            totalcondition = ifcond;
        } else {
            // resultant condition
            if( logical == AND ) {
                totalcondition &= ifcond;
            } else {
                totalcondition |= ifcond;
            }
        }

        if( totalcondition ) {          // set if true / false flags
            cb->if_flags[cb->if_level].iftrue = true;
            cb->if_flags[cb->if_level].iffalse = false;
        } else {
            cb->if_flags[cb->if_level].iffalse = true;
            cb->if_flags[cb->if_level].iftrue = false;
        }

        while( *scan_start == ' ' ) {
            scan_start++;
        }

/*
 * test logical condition if not line end
 *         .if a = b or c GT d
 *                   ^^
 */
        if( *scan_start ) {
            if( *scan_start == SCR_char ) {
                break;                  // .xx can't be logical operator
            }
            if( *(scan_start + 1) == ' ' ) {// single char + blank
                if( *scan_start  == '&' ) {
                    logical = AND;
                    scan_start += 2;
                    continue;           // do next conditions
                } else if( *scan_start == '|' ) {
                    logical = OR;
                    scan_start += 2;
                    continue;           // do next conditions
                }
            } else {
                if( !strnicmp( scan_start, "and ", 4 ) ) {
                    logical = AND;
                    scan_start += 4;
                    continue;           // do next conditions
                } else if( !strnicmp( scan_start, "or ", 3 ) ) {
                        logical = OR;
                        scan_start += 3;
                        continue;       // do next conditions
                }
            }

        }
        break;                          // no more operators / conditions
    }


    if( cb->if_level > 1 ) {            // nested if
        if( cb->if_flags[cb->if_level - 1].ifthen ) { // object of .th
            if( cb->if_flags[cb->if_level - 1].iffalse ) {// last .if false

                cb->if_flags[cb->if_level].iftrue = true;// process nothing
                cb->if_flags[cb->if_level].iffalse = true;
            }
        } else {
            if( cb->if_flags[cb->if_level - 1].ifelse // object of .el
                && cb->if_flags[cb->if_level - 1].iftrue ) {// last .if true

                cb->if_flags[cb->if_level].iftrue = true;// process nothing
                cb->if_flags[cb->if_level].iffalse = true;
            }
        }
    }
    if( input_cbs->fmflags & II_research && GlobalFlags.firstpass ) {
          show_ifcb( "if", cb );
#if 0
          out_msg( "\t.if is %s Level %d\n"
                 "\t.ifcb iftrue %d, iffalse %d\n",
                 totalcondition ? "true " : "false",
                 cb->if_level,
                 cb->if_flags[cb->if_level].iftrue,
                 cb->if_flags[cb->if_level].iffalse );
#endif
    }

    if( *scan_start ) {                 // rest of line is not empty
        split_input(  buff2, scan_start, false );   // split and process next
    }
    scan_restart = scan_stop;
    return;
}
Example #6
0
RTPStream *RP_NewStream(RTPClient *rtp, GF_SDPMedia *media, GF_SDPInfo *sdp, RTPStream *input_stream)
{
	GF_RTSPRange *range;
	RTPStream *tmp;
	GF_RTPMap *map;
	u32 i, ESID, ODID, ssrc, rtp_seq, rtp_time;
	Bool force_bcast = 0;
	Double Start, End;
	Float CurrentTime;
	u16 rvc_predef = 0;
	char *rvc_config_att = NULL;
	u32 s_port_first, s_port_last;
	GF_X_Attribute *att;
	Bool is_migration = 0;
	char *ctrl;
	GF_SDPConnection *conn;
	GF_RTSPTransport trans;
	u32 mid, prev_stream, base_stream;

	//extract all relevant info from the GF_SDPMedia
	Start = 0.0;
	End = -1.0;
	CurrentTime = 0.0f;
	ODID = 0;
	ESID = 0;
	ctrl = NULL;
	range = NULL;
	s_port_first = s_port_last = 0;
	ssrc = rtp_seq = rtp_time = 0;
	mid = prev_stream = base_stream = 0;
	i=0;
	while ((att = (GF_X_Attribute*)gf_list_enum(media->Attributes, &i))) {
		if (!stricmp(att->Name, "control")) ctrl = att->Value;
		else if (!stricmp(att->Name, "gpac-broadcast")) force_bcast = 1;
		else if (!stricmp(att->Name, "mpeg4-esid") && att->Value) ESID = atoi(att->Value);
		else if (!stricmp(att->Name, "mpeg4-odid") && att->Value) ODID = atoi(att->Value);
		else if (!stricmp(att->Name, "range") && !range) range = gf_rtsp_range_parse(att->Value);
		else if (!stricmp(att->Name, "x-stream-state") ) {
			sscanf(att->Value, "server-port=%u-%u;ssrc=%X;npt=%g;seq=%u;rtptime=%u",
			       &s_port_first, &s_port_last, &ssrc, &CurrentTime, &rtp_seq, &rtp_time);
			is_migration = 1;
		}
		else if (!stricmp(att->Name, "x-server-port") ) {
			sscanf(att->Value, "%u-%u", &s_port_first, &s_port_last);
		} else if (!stricmp(att->Name, "rvc-config-predef")) {
			rvc_predef = atoi(att->Value);
		} else if (!stricmp(att->Name, "rvc-config")) {
			rvc_config_att = att->Value;
		} else if (!stricmp(att->Name, "mid")) {
			sscanf(att->Value, "L%d", &mid);
		} else if (!stricmp(att->Name, "depend")) {
			char buf[3000];
			memset(buf, 0, 3000);
			sscanf(att->Value, "%*d lay L%d %*s %s", &base_stream, buf);
			if (!strlen(buf))
				sscanf(att->Value, "%*d lay %s", buf);
			sscanf(buf, "L%d", &prev_stream);
		}
	}

	if (range) {
		Start = range->start;
		End = range->end;
		gf_rtsp_range_del(range);
	}

	/*check connection*/
	conn = sdp->c_connection;
	if (conn && (!conn->host || !strcmp(conn->host, "0.0.0.0"))) conn = NULL;

	if (!conn) conn = (GF_SDPConnection*)gf_list_get(media->Connections, 0);
	if (conn && (!conn->host || !strcmp(conn->host, "0.0.0.0"))) conn = NULL;

	if (!conn) {
		/*RTSP RFC recommends an empty "c= " line but some server don't send it. Use session info (o=)*/
		if (!sdp->o_net_type || !sdp->o_add_type || strcmp(sdp->o_net_type, "IN")) return NULL;
		if (strcmp(sdp->o_add_type, "IP4") && strcmp(sdp->o_add_type, "IP6")) return NULL;
	} else {
		if (strcmp(conn->net_type, "IN")) return NULL;
		if (strcmp(conn->add_type, "IP4") && strcmp(conn->add_type, "IP6")) return NULL;
	}
	/*do we support transport*/
	if (strcmp(media->Profile, "RTP/AVP") && strcmp(media->Profile, "RTP/AVP/TCP")
	        && strcmp(media->Profile, "RTP/SAVP") && strcmp(media->Profile, "RTP/SAVP/TCP")
	   ) return NULL;

	/*check RTP map. For now we only support 1 RTPMap*/
	if (media->fmt_list || (gf_list_count(media->RTPMaps) > 1)) return NULL;

	/*check payload type*/
	map = (GF_RTPMap*)gf_list_get(media->RTPMaps, 0);

	/*this is an ESD-URL setup, we likely have namespace conflicts so overwrite given ES_ID
	by the app one (client side), but keep control (server side) if provided*/
	if (input_stream) {
		ESID = input_stream->ES_ID;
		if (!ctrl) ctrl = input_stream->control;
		tmp = input_stream;
	} else {
		tmp = RP_FindChannel(rtp, NULL, ESID, NULL, 0);
		if (tmp) return NULL;

		GF_SAFEALLOC(tmp, RTPStream);
		tmp->owner = rtp;
	}

	/*create an RTP channel*/
	tmp->rtp_ch = gf_rtp_new();
	if (ctrl) tmp->control = gf_strdup(ctrl);
	tmp->ES_ID = ESID;
	tmp->OD_ID = ODID;
	tmp->mid = mid;
	tmp->prev_stream = prev_stream;
	tmp->base_stream = base_stream;

	memset(&trans, 0, sizeof(GF_RTSPTransport));
	trans.Profile = media->Profile;
	trans.source = conn ? conn->host : sdp->o_address;
	trans.IsUnicast = gf_sk_is_multicast_address(trans.source) ? 0 : 1;
	if (!trans.IsUnicast) {
		trans.port_first = media->PortNumber;
		trans.port_last = media->PortNumber + 1;
		trans.TTL = conn ? conn->TTL : 0;
	} else {
		trans.client_port_first = media->PortNumber;
		trans.client_port_last = media->PortNumber + 1;
		trans.port_first = s_port_first ? s_port_first : trans.client_port_first;
		trans.port_last = s_port_last ? s_port_last : trans.client_port_last;
	}

	if (gf_rtp_setup_transport(tmp->rtp_ch, &trans, NULL) != GF_OK) {
		RP_DeleteStream(tmp);
		return NULL;
	}
	/*setup depacketizer*/
	tmp->depacketizer = gf_rtp_depacketizer_new(media, rtp_sl_packet_cbk, tmp);
	if (!tmp->depacketizer) {
		RP_DeleteStream(tmp);
		return NULL;
	}
	/*setup channel*/
	gf_rtp_setup_payload(tmp->rtp_ch, map);

//	tmp->status = NM_Disconnected;

	ctrl = (char *) gf_modules_get_option((GF_BaseInterface *) gf_service_get_interface(rtp->service), "Streaming", "DisableRTCP");
	if (!ctrl || stricmp(ctrl, "yes")) tmp->flags |= RTP_ENABLE_RTCP;

	/*setup NAT keep-alive*/
	ctrl = (char *) gf_modules_get_option((GF_BaseInterface *) gf_service_get_interface(rtp->service), "Streaming", "NATKeepAlive");
	if (ctrl) gf_rtp_enable_nat_keepalive(tmp->rtp_ch, atoi(ctrl));

	tmp->range_start = Start;
	tmp->range_end = End;
	if (End != -1.0) tmp->flags |= RTP_HAS_RANGE;

	if (force_bcast) tmp->flags |= RTP_FORCE_BROADCAST;

	if (is_migration) {
		tmp->current_start = (Double) CurrentTime;
		tmp->check_rtp_time = RTP_SET_TIME_RTP;
		gf_rtp_set_info_rtp(tmp->rtp_ch, rtp_seq, rtp_time, ssrc);
		tmp->status = RTP_SessionResume;
	}

	if (rvc_predef) {
		tmp->depacketizer->sl_map.rvc_predef = rvc_predef ;
	} else if (rvc_config_att) {
		char *rvc_data=NULL;
		u32 rvc_size;
		Bool is_gz = 0;
		if (!strncmp(rvc_config_att, "data:application/rvc-config+xml", 32) && strstr(rvc_config_att, "base64") ) {
			char *data = strchr(rvc_config_att, ',');
			if (data) {
				rvc_size = (u32) strlen(data) * 3 / 4 + 1;
				rvc_data = gf_malloc(sizeof(char) * rvc_size);
				rvc_size = gf_base64_decode(data, (u32) strlen(data), rvc_data, rvc_size);
				rvc_data[rvc_size] = 0;
			}
			if (!strncmp(rvc_config_att, "data:application/rvc-config+xml+gz", 35)) is_gz = 1;
		} else if (!strnicmp(rvc_config_att, "http://", 7) || !strnicmp(rvc_config_att, "https://", 8) ) {
			char *mime;
			if (gf_dm_get_file_memory(rvc_config_att, &rvc_data, &rvc_size, &mime) == GF_OK) {
				if (mime && strstr(mime, "+gz")) is_gz = 1;
				if (mime) gf_free(mime);
			}
		}
		if (rvc_data) {
			if (is_gz) {
#ifdef GPAC_DISABLE_ZLIB
				fprintf(stderr, "Error: no zlib support - RVC not supported in RTP\n");
				return NULL;
#endif
				gf_gz_decompress_payload(rvc_data, rvc_size, &tmp->depacketizer->sl_map.rvc_config, &tmp->depacketizer->sl_map.rvc_config_size);
				gf_free(rvc_data);
			} else {
				tmp->depacketizer->sl_map.rvc_config = rvc_data;
				tmp->depacketizer->sl_map.rvc_config_size = rvc_size;
			}
		}
	}

	return tmp;
}
Example #7
0
int EBuffer::FindStr(const char *Data, int Len, SearchReplaceOptions &opt) {
    int Options = opt.Options;
    int LLen, Start, End;
    int C, L;
    PELine X;
    char *P;

    if (Options & SEARCH_RE)
        return 0;
    if (Len <= 0)
        return 0;

    if (Options & SEARCH_NOPOS) {
        C = Match.Col;
        L = Match.Row;
    } else {
        C = CP.Col;
        L = VToR(CP.Row);
    }
    if (Match.Row != -1)
        Draw(Match.Row, Match.Row);
    Match.Row = -1;
    Match.Col = -1;
    X = RLine(L);
    C = CharOffset(X, C);

    if (Options & SEARCH_NEXT) {
        int CC = MatchCount ? 1 : 0;

        if (Options & SEARCH_BACK) {
            C -= CC;
            if (C < 0) {
                if (L == 0) return 0;
                L--;
                X = RLine(L);
                C = X->Count;
            }
        } else {
            if (Options & SEARCH_REPLACE &&
                    opt.lastInsertLen > 0) {
                C += CC * opt.lastInsertLen; // 0 or opt.lastInsertLen
            } else {
                C += CC;
            }

            if (C >= X->Count) {
                C = 0;
                L++;
                if (L == RCount) return 0;
            }
        }
    }
    MatchLen = 0;
    MatchCount = 0;

    if (Options & SEARCH_BLOCK) {
        if (Options & SEARCH_BACK) {
            if (BlockMode == bmStream) {
                if (L > BE.Row) {
                    L = BE.Row;
                    C = BE.Col;
                }
                if (L == BE.Row && C > BE.Col)
                    C = BE.Col;
            } else {
                if (L >= BE.Row && BE.Row > 0) {
                    L = BE.Row - 1;
                    C = RLine(L)->Count;
                }
                if (BlockMode == bmColumn)
                    if (L == BE.Row - 1 && C >= BE.Col)
                        C = BE.Col;
            }
        } else {
            if (L < BB.Row) {
                L = BB.Row;
                C = 0;
            }
            if (L == BB.Row && C < BB.Col)
                C = BB.Col;
        }
    }
    while (1) {
        if (Options & SEARCH_BLOCK) {
            if (BlockMode == bmStream) {
                if (L > BE.Row || L < BB.Row) break;
            } else
                if (L >= BE.Row || L < BB.Row) break;
        } else
            if (L >= RCount || L < 0) break;

        X = RLine(L);

        LLen = X->Count;
        P = X->Chars;
        Start = 0;
        End = LLen;

        if (Options & SEARCH_BLOCK) {
            if (BlockMode == bmColumn) {
                Start = CharOffset(X, BB.Col);
                End = CharOffset(X, BE.Col);
            } else if (BlockMode == bmStream) {
                if (L == BB.Row)
                    Start = CharOffset(X, BB.Col);
                if (L == BE.Row)
                    End = CharOffset(X, BE.Col);
            }
        }
        if (Options & SEARCH_BACK) {
            if (C >= End - Len)
                C = End - Len;
        } else {
            if (C < Start)
                C = Start;
        }

        while (((!(Options & SEARCH_BACK)) && (C <= End - Len)) || ((Options & SEARCH_BACK) && (C >= Start))) {
            if ((!(Options & SEARCH_WORDBEG)
                    || (C == 0)
                    || (WGETBIT(Flags.WordChars, P[C - 1]) == 0))
                    &&
                    (!(Options & SEARCH_WORDEND)
                     || (C + Len >= End)
                     || (WGETBIT(Flags.WordChars, P[C + Len]) == 0))
                    &&
                    ((!(Options & SEARCH_NCASE)
                      && (P[C] == Data[0])
                      && (memcmp(P + C, Data, Len) == 0))
                     ||
                     ((Options & SEARCH_NCASE)
                      && (toupper(P[C]) == toupper(Data[0]))
                      && (strnicmp(P + C, Data, Len) == 0))) /* && BOL | EOL */
               ) {
                Match.Col = ScreenPos(X, C);
                Match.Row = L;
                MatchCount = Len;
                MatchLen = ScreenPos(X, C + Len) - Match.Col;
                if (!(Options & SEARCH_NOPOS)) {
                    if (Options & SEARCH_CENTER)
                        CenterPosR(Match.Col, Match.Row);
                    else
                        SetPosR(Match.Col, Match.Row);
                }
                Draw(L, L);
                return 1;
            }
            if (Options & SEARCH_BACK) C--;
            else C++;
        }
        if (Options & SEARCH_BACK) {
            L--;
            if (L >= 0)
                C = RLine(L)->Count;
        } else {
            C = 0;
            L++;
        }
    }
    //SetPos(OC, OL);
    return 0;
}
Example #8
0
//GPAC player Event Handler. not yet implemented, just dummies here
Bool CGPAXPlugin::EventProc(GF_Event *evt)
{
	char msg[1024];
	if (!m_term) return 0;

    switch (evt->type) {
	case GF_EVENT_MESSAGE:
		if (evt->message.error) {
			sprintf(msg, "(GPAC) %s (%s)", evt->message.message, gf_error_to_string(evt->message.error));
		} else {
			sprintf(msg, "(GPAC) %s", evt->message.message);
		}
		SetStatusText(msg);
        break;
	case GF_EVENT_PROGRESS:
		if (evt->progress.done == evt->progress.total) {
			SetStatusText(NULL);
		} else {
			char *szTitle = "";
			if (evt->progress.progress_type==0) szTitle = "Buffer ";
			else if (evt->progress.progress_type==1) szTitle = "Download ";
			else if (evt->progress.progress_type==2) szTitle = "Import ";
			sprintf(msg, "(GPAC) %s: %02.2f", szTitle, (100.0*evt->progress.done) / evt->progress.total);
			SetStatusText(msg);
		}
		break;
    case GF_EVENT_CONNECT:
        m_bIsConnected = evt->connect.is_connected;
        break;
	/*IGNORE any scene size, just work with the size allocated in the parent doc*/
	case GF_EVENT_SCENE_SIZE:
        gf_term_set_size(m_term, m_width, m_height);
        break;
	/*window has been resized (full-screen plugin), resize*/
	case GF_EVENT_SIZE:
		m_width = evt->size.width;
		m_height = evt->size.height;
        gf_term_set_size(m_term, m_width, m_height);
        break;
	case GF_EVENT_DBLCLICK:
		gf_term_set_option(m_term, GF_OPT_FULLSCREEN, !gf_term_get_option(m_term, GF_OPT_FULLSCREEN));
		break;
	case GF_EVENT_KEYDOWN:
		if ((evt->key.flags  & GF_KEY_MOD_ALT)) {
	    } else {
			switch (evt->key.key_code) {
			case GF_KEY_HOME:
				gf_term_set_option(m_term, GF_OPT_NAVIGATION_TYPE, 1);
				break;
			case GF_KEY_ESCAPE:
				gf_term_set_option(m_term, GF_OPT_FULLSCREEN, !gf_term_get_option(m_term, GF_OPT_FULLSCREEN));
				break;
			}
		}
	    break;
	case GF_EVENT_NAVIGATE_INFO:
		strcpy(msg, evt->navigate.to_url);
		SetStatusText(msg);
		break;
	case GF_EVENT_NAVIGATE:
		if (gf_term_is_supported_url(m_term, evt->navigate.to_url, 1, 1)) {
			gf_term_navigate_to(m_term, evt->navigate.to_url);
			return 1;
		} 
#ifndef _WIN32_WCE
		else if (m_pBrowser) {
			u32 i;
			const char **sz_ptr;
			u16 w_szTar[1024], w_szURL[1024];
			VARIANT target, flags;
			flags.intVal = 0;
			target.bstrVal = L"_SELF";

			for (i=0; i<evt->navigate.param_count; i++) {
				if (!strcmp(evt->navigate.parameters[i], "_parent")) target.bstrVal = L"_PARENT";
				else if (!strcmp(evt->navigate.parameters[i], "_blank")) target.bstrVal = L"_BLANK";
				else if (!strcmp(evt->navigate.parameters[i], "_top")) target.bstrVal = L"_TOP";
				else if (!strcmp(evt->navigate.parameters[i], "_new")) flags.intVal |= navOpenInNewWindow;
				else if (!strnicmp(evt->navigate.parameters[i], "_target=", 8)) {
					sz_ptr = & evt->navigate.parameters[i]+8;
					gf_utf8_mbstowcs(w_szTar, 1024, (const char **)sz_ptr);
					target.bstrVal = (BSTR) w_szTar;
				}
			}
			sz_ptr = & evt->navigate.to_url;
			gf_utf8_mbstowcs(w_szURL, 1024, (const char **)sz_ptr);
			m_pBrowser->Navigate((BSTR) w_szURL, &flags, &target, NULL, NULL);;
			return 1;
		}
#endif
		break;
    }
    return 0;
}
Example #9
0
int CMD_DoorTarget(int argc, char *argv[])
{
 
   if (!ppSwitchMgr) return 0;
   if (!pSwitchMgr) return 0;
   PDOORTABLE pDoorTable = (PDOORTABLE)pSwitchMgr;
   DWORD Count;

   PSPAWNINFO pChar = (PSPAWNINFO)pLocalPlayer;
   CHAR szBuffer[MAX_STRING] = {0};
   CHAR szSearch[MAX_STRING] = {0};
   FLOAT cDistance = 100000.0f;
   BYTE ID = -1;
   ZeroMemory(&DoorEnviroTarget,sizeof(DoorEnviroTarget));
   pDoorTarget = NULL;

   if (argc > 1 && !stricmp(argv[1], "id")) {
      if (argc < 3) {
         WriteChatf("DoorTarget: id specified but no number provided.");
         return 0;
      }

      ID = atoi(argv[2]);
      for (Count=0; Count<pDoorTable->NumEntries; Count++) {
         if (pDoorTable->pDoor[Count]->ID == ID) {
            strcpy(DoorEnviroTarget.Name, pDoorTable->pDoor[Count]->Name);
            DoorEnviroTarget.Y = pDoorTable->pDoor[Count]->Y;
            DoorEnviroTarget.X = pDoorTable->pDoor[Count]->X;
            DoorEnviroTarget.Z = pDoorTable->pDoor[Count]->Z;
            DoorEnviroTarget.Heading = pDoorTable->pDoor[Count]->Heading;
			DoorEnviroTarget.Type = SPAWN_NPC;
			DoorEnviroTarget.HPCurrent = 1;
			DoorEnviroTarget.HPMax = 1;
            pDoorTarget = pDoorTable->pDoor[Count];
            break;
         }
      }
   } else {
		if (argc > 1)
			strcpy(szSearch, argv[1]);
		for (Count=0; Count<pDoorTable->NumEntries; Count++) {
			if (((szSearch[0]==0) ||
				(!strnicmp(pDoorTable->pDoor[Count]->Name,szSearch,strlen(szSearch)))) &&
				((gZFilter >=10000.0f) ||
				((pDoorTable->pDoor[Count]->Z <= pChar->Z + gZFilter) &&
				(pDoorTable->pDoor[Count]->Z >= pChar->Z - gZFilter)))) {
				SPAWNINFO tSpawn;
				ZeroMemory(&tSpawn,sizeof(tSpawn));
				strcpy(tSpawn.Name,pDoorTable->pDoor[Count]->Name);
				tSpawn.Y=pDoorTable->pDoor[Count]->Y;
				tSpawn.X=pDoorTable->pDoor[Count]->X;
				tSpawn.Z=pDoorTable->pDoor[Count]->Z;
				tSpawn.Type = SPAWN_NPC;
				tSpawn.HPCurrent = 1;
				tSpawn.HPMax = 1;
				tSpawn.Heading=pDoorTable->pDoor[Count]->Heading;
				FLOAT Distance = DistanceToSpawn(pChar,&tSpawn);
				if (Distance<cDistance) {
				   CopyMemory(&DoorEnviroTarget,&tSpawn,sizeof(DoorEnviroTarget));
				   pDoorTarget = pDoorTable->pDoor[Count];
				   cDistance=Distance;
				}
			}
		}
	}


   if (DoorEnviroTarget.Name[0]!=0) {
      sprintf(szBuffer,"Door %d '%s' targeted.", pDoorTarget->ID, DoorEnviroTarget.Name);
      WriteChatColor(szBuffer,USERCOLOR_DEFAULT);
   } else {
      WriteChatf("Couldn't find door to target.");
   }
   return 0;
} 
Example #10
0
void
execcmd( 
	char *string,
	void (*func)( void *closure, int status, timing_info* ),
	void *closure,
	LIST *shell )
{
    int pid;
    int slot;
    int raw_cmd = 0 ;
    char *argv_static[ MAXARGC + 1 ];	/* +1 for NULL */
    char **argv = argv_static;
    char *p;

    /* Check to see if we need to hack around the line-length limitation. */
    /* Look for a JAMSHELL setting of "%", indicating that the command
     * should be invoked directly */
    if ( shell && !strcmp(shell->string,"%") && !list_next(shell) )
    {
        raw_cmd = 1;
        shell = 0;
    }

    if ( !is_win95_defined )
        set_is_win95();
          
    /* Find a slot in the running commands table for this one. */
    if ( is_win95 )
    {
        /* only synchronous spans are supported on Windows 95/98 */
        slot = 0;
    }
    else
    {
        for( slot = 0; slot < MAXJOBS; slot++ )
            if( !cmdtab[ slot ].pid )
                break;
    }
    if( slot == MAXJOBS )
    {
        printf( "no slots for child!\n" );
        exit( EXITBAD );
    }
  
    if( !cmdtab[ slot ].tempfile )
    {
        const char *tempdir = path_tmpdir();
        DWORD procID = GetCurrentProcessId();
  
        /* SVA - allocate 64 other just to be safe */
        cmdtab[ slot ].tempfile = malloc( strlen( tempdir ) + 64 );
        if ( DEBUG_PROFILE )
            profile_memory( strlen( tempdir ) + 64 );
  
        sprintf( cmdtab[ slot ].tempfile, "%s\\jam%d-%02d.bat", 
                 tempdir, procID, slot );		
    }

    /* Trim leading, ending white space */

    while( isspace( *string ) )
        ++string;

    /* Write to .BAT file unless the line would be too long and it
     * meets the other spawnability criteria.
     */
    if( raw_cmd && can_spawn( string ) >= MAXLINE )
    {
        if( DEBUG_EXECCMD )
            printf("Executing raw command directly\n");        
    }
    else
    {
        FILE *f = 0;
        int tries = 0;
        raw_cmd = 0;
        
        /* Write command to bat file. For some reason this open can
           fails intermitently. But doing some retries works. Most likely
           this is due to a previously existing file of the same name that
           happens to be opened by an active virus scanner. Pointed out,
           and fix by Bronek Kozicki. */
        for (; !f && tries < 4; ++tries)
        {
            f = fopen( cmdtab[ slot ].tempfile, "w" );
            if ( !f && tries < 4 ) Sleep( 250 );
        }
        if (!f)
        {
            printf( "failed to write command file!\n" );
            exit( EXITBAD );
        }
        fputs( string, f );
        fclose( f );

        string = cmdtab[ slot ].tempfile;
        
        if( DEBUG_EXECCMD )
        {
            if (shell)
                printf("using user-specified shell: %s", shell->string);
            else
                printf("Executing through .bat file\n");
        }
    }

    /* Forumulate argv */
    /* If shell was defined, be prepared for % and ! subs. */
    /* Otherwise, use stock /bin/sh (on unix) or cmd.exe (on NT). */

    if( shell )
    {
        int i;
        char jobno[4];
        int gotpercent = 0;

        sprintf( jobno, "%d", slot + 1 );

        for( i = 0; shell && i < MAXARGC; i++, shell = list_next( shell ) )
        {
            switch( shell->string[0] )
            {
            case '%':	argv[i] = string; gotpercent++; break;
            case '!':	argv[i] = jobno; break;
            default:	argv[i] = shell->string;
            }
            if( DEBUG_EXECCMD )
                printf( "argv[%d] = '%s'\n", i, argv[i] );
        }

        if( !gotpercent )
            argv[i++] = string;

        argv[i] = 0;
    }
    else if (raw_cmd)
    {
        argv = string_to_args(string);
    }
    else
    {
        /* don't worry, this is ignored on Win95/98, see later.. */
        argv[0] = "cmd.exe";
        argv[1] = "/Q/C";		/* anything more is non-portable */
        argv[2] = string;
        argv[3] = 0;
    }

    /* Catch interrupts whenever commands are running. */

    if( !cmdsrunning++ )
        istat = signal( SIGINT, onintr );

    /* Start the command */

    /* on Win95, we only do a synchronous call */
    if ( is_win95 )
    {
        static const char* hard_coded[] =
            {
                "del", "erase", "copy", "mkdir", "rmdir", "cls", "dir",
                "ren", "rename", "move", 0
            };
          
        const char**  keyword;
        int           len, spawn = 1;
        int           result;
        timing_info time = {0,0};
          
        for ( keyword = hard_coded; keyword[0]; keyword++ )
        {
            len = strlen( keyword[0] );
            if ( strnicmp( string, keyword[0], len ) == 0 &&
                 !isalnum(string[len]) )
            {
                /* this is one of the hard coded symbols, use 'system' to run */
                /* them.. except for "del"/"erase"                            */
                if ( keyword - hard_coded < 2 )
                    result = process_del( string );
                else
                    result = system( string );

                spawn  = 0;
                break;
            }
        }
          
        if (spawn)
        {
            char**  args;
            
            /* convert the string into an array of arguments */
            /* we need to take care of double quotes !!      */
            args = string_to_args( string );
            if ( args )
            {
#if 0
                char** arg;
                fprintf( stderr, "%s: ", args[0] );
                arg = args+1;
                while ( arg[0] )
                {
                    fprintf( stderr, " {%s}", arg[0] );
                    arg++;
                }
                fprintf( stderr, "\n" );
#endif              
                result = spawnvp( P_WAIT, args[0], args );
                record_times(result, &time);
                free_argv( args );
            }
            else
                result = 1;
        }
        func( closure, result ? EXEC_CMD_FAIL : EXEC_CMD_OK, &time );
        return;
    }

    if( DEBUG_EXECCMD )
    {
        char **argp = argv;

        printf("Executing command");
        while(*argp != 0)
        {
            printf(" [%s]", *argp);
            argp++;
        }
        printf("\n");
    }

    /* the rest is for Windows NT only */
    /* spawn doesn't like quotes around the command name */
    if ( argv[0][0] == '"')
    {
        int l = strlen(argv[0]);

        /* Clobber any closing quote, shortening the string by one
         * element */
        if (argv[0][l-1] == '"')
            argv[0][l-1] = '\0';
        
        /* Move everything *including* the original terminating zero
         * back one place in memory, covering up the opening quote */
        memmove(argv[0],argv[0]+1,l);
    }
    if( ( pid = spawnvp( P_NOWAIT, argv[0], argv ) ) == -1 )
    {
        perror( "spawn" );
        exit( EXITBAD );
    }
    /* Save the operation for execwait() to find. */

    cmdtab[ slot ].pid = pid;
    cmdtab[ slot ].func = func;
    cmdtab[ slot ].closure = closure;

    /* Wait until we're under the limit of concurrent commands. */
    /* Don't trust globs.jobs alone.                            */

    while( cmdsrunning >= MAXJOBS || cmdsrunning >= globs.jobs )
        if( !execwait() )
            break;
    
    if (argv != argv_static)
    {
        free_argv(argv);
    }
}
Example #11
0
int String::CompareLeftNoCase(const char *cstr, int count) const
{
    int cstr_len = cstr ? strlen(cstr) : 0;
    count = count >= 0 ? count : cstr_len;
    return strnicmp(GetCStr(), cstr ? cstr : "", count);
}
Example #12
0
bool CPointBase::r_WriteVal( LPCTSTR pszKey, CGString & sVal ) const
{
	ADDTOCALLSTACK("CPointBase::r_WriteVal");
	if ( !strnicmp( pszKey, "STATICS", 7 ) )
	{
		pszKey	+= 7;
		const CGrayMapBlock * pBlock = g_World.GetMapBlock( *(this) );
		if ( !pBlock ) return false;

		if ( *pszKey == '\0' )
		{
			int iStaticQty = 0;
			for ( size_t i = 0; i < pBlock->m_Statics.GetStaticQty(); i++ )
			{
				const CUOStaticItemRec * pStatic = pBlock->m_Statics.GetStatic( i );
				CPointMap ptTest( pStatic->m_x+pBlock->m_x, pStatic->m_y+pBlock->m_y, pStatic->m_z, this->m_map );
				if ( this->GetDist( ptTest ) > 0 )
					continue;
				iStaticQty++;
			}

			sVal.FormatVal( iStaticQty );
			return true;
		}

		SKIP_SEPARATORS( pszKey );

		const CUOStaticItemRec * pStatic = NULL;
		int iStatic = 0;
		int type = 0;
		
		if ( !strnicmp( pszKey, "FINDID", 6 ) )
		{
			pszKey += 6;
			SKIP_SEPARATORS( pszKey );
			iStatic = Exp_GetVal( pszKey );
			type = RES_GET_TYPE( iStatic );
			if ( type == 0 )
				type = RES_ITEMDEF;
			SKIP_SEPARATORS( pszKey );
		}
		else
		{
			iStatic = Exp_GetVal( pszKey );
			type = RES_GET_TYPE( iStatic );
		}
		
		if ( type == RES_ITEMDEF )
		{
			const CItemBase * pItemDef = CItemBase::FindItemBase(static_cast<ITEMID_TYPE>(RES_GET_INDEX(iStatic)));
			if ( !pItemDef )
			{
				sVal.FormatVal( 0 );
				return false;
			}
			for ( size_t i = 0; i < pBlock->m_Statics.GetStaticQty(); pStatic = NULL, i++ )
			{
				pStatic = pBlock->m_Statics.GetStatic( i );
				CPointMap ptTest( pStatic->m_x+pBlock->m_x, pStatic->m_y+pBlock->m_y, pStatic->m_z, this->m_map);
				if ( this->GetDist( ptTest ) > 0 )
					continue;
				if ( pStatic->GetDispID() == pItemDef->GetDispID() )
					break;
			}
		}
		else
		{
			for ( size_t i = 0; i < pBlock->m_Statics.GetStaticQty(); pStatic = NULL, i++ )
			{
				pStatic = pBlock->m_Statics.GetStatic( i );
				CPointMap ptTest( pStatic->m_x+pBlock->m_x, pStatic->m_y+pBlock->m_y, pStatic->m_z, this->m_map);
				if ( this->GetDist( ptTest ) > 0 )
					continue;
				if ( iStatic == 0 )
					break;
				iStatic--;
			}
		}

		if ( !pStatic )
		{
			sVal.FormatHex(0);
			return true;
		}

		SKIP_SEPARATORS( pszKey );
		if ( !*pszKey )
			pszKey	= "ID";

		ITEMID_TYPE idTile = pStatic->GetDispID();

		if ( !strnicmp( pszKey, "COLOR", 5 ) )
		{
			sVal.FormatHex( pStatic->m_wHue );
			return true;
		}
		else if ( !strnicmp( pszKey, "ID", 2 ) )
		{
			sVal.FormatHex( idTile );
			return true;
		}
		else if ( !strnicmp( pszKey, "Z", 1 ) )
		{
			sVal.FormatVal( pStatic->m_z );
			return true;
		}

		// Check the script def for the item.
		CItemBase * pItemDef = CItemBase::FindItemBase( idTile );
		if ( pItemDef == NULL )
		{
			DEBUG_ERR(("Must have ITEMDEF section for item ID 0%x\n", idTile ));
			return false;
		}

		return pItemDef->r_WriteVal( pszKey, sVal, &g_Serv );
	}
	else if ( !strnicmp( pszKey, "COMPONENTS", 10) )
	{
		pszKey += 10;
		
		CRegionLinks rlinks;
		const CRegionBase* pRegion = NULL;
		CItem* pItem = NULL;
		const CGrayMulti* pMulti = NULL;
		const CUOMultiItemRec2* pMultiItem = NULL;
		size_t iMultiQty = GetRegions(REGION_TYPE_MULTI, rlinks);

		if ( *pszKey == '\0' )
		{
			int iComponentQty = 0;
			for (size_t i = 0; i < iMultiQty; i++)
			{
				pRegion = rlinks.GetAt(i);
				if (pRegion == NULL)
					continue;

				pItem = pRegion->GetResourceID().ItemFind();
				if (pItem == NULL)
					continue;

				const CPointMap ptMulti = pItem->GetTopPoint();
				pMulti = g_Cfg.GetMultiItemDefs(pItem);
				if (pMulti == NULL)
					continue;

				size_t iQty = pMulti->GetItemCount();
				for (size_t ii = 0; ii < iQty; ii++)
				{
					pMultiItem = pMulti->GetItem(ii);
					if (pMultiItem == NULL)
						break;
					if (pMultiItem->m_visible == 0)
						continue;

					CPointMap ptTest(static_cast<WORD>(ptMulti.m_x + pMultiItem->m_dx), static_cast<WORD>(ptMulti.m_y + pMultiItem->m_dy), static_cast<signed char>(ptMulti.m_z + pMultiItem->m_dz), this->m_map);
					if (GetDist(ptTest) > 0)
						continue;

					iComponentQty++;
				}
			}

			sVal.FormatVal( iComponentQty );
			return true;
		}

		SKIP_SEPARATORS( pszKey );

		int iComponent = 0;
		int type = 0;
		
		if ( strnicmp( pszKey, "FINDID", 6 ) == 0 )
		{
			pszKey += 6;
			SKIP_SEPARATORS( pszKey );
			iComponent = Exp_GetVal( pszKey );
			type = RES_GET_TYPE( iComponent );
			if ( type == 0 )
				type = RES_ITEMDEF;
			SKIP_SEPARATORS( pszKey );
		}
		else
		{
			iComponent = Exp_GetVal( pszKey );
			type = RES_GET_TYPE( iComponent );
		}
		
		if ( type == RES_ITEMDEF )
		{
			const CItemBase * pItemDef = CItemBase::FindItemBase(static_cast<ITEMID_TYPE>(RES_GET_INDEX(iComponent)));
			if ( pItemDef == NULL )
			{
				sVal.FormatVal( 0 );
				return false;
			}
			
			for (size_t i = 0; i < iMultiQty; i++)
			{
				pRegion = rlinks.GetAt(i);
				if (pRegion == NULL)
					continue;

				pItem = pRegion->GetResourceID().ItemFind();
				if (pItem == NULL)
					continue;

				const CPointMap ptMulti = pItem->GetTopPoint();
				pMulti = g_Cfg.GetMultiItemDefs(pItem);
				if (pMulti == NULL)
					continue;

				size_t iQty = pMulti->GetItemCount();
				for (size_t ii = 0; ii < iQty; pMultiItem = NULL, ii++)
				{
					pMultiItem = pMulti->GetItem(ii);
					if (pMultiItem == NULL)
						break;
					if (pMultiItem->m_visible == 0)
						continue;
					CPointMap ptTest(static_cast<WORD>(ptMulti.m_x + pMultiItem->m_dx), static_cast<WORD>(ptMulti.m_y + pMultiItem->m_dy), static_cast<signed char>(ptMulti.m_z + pMultiItem->m_dz), this->m_map);
					if (GetDist(ptTest) > 0)
						continue;

					const CItemBase* pMultiItemDef = CItemBase::FindItemBase(pMultiItem->GetDispID());
					if (pMultiItemDef != NULL && pMultiItemDef->GetDispID() == pItemDef->GetDispID())
						break;
				}

				if (pMultiItem != NULL)
					break;
			}
		}
		else
		{
			for (size_t i = 0; i < iMultiQty; i++)
			{
				pRegion = rlinks.GetAt(i);
				if (pRegion == NULL)
					continue;

				pItem = pRegion->GetResourceID().ItemFind();
				if (pItem == NULL)
					continue;

				const CPointMap ptMulti = pItem->GetTopPoint();
				pMulti = g_Cfg.GetMultiItemDefs(pItem);
				if (pMulti == NULL)
					continue;

				size_t iQty = pMulti->GetItemCount();
				for (size_t ii = 0; ii < iQty; pMultiItem = NULL, ii++)
				{
					pMultiItem = pMulti->GetItem(ii);
					if (pMultiItem == NULL)
						break;
					if (pMultiItem->m_visible == 0)
						continue;
					CPointMap ptTest(static_cast<WORD>(ptMulti.m_x + pMultiItem->m_dx), static_cast<WORD>(ptMulti.m_y + pMultiItem->m_dy), static_cast<signed char>(ptMulti.m_z + pMultiItem->m_dz), this->m_map);
					if (GetDist(ptTest) > 0)
						continue;

					if (iComponent == 0)
						break;

					iComponent--;
				}

				if (pMultiItem != NULL)
					break;
			}
		}

		if ( pMultiItem == NULL )
		{
			sVal.FormatHex(0);
			return true;
		}

		SKIP_SEPARATORS( pszKey );
		if ( !*pszKey )
			pszKey	= "ID";

		ITEMID_TYPE idTile = pMultiItem->GetDispID();

		if ( strnicmp( pszKey, "ID", 2 ) == 0 )
		{
			sVal.FormatHex( idTile );
			return true;
		}
		else if ( strnicmp( pszKey, "MULTI", 5 ) == 0 )
		{
			pszKey += 5;
			if (*pszKey != '\0')
			{
				SKIP_SEPARATORS(pszKey);
				return pItem->r_WriteVal( pszKey, sVal, &g_Serv );
			}

			sVal.FormatHex( pItem->GetUID() );
			return true;
		}
		else if ( strnicmp( pszKey, "Z", 1 ) == 0 )
		{
			sVal.FormatVal( pItem->GetTopZ() + pMultiItem->m_dz );
			return true;
		}

		// Check the script def for the item.
		CItemBase * pItemDef = CItemBase::FindItemBase( idTile );
		if ( pItemDef == NULL )
		{
			DEBUG_ERR(("Must have ITEMDEF section for item ID 0%x\n", idTile ));
			return false;
		}

		return pItemDef->r_WriteVal( pszKey, sVal, &g_Serv );
	}
	
	int index = FindTableHeadSorted( pszKey, sm_szLoadKeys, COUNTOF(sm_szLoadKeys)-1 );
	if ( index < 0 )
		return false;

	switch ( index )
	{
		case PT_M:
		case PT_MAP:
			sVal.FormatVal(m_map);
			break;
		case PT_X:
			sVal.FormatVal(m_x);
			break;
		case PT_Y:
			sVal.FormatVal(m_y);
			break;
		case PT_Z:
			sVal.FormatVal(m_z);
			break;
		case PT_ISNEARTYPE:
		{
			pszKey += 10;
			SKIP_SEPARATORS( pszKey );
			SKIP_ARGSEP( pszKey );

			int iType = g_Cfg.ResourceGetIndexType( RES_TYPEDEF, pszKey );
			int iDistance = 0;
			bool bCheckMulti = false;

			SKIP_IDENTIFIERSTRING( pszKey );
			SKIP_SEPARATORS( pszKey );
			SKIP_ARGSEP( pszKey );

			if ( *pszKey ) iDistance = Exp_GetVal(pszKey);
			if ( *pszKey ) bCheckMulti = Exp_GetVal(pszKey) != 0;
			sVal.FormatVal( g_World.IsItemTypeNear(*this, static_cast<IT_TYPE>(iType), iDistance, bCheckMulti));
			break;
		}
		case PT_REGION:
		{
			// Check that the syntax is correct.
			if ( pszKey[6] && pszKey[6] != '.' )
				return false;

			CRegionWorld * pRegionTemp = dynamic_cast <CRegionWorld*>(this->GetRegion(REGION_TYPE_AREA | REGION_TYPE_MULTI));

			if ( !pszKey[6] )
			{
				// We're just checking if the reference is valid.
				sVal.FormatVal( pRegionTemp? 1:0 );
				return true;
			}
			
			// We're trying to retrieve a property from the region.
			pszKey += 7;
			if ( pRegionTemp )
				return pRegionTemp->r_WriteVal( pszKey, sVal, &g_Serv );

			return false;
		}
		case PT_ROOM:
		{
			if ( pszKey[4] && pszKey[4] != '.' )
				return false;

			CRegionBase * pRegionTemp = this->GetRegion( REGION_TYPE_ROOM );

			if ( !pszKey[4] )
			{
				sVal.FormatVal( pRegionTemp? 1:0 );
				return true;
			}

			pszKey += 5;
			if ( pRegionTemp )
				return pRegionTemp->r_WriteVal( pszKey, sVal, &g_Serv );

			return false;
		}
		case PT_SECTOR:
		{
			if ( pszKey[6] == '.' )
			{
				pszKey += 7;
				CSector * pSectorTemp = this->GetSector();
				if (pSectorTemp)
					return pSectorTemp->r_WriteVal(pszKey, sVal, &g_Serv);
			}
			return false;
		}
		default:
		{
			const CUOMapMeter * pMeter = g_World.GetMapMeter(*this);
			if ( pMeter )
			{
				switch( index )
				{
					case PT_TYPE:
						{
							CItemTypeDef * pTypeDef = g_World.GetTerrainItemTypeDef( pMeter->m_wTerrainIndex );
							if ( pTypeDef != NULL )
								sVal = pTypeDef->GetResourceName();
							else
								sVal = "";
						} return true;	
					case PT_TERRAIN:
						{
							pszKey += strlen(sm_szLoadKeys[index]);
							if ( *pszKey == '.' )	// do we have an argument?
							{
								SKIP_SEPARATORS( pszKey );
								if ( !strnicmp( pszKey, "Z", 1 ))
								{
									sVal.FormatVal( pMeter->m_z );
									return( true );
								}
								
								return( false );
							}
							else
							{
								sVal.FormatHex( pMeter->m_wTerrainIndex );
							}
						} return true;
				}
			}
			return false;
		}
	}

	return true;
}
Example #13
0
static void GLimp_InitExtensions( void )
{
	if ( !r_allowExtensions->integer )
	{
		Com_Printf ("*** IGNORING OPENGL EXTENSIONS ***\n" );
		g_bDynamicGlowSupported = false;
		Cvar_Set( "r_DynamicGlow","0" );
		return;
	}

	Com_Printf ("Initializing OpenGL extensions\n" );

	// Select our tc scheme
	GLW_InitTextureCompression();

	// GL_EXT_texture_env_add
	glConfig.textureEnvAddAvailable = qfalse;
	if ( strstr( glConfig.extensions_string, "EXT_texture_env_add" ) )
	{
		if ( r_ext_texture_env_add->integer )
		{
			glConfig.textureEnvAddAvailable = qtrue;
			Com_Printf ("...using GL_EXT_texture_env_add\n" );
		}
		else
		{
			glConfig.textureEnvAddAvailable = qfalse;
			Com_Printf ("...ignoring GL_EXT_texture_env_add\n" );
		}
	}
	else
	{
		Com_Printf ("...GL_EXT_texture_env_add not found\n" );
	}

	// GL_EXT_texture_filter_anisotropic
	glConfig.maxTextureFilterAnisotropy = 0;
	if ( strstr( glConfig.extensions_string, "EXT_texture_filter_anisotropic" ) )
	{
#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF	//can't include glext.h here ... sigh
		qglGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &glConfig.maxTextureFilterAnisotropy );
		Com_Printf ("...GL_EXT_texture_filter_anisotropic available\n" );

		if ( r_ext_texture_filter_anisotropic->integer>1 )
		{
			Com_Printf ("...using GL_EXT_texture_filter_anisotropic\n" );
		}
		else
		{
			Com_Printf ("...ignoring GL_EXT_texture_filter_anisotropic\n" );
		}
		Cvar_Set( "r_ext_texture_filter_anisotropic_avail", va("%f",glConfig.maxTextureFilterAnisotropy) );
		if ( r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy )
		{
			Cvar_Set( "r_ext_texture_filter_anisotropic", va("%f",glConfig.maxTextureFilterAnisotropy) );
		}
	}
	else
	{
		Com_Printf ("...GL_EXT_texture_filter_anisotropic not found\n" );
		Cvar_Set( "r_ext_texture_filter_anisotropic_avail", "0" );
	}

	// GL_EXT_clamp_to_edge
	glConfig.clampToEdgeAvailable = qfalse;
	if ( strstr( glConfig.extensions_string, "GL_EXT_texture_edge_clamp" ) )
	{
		glConfig.clampToEdgeAvailable = qtrue;
		Com_Printf ("...Using GL_EXT_texture_edge_clamp\n" );
	}

	// GL_ARB_multitexture
	qglMultiTexCoord2fARB = NULL;
	qglActiveTextureARB = NULL;
	qglClientActiveTextureARB = NULL;
	if ( strstr( glConfig.extensions_string, "GL_ARB_multitexture" )  )
	{
		if ( r_ext_multitexture->integer )
		{
			qglMultiTexCoord2fARB = ( PFNGLMULTITEXCOORD2FARBPROC ) SDL_GL_GetProcAddress( "glMultiTexCoord2fARB" );
			qglActiveTextureARB = ( PFNGLACTIVETEXTUREARBPROC ) SDL_GL_GetProcAddress( "glActiveTextureARB" );
			qglClientActiveTextureARB = ( PFNGLCLIENTACTIVETEXTUREARBPROC ) SDL_GL_GetProcAddress( "glClientActiveTextureARB" );

			if ( qglActiveTextureARB )
			{
				qglGetIntegerv( GL_MAX_ACTIVE_TEXTURES_ARB, &glConfig.maxActiveTextures );

				if ( glConfig.maxActiveTextures > 1 )
				{
					Com_Printf ("...using GL_ARB_multitexture\n" );
				}
				else
				{
					qglMultiTexCoord2fARB = NULL;
					qglActiveTextureARB = NULL;
					qglClientActiveTextureARB = NULL;
					Com_Printf ("...not using GL_ARB_multitexture, < 2 texture units\n" );
				}
			}
		}
		else
		{
			Com_Printf ("...ignoring GL_ARB_multitexture\n" );
		}
	}
	else
	{
		Com_Printf ("...GL_ARB_multitexture not found\n" );
	}

	// GL_EXT_compiled_vertex_array
	qglLockArraysEXT = NULL;
	qglUnlockArraysEXT = NULL;
	if ( strstr( glConfig.extensions_string, "GL_EXT_compiled_vertex_array" ) )
	{
		if ( r_ext_compiled_vertex_array->integer )
		{
			Com_Printf ("...using GL_EXT_compiled_vertex_array\n" );
			qglLockArraysEXT = ( void ( APIENTRY * )( int, int ) ) SDL_GL_GetProcAddress( "glLockArraysEXT" );
			qglUnlockArraysEXT = ( void ( APIENTRY * )( void ) ) SDL_GL_GetProcAddress( "glUnlockArraysEXT" );
			if (!qglLockArraysEXT || !qglUnlockArraysEXT) {
				Com_Error (ERR_FATAL, "bad getprocaddress");
			}
		}
		else
		{
			Com_Printf ("...ignoring GL_EXT_compiled_vertex_array\n" );
		}
	}
	else
	{
		Com_Printf ("...GL_EXT_compiled_vertex_array not found\n" );
	}

	qglPointParameterfEXT = NULL;
	qglPointParameterfvEXT = NULL;

	//3d textures -rww
	qglTexImage3DEXT = NULL;
	qglTexSubImage3DEXT = NULL;

	if ( strstr( glConfig.extensions_string, "GL_EXT_point_parameters" ) )
	{
		if ( r_ext_compiled_vertex_array->integer || 1)
		{
			Com_Printf ("...using GL_EXT_point_parameters\n" );
			qglPointParameterfEXT = ( void ( APIENTRY * )( GLenum, GLfloat) ) SDL_GL_GetProcAddress( "glPointParameterfEXT" );
			qglPointParameterfvEXT = ( void ( APIENTRY * )( GLenum, GLfloat *) ) SDL_GL_GetProcAddress( "glPointParameterfvEXT" );

			//3d textures -rww
			qglTexImage3DEXT = (void ( APIENTRY * ) (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *) ) SDL_GL_GetProcAddress( "glTexImage3DEXT" );
			qglTexSubImage3DEXT = (void ( APIENTRY * ) (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *) ) SDL_GL_GetProcAddress( "glTexSubImage3DEXT" );

			if (!qglPointParameterfEXT || !qglPointParameterfvEXT)
			{
				Com_Error (ERR_FATAL, "bad getprocaddress");
			}
		}
		else
		{
			Com_Printf ("...ignoring GL_EXT_point_parameters\n" );
		}
	}
	else
	{
		Com_Printf ("...GL_EXT_point_parameters not found\n" );
	}
	
	qglPointParameteriNV = NULL;
	qglPointParameterivNV = NULL;
	if ( strstr( glConfig.extensions_string, "GL_NV_point_sprite" ) )
	{
		if ( r_ext_nv_point_sprite->integer )
		{
			qglPointParameteriNV = ( void ( APIENTRY * )( GLenum, GLint) ) SDL_GL_GetProcAddress( "glPointParameteriNV" );
			qglPointParameterivNV = ( void ( APIENTRY * )( GLenum, const GLint *) ) SDL_GL_GetProcAddress( "glPointParameterivNV" );
			if (!qglPointParameteriNV || !qglPointParameterivNV)
			{
				Com_Error( ERR_FATAL, "Bad GetProcAddress for GL_NV_point_sprite");
			}
			Com_Printf( "...using GL_NV_point_sprite\n" );
		}
		else
		{
			Com_Printf( "...ignoring GL_NV_point_sprite\n" );
		}
	}
	else
	{
		Com_Printf( "...GL_NV_point_sprite not found\n" );
	}


	bool bNVRegisterCombiners = false;
	// Register Combiners.
	if ( strstr( glConfig.extensions_string, "GL_NV_register_combiners" ) )
	{
		// NOTE: This extension requires multitexture support (over 2 units).
		if ( glConfig.maxActiveTextures >= 2 )
		{
			bNVRegisterCombiners = true;
			// Register Combiners function pointer address load.	- AReis
			// NOTE: VV guys will _definetly_ not be able to use regcoms. Pixel Shaders are just as good though :-)
			// NOTE: Also, this is an nVidia specific extension (of course), so fragment shaders would serve the same purpose
			// if we needed some kind of fragment/pixel manipulation support.
			qglCombinerParameterfvNV = SDL_GL_GetProcAddress( "glCombinerParameterfvNV" );
			qglCombinerParameterivNV = SDL_GL_GetProcAddress( "glCombinerParameterivNV" );
			qglCombinerParameterfNV = SDL_GL_GetProcAddress( "glCombinerParameterfNV" );
			qglCombinerParameteriNV = SDL_GL_GetProcAddress( "glCombinerParameteriNV" );
			qglCombinerInputNV = SDL_GL_GetProcAddress( "glCombinerInputNV" );
			qglCombinerOutputNV = SDL_GL_GetProcAddress( "glCombinerOutputNV" );
			qglFinalCombinerInputNV = SDL_GL_GetProcAddress( "glFinalCombinerInputNV" );
			qglGetCombinerInputParameterfvNV	= SDL_GL_GetProcAddress( "glGetCombinerInputParameterfvNV" );
			qglGetCombinerInputParameterivNV	= SDL_GL_GetProcAddress( "glGetCombinerInputParameterivNV" );
			qglGetCombinerOutputParameterfvNV = SDL_GL_GetProcAddress( "glGetCombinerOutputParameterfvNV" );
			qglGetCombinerOutputParameterivNV = SDL_GL_GetProcAddress( "glGetCombinerOutputParameterivNV" );
			qglGetFinalCombinerInputParameterfvNV = SDL_GL_GetProcAddress( "glGetFinalCombinerInputParameterfvNV" );
			qglGetFinalCombinerInputParameterivNV = SDL_GL_GetProcAddress( "glGetFinalCombinerInputParameterivNV" );

			// Validate the functions we need.
			if ( !qglCombinerParameterfvNV || !qglCombinerParameterivNV || !qglCombinerParameterfNV || !qglCombinerParameteriNV || !qglCombinerInputNV ||
				 !qglCombinerOutputNV || !qglFinalCombinerInputNV || !qglGetCombinerInputParameterfvNV || !qglGetCombinerInputParameterivNV ||
				 !qglGetCombinerOutputParameterfvNV || !qglGetCombinerOutputParameterivNV || !qglGetFinalCombinerInputParameterfvNV || !qglGetFinalCombinerInputParameterivNV )
			{
				bNVRegisterCombiners = false;
				qglCombinerParameterfvNV = NULL;
				qglCombinerParameteriNV = NULL;
				Com_Printf ("...GL_NV_register_combiners failed\n" );
			}
		}
		else
		{
			bNVRegisterCombiners = false;
			Com_Printf ("...ignoring GL_NV_register_combiners\n" );
		}
	}
	else
	{
		bNVRegisterCombiners = false;
		Com_Printf ("...GL_NV_register_combiners not found\n" );
	}

	// NOTE: Vertex and Fragment Programs are very dependant on each other - this is actually a
	// good thing! So, just check to see which we support (one or the other) and load the shared
	// function pointers. ARB rocks!

	// Vertex Programs.
	bool bARBVertexProgram = false;
	if ( strstr( glConfig.extensions_string, "GL_ARB_vertex_program" ) )
	{
		bARBVertexProgram = true;
	}
	else
	{
		bARBVertexProgram = false;
		Com_Printf ("...GL_ARB_vertex_program not found\n" );
	}

	// Fragment Programs.
	bool bARBFragmentProgram = false;
	if ( strstr( glConfig.extensions_string, "GL_ARB_fragment_program" ) )
	{
		bARBFragmentProgram = true;
	}
	else
	{
		bARBFragmentProgram = false;
		Com_Printf ("...GL_ARB_fragment_program not found\n" );
	}

	// If we support one or the other, load the shared function pointers.
	if ( bARBVertexProgram || bARBFragmentProgram )
	{
		qglProgramStringARB					= (PFNGLPROGRAMSTRINGARBPROC)  SDL_GL_GetProcAddress("glProgramStringARB");
		qglBindProgramARB					= (PFNGLBINDPROGRAMARBPROC)    SDL_GL_GetProcAddress("glBindProgramARB");
		qglDeleteProgramsARB				= (PFNGLDELETEPROGRAMSARBPROC) SDL_GL_GetProcAddress("glDeleteProgramsARB");
		qglGenProgramsARB					= (PFNGLGENPROGRAMSARBPROC)    SDL_GL_GetProcAddress("glGenProgramsARB");
		qglProgramEnvParameter4dARB			= (PFNGLPROGRAMENVPARAMETER4DARBPROC)    SDL_GL_GetProcAddress("glProgramEnvParameter4dARB");
		qglProgramEnvParameter4dvARB		= (PFNGLPROGRAMENVPARAMETER4DVARBPROC)   SDL_GL_GetProcAddress("glProgramEnvParameter4dvARB");
		qglProgramEnvParameter4fARB			= (PFNGLPROGRAMENVPARAMETER4FARBPROC)    SDL_GL_GetProcAddress("glProgramEnvParameter4fARB");
		qglProgramEnvParameter4fvARB		= (PFNGLPROGRAMENVPARAMETER4FVARBPROC)   SDL_GL_GetProcAddress("glProgramEnvParameter4fvARB");
		qglProgramLocalParameter4dARB		= (PFNGLPROGRAMLOCALPARAMETER4DARBPROC)  SDL_GL_GetProcAddress("glProgramLocalParameter4dARB");
		qglProgramLocalParameter4dvARB		= (PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) SDL_GL_GetProcAddress("glProgramLocalParameter4dvARB");
		qglProgramLocalParameter4fARB		= (PFNGLPROGRAMLOCALPARAMETER4FARBPROC)  SDL_GL_GetProcAddress("glProgramLocalParameter4fARB");
		qglProgramLocalParameter4fvARB		= (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) SDL_GL_GetProcAddress("glProgramLocalParameter4fvARB");
		qglGetProgramEnvParameterdvARB		= (PFNGLGETPROGRAMENVPARAMETERDVARBPROC) SDL_GL_GetProcAddress("glGetProgramEnvParameterdvARB");
		qglGetProgramEnvParameterfvARB		= (PFNGLGETPROGRAMENVPARAMETERFVARBPROC) SDL_GL_GetProcAddress("glGetProgramEnvParameterfvARB");
		qglGetProgramLocalParameterdvARB	= (PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) SDL_GL_GetProcAddress("glGetProgramLocalParameterdvARB");
		qglGetProgramLocalParameterfvARB	= (PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) SDL_GL_GetProcAddress("glGetProgramLocalParameterfvARB");
		qglGetProgramivARB					= (PFNGLGETPROGRAMIVARBPROC)     SDL_GL_GetProcAddress("glGetProgramivARB");
		qglGetProgramStringARB				= (PFNGLGETPROGRAMSTRINGARBPROC) SDL_GL_GetProcAddress("glGetProgramStringARB");
		qglIsProgramARB						= (PFNGLISPROGRAMARBPROC)        SDL_GL_GetProcAddress("glIsProgramARB");

		// Validate the functions we need.
		if ( !qglProgramStringARB || !qglBindProgramARB || !qglDeleteProgramsARB || !qglGenProgramsARB ||
			 !qglProgramEnvParameter4dARB || !qglProgramEnvParameter4dvARB || !qglProgramEnvParameter4fARB ||
             !qglProgramEnvParameter4fvARB || !qglProgramLocalParameter4dARB || !qglProgramLocalParameter4dvARB ||
             !qglProgramLocalParameter4fARB || !qglProgramLocalParameter4fvARB || !qglGetProgramEnvParameterdvARB ||
             !qglGetProgramEnvParameterfvARB || !qglGetProgramLocalParameterdvARB || !qglGetProgramLocalParameterfvARB ||
             !qglGetProgramivARB || !qglGetProgramStringARB || !qglIsProgramARB )
		{
			bARBVertexProgram = false;
			bARBFragmentProgram = false;
			qglGenProgramsARB = NULL;	//clear ptrs that get checked
			qglProgramEnvParameter4fARB = NULL;
			Com_Printf ("...ignoring GL_ARB_vertex_program\n" );
			Com_Printf ("...ignoring GL_ARB_fragment_program\n" );
		}
	}

	// Figure out which texture rectangle extension to use.
	bool bTexRectSupported = false;
	if ( strnicmp( glConfig.vendor_string, "ATI Technologies",16 )==0
		&& strnicmp( glConfig.version_string, "1.3.3",5 )==0
		&& glConfig.version_string[5] < '9' ) //1.3.34 and 1.3.37 and 1.3.38 are broken for sure, 1.3.39 is not
	{
		g_bTextureRectangleHack = true;
	}

	if ( strstr( glConfig.extensions_string, "GL_NV_texture_rectangle" )
		   || strstr( glConfig.extensions_string, "GL_EXT_texture_rectangle" ) )
	{
		bTexRectSupported = true;
	}

	// Find out how many general combiners they have.
	#define GL_MAX_GENERAL_COMBINERS_NV       0x854D
	GLint iNumGeneralCombiners = 0;
	qglGetIntegerv( GL_MAX_GENERAL_COMBINERS_NV, &iNumGeneralCombiners );

	// Only allow dynamic glows/flares if they have the hardware
	if ( bTexRectSupported && bARBVertexProgram /*whee && bHasRenderTexture*/ && qglActiveTextureARB && glConfig.maxActiveTextures >= 4 &&
		( ( bNVRegisterCombiners && iNumGeneralCombiners >= 2 ) || bARBFragmentProgram ) )
	{
		g_bDynamicGlowSupported = true;
		// this would overwrite any achived setting gwg
		// Cvar_Set( "r_DynamicGlow", "1" );
	}
	else
	{
		g_bDynamicGlowSupported = false;
		Cvar_Set( "r_DynamicGlow","0" );
	}
}
Example #14
0
bool CTaksiConfig::WriteIniFile()
{
	// RETURN: true = success
	//  false = cant save!
	//
	char* pFileOld = NULL;
	DWORD nSizeOld = 0;

	TCHAR szIniFileName[_MAX_PATH];
	Str_MakeFilePath( szIniFileName, COUNTOF(szIniFileName), 
		sg_Shared.m_szIniDir, _T(TAKSI_INI_FILE) );

	// first read all lines
	CNTHandle FileOld( ::CreateFile( szIniFileName, 
		GENERIC_READ, 0, NULL,
		OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ));
	if ( FileOld.IsValidHandle())
	{
		nSizeOld = ::GetFileSize(FileOld, NULL);
		pFileOld = (char*) ::HeapAlloc( g_Proc.m_hHeap, HEAP_ZERO_MEMORY, nSizeOld);
		if (pFileOld == NULL) 
			return false;

		DWORD dwBytesRead = 0;
		::ReadFile(FileOld, pFileOld, nSizeOld, &dwBytesRead, NULL);
		if (dwBytesRead != nSizeOld) 
		{
			::HeapFree( g_Proc.m_hHeap, 0, pFileOld );
			return false;
		}
		FileOld.CloseHandle();
	}

	// create new file
	FILE* pFile = fopen( TAKSI_INI_FILE, "wt");
	if ( pFile == NULL )
		return false;

	// loop over every line from the old file, and overwrite it in the new file
	// if necessary. Otherwise - copy the old line.
	
	CIniObject* pObj = NULL;
	char* pszLine = pFileOld; 

	if (pFileOld)
	while (true)
	{
		if ( pszLine >= pFileOld + nSizeOld )
			break;

		if ( *pszLine == '[' )
		{
			if ( pObj ) // finish previous section.
			{
				pObj->PropsWrite(pFile);
			}
			if ( ! strnicmp( pszLine, "[" TAKSI_SECTION "]", sizeof(TAKSI_SECTION)+1 ))
			{
				pObj = this;
			}
			else if ( ! strnicmp( pszLine, "[" TAKSI_CUSTOM_SECTION " ", sizeof(TAKSI_CUSTOM_SECTION)+1 ))
			{
				TCHAR szSection[ _MAX_PATH ];
#ifdef _UNICODE
				ASSERT(0);
#else
				strncpy( szSection, pszLine+14, sizeof(szSection));
#endif
				TCHAR* pszEnd = _tcschr(szSection, ']');
				if (pszEnd)
					*pszEnd = '\0';
				pObj = CustomConfig_FindAppId(szSection);
			}
			else
			{
				pObj = NULL;
			}
		}

		char* pszEndLine = strchr(pszLine, '\n' ); // INI_CR
		if (pszEndLine) 
		{
			// covers \n or \r\n
			char* pszTmp = pszEndLine;
			for ( ; pszTmp >= pszLine && Str_IsSpace(*pszTmp); pszTmp-- )
				pszTmp[0] = '\0'; 
			pszEndLine++;
		}

		// it's a custom setting.
		bool bReplaced;
		if (pObj)
		{
			bReplaced = pObj->PropWriteName( pFile, pszLine );
		}
		else
		{
			bReplaced = false;
		}
		if (!bReplaced)
		{
			// take the old line as it was, might be blank or comment.
			fprintf(pFile, "%s" INI_CR, pszLine);
		}
		if (pszEndLine == NULL)
			break;
		pszLine = pszEndLine;
	}

	// release buffer
	if(pFileOld)
	{
		::HeapFree( g_Proc.m_hHeap, 0, pFileOld );
	}

	if ( pObj ) // finish previous section.
	{
		pObj->PropsWrite(pFile);
	}

	// if wasn't written, make sure we write it.
	if  (!m_dwWrittenMask)
	{
		fprintf( pFile, "[" TAKSI_SECTION "]" INI_CR );
		PropsWrite(pFile);
	}
	PropsInit();

	// same goes for NEW custom configs
	CTaksiConfigCustom* p = m_pCustomList;
	while (p != NULL)
	{
		if ( ! p->m_dwWrittenMask )
		{
			fprintf( pFile, "[" TAKSI_CUSTOM_SECTION " %s]" INI_CR, p->m_szAppId );
			p->PropsWrite(pFile);
		}
		p->PropsInit();
		p = p->m_pNext;
	}

	fclose(pFile);
	return true;
}
bool CAI_SchedulesManager::LoadSchedulesFromBuffer( const char *prefix, char *pStartFile, CAI_ClassScheduleIdSpace *pIdSpace )
{
	char token[1024];
	char save_token[1024];
	const char *pfile = engine->ParseFile(pStartFile, token, sizeof( token ) );

	while (!stricmp("Schedule",token))
	{
		pfile = engine->ParseFile(pfile, token, sizeof( token ) );

		// -----------------------------
		// Check for duplicate schedule
		// -----------------------------
		if (GetScheduleByName(token))
		{
			DevMsg("ERROR: file contains a schedule (%s) that has already been defined!\n",token);
			DevMsg("       Aborting schedule load.\n");
			Assert(0);
			return false;
		}

		int scheduleID = CAI_BaseNPC::GetScheduleID(token);
		if (scheduleID == -1)
		{
			DevMsg( "ERROR: LoadSchd (%s): Unknown schedule type (%s)\n", prefix, token);
			// FIXME: .sch's not being in code/perforce makes it hard to share branches between developers
			// for now, just stop processing this entities schedules if one is found that isn't in the schedule registry
			break;
			// return false;
		}

		CAI_Schedule *new_schedule = CreateSchedule(token,scheduleID);

		pfile = engine->ParseFile(pfile, token, sizeof( token ) );
		if (stricmp(token,"Tasks"))
		{
			DevMsg( "ERROR: LoadSchd (%s): (%s) Malformed AI Schedule.  Expecting 'Tasks' keyword.\n",prefix,new_schedule->GetName());
			Assert(0);
			return false;
		}

		// ==========================
		// Now read in the tasks
		// ==========================
		// Store in temp array until number of tasks is known
		Task_t tempTask[50];
		int	   taskNum = 0;

		pfile = engine->ParseFile(pfile, token, sizeof( token ) );
		while ((token[0] != '\0') && (stricmp("Interrupts", token)))
		{
			// Convert generic ID to sub-class specific enum
			int taskID = CAI_BaseNPC::GetTaskID(token);
			tempTask[taskNum].iTask = (pIdSpace) ? pIdSpace->TaskGlobalToLocal(taskID) : AI_RemapFromGlobal( taskID );
			
			// If not a valid condition, send a warning message
			if (tempTask[taskNum].iTask == -1)
			{
				DevMsg( "ERROR: LoadSchd (%s): (%s) Unknown task %s!\n", prefix,new_schedule->GetName(), token);
				Assert(0);
				return false;
			}

			Assert( AI_IdIsLocal( tempTask[taskNum].iTask ) );

			// Read in the task argument
			pfile = engine->ParseFile(pfile, token, sizeof( token ) );

			if (!stricmp("Activity",token))
			{
				// Skip the ";", but make sure it's present
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				if (stricmp(token,":"))
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Malformed AI Schedule.  Expecting ':' after type 'ACTIVITY.\n",prefix,new_schedule->GetName());
					Assert(0);
					return false;
				}

				// Load the activity and make sure its valid
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				tempTask[taskNum].flTaskData = CAI_BaseNPC::GetActivityID(token);
				if (tempTask[taskNum].flTaskData == -1)
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Unknown activity %s!\n", prefix,new_schedule->GetName(), token);
					Assert(0);
					return false;
				}
			}
			else if (!stricmp("Task",token))
			{
				// Skip the ";", but make sure it's present
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				if (stricmp(token,":"))
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Malformed AI Schedule.  Expecting ':' after type 'ACTIVITY.\n",prefix,new_schedule->GetName());
					Assert(0);
					return false;
				}

				// Load the activity and make sure its valid
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );

				// Convert generic ID to sub-class specific enum
				int taskID = CAI_BaseNPC::GetTaskID(token);
				tempTask[taskNum].flTaskData = (pIdSpace) ? pIdSpace->TaskGlobalToLocal(taskID) : AI_RemapFromGlobal( taskID );

				if (tempTask[taskNum].flTaskData == -1)
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Unknown task %s!\n", prefix,new_schedule->GetName(), token);
					Assert(0);
					return false;
				}
			}
			else if (!stricmp("Schedule",token))
			{
				// Skip the ";", but make sure it's present
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				if (stricmp(token,":"))
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Malformed AI Schedule.  Expecting ':' after type 'ACTIVITY.\n",prefix,new_schedule->GetName());
					Assert(0);
					return false;
				}

				// Load the schedule and make sure its valid
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );

				// Convert generic ID to sub-class specific enum
				int schedID = CAI_BaseNPC::GetScheduleID(token);
				tempTask[taskNum].flTaskData = (pIdSpace) ? pIdSpace->ScheduleGlobalToLocal(schedID) : AI_RemapFromGlobal( schedID );

				if (tempTask[taskNum].flTaskData == -1)
				{
					DevMsg( "ERROR: LoadSchd %d (%s): (%s) Unknown shedule %s!\n", __LINE__, prefix,new_schedule->GetName(), token);
					Assert(0);
					return false;
				}
			}
			else if (!stricmp("State",token))
			{
				// Skip the ";", but make sure it's present
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				if (stricmp(token,":"))
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Malformed AI Schedule.  Expecting ':' after type 'STATE.\n",prefix,new_schedule->GetName());
					Assert(0);
					return false;
				}

				// Load the activity and make sure its valid
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				tempTask[taskNum].flTaskData = CAI_SchedulesManager::GetStateID(token);
				if (tempTask[taskNum].flTaskData == -1)
				{
					DevMsg( "ERROR: LoadSchd %d (%s): (%s) Unknown shedule %s!\n", __LINE__, prefix,new_schedule->GetName(), token);
					Assert(0);
					return false;
				}
			}
			else if (!stricmp("Memory",token))
			{

				// Skip the ";", but make sure it's present
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				if (stricmp(token,":"))
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Malformed AI Schedule.  Expecting ':' after type 'STATE.\n",prefix,new_schedule->GetName());
					Assert(0);
					return false;
				}

				// Load the activity and make sure its valid
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				tempTask[taskNum].flTaskData = CAI_SchedulesManager::GetMemoryID(token);
				if (tempTask[taskNum].flTaskData == -1)
				{
					DevMsg( "ERROR: LoadSchd %d (%s): (%s) Unknown shedule %s!\n", __LINE__, prefix,new_schedule->GetName(), token);
					Assert(0);
					return false;
				}
			}
			else if (!stricmp("Path",token))
			{
				// Skip the ";", but make sure it's present
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				if (stricmp(token,":"))
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Malformed AI Schedule.  Expecting ':' after type 'PATH.\n",prefix,new_schedule->GetName());
					Assert(0);
					return false;
				}

				// Load the activity and make sure its valid
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				tempTask[taskNum].flTaskData = CAI_SchedulesManager::GetPathID( token );
				if (tempTask[taskNum].flTaskData == -1)
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Unknown path type %s!\n", prefix,new_schedule->GetName(), token);
					Assert(0);
					return false;
				}
			}
			else if (!stricmp("Goal",token))
			{
				// Skip the ";", but make sure it's present
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				if (stricmp(token,":"))
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Malformed AI Schedule.  Expecting ':' after type 'GOAL.\n",prefix,new_schedule->GetName());
					Assert(0);
					return false;
				}

				// Load the activity and make sure its valid
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				tempTask[taskNum].flTaskData = CAI_SchedulesManager::GetGoalID( token );
				if (tempTask[taskNum].flTaskData == -1)
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Unknown goal type  %s!\n", prefix,new_schedule->GetName(), token);
					Assert(0);
					return false;
				}
			}
			else if ( !stricmp( "HintFlags",token ) )
			{
				// Skip the ":", but make sure it's present
				pfile = engine->ParseFile(pfile, token, sizeof( token ) );
				if (stricmp(token,":"))
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Malformed AI Schedule.  Expecting ':' after type 'HINTFLAG'\n",prefix,new_schedule->GetName());
					Assert(0);
					return false;
				}

				// Load the flags and make sure they are valid
				pfile = engine->ParseFile( pfile, token, sizeof( token ) );
				tempTask[taskNum].flTaskData = CAI_HintManager::GetFlags( token );
				if (tempTask[taskNum].flTaskData == -1)
				{
					DevMsg( "ERROR: LoadSchd (%s): (%s) Unknown hint flag type  %s!\n", prefix,new_schedule->GetName(), token);
					Assert(0);
					return false;
				}
			}
			else if (!stricmp("Interrupts",token) || !strnicmp("TASK_",token,5) )
			{
				// a parse error.  Interrupts is the next section, TASK_ is probably the next task, missing task argument?
				Warning( "ERROR: LoadSchd (%s): (%s) Bad syntax at task #%d (wasn't expecting %s)\n", prefix, new_schedule->GetName(), taskNum, token);
				Assert(0);
				return false;
			}
			else
			{
				tempTask[taskNum].flTaskData = atof(token);
			}
			taskNum++;

			// Read the next token
			Q_strncpy(save_token,token,sizeof(save_token));
			pfile = engine->ParseFile(pfile, token, sizeof( token ) );

			// Check for malformed task argument type
			if (!stricmp(token,":"))
			{
				DevMsg( "ERROR: LoadSchd (%s): Schedule (%s),\n        Task (%s), has a malformed AI Task Argument = (%s)\n",
						prefix,new_schedule->GetName(),taskID,save_token);
				Assert(0);
				return false;
			}
		}

		// Now copy the tasks into the new schedule
		new_schedule->m_iNumTasks = taskNum;
		new_schedule->m_pTaskList = new Task_t[taskNum];
		for (int i=0;i<taskNum;i++)
		{
			new_schedule->m_pTaskList[i].iTask		= tempTask[i].iTask;
			new_schedule->m_pTaskList[i].flTaskData = tempTask[i].flTaskData;

			Assert( AI_IdIsLocal( new_schedule->m_pTaskList[i].iTask ) );
		}

		// ==========================
		// Now read in the interrupts
		// ==========================
		pfile = engine->ParseFile(pfile, token, sizeof( token ) );
		while ((token[0] != '\0') && (stricmp("Schedule", token)))
		{
			// Convert generic ID to sub-class specific enum
			int condID = CAI_BaseNPC::GetConditionID(token);

			// If not a valid condition, send a warning message
			if (condID == -1)
			{
				DevMsg( "ERROR: LoadSchd (%s): Schedule (%s), Unknown condition %s!\n", prefix,new_schedule->GetName(),token);
				Assert(0);
			}

			// Otherwise, add to this schedules list of conditions
			else
			{
				int interrupt = AI_RemapFromGlobal(condID);
				Assert( AI_IdIsGlobal( condID ) && interrupt >= 0 && interrupt < MAX_CONDITIONS );
				new_schedule->m_InterruptMask.Set(interrupt);
			}

			// Read the next token
			pfile = engine->ParseFile(pfile, token, sizeof( token ) );
		}
	}
	return true;
}
Example #16
0
int CMD_EQFace(int argc, char *argv[])
{
//VOID Face(PSPAWNINFO pChar, PCHAR szLine)
//{
    if (!ppSpawnManager) return 0;
    if (!pSpawnList) return 0;
    PSPAWNINFO pSpawnClosest = NULL;
    PSPAWNINFO psTarget = NULL;
    SPAWNINFO LocSpawn = {0};
   PSPAWNINFO pChar = (PSPAWNINFO)pLocalPlayer;
    SEARCHSPAWN SearchSpawn;
    ClearSearchSpawn(&SearchSpawn);
    CHAR szMsg[MAX_STRING] = {0};
    CHAR szName[MAX_STRING] = {0};
    CHAR szArg[MAX_STRING] = {0};
   PCHAR pszArg = NULL;
    BOOL bArg = TRUE;
    BOOL bOtherArgs = FALSE;
    BOOL Away = FALSE;
    BOOL Predict = FALSE;
    BOOL Fast = FALSE;
    BOOL Look = TRUE;
    BOOL Parsing = TRUE;
    DOUBLE Distance;

   for(int qq=1; qq<argc; qq++)
   {
      if (!strcmp(argv[qq],"predict")) {
         Predict=TRUE;
      } else if (!strcmp(argv[qq],"fast")) {
         Fast = TRUE;
      } else if (!strcmp(argv[qq],"away")) {
         Away = TRUE;
      } else if (!strcmp(argv[qq],"nolook")) {
         Look = FALSE;
      } else if (!strnicmp(argv[qq], "loc", 3)) {
         pSpawnClosest = &LocSpawn;
         strcpy(LocSpawn.Name,"location");
         if (((++qq)<argc) && strstr(argv[qq],","))
         {
             pSpawnClosest->Y = (FLOAT)atof(argv[qq]);
            pszArg = strstr(argv[qq],",")+1;
              pSpawnClosest->X = (FLOAT)atof(pszArg);
         }
      } else if (!stricmp(argv[qq], "item")) {
         if (EnviroTarget.Name[0]==0) {
            printf("%s: item specified but no item targetted.", argv[0]);
            return 0;
         }
         pSpawnClosest = &EnviroTarget;
      }
	  else if (!stricmp(argv[qq], "door")) {
		  if (DoorEnviroTarget.Name[0] == 0) {
			  printf("%s: door specified but no door targetted.", argv[0]);
			  return 0;
		  }
		  pSpawnClosest = &DoorEnviroTarget;
      } else if (!strcmp(szArg,"help")) {
         printf("Usage: %s [spawn] [item] [door] [id #] [heading <ang>] [loc <y>,<x>] [away] [alert #]",argv[0]);
         return 0;
      } else {
         bOtherArgs = TRUE;
         qq+=ParseSearchSpawnArg(qq,argc,argv,SearchSpawn);
//         szFilter = ParseSearchSpawnArgs(szArg,szFilter,&SearchSpawn);
      }
   }

   if (!pSpawnClosest) {
      if (!bOtherArgs) {
         if (ppTarget && pTarget) {
            pSpawnClosest = (PSPAWNINFO)pTarget;
         }
      } else {
         pSpawnClosest = SearchThroughSpawns(&SearchSpawn,pChar);
      }
   }

   szMsg[0]=0;

   if (!pSpawnClosest) {
	   printf("There were no matches for: %s", FormatSearchSpawn(szArg, sizeof(szArg), &SearchSpawn));
   } else {
      if (Predict) {
         Distance = DistanceToSpawn(pChar, pSpawnClosest);
         gFaceAngle = (
            atan2((pSpawnClosest->X + (pSpawnClosest->SpeedX * Distance)) - pChar->X,
            (pSpawnClosest->Y + (pSpawnClosest->SpeedY * Distance)) - pChar->Y)
            * 256.0f / PI);
      } else {
         gFaceAngle = (
            atan2(pSpawnClosest->X - pChar->X,
            pSpawnClosest->Y - pChar->Y)
            * 256.0f / PI);
      }
      if (Look) {
         Distance = DistanceToSpawn(pChar, pSpawnClosest);
         gLookAngle = (
            atan2(pSpawnClosest->Z + pSpawnClosest->AvatarHeight*StateHeightMultiplier(pSpawnClosest->StandState) - pChar->Z - pChar->AvatarHeight*StateHeightMultiplier(pChar->StandState),
            (FLOAT)Distance)
            * 256.0f / PI);
         if (Away) gLookAngle = -gLookAngle;
         if (Fast) {
            pChar->CameraAngle = (FLOAT)gLookAngle;
            gLookAngle=10000.0f;
         }
      }
      if (Away) {
         gFaceAngle += 256.0f;
      }
      if (gFaceAngle>=512.0f) gFaceAngle -= 512.0f;
      if (gFaceAngle<0.0f) gFaceAngle += 512.0f;
      if (Fast) {
         ((PSPAWNINFO)pCharSpawn)->Heading = (FLOAT)gFaceAngle;
         gFaceAngle=10000.0f;
      }
      sprintf(szMsg,"Facing %s'%s'...",(Away)?"away from ":"", CleanupName(strcpy(szName,pSpawnClosest->Name),FALSE));
   }
   if (ppTarget && pTarget) {
      psTarget = (PSPAWNINFO)pTarget;
   }
   if (szMsg[0] && ((pSpawnClosest != &LocSpawn) && ((Away) || (pSpawnClosest != psTarget)))) WriteChatColor(szMsg,USERCOLOR_WHO);
   DebugSpew("Face - %s",szMsg);
   return 0;
}
Example #17
0
static unsigned int ip_nat_sip(struct sk_buff *skb, unsigned int dataoff,
			       const char **dptr, unsigned int *datalen)
{
	enum ip_conntrack_info ctinfo;
	struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
	enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
	unsigned int coff, matchoff, matchlen;
	enum sip_header_types hdr;
	union nf_inet_addr addr;
	__be16 port;
	int request, in_header;

	/* Basic rules: requests and responses. */
	if (strnicmp(*dptr, "SIP/2.0", strlen("SIP/2.0")) != 0) {
		if (ct_sip_parse_request(ct, *dptr, *datalen,
					 &matchoff, &matchlen,
					 &addr, &port) > 0 &&
		    !map_addr(skb, dataoff, dptr, datalen, matchoff, matchlen,
			      &addr, port))
			return NF_DROP;
		request = 1;
	} else
		request = 0;

	if (nf_ct_protonum(ct) == IPPROTO_TCP)
		hdr = SIP_HDR_VIA_TCP;
	else
		hdr = SIP_HDR_VIA_UDP;

	/* Translate topmost Via header and parameters */
	if (ct_sip_parse_header_uri(ct, *dptr, NULL, *datalen,
				    hdr, NULL, &matchoff, &matchlen,
				    &addr, &port) > 0) {
		unsigned int matchend, poff, plen, buflen, n;
		char buffer[sizeof("nnn.nnn.nnn.nnn:nnnnn")];

		/* We're only interested in headers related to this
		 * connection */
		if (request) {
			if (addr.ip != ct->tuplehash[dir].tuple.src.u3.ip ||
			    port != ct->tuplehash[dir].tuple.src.u.udp.port)
				goto next;
		} else {
			if (addr.ip != ct->tuplehash[dir].tuple.dst.u3.ip ||
			    port != ct->tuplehash[dir].tuple.dst.u.udp.port)
				goto next;
		}

		if (!map_addr(skb, dataoff, dptr, datalen, matchoff, matchlen,
			      &addr, port))
			return NF_DROP;

		matchend = matchoff + matchlen;

		/* The maddr= parameter (RFC 2361) specifies where to send
		 * the reply. */
		if (ct_sip_parse_address_param(ct, *dptr, matchend, *datalen,
					       "maddr=", &poff, &plen,
					       &addr) > 0 &&
		    addr.ip == ct->tuplehash[dir].tuple.src.u3.ip &&
		    addr.ip != ct->tuplehash[!dir].tuple.dst.u3.ip) {
			__be32 ip = ct->tuplehash[!dir].tuple.dst.u3.ip;
			buflen = sprintf(buffer, "%u.%u.%u.%u", NIPQUAD(ip));
			if (!mangle_packet(skb, dataoff, dptr, datalen,
					   poff, plen, buffer, buflen))
				return NF_DROP;
		}

		/* The received= parameter (RFC 2361) contains the address
		 * from which the server received the request. */
		if (ct_sip_parse_address_param(ct, *dptr, matchend, *datalen,
					       "received=", &poff, &plen,
					       &addr) > 0 &&
		    addr.ip == ct->tuplehash[dir].tuple.dst.u3.ip &&
		    addr.ip != ct->tuplehash[!dir].tuple.src.u3.ip) {
			__be32 ip = ct->tuplehash[!dir].tuple.src.u3.ip;
			buflen = sprintf(buffer, "%u.%u.%u.%u", NIPQUAD(ip));
			if (!mangle_packet(skb, dataoff, dptr, datalen,
					   poff, plen, buffer, buflen))
				return NF_DROP;
		}

		/* The rport= parameter (RFC 3581) contains the port number
		 * from which the server received the request. */
		if (ct_sip_parse_numerical_param(ct, *dptr, matchend, *datalen,
						 "rport=", &poff, &plen,
						 &n) > 0 &&
		    htons(n) == ct->tuplehash[dir].tuple.dst.u.udp.port &&
		    htons(n) != ct->tuplehash[!dir].tuple.src.u.udp.port) {
			__be16 p = ct->tuplehash[!dir].tuple.src.u.udp.port;
			buflen = sprintf(buffer, "%u", ntohs(p));
			if (!mangle_packet(skb, dataoff, dptr, datalen,
					   poff, plen, buffer, buflen))
				return NF_DROP;
		}
	}

next:
	/* Translate Contact headers */
	coff = 0;
	in_header = 0;
	while (ct_sip_parse_header_uri(ct, *dptr, &coff, *datalen,
				       SIP_HDR_CONTACT, &in_header,
				       &matchoff, &matchlen,
				       &addr, &port) > 0) {
		if (!map_addr(skb, dataoff, dptr, datalen, matchoff, matchlen,
			      &addr, port))
			return NF_DROP;
	}

	if (!map_sip_addr(skb, dataoff, dptr, datalen, SIP_HDR_FROM) ||
	    !map_sip_addr(skb, dataoff, dptr, datalen, SIP_HDR_TO))
		return NF_DROP;

	return NF_ACCEPT;
}
Example #18
0
// Format the XML corresponding to the FileInfo geolocation info
CNCSError CNCSJP2File::CNCSJP2GMLGeoLocationBox::FormatXML(char *pBuf, UINT32 nBufLen)
{
    if (NCSIsFileInfoExGeoreferenced(&m_GMLFileInfo))
    {
        CNCSGDTEPSG& Epsg = *CNCSGDTEPSG::Instance();
        char szSRSName[32];
        *szSRSName = '\0';
        UINT32 nEPSGCode = Epsg.GetEPSG(m_GMLFileInfo.szProjection, m_GMLFileInfo.szDatum);
        if (nEPSGCode) sprintf(szSRSName," srsName=\"epsg:%u\"",nEPSGCode);
        else if (strnicmp(m_GMLFileInfo.szProjection,"epsg:",5) == 0) //we have an unknown EPSG
        {
            char *pColon = strchr(m_GMLFileInfo.szProjection,':');
            pColon++;
            nEPSGCode = atoi(pColon); //grab EPSG code
            sprintf(szSRSName," srsName=\"epsg:%u\"",nEPSGCode);
        }
        double dRegistrationX = m_GMLFileInfo.fOriginX;
        double dRegistrationY = m_GMLFileInfo.fOriginY;
        double dCellSizeX = m_GMLFileInfo.fCellIncrementX;
        double dCellSizeY = m_GMLFileInfo.fCellIncrementY;
        //move rotation to the (-180,180] interval
        while (m_GMLFileInfo.fCWRotationDegrees <= -180.0)
            m_GMLFileInfo.fCWRotationDegrees += 360.0;
        while (m_GMLFileInfo.fCWRotationDegrees > 180.0)
            m_GMLFileInfo.fCWRotationDegrees -= 360.0;
        double dCWRotationDegrees = m_GMLFileInfo.fCWRotationDegrees;
        UINT32 nImageWidth = m_GMLFileInfo.nSizeX;
        UINT32 nImageHeight = m_GMLFileInfo.nSizeY;
        IEEE8 dMeterFactor = 1.0;

        if(m_GMLFileInfo.eCellSizeUnits == ECW_CELL_UNITS_FEET) {
            dCellSizeX *= NCS_FEET_FACTOR;
            dCellSizeY *= NCS_FEET_FACTOR;
            dRegistrationX *= NCS_FEET_FACTOR;
            dRegistrationY *= NCS_FEET_FACTOR;
        }

        double p1[3] = { (sin(Deg2Rad(dCWRotationDegrees)) * dCellSizeX), (cos(Deg2Rad(dCWRotationDegrees)) * dCellSizeY), 0.0 };
        double p2[3] = { (cos(Deg2Rad(dCWRotationDegrees)) * dCellSizeX), -(sin(Deg2Rad(dCWRotationDegrees)) * dCellSizeY), 0.0 };

        snprintf(pBuf, nBufLen,
                 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
                 "<JPEG2000_GeoLocation>\r\n"
                 "	<gml:RectifiedGrid xmlns:gml=\"http://www.opengis.net/gml\" gml:id=\"JPEG2000_GeoLocation_1\" dimension=\"2\">\r\n"
                 "		<gml:origin>\r\n"
                 "			<gml:Point gml:id=\"JPEG2000_Origin\"%s>\r\n"
                 "				<gml:coordinates>%.13lf,%.13lf</gml:coordinates>\r\n"
                 "			</gml:Point>\r\n"
                 "			</gml:origin>\r\n"
                 "		<gml:offsetVector gml:id=\"p1\">%.13lf,%.13lf,%.13lf</gml:offsetVector>\r\n"
                 "		<gml:offsetVector gml:id=\"p2\">%.13lf,%.13lf,%.13lf</gml:offsetVector>\r\n"
                 "	</gml:RectifiedGrid>\r\n"
                 "</JPEG2000_GeoLocation>\r\n",
                 szSRSName,
                 dRegistrationX - nImageHeight * p1[0],
                 dRegistrationY - nImageHeight * p1[1],
                 p1[0], p1[1], p1[2],
                 p2[0], p2[1], p2[2]);
        return(NCS_SUCCESS);
    } else {
#ifdef NCS_BUILD_WITH_STDERR_DEBUG_INFO
        fprintf(stderr,"File not georeferenced: no GML box created\n");
#endif
        return(CNCSError(NCS_JP2_GEODATA_NOT_GEOREFERENCED));
    }
}
// Got a notify message from PutDiskObject()
BOOL backdrop_check_notify(
	BackdropInfo *info,
	DOpusNotify *notify,
	Lister *lister)
{
	char *name_buf;
	BOOL disk=0,ret=0;
	struct List *search;
	BackdropObject *object;

	if (!(name_buf=AllocVec(256,0)))
		return 0;

	// Disk icon?
	if (notify->dn_Name[strlen(notify->dn_Name)-1]==':')
	{
		char *ptr;

		// Get volume name
		if ((ptr=strchr(notify->dn_Name,':')))
		{
			stccpy(name_buf,notify->dn_Name,ptr-notify->dn_Name+1);
			disk=1;
		}
	}

	// Otherwise copy name and clear it
	else
	{
		// Get name pointer
		char *name=FilePart(notify->dn_Name);

		// Copy name
		strcpy(name_buf,name);
		*name=0;

		// Strip trailing '/'
		if (*(name-1)=='/') *(name-1)=0;
	}

	// Is this a lister?
	if (lister)
	{
		short len;
		BOOL ok=0;

		// Match length
		len=strlen(notify->dn_Name);

		// See if strings match
		if (strnicmp(lister->cur_buffer->buf_Path,notify->dn_Name,len)==0)
		{
			// Check termination
			if (lister->cur_buffer->buf_Path[len]=='\0') ok=1;

			// / can terminate too
			else
			if (lister->cur_buffer->buf_Path[len]=='/' &&
				lister->cur_buffer->buf_Path[len+1]=='\0') ok=1;
		}

		// Didn't match?
		if (!ok)
		{
			// Free message
			ReplyFreeMsg(notify);	
			FreeVec(name_buf);
			return 0;
		}
	}

	// Lock backdrop list
	lock_listlock(&info->objects,1);

	// See if there's an icon of this name
	search=&info->objects.list;
	while ((object=(BackdropObject *)FindNameI(search,name_buf)))
	{
		// Disk?
		if (object->type==BDO_DISK && disk)
		{
			// Matched
			break;
		}

		// Valid object?
		else
		if (object->type!=BDO_APP_ICON &&
			object->type!=BDO_BAD_DISK &&
			object->path)
		{
			char *path=0;
			BPTR lock;

			// If no lister, get full path of object
			if (!lister && (path=AllocVec(512,0)))
			{
				// Lock path
				if ((lock=Lock(object->path,ACCESS_READ)))
				{
					// Get full path
					DevNameFromLockDopus(lock,path,512);
					UnLock(lock);
				}

				// Failed
				else strcpy(path,object->path);
			}
					
			// Objects in same directory?
			if (lister || stricmp(notify->dn_Name,(path)?path:object->path)==0)
			{
				// Free path
				if (path) FreeVec(path);

				// Matched
				break;
			}

			// Free path
			if (path) FreeVec(path);
		}

		// If this is a lister, there could only be one
		if (lister)
		{
			object=0;
			break;
		}

		// Keep searching from this object
		search=(struct List *)object;
	}

	// Got object?
	if (object)
	{
		ULONG old_image1=0,old_image2=0,new_image1,new_image2,old_flags=0,new_flags;
		BOOL redraw=0;
		struct DiskObject *old;

		// Save old icon
		old=object->icon;
		object->icon=0;

		// Not deleted?
		if (!notify->dn_Flags)
		{
			// Get image checksums
			old_image1=IconCheckSum(old,0);
			old_image2=IconCheckSum(old,1);
			old_flags=GetIconFlags(old);

			// Get new icon
			backdrop_get_icon(info,object,GETICON_CD|GETICON_NO_POS|GETICON_FAIL);
		}

		// No icon now?
		if (!object->icon)
		{
			// Replace old icon
			object->icon=old;

			// Erase old object
			backdrop_erase_icon(info,object,BDSF_RECALC);

			// Is object a disk?
			if (object->type==BDO_DISK)
			{
				// Signal to refresh drives
				IPC_Command(info->ipc,MAINCMD_REFRESH_DRIVES,0,0,0,0);
			}

			// Remove object from list
			backdrop_remove_object(info,object);
		}

		// Ok to keep going
		else
		{
			// Get image checksums
			new_image1=IconCheckSum(object->icon,0);
			new_image2=IconCheckSum(object->icon,1);
			new_flags=GetIconFlags(object->icon);

			// Mask out uninteresting flag bits
			old_flags&=ICONF_BORDER_OFF|ICONF_BORDER_ON|ICONF_NO_LABEL;
			new_flags&=ICONF_BORDER_OFF|ICONF_BORDER_ON|ICONF_NO_LABEL;

			// Need to redraw?
			if (old_image1!=new_image1 ||
				old_image2!=new_image2 ||
				old_flags!=new_flags)
			{
				// Erase old object
				backdrop_erase_icon(info,object,0);
				redraw=1;
			}

			// Free old icon
			if (old)
			{
				// Free icon remapping
				RemapIcon(old,(info->window)?info->window->WScreen:0,1);

				// Free icon
				FreeCachedDiskObject(old);
			}

			// Fix new icon size
			backdrop_get_icon(info,object,GETICON_POS_ONLY|GETICON_SAVE_POS|GETICON_KEEP);

			// Need to get masks?
			if (!backdrop_icon_border(object))
			{
				// Get masks for this icon
				backdrop_get_masks(object);
			}
			
			// Show new icon
			if (redraw) backdrop_render_object(info,object,BRENDERF_CLIP);
		}

		ret=1;
	}

	// Otherwise, got lister?
	else
	if (lister)
	{
		// Tell lister to get icons
		IPC_Command(lister->ipc,LISTER_GET_ICONS,0,0,0,0);
		ret=1;
	}

	// Or, on the desktop?
	else
	if (info->flags&BDIF_MAIN_DESKTOP)
	{
		BPTR lock1,lock2;

		// Lock the desktop folder and the changed directory
		if ((lock1=Lock(environment->env->desktop_location,ACCESS_READ)) &&
			(lock2=Lock(notify->dn_Name,ACCESS_READ)))
		{
			// Same directory?
			if (SameLock(lock1,lock2)==LOCK_SAME)
			{
				// Update the desktop folder
				misc_startup("dopus_desktop_update",MENU_UPDATE_DESKTOP,GUI->window,0,TRUE);
			}

			// Unlock second lock
			UnLock(lock2);
		}

		// Unlock first lock
		UnLock(lock1);
	}

	// Unlock list
	unlock_listlock(&info->objects);

	// Free message
	ReplyFreeMsg(notify);	
	FreeVec(name_buf);
	return ret;
}
Example #20
0
void ChttpGet::GetFile(char *URL,char *localfile)
{
	m_DataSock = INVALID_SOCKET;
	m_iBytesIn = 0;
	m_iBytesTotal = 0;
	m_State = HTTP_STATE_STARTUP;;
	m_Aborting = false;
	m_Aborted = false;

	strncpy(m_URL,URL,MAX_URL_LEN-1);
	m_URL[MAX_URL_LEN-1] = 0;

	LOCALFILE = fopen(localfile,"wb");
	if(NULL == LOCALFILE)
	{
		m_State = HTTP_STATE_CANT_WRITE_FILE;
		return;
	}
	m_DataSock = socket(AF_INET, SOCK_STREAM, 0);
	if(INVALID_SOCKET == m_DataSock)
	{
		m_State = HTTP_STATE_SOCKET_ERROR;
		return;
	}
	unsigned long arg;

	arg = true;
//#ifndef __LINUX__
#ifndef PLAT_UNIX
	ioctlsocket( m_DataSock, FIONBIO, &arg );
#else
	ioctl( m_DataSock, FIONBIO, &arg );
#endif

	char *pURL = URL;
	if(strnicmp(URL,"http:",5)==0)
	{
		pURL +=5;
		while(*pURL == '/')
		{
			pURL++;
		}
	}
	//There shouldn't be any : in this string
	if(strchr(pURL,':'))
	{
		m_State = HTTP_STATE_URL_PARSING_ERROR;
		return;
	}
	//read the filename by searching backwards for a /
	//then keep reading until you find the first /
	//when you found it, you have the host and dir
	char *filestart = NULL;
	char *dirstart = NULL;
	for(int i = strlen(pURL);i>=0;i--)
	{
		if(pURL[i]== '/')
		{
			if(!filestart)
			{
				filestart = pURL+i+1;
				dirstart = pURL+i+1;
				strcpy(m_szFilename,filestart);
			}
			else
			{
				dirstart = pURL+i+1;
			}
		}
	}
	if((dirstart==NULL) || (filestart==NULL))
	{
		m_State = HTTP_STATE_URL_PARSING_ERROR;
		return;
	}
	else
	{
		strcpy(m_szDir,dirstart);//,(filestart-dirstart));
		//m_szDir[(filestart-dirstart)] = NULL;
		strncpy(m_szHost,pURL,(dirstart-pURL));
		m_szHost[(dirstart-pURL)-1] = '\0';
	}
// #ifdef WIN32
	if(0==_beginthread(HTTPObjThread,0,this))
	{
		m_State = HTTP_STATE_INTERNAL_ERROR;
		return;
	}
	/*
#elif defined(__LINUX__)
	pthread_t thread;
	if(!inet_LoadThreadLib())
	{
		m_State = HTTP_STATE_INTERNAL_ERROR;
		return;
	}
	if(df_pthread_create(&thread,NULL,HTTPObjThread,this)!=0)
	{
		m_State = HTTP_STATE_INTERNAL_ERROR;
		return;
	}
#endif
	*/
}
Example #21
0
BOOL
HttpGetSocket(
    char * Verb,
    char * Server,
    char * URL,
    BOOL   DisplayHeaders,
    DWORD  ClientDataSize,
    PSTR   pchUserName,
    PSTR   pchPassword,
    PSTR   pszStore,
    PSTR   pszPref
    )
/*++

 Routine Description:

    Issue a command to a HTTP server using authentication

 Arguments:

    Verb                HTTP command : GET / HEAD / ...
    Server              server name
    URL                 URL to send to the server
    DisplayHeaders      TRUE to display headers as received
    ClientDataSize      number of bytes to send in the request
    pchUserName         user name for authentication
    pchPassword         password for authentication
    pszStore            file name where to dump reply from server

 Return Value:

    Returns TRUE is successful; otherwise FALSE is returned.

--*/
{
    char               ReceiveBuffer[8*1024];
    int                Error;
    BYTE               Request[1024];
    int                RequestSize;
    char *             AcceptTypes[2] = {"*/*", NULL};
    SOCKET             Socket = INVALID_SOCKET;
    WSADATA            WsaData;
    struct sockaddr_in Address;
    struct hostent *   HostEntry;
    char               Headers[] =
                           "HTTP/1.0\r\n"
                           "User-Agent: AuthClient\r\n"
                           "Accept: */*\r\n";
    char               CrLf[] = "\r\n";
    BYTE               ClientData[64*1024];
    BOOL               fKeepAlive = FALSE;
    int                cRec;
    DWORD              cLen;
    BOOL               fInHeader;
    PSTR               pchAuthData;
    BOOL               fServerKeepAlive = FALSE;
    BOOL               fNeedMoreData;
    BOOL               fNeedAuthenticate;
    PSTR               pH;
    PSTR               pN;
    BOOL               fStatusLine;
    int                Status = -1;
    DWORD              cToRead;
    PSTR               paAuth = achAuth;
    BOOL               fSt = FALSE;
    int                hnd = EOF;

    Error = WSAStartup (0x101, &WsaData);

    if (Error == SOCKET_ERROR)
    {
        fprintf(stderr, "Error in WSAStartup = %d\n", GetLastError());
        return FALSE;
    }

    if ( !InitAuthorizationHeader() )
    {
        fprintf(stderr, "Cannot initialize security module\n" );
        return FALSE;
    }

    memset( achAuth, '\0', sizeof(achAuth) );
    pchAuthData = NULL;
    fNeedAuthenticate = FALSE;

    //
    // Connect to the server
    //

    if  ( pszStore != NULL )
        if ( (hnd = _open( pszStore, _O_BINARY | _O_CREAT | _O_TRUNC | _O_RDWR, S_IREAD|S_IWRITE )) == EOF )
        {
            fprintf( stderr, "Can't create file %s\n", pszStore );
            return FALSE;
        }

again:

    if ( Socket == INVALID_SOCKET )
    {
        Socket = socket(AF_INET, SOCK_STREAM, 0);

        if (Socket == INVALID_SOCKET)
        {
            fprintf(stderr, "Error creating socket = %d\n", GetLastError());
            fSt = FALSE;
            goto ex;
        }

        Address.sin_family = AF_INET;
        Address.sin_port = 0;
        Address.sin_addr.s_addr = INADDR_ANY;

        Error =
        bind(
            Socket,
            (struct sockaddr *) &Address,
            sizeof(Address));

        if (Error)
        {
            fprintf(stderr, "Error in bind = %d\n", GetLastError());
            fSt = FALSE;
            goto ex;
        }

        Address.sin_family = AF_INET;
        Address.sin_port = htons(80);
        Address.sin_addr.s_addr = inet_addr(Server);

        if (Address.sin_addr.s_addr == -1)
        {
            //
            // Must be a server name
            //
            HostEntry = gethostbyname(Server);
            if (HostEntry == NULL)
            {
                printf("unable to resolve %s\n", Server);
                fSt = FALSE;
                goto ex;
            } else
            {
                Address.sin_addr.s_addr = *((unsigned long *) HostEntry->h_addr);
            }
        }

        Error =
        connect(
            Socket,
            (struct sockaddr *) &Address,
            sizeof(Address));

        if (Error)
        {
            fprintf(stderr, "Error connecting to %s = %d\n", Server, GetLastError());
            fSt = FALSE;
            goto ex;
        }
    }

    //
    // Send the client request
    //

    strcpy(Request, Verb);
    strcat(Request, " ");
    strcat(Request, URL);
    strcat(Request, " ");
    strcat(Request, Headers);
    if (ClientDataSize)
    {
        sprintf(ClientData, "Content-Length: %d\r\n", ClientDataSize);
        strcat(Request, ClientData);
    }
    if ( fKeepAlive )
    {
        strcat(Request, "Connection: Keep-Alive\r\n" );
    }

    if ( !AddAuthorizationHeader( Request + strlen(Request), achAuth, pchAuthData, pchUserName, pchPassword, &fNeedMoreData ) )
    {
        printf( "Authentication failed\n" );
        fSt = FALSE;
        goto ex;
    }

    strcat(Request, CrLf);

    RequestSize = (int)strlen(Request);

    Error =
    send(
        Socket,
        Request,
        RequestSize,
        0);

    if (Error != RequestSize)
    {
        printf("Error in client send = %d, %d\n", Error, GetLastError());
        fSt = FALSE;
        goto ex;
    }

    if (ClientDataSize)
    {
        memset( ClientData, ' ', ClientDataSize );

        //
        // Send the client data
        //

        Error =
        send(
            Socket,
            ClientData,
            ClientDataSize,
            0);

        if ( (DWORD)Error != ClientDataSize)
        {
            printf("Error in client send = %d, %d\n", Error, GetLastError());
            fSt = FALSE;
            goto ex;
        }
    }

    // parse status & header

    cLen = (DWORD)-1;
    fInHeader = TRUE;
    fServerKeepAlive = FALSE;
    fNeedAuthenticate = FALSE;

    for ( pH = ReceiveBuffer, fStatusLine = TRUE ; fInHeader ; )
    {
        cRec = recv( Socket, pH, (int)(ReceiveBuffer+sizeof(ReceiveBuffer)-pH), 0 );
        if ( cRec <= 0 )
        {
            closesocket( Socket );
            Socket = INVALID_SOCKET;
            break;
        }
        pH[ cRec ] = '\0';

        // Iterate on header fields

        while ( pN = strstr(pH, "\r\n" ) )
        {
            *pN = '\0';

            if ( DisplayHeaders )
            {
                printf( "%s\n", pH );
            }

            if ( fStatusLine )
            {
                // This is the status line, decode status

                SkipNonWhite( &pH );
                SkipWhite( &pH );
                Status = atoi( pH );
                if ( Status == 401 )
                {
                    fNeedAuthenticate = TRUE;
                }
                fStatusLine = FALSE;
            }
            else if ( pN == pH )    // end of header fields
            {
                if ( hnd != EOF )
                    write( hnd, pH+2, (int)(ReceiveBuffer+cRec-pH-2) );

                cLen -= (int)(ReceiveBuffer+cRec-pH-2 );
                fInHeader = FALSE;
                break;
            }
            else if ( !strnicmp( pH, HD_AUTHENTICATE, sizeof(HD_AUTHENTICATE)-1 ) )
            {
                SkipNonWhite( &pH );
                SkipWhite( &pH );

                // check if we are already in the authentication sequence

                if ( !IsInAuthorizationSequence() )
                {
                    // append to list of supported authentication methods

                    strcpy( paAuth, pH );
                    paAuth += strlen( pH ) + 1;
                }
                else
                {
                    // store pointer to authenticate blob

                    SkipNonWhite( &pH );
                    SkipWhite( &pH );
                    pchAuthData = pH;
                }
            }
            else if ( !strnicmp( pH, HD_LENGTH, sizeof(HD_LENGTH)-1 ) )
            {
                // get content length

                SkipNonWhite( &pH );
                SkipWhite( &pH );
                cLen = atoi( pH );
            }
            else if ( !strnicmp( pH, HD_CONNECTION, sizeof(HD_CONNECTION)-1 ) )
            {
                // check for keep-alive flag

                SkipNonWhite( &pH );
                SkipWhite( &pH );
                if ( !strnicmp( pH, "Keep-Alive", sizeof("Keep-Alive")-1 ) )
                    fServerKeepAlive = TRUE;
            }

            pH = pN + 2;
        }
    }

    // add final delimiter to list of supported authentication methods

    if ( !IsInAuthorizationSequence() && fNeedAuthenticate )
    {
        *paAuth = '\0';

        // Insure specified methods are supported localy

        if ( !ValidateAuthenticationMethods( achAuth, pszPref ) )
        {
            // None of the server specified authentication methods
            // are supported localy.

            SetLastError( ERROR_ACCESS_DENIED );

            fprintf( stderr, "No supported authentication method\n" );

            fSt = FALSE;
            goto ex;
        }
    }

    // read message body

    if ( Socket != INVALID_SOCKET )
    {
        for ( ; cLen ; )
        {
            if ( (cToRead = sizeof(ReceiveBuffer)) > cLen )
                cToRead = cLen;
            cRec = recv( Socket, ReceiveBuffer, cToRead, 0 );

            if ( cRec <= 0 )
            {
                closesocket( Socket );
                Socket = INVALID_SOCKET;
                break;
            }
            if ( hnd != EOF )
                write( hnd, ReceiveBuffer, cRec );

            cLen -= cRec;
        }
    }

    if ( !fServerKeepAlive )
    {
        if ( IsInAuthorizationSequence() )
        {
            fprintf( stderr, "Authentication rejected by server\n" );

            fNeedAuthenticate = FALSE;  // authentication failed
        }

        closesocket( Socket );
        Socket = INVALID_SOCKET;
    }

    if ( fNeedAuthenticate )
    {
        fKeepAlive = TRUE;
        goto again;
    }

    if ( Socket != INVALID_SOCKET )
        closesocket(Socket);

    fSt = Status == 200;

ex:
    TerminateAuthorizationHeader();

    if ( hnd != EOF )
        close( hnd );

    return fSt;
}
Example #22
0
void ChttpGet::WorkerThread()
{
	char szCommand[1000];
	char *p;
	int irsp = 0;
	ConnectSocket();
	if(m_Aborting)
	{
		fclose(LOCALFILE);
		return;
	}
	if(m_State != HTTP_STATE_CONNECTED)
	{
		fclose(LOCALFILE);
		return;
	}
	sprintf(szCommand,"GET %s%s HTTP/1.1\nAccept: */*\nAccept-Encoding: deflate\nHost: %s\n\n\n",m_ProxyEnabled?"":"/",m_ProxyEnabled?m_URL:m_szDir,m_szHost);
	send(m_DataSock,szCommand,strlen(szCommand),0);
	p = GetHTTPLine();
	if(strnicmp("HTTP/",p,5)==0)
	{
		char *pcode;
		pcode = strchr(p,' ')+1;
		if(!pcode)
		{
			m_State = HTTP_STATE_UNKNOWN_ERROR;	
			fclose(LOCALFILE);
			return;

		}
		pcode[3] = '\0';
		irsp = atoi(pcode);

		if(irsp == 0)
		{
			m_State = HTTP_STATE_UNKNOWN_ERROR;	
			fclose(LOCALFILE);
			return;
		}
		if(irsp==200)
		{
			int idataready=0;
			do
			{
				p = GetHTTPLine();
				if(p==NULL)
				{
					m_State = HTTP_STATE_UNKNOWN_ERROR;	
					fclose(LOCALFILE);
					return;
				}
				if(*p=='\0')
				{
					idataready = 1;
					break;
				}
				if(strnicmp(p,"Content-Length:",strlen("Content-Length:"))==0)
				{
					char *s = strchr(p,' ')+1;
					p = s;
					if(s)
					{
						while(*s)
						{
							if(!isdigit(*s))
							{
								*s='\0';
							}
							s++;
						};
						m_iBytesTotal = atoi(p);
					}

				}

				Sleep(1);
			}while(!idataready);
		ReadDataChannel();
		return;
		}
		m_State = HTTP_STATE_FILE_NOT_FOUND;
		fclose(LOCALFILE);
		return;
	}
	else
	{
		m_State = HTTP_STATE_UNKNOWN_ERROR;
		fclose(LOCALFILE);
		return;
	}
}
Example #23
0
/* =========================== */
int
PLP_bars( )
{
int i;
char attr[NAMEMAXLEN], val[256];
char *line, *lineval;
int nt, lvp;
int first;

char buf[256];
int j;
int stat;
int align;
double adjx, adjy;
int lenfield;
int locfield;
char color[COLORLEN];
char outline[256];
int do_outline;
double halfw;
double x, y, y0, xleft, xright;
char axis, baseax;
double barwidth;
int showvals;
char labeldetails[256];
int nstackf;
int stackf[MAXSTACKFIELDS];
double fval;
int ncluster;
int clusterpos;
char crossover[40];
double cr;
double laby;
char backbox[COLORLEN];
int labelfld;
char labelword[NAMEMAXLEN], labelstr[NAMEMAXLEN]; 
int lwl; /* do longwise labels */
int reverse;
int stopfld;
double taillen;
int errbars, errlofld, errhifld, reflecterr;
char selectex[256];
int result;
char legendlabel[256]; /* raised from 120 because it can contain long URLs... scg 4/22/04 */
int reverseorder, reversespecified;
char rangelo[40], rangehi[40];
double rlo, rhi;
double clustsep;
int trunc;
int y_endin, y0_endin;
int label0val;
char thinbarline[256];
int leftticfld, rightticfld, midticfld;
double ticlen;
double ytic;
char colorlist[256];
char *colorlp[MAXCLP];
int ncolorlp;
char dcolor[40];
char lblpos[40];
int taillengiven;
char numstrfmt[40];
int barwidthfield;
int hidezerobars; /* scg 11/29/00 */
double errbarmult;
int ibar;
int colorfield;
char mapurl[MAXPATH], expurl[MAXPATH];
int irow;
int segmentflag;
char constantlen[40], constantloc[40];
char maplabel[MAXTT], explabel[MAXTT]; 
int clickmap_on;
int exactcolorfield;
double minlabel;
int lwl_mustfit;
char overlapcolor[40];
double prev_y, prev_y0; /* used in segment bar overlap */
char labelselectex[256];
int labelmaxlen;

TDH_errprog( "pl proc bars" );



/* initialize */
axis = 'y';
lenfield = -1;
locfield = -1;
strcpy( color, "0.7" );
do_outline = 1;
strcpy( outline, "yes" );
barwidth = 0.0;
showvals = 0;
strcpy( labeldetails, "" );
nstackf = 0;
ncluster = 1;
clusterpos = 1;
strcpy( crossover, "" );
strcpy( backbox, "" );
strcpy( labelword, "" );
labelfld = -1;
lwl = 0;
stopfld = -1;
taillen = 0.0;
errbars = 0;
errlofld = errhifld = -1;
reflecterr = 0;
strcpy( selectex, "" );
strcpy( labelselectex, "" );
reverseorder = 0;
reversespecified = 0;
strcpy( rangelo, "" );
strcpy( rangehi, "" );
clustsep = 0.0;
trunc = 0;
label0val = 0;
strcpy( thinbarline, "" );
leftticfld = rightticfld = midticfld = -1;
ticlen = 0.02;
strcpy( colorlist, "" );
strcpy( lblpos, "" );
ncolorlp = 0;
taillengiven = 0;
strcpy( numstrfmt, "%g" );
barwidthfield = -1;
hidezerobars = 0;
errbarmult = 1.0;
colorfield = -1;
strcpy( mapurl, "" );
segmentflag = 0;
strcpy( constantlen, "" );
strcpy( constantloc, "" );
strcpy( maplabel, "" ); 
clickmap_on = 0;
exactcolorfield = -1;
labelrot = 0;
minlabel = NEGHUGE;
lwl_mustfit = 0;
strcpy( overlapcolor, "" );
strcpy( legendlabel, "" );
labelmaxlen = 250;



/* get attributes.. */
first = 1;
while( 1 ) {
	line = getnextattr( first, attr, val, &lvp, &nt );
	if( line == NULL ) break;
	first = 0;
	lineval = &line[lvp];


	if( stricmp( attr, "lenfield" )==0 ) lenfield = fref( val ) -1;
	else if( stricmp( attr, "locfield" )==0 ) locfield = fref( val ) -1; 
	else if( stricmp( attr, "axis" )==0 ) axis = tolower(val[0]);
	else if( stricmp( attr, "horizontalbars" )==0 ) axis = 'x';
	else if( stricmp( attr, "color" )==0 ) strcpy( color, val );
	else if( stricmp( attr, "outline" )==0 ) strcpy( outline, lineval );
	else if( stricmp( attr, "barwidth" )==0 ) {
		barwidth = atof( val );
		if( PLS.usingcm ) barwidth /= 2.54;
		}
	else if( strnicmp( attr, "stackfield", 10 )==0 ) {
		int ix;
		char fname[50];
		/* if( strcmp( val, "*" )==0 || strcmp( val, "all" )==0 ) strcpy( lineval, stacklist ); */
		for( ix = 0, j = 0; j < MAXSTACKFIELDS; j++ ) {
                        if( GL_smember( val, "* all" )) strcpy( fname, GL_getok( stacklist, &ix ) );
                        else strcpy( fname, GL_getok( lineval, &ix ) );
			if( fname[0] == '\0' ) break;
			stackf[j] = fref( fname );
			}
		nstackf = j;
		}
	else if( stricmp( attr, "cluster" )==0 ) {
		nt = sscanf( lineval, "%d %s %d", &clusterpos, buf, &ncluster );
		if( nt == 2 ) sscanf( lineval, "%d %d", &clusterpos, &ncluster );
		}
	else if( stricmp( attr, "clustersep" )==0 ) {
		clustsep = atof( val );
		if( PLS.usingcm ) clustsep /= 2.54;
		}
	else if( stricmp( attr, "crossover" )==0 ) strcpy( crossover, val );
	else if( strnicmp( attr, "constantlen", 11 )==0 ) strcpy( constantlen, val );
	else if( strnicmp( attr, "constantloc", 11 )==0 ) strcpy( constantloc, val );
	else if( strnicmp( attr, "segmentfield", 12 )==0 ) {
		char fnames[2][50];
		/* nt = sscanf( lineval, "%d %d", &stackf[0], &stopfld ); */
		nt = sscanf( lineval, "%s %s", fnames[0], fnames[1] );
		
		if( nt == 1 ) stopfld = fref( fnames[0] );
		
		if( nt == 2 ) {
			nstackf = 1;
			stackf[0] = fref( fnames[0] );
			stopfld = fref( fnames[1] );
			}
		segmentflag = 1;
		}
	else if( strnicmp( attr, "errbarfield", 11 )==0 ) {
		char fname[2][50];
		errbars = 1;
		nt = sscanf( lineval, "%s %s", fname[0], fname[1] );
		if( strcmp( fname[0], "0" )==0 ) {  /* allow oneway error bars   scg 4/11/04 */
			if( nt == 1 ) { Eerr( 3845, "incorrect errbarfield spec", "" ); errbars = 0; }
			else errlofld = 0; 
			}
		else errlofld = fref( fname[0] ); 
		if( nt == 1 ) reflecterr = 1; /* use -val for lo, +val for hi */
		else 	{
			reflecterr = 0;
			errhifld = fref( fname[1] );
			}
		/* taillen = 0.2; */ /* default */ /* can't set taillen here- 
						messes up cloning of tails - scg 12/21/99 */
		/* barwidth = 0.001; */ /* force lines */
		}
	else if( strnicmp( attr, "errbarmult", 10 )==0 ) {
		errbarmult = atof( val );
		}
	else if( stricmp( attr, "tails" )==0 ) {
		taillen = atof( val );
		taillengiven = 1;
		if( PLS.usingcm ) taillen /= 2.54;
		}
	else if( stricmp( attr, "showvalues" )==0 ) {
		if( strnicmp( val, YESANS, 1 )==0 ) showvals = 1;
		else showvals = 0;
		}
	else if( stricmp( attr, "numbersformat" )==0 ) strcpy( numstrfmt, val );
	else if( stricmp( attr, "labelzerovalue" )==0 ) {
		if( strnicmp( val, YESANS, 1 )==0 ) label0val = 1;
		else label0val = 0;
		}
	else if( stricmp( attr, "minlabel" )==0 ) minlabel = atof( val );
	else if( stricmp( attr, "truncate" )==0 ) {
		if( strnicmp( val, YESANS, 1 )==0 ) trunc = 1;
		else trunc = 0;
		}
	else if( stricmp( attr, "labeldetails" )==0 ) strcpy( labeldetails, lineval );
	else if( stricmp( attr, "backbox" )==0 ) strcpy( backbox, val );
	else if( stricmp( attr, "labelfield" )==0 ) labelfld = fref( val ) - 1;
	else if( stricmp( attr, "labelword" )==0 ) strcpy( labelword, lineval );
	else if( stricmp( attr, "thinbarline" )==0 ) strcpy( thinbarline, lineval );
	else if( stricmp( attr, "leftticfield" )==0 ) leftticfld = fref( val ) -1;
	else if( stricmp( attr, "rightticfield" )==0 ) rightticfld = fref( val ) -1;
	else if( stricmp( attr, "midticfield" )==0 ) midticfld = fref( val ) -1;
	else if( stricmp( attr, "ticlen" )==0 ) ticlen = atof( val );
	else if( stricmp( attr, "reverseorder" )==0 ) {
		if( strnicmp( val, YESANS, 1 )==0 ) { reversespecified = 1; reverseorder = 1; }
		else reverseorder = 0;
		}
	else if( stricmp( attr, "hidezerobars" )==0 ) {
		if( strnicmp( val, YESANS, 1 )==0 ) hidezerobars = 1;
		else hidezerobars = 0;
		}

	else if( stricmp( attr, "barsrange" )==0 ) sscanf( lineval, "%s %s", rangelo, rangehi );
	else if( stricmp( attr, "colorlist" )==0 ) strcpy( colorlist, lineval );
	else if( stricmp( attr, "colorfield" )==0 ) colorfield = fref( val ) -1;
	else if( stricmp( attr, "exactcolorfield" )==0 ) exactcolorfield = fref( val ) -1;

	else if( stricmp( attr, "longwayslabel" )==0 ) {
		if( strnicmp( val, YESANS, 1 )==0 ) lwl = 1;
		else lwl = 0;
		}
	else if( stricmp( attr, "labelmustfit" )==0 ) {
		if( stricmp( val, "omit" )==0 ) lwl_mustfit = 1;
		else if( stricmp( val, "truncate" )==0 ) lwl_mustfit = 2;
		else lwl_mustfit = 0;
		}

	else if( stricmp( attr, "labelmaxlen" )==0 ) labelmaxlen = atoi( val );
	else if( strnicmp( attr, "labelrot", 8 )==0 ) labelrot = atoi( val );
	else if( stricmp( attr, "select" )==0 ) strcpy( selectex, lineval );
	else if( stricmp( attr, "labelselect" )==0 ) strcpy( labelselectex, lineval );
	else if( stricmp( attr, "legendlabel" )==0 ) strcpy( legendlabel, lineval );
	else if( stricmp( attr, "labelpos" )==0 ) strcpy( lblpos, val );
	else if( stricmp( attr, "barwidthfield" )==0 ) barwidthfield = fref( val ) -1;
	else if( stricmp( attr, "overlapcolor" )==0 ) strcpy( overlapcolor, val );
	else if( stricmp( attr, "clickmapurl" )==0 ) {
		if( PLS.clickmap ) { strcpy( mapurl, val ); clickmap_on = 1; }
		}
	else if( stricmp( attr, "clickmaplabel" )==0 ) {
		if( PLS.clickmap ) { strcpy( maplabel, lineval ); clickmap_on = 1; }
		}
	else if( stricmp( attr, "clickmaplabeltext" )==0 ) {
		if( PLS.clickmap ) { getmultiline( "clickmaplabeltext", lineval, MAXTT, maplabel ); clickmap_on = 1; }
		}
	else Eerr( 1, "attribute not recognized", attr );
	}


/* -------------------------- */
/* overrides and degenerate cases */
/* -------------------------- */
if( axis == 'y' ) baseax = 'x';
else baseax = 'y';

if( Nrecords < 1 ) return( Eerr( 17, "No data has been read yet w/ proc getdata", "" ) );
if( !scalebeenset() )
         return( Eerr( 51, "No scaled plotting area has been defined yet w/ proc areadef", "" ) );



if( locfield > Nfields ) return( Eerr( 52, "locfield out of range", "" ) );
if( lenfield > Nfields ) return( Eerr( 52, "lenfield out of range", "" ) );
if( lenfield < 0 && !segmentflag && constantlen[0] == '\0' ) 
	return( Eerr( 2805, "Either lenfield, segmentfields, or constantlen must be defined", ""));

if( stopfld >= 0 ) {
	if( nstackf > 1 )  /* but 1 is ok */
		{ Eerr( 2984, "stackfield may not be used with segments", "" ); nstackf=0; }
	}

if( labelword[0] != '\0' ) showvals = 1;
if( showvals && labelword[0] == '\0' ) strcpy( labelword, "@N" );

if( locfield == lenfield && locfield >= 0 ) Eerr( 2479, "Warning, locfield same as lenfield", "" );

for( i = 0; i < nstackf; i++ ) {
	if( (lenfield+1) == stackf[i] ) Eerr( 2479, "Warning, lenfield same as a stackfield", "" );
	if( (locfield+1) == stackf[i] ) Eerr( 2479, "Warning, locfield same as a stackfield", "" );
	}

if( axis == 'x' && !reversespecified ) reverseorder = 1;

if( strnicmp( legendlabel, "#usefname", 9 )==0 ) getfname( lenfield+1, legendlabel );

if( segmentflag ) lwl = 1;  /* when doing floating segment bars, default to use labels that are centered within the bar - scg 5/8/06 */


/* -------------------------- */
/* now do the plotting work.. */
/* -------------------------- */
if( baseax == 'y' ) Eflip = 1;

if( rangelo[0] != '\0' ) rlo = Econv( baseax, rangelo );
else rlo = Elimit( baseax, 'l', 's' );
if( rangehi[0] != '\0' ) rhi = Econv( baseax, rangehi );
else rhi = Elimit( baseax, 'h', 's' );

/* maintain stacklist */
if( clusterpos != prevclust ) {
	PL_resetstacklist();
	if( !segmentflag ) nstackf = 0; /* needed for current bar */
	}
prevclust = clusterpos;
sprintf( buf, "%d ", lenfield+1 );
strcat( stacklist, buf );


if( barwidth > 0.0 ) halfw = barwidth * 0.5;
else	{
	if( ncluster <= 1 ) halfw = ( Ea( X, 1.0 ) - Ea( X, 0.0 ) ) * 0.4;
	else if( ncluster > 1 ) halfw = (( Ea( X, 1.0 ) - Ea( X, 0.0 ) ) * 0.4)/ (double)ncluster;
	if( halfw > 0.5 ) halfw = 0.1; /* sanity  - to prevent huge bars */
	}



if( outline[0] == '\0' || strnicmp( outline, "no", 2 )==0 ) do_outline = 0;
else do_outline = 1;


if( crossover[0] == '\0' ) cr = Elimit( axis, 'l', 's' );
else cr = Econv( axis, crossover );
if( cr < Elimit( axis, 'l', 's' )) cr = Elimit( axis, 'l', 's' );  /* be sure crossover is in range .. added scg 8/25/04 */
if( cr > Elimit( axis, 'h', 's' )) cr = Elimit( axis, 'h', 's' );  /* be sure crossover is in range .. added scg 8/25/04 */

/* parse colorlist if any */
if( colorlist[0] != '\0' ) {
	int ix, ixx; char tok[40];
	/* initialize all pointers to default color.. */
	strcpy( dcolor, color );
	for( i = 0; i < MAXCLP; i++ ) colorlp[i] = dcolor;
	ix = 0; ixx = 0;
	i = 0;
	while( 1 ) {
		strcpy( tok, GL_getok( colorlist, &ix ) ); 
		if( tok[0] == '\0' ) break;
		if( atoi( tok ) > 0 && atoi( tok ) < MAXCLP ) {
			colorlp[ atoi(tok) - 1 ] = &colorlist[ix];
			GL_getok( colorlist, &ix );
			}
		else if( i < MAXCLP ) {
			colorlp[ i ] = &colorlist[ ixx ];
			i++;
			}
		ixx = ix;
		}
	}

linedet( "outline", outline, 0.5 );
/* "draw" something so that line color is persistent - related to recent color chg opt - scg 10/21/04 */
PLG_pcodeboundingbox( 0 );
Emovu( 0.0, 0.0 ); Elinu( 0.0, 0.0 );   /* CC-DOT */
PLG_pcodeboundingbox( 1 );

if( thinbarline[0] != '\0' && strnicmp( thinbarline, "no", 2 ) != 0 ) 
	linedet( "thinbarline", thinbarline, 0.3 );

if( errbars && !taillengiven ) taillen = 0.2; /* set a default taillen for errorbars */


/* ---------------- */
/* loop through current data set, draw bars.. */
/* ---------------- */
ibar = -1;
prev_y = NEGHUGE; prev_y0 = NEGHUGE;
for( irow = 0; irow < Nrecords; irow++ ) {


	if( selectex[0] != '\0' ) { /* process against selection condition if any.. */
                stat = do_select( selectex, irow, &result );
                if( stat != 0 ) { Eerr( stat, "Select error", selectex ); continue; }
                if( result == 0 ) continue; /* reject */
                }
	ibar++;


	if( lenfield >= 0 ) {
		y = fda( irow, lenfield, axis );
		if( Econv_error() ) { conv_msg( irow, lenfield, "lenfield" ); continue; }
		}
	else if( constantlen[0] != '\0' ) y = Econv( axis, constantlen );

	if( constantloc[0] != '\0' ) x = Econv( baseax, constantloc );
	else if( locfield < 0 ) {
		if( reverseorder ) x = (Elimit( baseax, 'h', 's' ) - 1.0) - (double)ibar;
		else x = (double)ibar+1;
		if( x > Elimit( baseax, 'h', 's' ) ) {
			fprintf( PLS.errfp, "bars warning, skipping bar# %d, loc is out of range\n", ibar+1 );
			continue; /* out of range hi */
			}
		}	
	else 	{
		x = fda( irow, locfield, baseax );
		if( Econv_error() ) { conv_msg( irow, locfield, "locfield" ); continue; }
		if( x < rlo ) continue;  /* out of range low */
		if( x > rhi ) continue;  /* out of range high */
		}

	/* y0 = Elimit( axis, 'l', 's' ); */
	if( nstackf > 0 && !segmentflag ) y0 = 0.0; /* added scg 11/27/01 */
	else y0 = cr;


	/* if barwidthfield was specified, set bar width now.. */
	if( barwidthfield >= 0 ) {
		double bw;
		bw = fda( irow, barwidthfield, axis );
		halfw = (Ea( X, bw ) - Ea( X, 0.0 )) * 0.5;
		if( Econv_error() ) { 
			conv_msg( irow, barwidthfield, "barwidthfield" ); 
			halfw = 0.05; 
			}
		}

	if( nstackf > 0 ) /* stacking */
		for( j = 0; j < nstackf; j++ ) {
			/* BDB: here is where scott barrett's bug seems to occur.. */
			/* Digital UNIX 4.0g on a Compaq ES-40 Server.  debugger indicates abend in proc_bars.c */
			fval = fda( irow, stackf[j]-1, axis );
			if( segmentflag ) fval -= cr; /* normalize? */
			y0 += fval;
			if( !segmentflag ) y += fval; /* condition added scg 9/26/03 .. because y is undefined at this point */
			}


	if( ncluster > 1 ) {   /* clustering - move sideways a little.. */
		xleft = Ea( X, x ) - ((halfw+clustsep) * (double)(ncluster));
		xleft += clustsep;
		if( baseax == Y ) xleft += ((halfw+clustsep) * (ncluster-clusterpos)*2.0);
		else xleft += ((halfw+clustsep) * (clusterpos-1)*2.0);
		xright = xleft + (halfw*2.0);
		}
	else	{
		xleft = Ea( X, x) - halfw;
		xright = Ea( X, x) + halfw;
		}

	y_endin = y0_endin = 1;

	if( segmentflag ) { /* set y from stopfld; bar start is done via stacking, above */
		y = fda( irow, stopfld-1, axis );
		}
	if( errbars ) { /* set y and y0 as offsets from original y */
		double eblen;
		if( errlofld == 0 ) { y0 = y; y0_endin = 0; }
		else 	{
			eblen = (fda( irow, errlofld-1, axis ) * errbarmult);
			if( y < cr ) y0 = y + eblen;
			else y0 = y - eblen;
			}
		if( reflecterr ) eblen = fda( irow, errlofld-1, axis ) * errbarmult;
		else eblen = fda( irow, errhifld-1, axis ) * errbarmult;
		if( y < cr ) y -= eblen; /* downward/leftward bar.. reverse direction */
		else y += eblen;      /* normal */
		}

	/* catch units errors for stopfld and errflds.. */
	if( segmentflag && Econv_error() ) {conv_msg( irow, stopfld, "segmentfields" );continue;}
	if( errbars && Econv_error() ){conv_msg( irow, stopfld, "errbarfields" );continue;} 

	/* null-length bars.. skip out.. scg 11/29/00 */
	if( hidezerobars && y == y0 ) continue;

	/* truncate to plotting area.. scg 5/12/99 */
	if( trunc ) {

		if( y0 <= Elimit( axis, 'l', 's' ) && y < Elimit( axis, 'l', 's' ) ) {
			fprintf( PLS.errfp, "warning, bar completely out of %c plotting area\n", axis );
			continue; /* skip entirely */
			}
		if( y0 >= Elimit( axis, 'h', 's' ) && y > Elimit( axis, 'h', 's' ) ) {
			fprintf( PLS.errfp, "warning, bar completely out of %c plotting area\n", axis );
			continue; /* skip entirely */
			}

		if( !Ef_inr( axis, y0 ) ) {
			if( y0 < y ) y0 = Elimit( axis, 'l', 's' );
			else y0 = Elimit( axis, 'h', 's' );
			y0_endin = 0;
			}
		if( !Ef_inr( axis, y ) ) {
			if( y0 < y ) y = Elimit( axis, 'h', 's' );
			else y = Elimit( axis, 'l', 's' );
			y_endin = 0;
			}
		}

	/* if colorfield used, get color.. */
	if( colorfield >= 0 ) {
		strcpy( color, "" );
		PL_get_legent( da( irow, colorfield ), val, NULL, NULL );
		sscanf( val, "%s", color ); /* strip off any space */
		}
	else if( exactcolorfield >= 0 ) strcpy( color, da( irow, exactcolorfield ));

	/* if colorlist used, get color.. */
	if( colorlist[0] != '\0' && ibar < MAXCLP ) sscanf( colorlp[ibar], "%s", color ); 

	/* now do the bar.. */

	/* allow @field substitutions into url */
	if( clickmap_on ) {
		do_subst( expurl, mapurl, irow, URL_ENCODED );
		do_subst( explabel, maplabel, irow, NORMAL );
		}


	/* if thinbarline specified, or if doing error bars, render bar as a line */
	if( ( thinbarline[0] != '\0' && strnicmp( thinbarline, "no", 2 )!= 0 ) || errbars ) { 
		Emov( xleft+halfw, Ea( Y, y0 ) ); 
		Elin( xleft+halfw, Ea( Y, y ) ); 
		}

  	/* otherwise, render bar as a rectangle */
  	else 	{
		Ecblock( xleft, Ea( Y, y0 ), xright, Ea( Y, y ), color, 0 ); 

		if( overlapcolor != "" && segmentflag ) {   /* not documented in 2.33 - color change glitches on GD */
			/* See if segments overlap.. if so show the overlap region. Do this before outline.  added scg 5/11/06 */
			if( y0 < prev_y ) Ecblock( xleft, Ea( Y, y0 ), xright, Ea( Y, prev_y ), overlapcolor, do_outline );
			}

		if( do_outline ) {   /* render bar outline.. but no outline where truncated.. added scg 5/11/06 */
			Emov( xleft, Ea( Y, y0 ) );
			Elin( xleft, Ea( Y, y ) );
			if( y_endin ) Elin( xright, Ea( Y, y ) );
			else Emov( xright, Ea( Y, y ) );
			Elin( xright, Ea( Y, y0 ) );
			if( y0_endin ) Elin( xleft, Ea( Y, y0 ) );
			}

#ifdef HOLD	
		/* if bar was truncated do the "fadeout" effect.. */
		/* on hold for now.. needs some adjustment, and undesired interaction with outline color scg 5/17/06 */
		if( !y_endin ){	
			Ecblock( xleft, Ea( Y, y)+0.03, xright, Ea( Y, y)+0.07, color, 0 );
			Ecblock( xleft, Ea( Y, y)+0.09, xright, Ea( Y, y)+0.11, color, 0 );
			}
		if( !y0_endin ) {
			Ecblock( xleft, Ea( Y, y0)-0.07, xright, Ea( Y, y0)-0.03, color, 0 );
			Ecblock( xleft, Ea( Y, y0)-0.11, xright, Ea( Y, y0)-0.09, color, 0 );
			}
#endif

		if( clickmap_on ) {
			if( Eflip ) clickmap_entry( 'r', expurl, 0, Ea( Y, y0 ), xleft, Ea( Y, y ), xright, 0, 0, explabel );
			else clickmap_entry( 'r', expurl, 0, xleft, Ea( Y, y0 ), xright, Ea( Y, y ), 0, 0, explabel );
			}

		}
  
  	/* do tics if requested */  /* don't do if trunc && outside area - scg 11/21/00 */ 
	/* Bug fix - ticks not being drawn at bars when truncating was not switched on.
         * Supplied by Michael Rausch ([email protected]) date: 04 Jun 2001 */
  	if( leftticfld >= 0 ) { 
  		ytic = fda( irow, leftticfld, axis );
  		if( !Econv_error() && ( !trunc || Ef_inr( axis, ytic ) ) ) { 
  			Emov( (xleft+halfw), Ea(Y,ytic) ); 
  			Elin( (xleft+halfw)-ticlen, Ea(Y,ytic) ); 
  			}
  		}
  	if( rightticfld >= 0 ) { 
  		ytic = fda( irow, rightticfld, axis );
  		if( !Econv_error() && ( !trunc || Ef_inr( axis, ytic ) ) ) {
  			Emov( (xleft+halfw), Ea(Y,ytic) ); 
  			Elin( (xleft+halfw)+ticlen, Ea(Y,ytic) ); 
  			}
  		}
  	if( midticfld >= 0 ) { 
  		ytic = fda( irow, midticfld, axis );
  		if( !Econv_error() && ( !trunc || Ef_inr( axis, ytic ) ) ) { 
  			Emov( (xleft+halfw)-(ticlen/2.0), Ea(Y,ytic) ); 
  			Elin( (xleft+halfw)+(ticlen/2.0), Ea(Y,ytic) ); 
  			}
		}


	/* do tails if requested */
	if( taillen > 0.0 ) {
		double g, h;
		g = xleft + ((xright-xleft)  / 2.0);
		h = taillen / 2.0;
		if( y_endin ) { Emov( g-h, Ea(Y,y) ); Elin( g+h, Ea(Y,y) ); }
		if( y0_endin ) { Emov( g-h, Ea(Y,y0) ); Elin( g+h, Ea(Y,y0) ); }
		}

	prev_y = y; prev_y0 = y0;
	}



/* ---------------- */
/* now add labels if any */
/* ---------------- */

if( showvals || labelfld >= 0 ) { 
	textdet( "labeldetails", labeldetails, &align, &adjx, &adjy, -3, "R", 1.0 );
	if( adjy == 0.0 ) adjy = 0.02; /* so label is a little above end of bar */
	if( align == '?' ) align = 'C';
	ibar = -1;
	for( i = 0; i < Nrecords; i++ ) {


		if( selectex[0] != '\0' ) { /* added 8/23/01 - process against selection condition if any.. */
                	stat = do_select( selectex, i, &result );
                	if( stat != 0 ) { Eerr( stat, "Select error", selectex ); continue; }
                	if( result == 0 ) continue; /* reject */
                	}
		ibar++;

		if( labelselectex[0] != '\0' ) { /* process against label selection condition if any.. added scg 5/11/06 */
                	stat = do_select( labelselectex, i, &result );
                	if( stat != 0 ) { Eerr( stat, "Select error", selectex ); continue; }
                	if( result == 0 ) continue; /* reject */
			}

		if( lenfield >= 0 ) {
			y = fda( i, lenfield, axis );
			if( Econv_error() ) continue; /* don't bother to label bad values */
			if( !label0val && GL_close_to( y, cr, 0.000001 )) continue; /* don't label 0 */
			if( y < minlabel ) continue;   /* suppress labels for small bars , added 5/4/04, thanks to Jessika Feustel */
			}
			
		if( constantloc[0] != '\0' ) x = Econv( baseax, constantloc );
		else if( locfield < 0 ) {
		        if( reverseorder ) x = (Elimit( baseax, 'h', 's' ) - 1.0) - (double)ibar;
			else x = (double)ibar+1;
			}	
		else 	{
			x = fda( i, locfield, baseax );
			if( Econv_error() ) continue; /* don't bother to label bad values - added scg 8/10/05 */
			if( x < rlo ) continue; /* out of range low */
			if( x > rhi ) continue; /* out of range high */
			}


		/* compose label.. */ 
		if( labelfld >= 0 ) strcpy( labelstr, da( i, labelfld ) );
		else 	{
			if( segmentflag ) y = fda( i, stopfld-1, axis ); /* get y now.. scg 9/27/04 */
			strcpy( labelstr, labelword );
			}
		stat = Euprint( buf, axis, y, numstrfmt );
		GL_varsub( labelstr, "@N", buf );


		/* check / truncate length.. */
		if( strlen( labelstr ) > labelmaxlen ) {
			labelstr[ labelmaxlen+2 ] = '\0';
			labelstr[ labelmaxlen+1 ] = '.';
			labelstr[ labelmaxlen ] = '.';
			}

		fval = cr; /* needed in case we want to center long text label along len of bar */
		if( nstackf > 0 ) {   /* stacking affects label placement */
			double ff;
			for( j = 0; j < nstackf; j++ ) {
				ff = fda( i, stackf[j]-1, axis ); 
				if( !segmentflag ) fval += ff;	/* scg 4/28/04 */
				else fval = ff;
				/* fval is used below to center longwise labels */
				if( segmentflag ) y += (ff - cr);  
				else y += ff;	
				}
			}

		if( segmentflag ) {  /* set y from stopfld; bar start is done via stacking, above */
			y = fda( i, stopfld-1, axis );
			if( Econv_error() ) continue;
			}

		if( errbars ) { /* set y and y0 as offsets from original y */
			if( errlofld == 0 ) y0 = y;
			else y0 = y - fda( i, errlofld+1, axis );
			if( reflecterr ) y += fda( i, errlofld-1, axis );
			else y += fda( i, errhifld+1, axis );
			if( Econv_error() ) continue;
			}


		/* truncate to plotting area.. scg 5/12/99 */
		if( trunc ) {

			/* if bar completely out of plotting area, omit  - added scg 8/10/05 */
			if( y < Elimit( axis, 'l', 's' ) ) continue; 

			if( lwl ) {  /* longways labels.. revise bar start & stop so label is properly centered - added scg 5/10/06 */
				if( fval > Elimit( axis, 'h', 's' )) continue;  /* bar completely off hi end.. omit */
				if( y > Elimit( axis, 'h', 's' )) y = Elimit( axis, 'h', 's' ); 
				if( fval < Elimit( axis, 'l', 's' )) fval = Elimit( axis, 'l', 's' ); 
				}
			else if( y > Elimit( axis, 'h', 's' ) ) continue;  /* for regular labels, if top of bar is off, don't show it */
			
			if( !Ef_inr( axis, y ) ) {
				if( y > Elimit( axis, 'h', 's' ) )  y = Elimit( axis, 'h', 's' );
				else laby = y = Elimit( axis, 'l', 's' );
				}
			}

		if( y < cr ) { 
			laby = Ea( Y, y ) + (adjy*(-1.0));
			if( !Eflip ) laby -= Ecurtextheight;
			reverse = 1;
			}
		else 	{
			laby = (Ea( Y, y )+adjy);
			reverse = 0;
			}


		/* if explicit label position given, use it.. */
		if( lblpos[0] != '\0' ) Eposex( lblpos, axis, &laby );


		if( ncluster > 1 ) { /* if clusters, move sideways a little bit.. */
			x = Ea( X, x ) - ((halfw+clustsep) * (double)(ncluster));
			x += clustsep;
		        if( baseax == Y ) x += ((halfw+clustsep) * (ncluster-clusterpos)*2.0);
			else x += ((halfw+clustsep) * (clusterpos-1)*2.0);
			x += halfw;
			if( lwl ) do_lwl( labelstr, x+adjx, Ea(Y,y)+adjy, Ea(Y,fval), align, reverse, lwl_mustfit );
			else do_label( labelstr, x+adjx, laby, align, backbox, reverse );
			}
		else 	{
			if( lwl ) do_lwl( labelstr, Ea(X,x)+adjx, Ea(Y,y)+adjy, Ea(Y,fval), align, reverse, lwl_mustfit );
			else do_label( labelstr, Ea(X,x)+adjx, laby, align, backbox, reverse );
			}
		}
	}



if( legendlabel[0] != '\0' ) {
	if( errbars || ( thinbarline[0] != '\0' && strnicmp( thinbarline, "no", 2 )!= 0) ) 
		PL_add_legent( LEGEND_LINE, legendlabel, "", thinbarline, "", "" );

	else PL_add_legent( LEGEND_COLOR, legendlabel, "", color, "", "" );
	}

if( baseax == 'y' ) Eflip = 0;
return( 0 );
}
Example #24
0
void gf_rtsp_set_response_value(GF_RTSPResponse *rsp, char *Header, char *Value)
{
	char LineBuffer[400], buf[1000], param_name[100], param_val[1000];
	s32 LinePos, Pos, nPos, s_val;
	GF_RTPInfo *info;
	GF_RTSPTransport *trans;
	GF_X_Attribute *x_Att;

	if (!stricmp(Header, "Accept")) rsp->Accept = gf_strdup(Value);
	else if (!stricmp(Header, "Accept-Encoding")) rsp->Accept_Encoding = gf_strdup(Value);
	else if (!stricmp(Header, "Accept-Language")) rsp->Accept_Language = gf_strdup(Value);
	else if (!stricmp(Header, "Allow")) rsp->Allow = gf_strdup(Value);
	else if (!stricmp(Header, "Authorization")) rsp->Authorization = gf_strdup(Value);
	else if (!stricmp(Header, "Bandwidth")) sscanf(Value, "%u", &rsp->Bandwidth);
	else if (!stricmp(Header, "Blocksize")) sscanf(Value, "%u", &rsp->Blocksize);
	else if (!stricmp(Header, "Cache-Control")) rsp->Cache_Control = gf_strdup(Value);
	else if (!stricmp(Header, "Conference")) rsp->Conference = gf_strdup(Value);
	else if (!stricmp(Header, "Connection")) rsp->Connection = gf_strdup(Value);
	else if (!stricmp(Header, "Content-Base")) rsp->Content_Base = gf_strdup(Value);	
	else if (!stricmp(Header, "Content-Encoding")) rsp->Content_Encoding = gf_strdup(Value);	
	else if (!stricmp(Header, "Content-Length")) sscanf(Value, "%u", &rsp->Content_Length);
	else if (!stricmp(Header, "Content-Language")) rsp->Content_Language = gf_strdup(Value);	
	else if (!stricmp(Header, "Content-Location")) rsp->Content_Location = gf_strdup(Value);	
	else if (!stricmp(Header, "Content-Type")) rsp->Content_Type = gf_strdup(Value);	
	else if (!stricmp(Header, "CSeq")) sscanf(Value, "%u", &rsp->CSeq);
	else if (!stricmp(Header, "Date")) rsp->Date = gf_strdup(Value);	
	else if (!stricmp(Header, "Expires")) rsp->Expires = gf_strdup(Value);	
	else if (!stricmp(Header, "From")) rsp->From = gf_strdup(Value);	
	else if (!stricmp(Header, "Host")) rsp->Host = gf_strdup(Value);	
	else if (!stricmp(Header, "If-Match")) rsp->If_Match = gf_strdup(Value);	
	else if (!stricmp(Header, "If-Modified-Since")) rsp->If_Modified_Since = gf_strdup(Value);	
	else if (!stricmp(Header, "Last-Modified")) rsp->Last_Modified = gf_strdup(Value);	
	else if (!stricmp(Header, "Location")) rsp->Location = gf_strdup(Value);	
	else if (!stricmp(Header, "Proxy-Authenticate")) rsp->Proxy_Authenticate = gf_strdup(Value);	
	else if (!stricmp(Header, "Proxy-Require")) rsp->Proxy_Require = gf_strdup(Value);	
	else if (!stricmp(Header, "Public")) rsp->Public = gf_strdup(Value);	
	else if (!stricmp(Header, "Referer")) rsp->Referer = gf_strdup(Value);	
	else if (!stricmp(Header, "Require")) rsp->Require = gf_strdup(Value);	
	else if (!stricmp(Header, "Retry-After")) rsp->Retry_After = gf_strdup(Value);	
	else if (!stricmp(Header, "Scale")) sscanf(Value, "%lf", &rsp->Scale);
	else if (!stricmp(Header, "Server")) rsp->Server = gf_strdup(Value);	
	else if (!stricmp(Header, "Speed")) sscanf(Value, "%lf", &rsp->Speed);
	else if (!stricmp(Header, "Timestamp")) rsp->Timestamp = gf_strdup(Value);	
	else if (!stricmp(Header, "Unsupported")) rsp->Unsupported = gf_strdup(Value);	
	else if (!stricmp(Header, "User-Agent")) rsp->User_Agent = gf_strdup(Value);	
	else if (!stricmp(Header, "Vary")) rsp->Vary = gf_strdup(Value);	
	else if (!stricmp(Header, "Via")) rsp->Vary = gf_strdup(Value);	
	else if (!stricmp(Header, "WWW_Authenticate")) rsp->Vary = gf_strdup(Value);	
	else if (!stricmp(Header, "Transport")) {
		LinePos = 0;
		while (1) {
			LinePos = gf_token_get(Value, LinePos, "\r\n", LineBuffer, 400);
			if (LinePos <= 0) return;
			trans = gf_rtsp_transport_parse(Value);
			if (trans) gf_list_add(rsp->Transports, trans);
		}
	}
	//Session
	else if (!stricmp(Header, "Session")) {
		LinePos = gf_token_get(Value, 0, ";\r\n", LineBuffer, 400);
		rsp->Session = gf_strdup(LineBuffer);
		//get timeout if any
		if (Value[LinePos] == ';') {
			LinePos += 1;
			LinePos = gf_token_get(Value, LinePos, ";\r\n", LineBuffer, 400);
			//default
			rsp->SessionTimeOut = 60;
			sscanf(LineBuffer, "timeout=%u", &rsp->SessionTimeOut);
		}
	}

	//Range
	else if (!stricmp(Header, "Range")) rsp->Range = gf_rtsp_range_parse(Value);
	//RTP-Info
	else if (!stricmp(Header, "RTP-Info")) {
		LinePos = 0;
		while (1) {
			LinePos = gf_token_get(Value, LinePos, ",\r\n", LineBuffer, 400);
			if (LinePos <= 0) return;

			GF_SAFEALLOC(info, GF_RTPInfo);
			Pos = 0;
			while (1) {	
				Pos = gf_token_get(LineBuffer, Pos, " ;", buf, 1000);
				if (Pos <= 0) break;
				if (strstr(buf, "=")) {
					nPos = gf_token_get(buf, 0, "=", param_name, 100);
					nPos += 1;
					nPos = gf_token_get(buf, nPos, "", param_val, 1000);
				} else {
					strcpy(param_name, buf);
				}
				if (!stricmp(param_name, "url")) info->url = gf_strdup(param_val);
				else if (!stricmp(param_name, "seq")) sscanf(param_val, "%u", &info->seq);
				else if (!stricmp(param_name, "rtptime")) {
					sscanf(param_val, "%i", &s_val);
					info->rtp_time = (s_val>0) ? s_val : 0;
				}
				else if (!stricmp(param_name, "ssrc")) {
					sscanf(param_val, "%i", &s_val);
					info->ssrc = (s_val>0) ? s_val : 0;
				}
			}
			gf_list_add(rsp->RTP_Infos, info);
		}
	}
	//check for extended attributes
	else if (!strnicmp(Header, "x-", 2)) {
		x_Att = (GF_X_Attribute*)gf_malloc(sizeof(GF_X_Attribute));
		x_Att->Name = gf_strdup(Header+2);
		x_Att->Value = NULL;
		if (Value && strlen(Value)) x_Att->Value = gf_strdup(Value);
		gf_list_add(rsp->Xtensions, x_Att);
	}
	//unknown field - skip it
}
Example #25
0
void    scr_do( void )
{
    ifcb    *   cb = input_cbs->if_cb;
    condcode    cc;

    scan_err = false;
    garginit();                         // find end of control word
    cc = getarg();

    cb->if_flags[cb->if_level].ifcwdo = false;
    if( cc == omit || !strnicmp( tok_start, "begin", 5 )) {

        if( !(cb->if_flags[cb->if_level].ifthen
              || cb->if_flags[cb->if_level].ifelse)
            || cb->if_flags[cb->if_level].ifdo ) {

            scan_err = true;
            g_err( err_if_do );
            g_info_inp_pos();
            show_ifcb( "dobegin", cb );
            show_include_stack();
            err_count++;
            return;
        }
        cb->if_flags[cb->if_level].ifdo = true;
        if( input_cbs->fmflags & II_research && GlobalFlags.firstpass ) {
            show_ifcb( "dobegin", cb );
        }
        scan_restart = scan_stop;
        return;
    } else {
        if( !strnicmp( tok_start, "end", 3 )) {
            if( input_cbs->fmflags & II_research && GlobalFlags.firstpass ) {
                show_ifcb( "doend", cb );
            }
            do {                            // loop for last active .do begin

                if( cb->if_flags[cb->if_level].ifdo ) {

                    cb->if_flags[cb->if_level].ifdo = false;
                    if( input_cbs->fmflags & II_research &&
                        GlobalFlags.firstpass ) {
                        show_ifcb( "doend", cb );
                    }
                    scan_restart = scan_stop;
                    return;
                }
                if( cb->if_flags[cb->if_level].ifthen
                    || cb->if_flags[cb->if_level].ifelse
                    || !(cb->if_flags[cb->if_level].iftrue
                         || cb->if_flags[cb->if_level].iffalse) ) {

                    scan_err = true;
                    g_err( err_if_do_end );
                    g_info_inp_pos();
                    show_ifcb( "doend", cb );
                    show_include_stack();
                    err_count++;
                    return;
                }

            } while( cb->if_level-- > 0 );
#if 0
            if( input_cbs->fmflags & II_research && GlobalFlags.firstpass ) {
                out_msg( "\t.do end Level %d\n"
                         "\t.ifcb iftrue %d, iffalse %d\n",
                         cb->if_level,
                         cb->if_flags[cb->if_level].iftrue,
                         cb->if_flags[cb->if_level].iffalse );
            }
#endif
        } else {
            scan_err = true;
            g_err( err_if_do_fun );
            g_info_inp_pos();
            show_include_stack();
            err_count++;
            return;
        }
    }
    if( input_cbs->fmflags & II_research && GlobalFlags.firstpass ) {
        show_ifcb( "do xx", cb );
    }
    scan_restart = scan_stop;
    return;
}
const char *ShellOpenPlugin::consoleCallback(CMDConsole* /**/,
        int         id,
        int         argc,
        const char* argv[])
{
    switch(id)
    {
#ifdef DEBUG
    case ShellOpen: {
        if ((argc == 2) || (argc == 3)) {
            ShellExecute(NULL,            // Parent Window
                         "open",
                         argv[1],
                         (argc == 3) ? argv[2] : NULL,
                         NULL,
                         SW_SHOWNORMAL);
        } else {
            console->printf("shellOpen <filename>" );
            break;
        }
        return "True";
    }
    case ShellOpenAndGoWin: {
        if ((argc == 4) || (argc == 3))
        {
            SimCanvas *sc = dynamic_cast<SimCanvas *>( manager->findObject(argv[1]) );
            if (sc)
            {
                sc->setFullScreen(false);
                ShellExecute(NULL,            // Parent Window
                             "open",
                             argv[2],
                             (argc == 4) ? argv[3] : NULL,
                             NULL,
                             SW_SHOWNORMAL);
                return "True";
            }
        }
        console->printf("shellOpenAndGoWin <simCanvas> <filename>" );
        break;
    }
#endif
    case HTMLOpen: {
        if (argc == 2) {

            if (strnicmp(argv[1], "http://", 7) != 0) {
                console->printf("HTMLOpen: can only open properly prefixed HTML URLs.");
                break;
            }

            ShellExecute(NULL,            // Parent Window
                         "open",
                         argv[1],
                         NULL,
                         NULL,
                         SW_SHOWNORMAL);
        } else {
            console->printf("HTMLOpen(<filename>);" );
            break;
        }
        return "True";
    }
    case Notepad: {
        if (argc == 2)
        {
            //make sure the statement is a single word, followed by .txt
            const char *tmp = argv[1];
            while (*tmp != '\0')
            {
                if (*tmp == ' ')
                {
                    Console->printf("Notepad: can only open .txt files");
                    break;
                }
                tmp++;
            }
            tmp = strrchr(argv[1], '.');
            if (! tmp)
            {
                Console->printf("Notepad: can only open .txt files");
                break;
            }
            if (stricmp(tmp, ".txt"))
            {
                Console->printf("Notepad: can only open .txt files");
                break;
            }

            //open the file
            ShellExecute(NULL,            // Parent Window
                         "open",
                         argv[1],
                         NULL,
                         NULL,
                         SW_SHOWNORMAL);
        }
        else
        {
            Console->printf("Notepad(<filename>);");
        }
        return "True";
    }
    case HTMLOpenAndGoWin: {
        if (argc == 3)
        {
            if (strnicmp(argv[2], "http://", 7) != 0) {
                console->printf("HTMLOpenAndGoWin: can only open properly prefixed HTML URLs.");
                break;
            }

            SimCanvas *sc = dynamic_cast<SimCanvas *>( manager->findObject(argv[1]) );
            if (sc)
            {
                sc->setFullScreen(false);
                ShellExecute(NULL,            // Parent Window
                             "open",
                             argv[2],
                             NULL,
                             NULL,
                             SW_SHOWNORMAL);
                return "True";
            }
        }
        console->printf("HTMLOpenAndGoWin(<simCanvas>, <filename>);" );
        break;
    }
    }
    return "False";
}
Example #27
0
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE hi, LPSTR lpCmdLine, INT iMain)
{
	// memory leaks detection
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

	// NACTI DLL MODULY Z ADRESARE VE KTEREM JE EXE
	char szExePath[MAX_PATH];
	GetModuleFileName(hInst, szExePath, MAX_PATH);
	for(int i=(int)strlen(szExePath); i > 0; i--)
	{
		if (szExePath[i]=='/' || szExePath[i]=='\\') 
		{
			szExePath[i]=0;
			break;
		}
	}
	// ---------------------------------
	I_Initialize(szExePath); // initialize dll module system
	// ---------------------------------

	// get game module name
	char szGame[64]="main";
	for(unsigned int i=0;i<=strlen(lpCmdLine);i++)
	{
		if (!strnicmp(&lpCmdLine[i], "-game ", 6))
		{
			for(unsigned int ii=i+6;ii<=strlen(lpCmdLine);ii++)
			{
				if (lpCmdLine[i]==' ' || lpCmdLine[i]==0)
				{
					strncpy(szGame, &lpCmdLine[i+6], ii-i);
					break;
				}
			}
			break;
		}
	}
	strcat(szGame, ".game");

	// Load game module
	// ---------------------------------
	I_LoadNewModule(szGame); // load game module
	IP3DGame *pGame = (IP3DGame *)I_GetClass(IP3DGAME_GAME);
	if (!pGame)
	{
		MessageBox(0, "Can't load main game singleton!", "CAN'T LAUNCH GAME!", MB_ICONSTOP | MB_SYSTEMMODAL);
		I_Shutdown(); // shutdown module dll system
		return -1;
	}

	// Run game
	// ---------------------------------
	DWORD nMinPlayed=0;
	if (pGame->InitGame(lpCmdLine, false))
	{
		DWORD tickStart = GetTickCount();
		pGame->RunGame();
		nMinPlayed = (GetTickCount()-tickStart)/60000;
	}

	// post-run actions :-P
	if (!IsDebuggerPresent())
	{
		// get game information
		GameInfo game;
		pGame->GetGameInfo(game);

		// send statistics / show browser window when website is available
		if (game.szWebsite && game.szWebsite[0]!=0)
		{
			// create url
			char url[512];
			sprintf(url, "%s?game=%s&version=%d.%d.%d.%d&time=%d", game.szWebsite, game.szName, game.szVersion[0],
				game.szVersion[1], game.szVersion[2], game.szVersion[3], nMinPlayed);

			// send statistics
			if (game.bSendStats)
			{
				HINTERNET hInet = InternetOpen("P3DStats", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
				HINTERNET hFile = InternetOpenUrl(hInet, url, NULL, 0, INTERNET_FLAG_RELOAD, 0);
				if (hInet && hFile) 
				{
					DWORD size;
					char dummy[16];
					if (InternetReadFile(hFile, dummy, 8, &size))
					InternetCloseHandle(hFile);
					InternetCloseHandle(hInet);
				}
			}
			// open browser window with game information
			if (game.bOpenBrowser)
			{
				ShellExecute(0, "open", url, "", "", 1);
			}
		}
	}

	// Shutdown
	// ----------------------------------
	I_Shutdown(); // shutdown module dll system

	return 0;
}
Example #28
0
bool AuthenticateAcceptedConnection(MPD_Context **pp)
{
    int ret_val;
    MPD_Context *p;

    if (pp == NULL)
	return false;
    p = *pp;

    // generate the challenge string and the encrypted result
    if (!GenAuthenticationStrings(p->pszOut, p->pszCrypt))
    {
	err_printf("AuthenticateAcceptedConnection: failed to generate the authentication strings\n");
	RemoveContext(p);
	*pp = NULL;
	return false;
    }

    // write the challenge string
    if (WriteString(p->sock, p->pszOut) == SOCKET_ERROR)
    {
	err_printf("AuthenticateAcceptedConnection: Writing challenge string failed, error %d\n", WSAGetLastError());
	RemoveContext(p);
	*pp = NULL;
	return false;
    }

    // read the response
    if (!ReadString(p->sock, p->pszIn))
    {
	err_printf("AuthenticateAcceptedConnection: Reading challenge response failed, error %d\n", WSAGetLastError());
	RemoveContext(p);
	*pp = NULL;
	return false;
    }

    // compare the response with the encrypted result and write success or failure
    if (strcmp(p->pszIn, p->pszCrypt) == 0)
	ret_val = WriteString(p->sock, "SUCCESS");
    else
	ret_val = WriteString(p->sock, "FAIL");
    if (ret_val == SOCKET_ERROR)
    {
	err_printf("AuthenticateAcceptedConnection: Writing authentication result failed, error %d\n", WSAGetLastError());
	RemoveContext(p);
	*pp = NULL;
	return false;
    }

    // read the type of connection
    if (!ReadString(p->sock, p->pszIn))
    {
	err_printf("AuthenticateAcceptedConnection: Reading the connection type failed, error %d\n", WSAGetLastError());
	RemoveContext(p);
	*pp = NULL;
	return false;
    }

    // set the state appropriate for the type of connection
    if (stricmp(p->pszIn, "console") == 0)
    {
	dbg_printf("AuthenticateAcceptedConnection: MPD_CONSOLE_SOCKET(%d)\n", p->sock);
	p->nType = MPD_CONSOLE_SOCKET;
	p->nLLState= MPD_READING_CMD;
    }
    else if (strnicmp(p->pszIn, "left ", 5) == 0)
    {
	dbg_printf("AuthenticateAcceptedConnection: MPD_LEFT_SOCKET(%d)\n", p->sock);
	p->nType = MPD_LEFT_SOCKET;
	p->nLLState= MPD_READING_CMD;
	strncpy(p->pszHost, &p->pszIn[5], MAX_HOST_LENGTH);
	p->pszHost[MAX_HOST_LENGTH-1] = '\0';
    }
    else if (strnicmp(p->pszIn, "right ", 6) == 0)
    {
	dbg_printf("AuthenticateAcceptedConnection: MPD_RIGHT_SOCKET(%d)\n", p->sock);
	p->nType = MPD_RIGHT_SOCKET;
	p->nLLState= MPD_READING_CMD;
	strncpy(p->pszHost, &p->pszIn[6], MAX_HOST_LENGTH);
	p->pszHost[MAX_HOST_LENGTH-1] = '\0';
    }
    else
    {
	err_printf("AuthenticateAcceptedConnection: unknown socket type read: '%s'\n", p->pszIn);
	RemoveContext(p);
	*pp = NULL;
	return false;
    }
    p->nState = MPD_IDLE;

    return true;
}
bool CItemStone::r_WriteVal( LPCTSTR pszKey, CGString & sVal, CTextConsole * pSrc )
{
	ADDTOCALLSTACK("CItemStone::r_WriteVal");
	EXC_TRY("WriteVal");
	CChar * pCharSrc = pSrc->GetChar();

	if ( !strnicmp("member.",pszKey,7) )
	{
		LPCTSTR pszCmd = pszKey + 7;

		if ( !strnicmp("COUNT",pszCmd,5) )
		{
			pszCmd = pszCmd + 5;

			int i = 0;
			CStoneMember * pMember = STATIC_CAST <CStoneMember *>(GetHead());

			if ( *pszCmd )
			{
				SKIP_ARGSEP(pszCmd);
				STONEPRIV_TYPE iPriv = static_cast<STONEPRIV_TYPE>(Exp_GetVal(pszCmd));

				for (; pMember != NULL; pMember = pMember->GetNext())
				{
					if ( !pMember->GetLinkUID().IsChar() )
						continue;

					if ( pMember->GetPriv() != iPriv )
						continue;

					i++;
				}
			}
			else
			{
				for (; pMember != NULL; pMember = pMember->GetNext())
				{
					if (!pMember->GetLinkUID().IsChar()) 
						continue;

					i++;
				}
			}

			sVal.FormatVal(i);
			return true;
		}
		int nNumber = Exp_GetVal(pszCmd);
		SKIP_SEPARATORS(pszCmd);

		CStoneMember * pMember = STATIC_CAST <CStoneMember *>(GetHead());
		sVal.FormatVal(0);

		for ( int i = 0 ; pMember != NULL; pMember = pMember->GetNext() )
		{
			if (!pMember->GetLinkUID().IsChar()) 
				continue;
				
			if ( nNumber == i )
			{
				if (!pszCmd[0]) 
					return true;

				return pMember->r_WriteVal(pszCmd, sVal, pSrc);
			}

			i++;
		}

		return true;
	}
	else if ( !strnicmp("memberfromuid.", pszKey, 14) )
	{
		LPCTSTR pszCmd = pszKey + 14;
		sVal.FormatVal(0);

		if ( !pszCmd[0] )
			return true;

		CGrayUID pMemberUid = static_cast<DWORD>(Exp_GetVal(pszCmd));
		SKIP_SEPARATORS(pszCmd);

		CChar * pMemberChar = pMemberUid.CharFind();
		if ( pMemberChar )
		{
			CStoneMember * pMemberGuild = GetMember( pMemberChar );
			if ( pMemberGuild )
			{
				return pMemberGuild->r_WriteVal(pszCmd, sVal, pSrc);
			}
		}

		return true;
	}
	else if ( !strnicmp("guild.",pszKey,6) )
	{
		LPCTSTR pszCmd = pszKey + 6;

		if ( !strnicmp("COUNT",pszCmd,5) )
		{
			pszCmd = pszCmd + 5;

			int i = 0;
			CStoneMember * pMember = STATIC_CAST <CStoneMember *>(GetHead());

			if ( *pszCmd )
			{
				SKIP_ARGSEP(pszCmd);
				int iToCheck = Exp_GetVal(pszCmd);

				for (; pMember != NULL; pMember = pMember->GetNext())
				{
					if ( pMember->GetLinkUID().IsChar() )
						continue;

					if ( ( iToCheck == 1 ) && ( pMember->GetWeDeclared() && !pMember->GetTheyDeclared() ) )
						i++;
					else if ( ( iToCheck == 2 ) && ( !pMember->GetWeDeclared() && pMember->GetTheyDeclared() ) )
						i++;
					else if ( ( iToCheck == 3 ) && ( pMember->GetWeDeclared() && pMember->GetTheyDeclared() ) )
						i++;
				}
			}
			else
			{
				for (; pMember != NULL; pMember = pMember->GetNext())
				{
					if (pMember->GetLinkUID().IsChar()) 
						continue;

					i++;
				}
			}

			sVal.FormatVal(i);
			return true;
		}
		int nNumber = Exp_GetVal(pszCmd);
		SKIP_SEPARATORS(pszCmd);

		CStoneMember * pMember = STATIC_CAST <CStoneMember *>(GetHead());
		sVal.FormatVal(0);

		for ( int i = 0 ; pMember != NULL; pMember = pMember->GetNext() )
		{
			if (pMember->GetLinkUID().IsChar()) 
				continue;
				
			if ( nNumber == i )
			{
				if (!pszCmd[0]) 
					return true;

				return pMember->r_WriteVal(pszCmd, sVal, pSrc);
			}

			i++;
		}

		return true;
	}
	else if ( !strnicmp("guildfromuid.", pszKey, 13) )
	{
		LPCTSTR pszCmd = pszKey + 13;
		sVal.FormatVal(0);

		if ( !pszCmd[0] )
			return true;

		CGrayUID pGuildUid = static_cast<DWORD>(Exp_GetVal(pszCmd));
		SKIP_SEPARATORS(pszCmd);

		CItem * pMemberGuild = pGuildUid.ItemFind();
		if ( pMemberGuild )
		{
			CStoneMember * pGuild = GetMember( pMemberGuild );
			if ( pGuild )
			{
				return pGuild->r_WriteVal(pszCmd, sVal, pSrc);
			}
		}

		return true;
	}
	else if ( !strnicmp(sm_szLoadKeys[STC_CHARTER], pszKey, 7) )
	{
		LPCTSTR pszCmd = pszKey + 7;
		unsigned int i = ATOI(pszCmd);
		if ( i >= COUNTOF(m_sCharter))
			sVal = "";
		else
			sVal = m_sCharter[i];

		return( true );
	}


	STC_TYPE iIndex = (STC_TYPE) FindTableSorted( pszKey, sm_szLoadKeys, COUNTOF( sm_szLoadKeys )-1 );

	switch ( iIndex )
	{
		case STC_ABBREV: // "ABBREV"
			sVal = m_sAbbrev;
			return true;
		case STC_ALIGN:
			sVal.FormatVal( GetAlignType());
			return true;
		case STC_WEBPAGE: // "WEBPAGE"
			sVal = GetWebPageURL();
			return true;
		case STC_AbbreviationToggle:
			{
				CStoneMember * pMember = GetMember(pCharSrc);
				CVarDefCont * pResult = NULL;

				if ( pMember == NULL )
				{
					pResult = g_Exp.m_VarDefs.GetKey("STONECONFIG_VARIOUSNAME_NONMEMBER");
				}
				else
				{
					pResult = pMember->IsAbbrevOn() ? g_Exp.m_VarDefs.GetKey("STONECONFIG_VARIOUSNAME_ABBREVON") :
								g_Exp.m_VarDefs.GetKey("STONECONFIG_VARIOUSNAME_ABBREVOFF");
				}

				sVal = pResult ? pResult->GetValStr() : "";
			}
			return true;
		case STC_AlignType:
			sVal = GetAlignName();
			return true;

		case STC_LoyalTo:
			{
				CStoneMember * pMember = GetMember(pCharSrc);
				CVarDefCont * pResult = NULL;

				if ( pMember == NULL )
				{
					pResult = g_Exp.m_VarDefs.GetKey("STONECONFIG_VARIOUSNAME_NONMEMBER");
				}
				else
				{
					CChar * pLoyalTo = pMember->GetLoyalToUID().CharFind();
					if ((pLoyalTo == NULL) || (pLoyalTo == pCharSrc ))
					{
						pResult = g_Exp.m_VarDefs.GetKey("STONECONFIG_VARIOUSNAME_YOURSELF");
					}
					else
					{
						sVal = pLoyalTo->GetName();
						return true;
					}
				}

				sVal = pResult ? pResult->GetValStr() : "";
			}
			return( true );
	
		case STC_Master:
			{
				CChar * pMaster = GetMaster();
				sVal = (pMaster) ? pMaster->GetName() : g_Exp.m_VarDefs.GetKeyStr("STONECONFIG_VARIOUSNAME_PENDVOTE");
			}
			return( true );
	
		case STC_MasterGenderTitle:
			{
				CChar * pMaster = GetMaster();
				if ( pMaster == NULL )
					sVal = ""; // If no master (vote pending)
				else if ( pMaster->Char_GetDef()->IsFemale())
					sVal = g_Exp.m_VarDefs.GetKeyStr("STONECONFIG_VARIOUSNAME_MASTERGENDERFEMALE");
				else
					sVal = g_Exp.m_VarDefs.GetKeyStr("STONECONFIG_VARIOUSNAME_MASTERGENDERMALE");
			}
			return( true );
	
		case STC_MasterTitle:
			{
				CStoneMember * pMember = GetMasterMember();
				sVal = (pMember) ? pMember->GetTitle() : "";
			}
			return( true );
	
		case STC_MasterUid:
			{
				CChar * pMaster = GetMaster();
				if ( pMaster )
					sVal.FormatHex( (DWORD) pMaster->GetUID() );
				else
					sVal.FormatHex( (DWORD) 0 );
			}
			return( true );
			
		default:
			return( CItem::r_WriteVal( pszKey, sVal, pSrc ));
	}

	EXC_CATCH;

	EXC_DEBUG_START;
	EXC_ADD_KEYRET(pSrc);
	EXC_DEBUG_END;
	return false;
}
Example #30
0
int arcemu_getopt_long_only(int ___argc, char* const* ___argv, const char* __shortopts, const struct arcemu_option* __longopts, int* __longind)
{
	// burlex todo: handle the shortops, at the moment it only works with longopts.

	if(___argc == 1 || arg_counter == ___argc)			// No arguments (apart from filename)
		return -1;

	const char* opt = ___argv[arg_counter];
//	int return_val = 0;

	// if we're not an option, return an error.
	if(strnicmp(opt, "--", 2) != 0)
		return 1;
	else
		opt += 2;


	// parse argument list
	int i = 0;
	for(; __longopts[i].name != 0; ++i)
	{
		if(!strnicmp(__longopts[i].name, opt, strlen(__longopts[i].name)))
		{
			// woot, found a valid argument =)
			char* par = 0;
			if((arg_counter + 1) != ___argc)
			{
				// grab the parameter from the next argument (if its not another argument)
				if(strnicmp(___argv[arg_counter + 1], "--", 2) != 0)
				{
					arg_counter++;		// Trash this next argument, we won't be needing it.
					par = ___argv[arg_counter];
				}
			}

			// increment the argument for next time
			arg_counter++;

			// determine action based on type
			if(__longopts[i].has_arg == arcemu_required_argument)
			{
				if(!par)
					return 1;

				// parameter missing and its a required parameter option
				if(__longopts[i].flag)
				{
					*__longopts[i].flag = atoi(par);
					return 0;
				}
			}

			// store argument in optarg
			if(par)
				strncpy(arcemu_optarg, par, 514);

			if(__longopts[i].flag != 0)
			{
				// this is a variable, we have to set it if this argument is found.
				*__longopts[i].flag = 1;
				return 0;
			}
			else
			{
				if(__longopts[i].val == -1 || par == 0)
					return 1;

				return __longopts[i].val;
			}
			break;
		}
	}

	// return 1 (invalid argument)
	return 1;
}