]> git.mxchange.org Git - flightgear.git/blob - src/Radio/radio.cxx
Write a few more properties:
[flightgear.git] / src / Radio / radio.cxx
1 // radio.cxx -- implementation of FGRadio
2 // Class to manage radio propagation using the ITM model
3 // Written by Adrian Musceac, started August 2011.
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <math.h>
26
27 #include <stdlib.h>
28 #include <deque>
29 #include "radio.hxx"
30 #include <simgear/scene/material/mat.hxx>
31 #include <Scenery/scenery.hxx>
32
33 #define WITH_POINT_TO_POINT 1
34 #include "itm.cpp"
35
36
37 FGRadioTransmission::FGRadioTransmission() {
38         
39         
40         _receiver_sensitivity = -110.0; // typical AM receiver sensitivity seems to be 0.8 microVolt at 12dB SINAD
41         
42         /** AM transmitter power in dBm.
43         *       Typical output powers for ATC ground equipment, VHF-UHF:
44         *       40 dBm - 10 W (ground, clearance)
45         *       44 dBm - 20 W (tower)
46         *       47 dBm - 50 W (center, sectors)
47         *       50 dBm - 100 W (center, sectors)
48         *       53 dBm - 200 W (sectors, on directional arrays)
49         **/
50         _transmitter_power = 43.0;
51         
52         _tx_antenna_height = 2.0; // TX antenna height above ground level
53         
54         _rx_antenna_height = 2.0; // RX antenna height above ground level
55         
56         
57         _rx_antenna_gain = 1.0; // gain expressed in dBi
58         _tx_antenna_gain = 1.0;
59         
60         _rx_line_losses = 2.0;  // to be configured for each station
61         _tx_line_losses = 2.0;
62         
63         _polarization = 1; // default vertical
64         
65         _propagation_model = 2; 
66         
67         _root_node = fgGetNode("sim/radio", true);
68         _terrain_sampling_distance = _root_node->getDoubleValue("sampling-distance", 90.0); // regular SRTM is 90 meters
69 }
70
71 FGRadioTransmission::~FGRadioTransmission() 
72 {
73 }
74
75
76 double FGRadioTransmission::getFrequency(int radio) {
77         double freq = 118.0;
78         switch (radio) {
79                 case 1:
80                         freq = fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
81                         break;
82                 case 2:
83                         freq = fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
84                         break;
85                 default:
86                         freq = fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
87                         
88         }
89         return freq;
90 }
91
92 /*** TODO: receive multiplayer chat message and voice
93 ***/
94 void FGRadioTransmission::receiveChat(SGGeod tx_pos, double freq, string text, int ground_to_air) {
95
96 }
97
98 /*** TODO: receive navaid 
99 ***/
100 double FGRadioTransmission::receiveNav(SGGeod tx_pos, double freq, int transmission_type) {
101         
102         // typical VOR/LOC transmitter power appears to be 200 Watt ~ 53 dBm
103         // vor/loc typical sensitivity between -107 and -101 dBm
104         // glideslope sensitivity between -85 and -81 dBm
105         if ( _propagation_model == 1) {
106                 return LOS_calculate_attenuation(tx_pos, freq, 1);
107         }
108         else if ( _propagation_model == 2) {
109                 return ITM_calculate_attenuation(tx_pos, freq, 1);
110         }
111         
112         return -1;
113
114 }
115
116 /*** Receive ATC radio communication as text
117 ***/
118 void FGRadioTransmission::receiveATC(SGGeod tx_pos, double freq, string text, int ground_to_air) {
119
120         
121         if(ground_to_air == 1) {
122                 _transmitter_power += 6.0;
123                 _tx_antenna_height += 30.0;
124                 _tx_antenna_gain += 3.0; 
125         }
126         
127         
128         double comm1 = getFrequency(1);
129         double comm2 = getFrequency(2);
130         if ( !(fabs(freq - comm1) <= 0.0001) &&  !(fabs(freq - comm2) <= 0.0001) ) {
131                 return;
132         }
133         else {
134         
135                 if ( _propagation_model == 0) {
136                         // skip propagation routines entirely
137                         fgSetString("/sim/messages/atc", text.c_str());
138                 }
139                 else if ( _propagation_model == 1 ) {
140                         // Use free-space, round earth
141                         double signal = LOS_calculate_attenuation(tx_pos, freq, ground_to_air);
142                         if (signal <= 0.0) {
143                                 return;
144                         }
145                         else {
146                                 
147                                 fgSetString("/sim/messages/atc", text.c_str());
148                                 /** write signal strength above threshold to the property tree
149                                 *       to implement a simple S-meter just divide by 3 dB per grade (VHF norm)
150                                 **/
151                                 _root_node->setDoubleValue("station[0]/signal", signal);
152                         }
153                 }
154                 else if ( _propagation_model == 2 ) {
155                         // Use ITM propagation model
156                         double signal = ITM_calculate_attenuation(tx_pos, freq, ground_to_air);
157                         if (signal <= 0.0) {
158                                 return;
159                         }
160                         if ((signal > 0.0) && (signal < 12.0)) {
161                                 /** for low SNR values implement a way to make the conversation
162                                 *       hard to understand but audible
163                                 *       in the real world, the receiver AGC fails to capture the slope
164                                 *       and the signal, due to being amplitude modulated, decreases volume after demodulation
165                                 *       the workaround below is more akin to what would happen on a FM transmission
166                                 *       therefore the correct way would be to work on the volume
167                                 **/
168                                 /*
169                                 string hash_noise = " ";
170                                 int reps = (int) (fabs(floor(signal - 11.0)) * 2);
171                                 int t_size = text.size();
172                                 for (int n = 1; n <= reps; ++n) {
173                                         int pos = rand() % (t_size -1);
174                                         text.replace(pos,1, hash_noise);
175                                 }
176                                 */
177                                 double volume = (fabs(signal - 12.0) / 12);
178                                 double old_volume = fgGetDouble("/sim/sound/voices/voice/volume");
179                                 SG_LOG(SG_GENERAL, SG_BULK, "Usable signal at limit: " << signal);
180                                 //cerr << "Usable signal at limit: " << signal << endl;
181                                 fgSetDouble("/sim/sound/voices/voice/volume", volume);
182                                 fgSetString("/sim/messages/atc", text.c_str());
183                                 _root_node->setDoubleValue("station[0]/signal", signal);
184                                 fgSetDouble("/sim/sound/voices/voice/volume", old_volume);
185                         }
186                         else {
187                                 fgSetString("/sim/messages/atc", text.c_str());
188                                 /** write signal strength above threshold to the property tree
189                                 *       to implement a simple S-meter just divide by 3 dB per grade (VHF norm)
190                                 **/
191                                 _root_node->setDoubleValue("station[0]/signal", signal);
192                         }
193                         
194                 }
195                 
196         }
197         
198 }
199
200 /***  Implement radio attenuation               
201           based on the Longley-Rice propagation model
202 ***/
203 double FGRadioTransmission::ITM_calculate_attenuation(SGGeod pos, double freq, int transmission_type) {
204
205         
206         
207         /** ITM default parameters 
208                 TODO: take them from tile materials (especially for sea)?
209         **/
210         double eps_dielect=15.0;
211         double sgm_conductivity = 0.005;
212         double eno = 301.0;
213         double frq_mhz;
214         if( (freq < 118.0) || (freq > 137.0) )
215                 frq_mhz = 125.0;        // sane value, middle of bandplan
216         else
217                 frq_mhz = freq;
218         int radio_climate = 5;          // continental temperate
219         int pol= _polarization; 
220         double conf = 0.90;     // 90% of situations and time, take into account speed
221         double rel = 0.90;      
222         double dbloss;
223         char strmode[150];
224         int p_mode = 0; // propgation mode selector: 0 LOS, 1 diffraction dominant, 2 troposcatter
225         double horizons[2];
226         int errnum;
227         
228         double clutter_loss = 0.0;      // loss due to vegetation and urban
229         double tx_pow = _transmitter_power;
230         double ant_gain = _rx_antenna_gain + _tx_antenna_gain;
231         double signal = 0.0;
232         
233         
234         double link_budget = tx_pow - _receiver_sensitivity - _rx_line_losses - _tx_line_losses + ant_gain;     
235         double signal_strength = tx_pow - _rx_line_losses - _tx_line_losses + ant_gain; 
236
237         FGScenery * scenery = globals->get_scenery();
238         
239         double own_lat = fgGetDouble("/position/latitude-deg");
240         double own_lon = fgGetDouble("/position/longitude-deg");
241         double own_alt_ft = fgGetDouble("/position/altitude-ft");
242         double own_alt= own_alt_ft * SG_FEET_TO_METER;
243         
244         
245         //cerr << "ITM:: pilot Lat: " << own_lat << ", Lon: " << own_lon << ", Alt: " << own_alt << endl;
246         
247         SGGeod own_pos = SGGeod::fromDegM( own_lon, own_lat, own_alt );
248         SGGeod max_own_pos = SGGeod::fromDegM( own_lon, own_lat, SG_MAX_ELEVATION_M );
249         SGGeoc center = SGGeoc::fromGeod( max_own_pos );
250         SGGeoc own_pos_c = SGGeoc::fromGeod( own_pos );
251         
252         
253         double sender_alt_ft,sender_alt;
254         double transmitter_height=0.0;
255         double receiver_height=0.0;
256         SGGeod sender_pos = pos;
257         
258         sender_alt_ft = sender_pos.getElevationFt();
259         sender_alt = sender_alt_ft * SG_FEET_TO_METER;
260         SGGeod max_sender_pos = SGGeod::fromGeodM( pos, SG_MAX_ELEVATION_M );
261         SGGeoc sender_pos_c = SGGeoc::fromGeod( sender_pos );
262         //cerr << "ITM:: sender Lat: " << parent->getLatitude() << ", Lon: " << parent->getLongitude() << ", Alt: " << sender_alt << endl;
263         
264         double point_distance= _terrain_sampling_distance; 
265         double course = SGGeodesy::courseRad(own_pos_c, sender_pos_c);
266         double distance_m = SGGeodesy::distanceM(own_pos, sender_pos);
267         double probe_distance = 0.0;
268         /** If distance larger than this value (300 km), assume reception imposssible */
269         if (distance_m > 300000)
270                 return -1.0;
271         /** If above 8000 meters, consider LOS mode and calculate free-space att */
272         if (own_alt > 8000) {
273                 dbloss = 20 * log10(distance_m) +20 * log10(frq_mhz) -27.55;
274                 SG_LOG(SG_GENERAL, SG_BULK,
275                         "ITM Free-space mode:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm, free-space attenuation");
276                 //cerr << "ITM Free-space mode:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm, free-space attenuation" << endl;
277                 signal = link_budget - dbloss;
278                 return signal;
279         }
280         
281                 
282         int max_points = (int)floor(distance_m / point_distance);
283         double delta_last = fmod(distance_m, point_distance);
284         
285         deque<double> _elevations;
286         deque<string> materials;
287         
288
289         double elevation_under_pilot = 0.0;
290         if (scenery->get_elevation_m( max_own_pos, elevation_under_pilot, NULL )) {
291                 receiver_height = own_alt - elevation_under_pilot; 
292         }
293
294         double elevation_under_sender = 0.0;
295         if (scenery->get_elevation_m( max_sender_pos, elevation_under_sender, NULL )) {
296                 transmitter_height = sender_alt - elevation_under_sender;
297         }
298         else {
299                 transmitter_height = sender_alt;
300         }
301         
302         
303         transmitter_height += _tx_antenna_height;
304         receiver_height += _rx_antenna_height;
305         
306         
307         SG_LOG(SG_GENERAL, SG_BULK,
308                         "ITM:: RX-height: " << receiver_height << " meters, TX-height: " << transmitter_height << " meters, Distance: " << distance_m << " meters");
309         //cerr << "ITM:: RX-height: " << receiver_height << " meters, TX-height: " << transmitter_height << " meters, Distance: " << distance_m << " meters" << endl;
310         _root_node->setDoubleValue("station[0]/rx-height", receiver_height);
311         _root_node->setDoubleValue("station[0]/tx-height", transmitter_height);
312         _root_node->setDoubleValue("station[0]/distance", distance_m);
313         
314         unsigned int e_size = (deque<unsigned>::size_type)max_points;
315         
316         while (_elevations.size() <= e_size) {
317                 probe_distance += point_distance;
318                 SGGeod probe = SGGeod::fromGeoc(center.advanceRadM( course, probe_distance ));
319                 const SGMaterial *mat = 0;
320                 double elevation_m = 0.0;
321         
322                 if (scenery->get_elevation_m( probe, elevation_m, &mat )) {
323                         if((transmission_type == 3) || (transmission_type == 4)) {
324                                 _elevations.push_back(elevation_m);
325                                 if(mat) {
326                                         const std::vector<string> mat_names = mat->get_names();
327                                         materials.push_back(mat_names[0]);
328                                 }
329                                 else {
330                                         materials.push_back("None");
331                                 }
332                         }
333                         else {
334                                  _elevations.push_front(elevation_m);
335                                  if(mat) {
336                                          const std::vector<string> mat_names = mat->get_names();
337                                          materials.push_front(mat_names[0]);
338                                 }
339                                 else {
340                                         materials.push_front("None");
341                                 }
342                         }
343                 }
344                 else {
345                         if((transmission_type == 3) || (transmission_type == 4)) {
346                                 _elevations.push_back(0.0);
347                                 materials.push_back("None");
348                         }
349                         else {
350                                 _elevations.push_front(0.0);
351                                 materials.push_front("None");
352                         }
353                 }
354         }
355         if((transmission_type == 3) || (transmission_type == 4)) {
356                 _elevations.push_front(elevation_under_pilot);
357                 if (delta_last > (point_distance / 2) )                 // only add last point if it's farther than half point_distance
358                         _elevations.push_back(elevation_under_sender);
359         }
360         else {
361                 _elevations.push_back(elevation_under_pilot);
362                 if (delta_last > (point_distance / 2) )
363                         _elevations.push_front(elevation_under_sender);
364         }
365         
366         
367         double num_points= (double)_elevations.size();
368
369         _elevations.push_front(point_distance);
370         _elevations.push_front(num_points -1);
371         int size = _elevations.size();
372         double itm_elev[size];
373         for(int i=0;i<size;i++) {
374                 itm_elev[i]=_elevations[i];
375                 //cerr << "ITM:: itm_elev: " << _elevations[i] << endl;
376         }
377
378         if((transmission_type == 3) || (transmission_type == 4)) {
379                 // the sender and receiver roles are switched
380                 point_to_point(itm_elev, receiver_height, transmitter_height,
381                         eps_dielect, sgm_conductivity, eno, frq_mhz, radio_climate,
382                         pol, conf, rel, dbloss, strmode, p_mode, horizons, errnum);
383                 if( _root_node->getBoolValue( "use-clutter-attenuation", false ) )
384                         clutterLoss(frq_mhz, distance_m, itm_elev, materials, receiver_height, transmitter_height, p_mode, horizons, clutter_loss);
385         }
386         else {
387                 point_to_point(itm_elev, transmitter_height, receiver_height,
388                         eps_dielect, sgm_conductivity, eno, frq_mhz, radio_climate,
389                         pol, conf, rel, dbloss, strmode, p_mode, horizons, errnum);
390                 if( _root_node->getBoolValue( "use-clutter-attenuation", false ) )
391                         clutterLoss(frq_mhz, distance_m, itm_elev, materials, transmitter_height, receiver_height, p_mode, horizons, clutter_loss);
392         }
393         
394         double pol_loss = 0.0;
395         if (_polarization == 1) {
396                 pol_loss = polarization_loss();
397         }
398         SG_LOG(SG_GENERAL, SG_BULK,
399                         "ITM:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm, " << strmode << ", Error: " << errnum);
400         //cerr << "ITM:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm, " << strmode << ", Error: " << errnum << endl;
401         _root_node->setDoubleValue("station[0]/link-budget", link_budget);
402         _root_node->setDoubleValue("station[0]/terrain-attenuation", dbloss);
403         _root_node->setStringValue("station[0]/prop-mode", strmode);
404         _root_node->setDoubleValue("station[0]/clutter-attenuation", clutter_loss);
405         _root_node->setDoubleValue("station[0]/polarization-attenuation", pol_loss);
406         //cerr << "Clutter loss: " << clutter_loss << endl;
407         //if (errnum == 4)      // if parameters are outside sane values for lrprop, the alternative method is used
408         //      return -1;
409         signal = link_budget - dbloss - clutter_loss + pol_loss;
410         double signal_strength_dbm = signal_strength - dbloss - clutter_loss + pol_loss;
411         double field_strength_uV = dbm_to_microvolt(signal_strength_dbm);
412         _root_node->setDoubleValue("station[0]/signal-dbm", signal_strength_dbm);
413         _root_node->setDoubleValue("station[0]/field-strength-uV", field_strength_uV);
414         return signal;
415
416 }
417
418 /*** Calculate losses due to vegetation and urban clutter (WIP)
419 *        We are only worried about clutter loss, terrain influence 
420 *        on the first Fresnel zone is calculated in the ITM functions
421 ***/
422 void FGRadioTransmission::clutterLoss(double freq, double distance_m, double itm_elev[], deque<string> materials,
423         double transmitter_height, double receiver_height, int p_mode,
424         double horizons[], double &clutter_loss) {
425         
426         distance_m = itm_elev[0] * itm_elev[1]; // only consider elevation points
427         
428         if (p_mode == 0) {      // LOS: take each point and see how clutter height affects first Fresnel zone
429                 int mat = 0;
430                 int j=1; 
431                 for (int k=3;k < (int)(itm_elev[0]) + 2;k++) {
432                         
433                         double clutter_height = 0.0;    // mean clutter height for a certain terrain type
434                         double clutter_density = 0.0;   // percent of reflected wave
435                         get_material_properties(materials[mat], clutter_height, clutter_density);
436                         
437                         double grad = fabs(itm_elev[2] + transmitter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m;
438                         // First Fresnel radius
439                         double frs_rad = 548 * sqrt( (j * itm_elev[1] * (itm_elev[0] - j) * itm_elev[1] / 1000000) / (  distance_m * freq / 1000) );
440                         
441                         //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
442                         
443                         double min_elev = SGMiscd::min(itm_elev[2] + transmitter_height, itm_elev[(int)itm_elev[0] + 2] + receiver_height);
444                         double d1 = j * itm_elev[1];
445                         if ((itm_elev[2] + transmitter_height) > ( itm_elev[(int)itm_elev[0] + 2] + receiver_height) ) {
446                                 d1 = (itm_elev[0] - j) * itm_elev[1];
447                         }
448                         double ray_height = (grad * d1) + min_elev;
449                         
450                         double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
451                         double intrusion = fabs(clearance);
452                         
453                         if (clearance >= 0) {
454                                 // no losses
455                         }
456                         else if (clearance < 0 && (intrusion < clutter_height)) {
457                                 
458                                 clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
459                         }
460                         else if (clearance < 0 && (intrusion > clutter_height)) {
461                                 clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
462                         }
463                         else {
464                                 // no losses
465                         }
466                         j++;
467                         mat++;
468                 }
469                 
470         }
471         else if (p_mode == 1) {         // diffraction
472                 
473                 if (horizons[1] == 0.0) {       //      single horizon: same as above, except pass twice using the highest point
474                         int num_points_1st = (int)floor( horizons[0] * itm_elev[0]/ distance_m ); 
475                         int num_points_2nd = (int)ceil( (distance_m - horizons[0]) * itm_elev[0] / distance_m ); 
476                         //cerr << "Diffraction 1 horizon:: points1: " << num_points_1st << " points2: " << num_points_2nd << endl;
477                         int last = 1;
478                         /** perform the first pass */
479                         int mat = 0;
480                         int j=1; 
481                         for (int k=3;k < num_points_1st + 2;k++) {
482                                 if (num_points_1st < 1)
483                                         break;
484                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
485                                 double clutter_density = 0.0;   // percent of reflected wave
486                                 get_material_properties(materials[mat], clutter_height, clutter_density);
487                                 
488                                 double grad = fabs(itm_elev[2] + transmitter_height - itm_elev[num_points_1st + 2] + clutter_height) / distance_m;
489                                 // First Fresnel radius
490                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_1st - j) * itm_elev[1] / 1000000) / ( num_points_1st * itm_elev[1] * freq / 1000) );
491                                 
492                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
493                                 
494                                 double min_elev = SGMiscd::min(itm_elev[2] + transmitter_height, itm_elev[num_points_1st + 2] + clutter_height);
495                                 double d1 = j * itm_elev[1];
496                                 if ( (itm_elev[2] + transmitter_height) > (itm_elev[num_points_1st + 2] + clutter_height) ) {
497                                         d1 = (num_points_1st - j) * itm_elev[1];
498                                 }
499                                 double ray_height = (grad * d1) + min_elev;
500                                 
501                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
502                                 double intrusion = fabs(clearance);
503                                 
504                                 if (clearance >= 0) {
505                                         // no losses
506                                 }
507                                 else if (clearance < 0 && (intrusion < clutter_height)) {
508                                         
509                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
510                                 }
511                                 else if (clearance < 0 && (intrusion > clutter_height)) {
512                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
513                                 }
514                                 else {
515                                         // no losses
516                                 }
517                                 j++;
518                                 mat++;
519                                 last = k;
520                         }
521                         
522                         /** and the second pass */
523                         mat +=1;
524                         j =1; // first point is diffraction edge, 2nd the RX elevation
525                         for (int k=last+2;k < (int)(itm_elev[0]) + 2;k++) {
526                                 if (num_points_2nd < 1)
527                                         break;
528                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
529                                 double clutter_density = 0.0;   // percent of reflected wave
530                                 get_material_properties(materials[mat], clutter_height, clutter_density);
531                                 
532                                 double grad = fabs(itm_elev[last+1] + clutter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m;
533                                 // First Fresnel radius
534                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_2nd - j) * itm_elev[1] / 1000000) / (  num_points_2nd * itm_elev[1] * freq / 1000) );
535                                 
536                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
537                                 
538                                 double min_elev = SGMiscd::min(itm_elev[last+1] + clutter_height, itm_elev[(int)itm_elev[0] + 2] + receiver_height);
539                                 double d1 = j * itm_elev[1];
540                                 if ( (itm_elev[last+1] + clutter_height) > (itm_elev[(int)itm_elev[0] + 2] + receiver_height) ) { 
541                                         d1 = (num_points_2nd - j) * itm_elev[1];
542                                 }
543                                 double ray_height = (grad * d1) + min_elev;
544                                 
545                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
546                                 double intrusion = fabs(clearance);
547                                 
548                                 if (clearance >= 0) {
549                                         // no losses
550                                 }
551                                 else if (clearance < 0 && (intrusion < clutter_height)) {
552                                         
553                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
554                                 }
555                                 else if (clearance < 0 && (intrusion > clutter_height)) {
556                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
557                                 }
558                                 else {
559                                         // no losses
560                                 }
561                                 j++;
562                                 mat++;
563                         }
564                         
565                 }
566                 else {  // double horizon: same as single horizon, except there are 3 segments
567                         
568                         int num_points_1st = (int)floor( horizons[0] * itm_elev[0] / distance_m ); 
569                         int num_points_2nd = (int)floor(horizons[1] * itm_elev[0] / distance_m ); 
570                         int num_points_3rd = (int)itm_elev[0] - num_points_1st - num_points_2nd; 
571                         //cerr << "Double horizon:: horizon1: " << horizons[0] << " horizon2: " << horizons[1] << " distance: " << distance_m << endl;
572                         //cerr << "Double horizon:: points1: " << num_points_1st << " points2: " << num_points_2nd << " points3: " << num_points_3rd << endl;
573                         int last = 1;
574                         /** perform the first pass */
575                         int mat = 0;
576                         int j=1; // first point is TX elevation, 2nd is obstruction elevation
577                         for (int k=3;k < num_points_1st +2;k++) {
578                                 if (num_points_1st < 1)
579                                         break;
580                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
581                                 double clutter_density = 0.0;   // percent of reflected wave
582                                 get_material_properties(materials[mat], clutter_height, clutter_density);
583                                 
584                                 double grad = fabs(itm_elev[2] + transmitter_height - itm_elev[num_points_1st + 2] + clutter_height) / distance_m;
585                                 // First Fresnel radius
586                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_1st - j) * itm_elev[1] / 1000000) / (  num_points_1st * itm_elev[1] * freq / 1000) );
587                                 
588                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
589                                 
590                                 double min_elev = SGMiscd::min(itm_elev[2] + transmitter_height, itm_elev[num_points_1st + 2] + clutter_height);
591                                 double d1 = j * itm_elev[1];
592                                 if ( (itm_elev[2] + transmitter_height) > (itm_elev[num_points_1st + 2] + clutter_height) ) {
593                                         d1 = (num_points_1st - j) * itm_elev[1];
594                                 }
595                                 double ray_height = (grad * d1) + min_elev;
596                                 
597                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
598                                 double intrusion = fabs(clearance);
599                                 
600                                 if (clearance >= 0) {
601                                         // no losses
602                                 }
603                                 else if (clearance < 0 && (intrusion < clutter_height)) {
604                                         
605                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
606                                 }
607                                 else if (clearance < 0 && (intrusion > clutter_height)) {
608                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
609                                 }
610                                 else {
611                                         // no losses
612                                 }
613                                 j++;
614                                 last = k;
615                         }
616                         mat +=1;
617                         /** and the second pass */
618                         int last2=1;
619                         j =1; // first point is 1st obstruction elevation, 2nd is 2nd obstruction elevation
620                         for (int k=last+2;k < num_points_1st + num_points_2nd +2;k++) {
621                                 if (num_points_2nd < 1)
622                                         break;
623                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
624                                 double clutter_density = 0.0;   // percent of reflected wave
625                                 get_material_properties(materials[mat], clutter_height, clutter_density);
626                                 
627                                 double grad = fabs(itm_elev[last+1] + clutter_height - itm_elev[num_points_1st + num_points_2nd + 2] + clutter_height) / distance_m;
628                                 // First Fresnel radius
629                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_2nd - j) * itm_elev[1] / 1000000) / (  num_points_2nd * itm_elev[1] * freq / 1000) );
630                                 
631                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
632                                 
633                                 double min_elev = SGMiscd::min(itm_elev[last+1] + clutter_height, itm_elev[num_points_1st + num_points_2nd +2] + clutter_height);
634                                 double d1 = j * itm_elev[1];
635                                 if ( (itm_elev[last+1] + clutter_height) > (itm_elev[num_points_1st + num_points_2nd + 2] + clutter_height) ) { 
636                                         d1 = (num_points_2nd - j) * itm_elev[1];
637                                 }
638                                 double ray_height = (grad * d1) + min_elev;
639                                 
640                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
641                                 double intrusion = fabs(clearance);
642                                 
643                                 if (clearance >= 0) {
644                                         // no losses
645                                 }
646                                 else if (clearance < 0 && (intrusion < clutter_height)) {
647                                         
648                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
649                                 }
650                                 else if (clearance < 0 && (intrusion > clutter_height)) {
651                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
652                                 }
653                                 else {
654                                         // no losses
655                                 }
656                                 j++;
657                                 mat++;
658                                 last2 = k;
659                         }
660                         
661                         /** third and final pass */
662                         mat +=1;
663                         j =1; // first point is 2nd obstruction elevation, 3rd is RX elevation
664                         for (int k=last2+2;k < (int)itm_elev[0] + 2;k++) {
665                                 if (num_points_3rd < 1)
666                                         break;
667                                 double clutter_height = 0.0;    // mean clutter height for a certain terrain type
668                                 double clutter_density = 0.0;   // percent of reflected wave
669                                 get_material_properties(materials[mat], clutter_height, clutter_density);
670                                 
671                                 double grad = fabs(itm_elev[last2+1] + clutter_height - itm_elev[(int)itm_elev[0] + 2] + receiver_height) / distance_m;
672                                 // First Fresnel radius
673                                 double frs_rad = 548 * sqrt( (j * itm_elev[1] * (num_points_3rd - j) * itm_elev[1] / 1000000) / (  num_points_3rd * itm_elev[1] * freq / 1000) );
674                                 
675                                 
676                                 //double earth_h = distance_m * (distance_m - j * itm_elev[1]) / ( 1000000 * 12.75 * 1.33 );    // K=4/3
677                                 
678                                 double min_elev = SGMiscd::min(itm_elev[last2+1] + clutter_height, itm_elev[(int)itm_elev[0] + 2] + receiver_height);
679                                 double d1 = j * itm_elev[1];
680                                 if ( (itm_elev[last2+1] + clutter_height) > (itm_elev[(int)itm_elev[0] + 2] + receiver_height) ) { 
681                                         d1 = (num_points_3rd - j) * itm_elev[1];
682                                 }
683                                 double ray_height = (grad * d1) + min_elev;
684                                 
685                                 double clearance = ray_height - (itm_elev[k] + clutter_height) - frs_rad * 8/10;                
686                                 double intrusion = fabs(clearance);
687                                 
688                                 if (clearance >= 0) {
689                                         // no losses
690                                 }
691                                 else if (clearance < 0 && (intrusion < clutter_height)) {
692                                         
693                                         clutter_loss += clutter_density * (intrusion / (frs_rad * 2) ) * (freq/100) * (itm_elev[1]/100);
694                                 }
695                                 else if (clearance < 0 && (intrusion > clutter_height)) {
696                                         clutter_loss += clutter_density * (clutter_height / (frs_rad * 2 ) ) * (freq/100) * (itm_elev[1]/100);
697                                 }
698                                 else {
699                                         // no losses
700                                 }
701                                 j++;
702                                 mat++;
703                                 
704                         }
705                         
706                 }
707         }
708         else if (p_mode == 2) {         //      troposcatter: ignore ground clutter for now...
709                 clutter_loss = 0.0;
710         }
711         
712 }
713
714 /***    Temporary material properties database
715 *               height: median clutter height
716 *               density: radiowave attenuation factor
717 ***/
718 void FGRadioTransmission::get_material_properties(string mat_name, double &height, double &density) {
719         
720         if(mat_name == "Landmass") {
721                 height = 15.0;
722                 density = 0.2;
723         }
724
725         else if(mat_name == "SomeSort") {
726                 height = 15.0;
727                 density = 0.2;
728         }
729
730         else if(mat_name == "Island") {
731                 height = 15.0;
732                 density = 0.2;
733         }
734         else if(mat_name == "Default") {
735                 height = 15.0;
736                 density = 0.2;
737         }
738         else if(mat_name == "EvergreenBroadCover") {
739                 height = 20.0;
740                 density = 0.2;
741         }
742         else if(mat_name == "EvergreenForest") {
743                 height = 20.0;
744                 density = 0.2;
745         }
746         else if(mat_name == "DeciduousBroadCover") {
747                 height = 15.0;
748                 density = 0.3;
749         }
750         else if(mat_name == "DeciduousForest") {
751                 height = 15.0;
752                 density = 0.3;
753         }
754         else if(mat_name == "MixedForestCover") {
755                 height = 20.0;
756                 density = 0.25;
757         }
758         else if(mat_name == "MixedForest") {
759                 height = 15.0;
760                 density = 0.25;
761         }
762         else if(mat_name == "RainForest") {
763                 height = 25.0;
764                 density = 0.55;
765         }
766         else if(mat_name == "EvergreenNeedleCover") {
767                 height = 15.0;
768                 density = 0.2;
769         }
770         else if(mat_name == "WoodedTundraCover") {
771                 height = 5.0;
772                 density = 0.15;
773         }
774         else if(mat_name == "DeciduousNeedleCover") {
775                 height = 5.0;
776                 density = 0.2;
777         }
778         else if(mat_name == "ScrubCover") {
779                 height = 3.0;
780                 density = 0.15;
781         }
782         else if(mat_name == "BuiltUpCover") {
783                 height = 30.0;
784                 density = 0.7;
785         }
786         else if(mat_name == "Urban") {
787                 height = 30.0;
788                 density = 0.7;
789         }
790         else if(mat_name == "Construction") {
791                 height = 30.0;
792                 density = 0.7;
793         }
794         else if(mat_name == "Industrial") {
795                 height = 30.0;
796                 density = 0.7;
797         }
798         else if(mat_name == "Port") {
799                 height = 30.0;
800                 density = 0.7;
801         }
802         else if(mat_name == "Town") {
803                 height = 10.0;
804                 density = 0.5;
805         }
806         else if(mat_name == "SubUrban") {
807                 height = 10.0;
808                 density = 0.5;
809         }
810         else if(mat_name == "CropWoodCover") {
811                 height = 10.0;
812                 density = 0.1;
813         }
814         else if(mat_name == "CropWood") {
815                 height = 10.0;
816                 density = 0.1;
817         }
818         else if(mat_name == "AgroForest") {
819                 height = 10.0;
820                 density = 0.1;
821         }
822         else {
823                 height = 0.0;
824                 density = 0.0;
825         }
826         
827 }
828
829 /*** implement simple LOS propagation model (WIP)
830 ***/
831 double FGRadioTransmission::LOS_calculate_attenuation(SGGeod pos, double freq, int transmission_type) {
832         double frq_mhz;
833         if( (freq < 118.0) || (freq > 137.0) )
834                 frq_mhz = 125.0;        // sane value, middle of bandplan
835         else
836                 frq_mhz = freq;
837         double dbloss;
838         double tx_pow = _transmitter_power;
839         double ant_gain = _rx_antenna_gain + _tx_antenna_gain;
840         double signal = 0.0;
841         
842         double sender_alt_ft,sender_alt;
843         double transmitter_height=0.0;
844         double receiver_height=0.0;
845         double own_lat = fgGetDouble("/position/latitude-deg");
846         double own_lon = fgGetDouble("/position/longitude-deg");
847         double own_alt_ft = fgGetDouble("/position/altitude-ft");
848         double own_alt= own_alt_ft * SG_FEET_TO_METER;
849         
850         
851         double link_budget = tx_pow - _receiver_sensitivity - _rx_line_losses - _tx_line_losses + ant_gain;     
852
853         //cerr << "ITM:: pilot Lat: " << own_lat << ", Lon: " << own_lon << ", Alt: " << own_alt << endl;
854         
855         SGGeod own_pos = SGGeod::fromDegM( own_lon, own_lat, own_alt );
856         
857         SGGeod sender_pos = pos;
858         
859         sender_alt_ft = sender_pos.getElevationFt();
860         sender_alt = sender_alt_ft * SG_FEET_TO_METER;
861         
862         receiver_height = own_alt;
863         transmitter_height = sender_alt;
864         
865         double distance_m = SGGeodesy::distanceM(own_pos, sender_pos);
866         
867         
868         transmitter_height += _tx_antenna_height;
869         receiver_height += _rx_antenna_height;
870         
871         
872         /** radio horizon calculation with wave bending k=4/3 */
873         double receiver_horizon = 4.12 * sqrt(receiver_height);
874         double transmitter_horizon = 4.12 * sqrt(transmitter_height);
875         double total_horizon = receiver_horizon + transmitter_horizon;
876         
877         if (distance_m > total_horizon) {
878                 return -1;
879         }
880         double pol_loss = 0.0;
881         if (_polarization == 1) {
882                 pol_loss = polarization_loss();
883         }
884         // free-space loss (distance calculation should be changed)
885         dbloss = 20 * log10(distance_m) +20 * log10(frq_mhz) -27.55;
886         signal = link_budget - dbloss + pol_loss;
887         SG_LOG(SG_GENERAL, SG_BULK,
888                         "LOS:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm ");
889         //cerr << "LOS:: Link budget: " << link_budget << ", Attenuation: " << dbloss << " dBm " << endl;
890         return signal;
891         
892 }
893
894 /*** calculate loss due to polarization mismatch
895 *       this function is only reliable for vertical polarization
896 *       due to the V-shape of horizontally polarized antennas
897 ***/
898 double FGRadioTransmission::polarization_loss() {
899         
900         double theta_deg;
901         double roll = fgGetDouble("/orientation/roll-deg");
902         if (fabs(roll) > 85.0)
903                 roll = 85.0;
904         double pitch = fgGetDouble("/orientation/pitch-deg");
905         if (fabs(pitch) > 85.0)
906                 pitch = 85.0;
907         double theta = fabs( atan( sqrt( 
908                 pow(tan(roll * SGD_DEGREES_TO_RADIANS), 2) + 
909                 pow(tan(pitch * SGD_DEGREES_TO_RADIANS), 2) )) * SGD_RADIANS_TO_DEGREES);
910         
911         if (_polarization == 0)
912                 theta_deg = 90.0 - theta;
913         else
914                 theta_deg = theta;
915         if (theta_deg > 85.0)   // we don't want to converge into infinity
916                 theta_deg = 85.0;
917         
918         double loss = 10 * log10( pow(cos(theta_deg * SGD_DEGREES_TO_RADIANS), 2) );
919         //cerr << "Polarization loss: " << loss << " dBm " << endl;
920         return loss;
921 }
922
923
924 double FGRadioTransmission::power_to_dbm(double power_watt) {
925         return 10 * log10(1000 * power_watt);   // returns dbm
926 }
927
928 double FGRadioTransmission::dbm_to_power(double dbm) {
929         return exp( (dbm-30) * log(10) / 10);   // returns Watts
930 }
931
932 double FGRadioTransmission::dbm_to_microvolt(double dbm) {
933         return sqrt(dbm_to_power(dbm) * 50) * 1000000;  // returns microvolts
934 }
935
936