Settings: Fix getNoiseParamsFromValue()
[oweals/minetest.git] / src / settings.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "settings.h"
21 #include "irrlichttypes_bloated.h"
22 #include "exceptions.h"
23 #include "jthread/jmutexautolock.h"
24 #include "strfnd.h"
25 #include <iostream>
26 #include <fstream>
27 #include <sstream>
28 #include "debug.h"
29 #include "log.h"
30 #include "util/serialize.h"
31 #include "filesys.h"
32 #include "noise.h"
33 #include <cctype>
34 #include <algorithm>
35
36
37 Settings::~Settings()
38 {
39         std::map<std::string, SettingsEntry>::const_iterator it;
40         for (it = m_settings.begin(); it != m_settings.end(); ++it)
41                 delete it->second.group;
42 }
43
44
45 Settings & Settings::operator += (const Settings &other)
46 {
47         update(other);
48
49         return *this;
50 }
51
52
53 Settings & Settings::operator = (const Settings &other)
54 {
55         if (&other == this)
56                 return *this;
57
58         JMutexAutoLock lock(m_mutex);
59         JMutexAutoLock lock2(other.m_mutex);
60
61         clearNoLock();
62         updateNoLock(other);
63
64         return *this;
65 }
66
67
68 std::string Settings::sanitizeString(const std::string &value)
69 {
70         std::string str = value;
71         for (const char *s = "\t\n\v\f\r\b =\""; *s; s++)
72                 str.erase(std::remove(str.begin(), str.end(), *s), str.end());
73
74         return str;
75 }
76
77
78 std::string Settings::getMultiline(std::istream &is)
79 {
80         std::string value;
81         std::string line;
82
83         while (is.good()) {
84                 std::getline(is, line);
85                 if (line == "\"\"\"")
86                         break;
87                 value += line;
88                 value.push_back('\n');
89         }
90
91         size_t len = value.size();
92         if (len)
93                 value.erase(len - 1);
94
95         return value;
96 }
97
98
99 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
100 {
101         JMutexAutoLock lock(m_mutex);
102
103         std::string line, name, value;
104
105         while (is.good()) {
106                 std::getline(is, line);
107                 SettingsParseEvent event = parseConfigObject(line, end, name, value);
108
109                 switch (event) {
110                 case SPE_NONE:
111                 case SPE_INVALID:
112                 case SPE_COMMENT:
113                         break;
114                 case SPE_KVPAIR:
115                         m_settings[name] = SettingsEntry(value);
116                         break;
117                 case SPE_END:
118                         return true;
119                 case SPE_GROUP: {
120                         Settings *branch = new Settings;
121                         if (!branch->parseConfigLines(is, "}"))
122                                 return false;
123
124                         m_settings[name] = SettingsEntry(branch);
125                         break;
126                 }
127                 case SPE_MULTILINE:
128                         m_settings[name] = SettingsEntry(getMultiline(is));
129                         break;
130                 }
131         }
132
133         return end.empty();
134 }
135
136
137 bool Settings::readConfigFile(const char *filename)
138 {
139         std::ifstream is(filename);
140         if (!is.good())
141                 return false;
142
143         return parseConfigLines(is, "");
144 }
145
146
147 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
148 {
149         JMutexAutoLock lock(m_mutex);
150
151         for (std::map<std::string, SettingsEntry>::const_iterator
152                         it = m_settings.begin();
153                         it != m_settings.end(); ++it) {
154                 bool is_multiline = it->second.value.find('\n') != std::string::npos;
155                 printValue(os, it->first, it->second, is_multiline, tab_depth);
156         }
157 }
158
159
160 void Settings::printValue(std::ostream &os, const std::string &name,
161         const SettingsEntry &entry, bool is_value_multiline, u32 tab_depth)
162 {
163         for (u32 i = 0; i != tab_depth; i++)
164                 os << "\t";
165         os << name << " = ";
166
167         if (is_value_multiline)
168                 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
169         else
170                 os << entry.value << "\n";
171
172         Settings *group = entry.group;
173         if (group) {
174                 for (u32 i = 0; i != tab_depth; i++)
175                         os << "\t";
176
177                 os << name << " = {\n";
178                 group->writeLines(os, tab_depth + 1);
179
180                 for (u32 i = 0; i != tab_depth; i++)
181                         os << "\t";
182
183                 os << "}\n";
184         }
185 }
186
187
188 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
189         const std::string &end, u32 tab_depth)
190 {
191         std::map<std::string, SettingsEntry>::const_iterator it;
192         std::set<std::string> settings_in_config;
193         bool was_modified = false;
194         bool end_found = false;
195         std::string line, name, value;
196
197         // Add any settings that exist in the config file with the current value
198         // in the object if existing
199         while (is.good() && !end_found) {
200                 std::getline(is, line);
201                 SettingsParseEvent event = parseConfigObject(line, end, name, value);
202
203                 switch (event) {
204                 case SPE_END:
205                         end_found = true;
206                         break;
207                 case SPE_KVPAIR:
208                 case SPE_MULTILINE:
209                         it = m_settings.find(name);
210                         if (it != m_settings.end()) {
211                                 if (event == SPE_MULTILINE)
212                                         value = getMultiline(is);
213
214                                 if (value != it->second.value) {
215                                         value = it->second.value;
216                                         was_modified = true;
217                                 }
218                         }
219
220                         settings_in_config.insert(name);
221
222                         printValue(os, name, SettingsEntry(value),
223                                 event == SPE_MULTILINE, tab_depth);
224
225                         break;
226                 case SPE_GROUP: {
227                         Settings *group = NULL;
228                         it = m_settings.find(name);
229                         if (it != m_settings.end())
230                                 group = it->second.group;
231
232                         settings_in_config.insert(name);
233
234                         os << name << " = {\n";
235
236                         if (group) {
237                                 was_modified |= group->updateConfigObject(is, os, "}", tab_depth + 1);
238                         } else {
239                                 Settings dummy_settings;
240                                 dummy_settings.updateConfigObject(is, os, "}", tab_depth + 1);
241                         }
242
243                         for (u32 i = 0; i != tab_depth; i++)
244                                 os << "\t";
245                         os << "}\n";
246                         break;
247                 }
248                 default:
249                         os << line << (is.eof() ? "" : "\n");
250                         break;
251                 }
252         }
253
254         // Add any settings in the object that don't exist in the config file yet
255         for (it = m_settings.begin(); it != m_settings.end(); ++it) {
256                 if (settings_in_config.find(it->first) != settings_in_config.end())
257                         continue;
258
259                 was_modified = true;
260
261                 bool is_multiline = it->second.value.find('\n') != std::string::npos;
262                 printValue(os, it->first, it->second, is_multiline, tab_depth);
263         }
264
265         return was_modified;
266 }
267
268
269 bool Settings::updateConfigFile(const char *filename)
270 {
271         JMutexAutoLock lock(m_mutex);
272
273         std::ifstream is(filename);
274         std::ostringstream os(std::ios_base::binary);
275
276         if (!updateConfigObject(is, os, ""))
277                 return true;
278
279         if (!fs::safeWriteToFile(filename, os.str())) {
280                 errorstream << "Error writing configuration file: \""
281                         << filename << "\"" << std::endl;
282                 return false;
283         }
284
285         return true;
286 }
287
288
289 bool Settings::parseCommandLine(int argc, char *argv[],
290                 std::map<std::string, ValueSpec> &allowed_options)
291 {
292         int nonopt_index = 0;
293         for (int i = 1; i < argc; i++) {
294                 std::string arg_name = argv[i];
295                 if (arg_name.substr(0, 2) != "--") {
296                         // If option doesn't start with -, read it in as nonoptX
297                         if (arg_name[0] != '-'){
298                                 std::string name = "nonopt";
299                                 name += itos(nonopt_index);
300                                 set(name, arg_name);
301                                 nonopt_index++;
302                                 continue;
303                         }
304                         errorstream << "Invalid command-line parameter \""
305                                         << arg_name << "\": --<option> expected." << std::endl;
306                         return false;
307                 }
308
309                 std::string name = arg_name.substr(2);
310
311                 std::map<std::string, ValueSpec>::iterator n;
312                 n = allowed_options.find(name);
313                 if (n == allowed_options.end()) {
314                         errorstream << "Unknown command-line parameter \""
315                                         << arg_name << "\"" << std::endl;
316                         return false;
317                 }
318
319                 ValueType type = n->second.type;
320
321                 std::string value = "";
322
323                 if (type == VALUETYPE_FLAG) {
324                         value = "true";
325                 } else {
326                         if ((i + 1) >= argc) {
327                                 errorstream << "Invalid command-line parameter \""
328                                                 << name << "\": missing value" << std::endl;
329                                 return false;
330                         }
331                         value = argv[++i];
332                 }
333
334                 set(name, value);
335         }
336
337         return true;
338 }
339
340
341
342 /***********
343  * Getters *
344  ***********/
345
346
347 const SettingsEntry &Settings::getEntry(const std::string &name) const
348 {
349         JMutexAutoLock lock(m_mutex);
350
351         std::map<std::string, SettingsEntry>::const_iterator n;
352         if ((n = m_settings.find(name)) == m_settings.end()) {
353                 if ((n = m_defaults.find(name)) == m_defaults.end())
354                         throw SettingNotFoundException("Setting [" + name + "] not found.");
355         }
356         return n->second;
357 }
358
359
360 Settings *Settings::getGroup(const std::string &name) const
361 {
362         Settings *group = getEntry(name).group;
363         if (group == NULL)
364                 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
365         return group;
366 }
367
368
369 std::string Settings::get(const std::string &name) const
370 {
371         return getEntry(name).value;
372 }
373
374
375 bool Settings::getBool(const std::string &name) const
376 {
377         return is_yes(get(name));
378 }
379
380
381 u16 Settings::getU16(const std::string &name) const
382 {
383         return stoi(get(name), 0, 65535);
384 }
385
386
387 s16 Settings::getS16(const std::string &name) const
388 {
389         return stoi(get(name), -32768, 32767);
390 }
391
392
393 s32 Settings::getS32(const std::string &name) const
394 {
395         return stoi(get(name));
396 }
397
398
399 float Settings::getFloat(const std::string &name) const
400 {
401         return stof(get(name));
402 }
403
404
405 u64 Settings::getU64(const std::string &name) const
406 {
407         u64 value = 0;
408         std::string s = get(name);
409         std::istringstream ss(s);
410         ss >> value;
411         return value;
412 }
413
414
415 v2f Settings::getV2F(const std::string &name) const
416 {
417         v2f value;
418         Strfnd f(get(name));
419         f.next("(");
420         value.X = stof(f.next(","));
421         value.Y = stof(f.next(")"));
422         return value;
423 }
424
425
426 v3f Settings::getV3F(const std::string &name) const
427 {
428         v3f value;
429         Strfnd f(get(name));
430         f.next("(");
431         value.X = stof(f.next(","));
432         value.Y = stof(f.next(","));
433         value.Z = stof(f.next(")"));
434         return value;
435 }
436
437
438 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
439         u32 *flagmask) const
440 {
441         std::string val = get(name);
442         return std::isdigit(val[0])
443                 ? stoi(val)
444                 : readFlagString(val, flagdesc, flagmask);
445 }
446
447
448 // N.B. if getStruct() is used to read a non-POD aggregate type,
449 // the behavior is undefined.
450 bool Settings::getStruct(const std::string &name, const std::string &format,
451         void *out, size_t olen) const
452 {
453         std::string valstr;
454
455         try {
456                 valstr = get(name);
457         } catch (SettingNotFoundException &e) {
458                 return false;
459         }
460
461         if (!deSerializeStringToStruct(valstr, format, out, olen))
462                 return false;
463
464         return true;
465 }
466
467
468 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
469 {
470         return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
471 }
472
473
474 bool Settings::getNoiseParamsFromValue(const std::string &name,
475         NoiseParams &np) const
476 {
477         std::string value;
478
479         if (!getNoEx(name, value))
480                 return false;
481
482         Strfnd f(value);
483
484         np.offset   = stof(f.next(","));
485         np.scale    = stof(f.next(","));
486         f.next("(");
487         np.spread.X = stof(f.next(","));
488         np.spread.Y = stof(f.next(","));
489         np.spread.Z = stof(f.next(")"));
490         f.next(",");
491         np.seed     = stoi(f.next(","));
492         np.octaves  = stoi(f.next(","));
493         np.persist  = stof(f.next(""));
494
495         return true;
496 }
497
498
499 bool Settings::getNoiseParamsFromGroup(const std::string &name,
500         NoiseParams &np) const
501 {
502         Settings *group = NULL;
503
504         if (!getGroupNoEx(name, group))
505                 return false;
506
507         group->getFloatNoEx("offset",      np.offset);
508         group->getFloatNoEx("scale",       np.scale);
509         group->getV3FNoEx("spread",        np.spread);
510         group->getS32NoEx("seed",          np.seed);
511         group->getU16NoEx("octaves",       np.octaves);
512         group->getFloatNoEx("persistence", np.persist);
513
514         return true;
515 }
516
517
518 bool Settings::exists(const std::string &name) const
519 {
520         JMutexAutoLock lock(m_mutex);
521
522         return (m_settings.find(name) != m_settings.end() ||
523                 m_defaults.find(name) != m_defaults.end());
524 }
525
526
527 std::vector<std::string> Settings::getNames() const
528 {
529         std::vector<std::string> names;
530         for (std::map<std::string, SettingsEntry>::const_iterator
531                         i = m_settings.begin();
532                         i != m_settings.end(); ++i) {
533                 names.push_back(i->first);
534         }
535         return names;
536 }
537
538
539
540 /***************************************
541  * Getters that don't throw exceptions *
542  ***************************************/
543
544 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
545 {
546         try {
547                 val = getEntry(name);
548                 return true;
549         } catch (SettingNotFoundException &e) {
550                 return false;
551         }
552 }
553
554
555 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
556 {
557         try {
558                 val = getGroup(name);
559                 return true;
560         } catch (SettingNotFoundException &e) {
561                 return false;
562         }
563 }
564
565
566 bool Settings::getNoEx(const std::string &name, std::string &val) const
567 {
568         try {
569                 val = get(name);
570                 return true;
571         } catch (SettingNotFoundException &e) {
572                 return false;
573         }
574 }
575
576
577 bool Settings::getFlag(const std::string &name) const
578 {
579         try {
580                 return getBool(name);
581         } catch(SettingNotFoundException &e) {
582                 return false;
583         }
584 }
585
586
587 bool Settings::getFloatNoEx(const std::string &name, float &val) const
588 {
589         try {
590                 val = getFloat(name);
591                 return true;
592         } catch (SettingNotFoundException &e) {
593                 return false;
594         }
595 }
596
597
598 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
599 {
600         try {
601                 val = getU16(name);
602                 return true;
603         } catch (SettingNotFoundException &e) {
604                 return false;
605         }
606 }
607
608
609 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
610 {
611         try {
612                 val = getS16(name);
613                 return true;
614         } catch (SettingNotFoundException &e) {
615                 return false;
616         }
617 }
618
619
620 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
621 {
622         try {
623                 val = getS32(name);
624                 return true;
625         } catch (SettingNotFoundException &e) {
626                 return false;
627         }
628 }
629
630
631 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
632 {
633         try {
634                 val = getU64(name);
635                 return true;
636         } catch (SettingNotFoundException &e) {
637                 return false;
638         }
639 }
640
641
642 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
643 {
644         try {
645                 val = getV2F(name);
646                 return true;
647         } catch (SettingNotFoundException &e) {
648                 return false;
649         }
650 }
651
652
653 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
654 {
655         try {
656                 val = getV3F(name);
657                 return true;
658         } catch (SettingNotFoundException &e) {
659                 return false;
660         }
661 }
662
663
664 // N.B. getFlagStrNoEx() does not set val, but merely modifies it.  Thus,
665 // val must be initialized before using getFlagStrNoEx().  The intention of
666 // this is to simplify modifying a flags field from a default value.
667 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
668         FlagDesc *flagdesc) const
669 {
670         try {
671                 u32 flags, flagmask;
672
673                 flags = getFlagStr(name, flagdesc, &flagmask);
674
675                 val &= ~flagmask;
676                 val |=  flags;
677
678                 return true;
679         } catch (SettingNotFoundException &e) {
680                 return false;
681         }
682 }
683
684
685 /***********
686  * Setters *
687  ***********/
688
689
690 void Settings::set(const std::string &name, const std::string &value)
691 {
692         {
693         JMutexAutoLock lock(m_mutex);
694
695         m_settings[name].value = value;
696         }
697         doCallbacks(name);
698 }
699
700
701 void Settings::setGroup(const std::string &name, Settings *group)
702 {
703         JMutexAutoLock lock(m_mutex);
704
705         delete m_settings[name].group;
706         m_settings[name].group = group;
707 }
708
709
710 void Settings::setDefault(const std::string &name, const std::string &value)
711 {
712         JMutexAutoLock lock(m_mutex);
713
714         m_defaults[name].value = value;
715 }
716
717
718 void Settings::setGroupDefault(const std::string &name, Settings *group)
719 {
720         JMutexAutoLock lock(m_mutex);
721
722         delete m_defaults[name].group;
723         m_defaults[name].group = group;
724 }
725
726
727 void Settings::setBool(const std::string &name, bool value)
728 {
729         set(name, value ? "true" : "false");
730 }
731
732
733 void Settings::setS16(const std::string &name, s16 value)
734 {
735         set(name, itos(value));
736 }
737
738
739 void Settings::setU16(const std::string &name, u16 value)
740 {
741         set(name, itos(value));
742 }
743
744
745 void Settings::setS32(const std::string &name, s32 value)
746 {
747         set(name, itos(value));
748 }
749
750
751 void Settings::setU64(const std::string &name, u64 value)
752 {
753         std::ostringstream os;
754         os << value;
755         set(name, os.str());
756 }
757
758
759 void Settings::setFloat(const std::string &name, float value)
760 {
761         set(name, ftos(value));
762 }
763
764
765 void Settings::setV2F(const std::string &name, v2f value)
766 {
767         std::ostringstream os;
768         os << "(" << value.X << "," << value.Y << ")";
769         set(name, os.str());
770 }
771
772
773 void Settings::setV3F(const std::string &name, v3f value)
774 {
775         std::ostringstream os;
776         os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
777         set(name, os.str());
778 }
779
780
781 void Settings::setFlagStr(const std::string &name, u32 flags,
782         const FlagDesc *flagdesc, u32 flagmask)
783 {
784         set(name, writeFlagString(flags, flagdesc, flagmask));
785 }
786
787
788 bool Settings::setStruct(const std::string &name, const std::string &format,
789         void *value)
790 {
791         std::string structstr;
792         if (!serializeStructToString(&structstr, format, value))
793                 return false;
794
795         set(name, structstr);
796         return true;
797 }
798
799
800 void Settings::setNoiseParams(const std::string &name, const NoiseParams &np)
801 {
802         Settings *group = new Settings;
803
804         group->setFloat("offset",      np.offset);
805         group->setFloat("scale",       np.scale);
806         group->setV3F("spread",        np.spread);
807         group->setS32("seed",          np.seed);
808         group->setU16("octaves",       np.octaves);
809         group->setFloat("persistence", np.persist);
810
811         setGroup(name, group);
812 }
813
814
815 bool Settings::remove(const std::string &name)
816 {
817         JMutexAutoLock lock(m_mutex);
818         return m_settings.erase(name);
819 }
820
821
822 void Settings::clear()
823 {
824         JMutexAutoLock lock(m_mutex);
825         clearNoLock();
826 }
827
828
829 void Settings::updateValue(const Settings &other, const std::string &name)
830 {
831         if (&other == this)
832                 return;
833
834         JMutexAutoLock lock(m_mutex);
835
836         try {
837                 std::string val = other.get(name);
838
839                 m_settings[name] = val;
840         } catch (SettingNotFoundException &e) {
841         }
842 }
843
844
845 void Settings::update(const Settings &other)
846 {
847         if (&other == this)
848                 return;
849
850         JMutexAutoLock lock(m_mutex);
851         JMutexAutoLock lock2(other.m_mutex);
852
853         updateNoLock(other);
854 }
855
856
857 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
858         const std::string &end, std::string &name, std::string &value)
859 {
860         std::string trimmed_line = trim(line);
861
862         if (trimmed_line.empty())
863                 return SPE_NONE;
864         if (trimmed_line[0] == '#')
865                 return SPE_COMMENT;
866         if (trimmed_line == end)
867                 return SPE_END;
868
869         size_t pos = trimmed_line.find('=');
870         if (pos == std::string::npos)
871                 return SPE_INVALID;
872
873         name  = trim(trimmed_line.substr(0, pos));
874         value = trim(trimmed_line.substr(pos + 1));
875
876         if (value == "{")
877                 return SPE_GROUP;
878         if (value == "\"\"\"")
879                 return SPE_MULTILINE;
880
881         return SPE_KVPAIR;
882 }
883
884
885 void Settings::updateNoLock(const Settings &other)
886 {
887         m_settings.insert(other.m_settings.begin(), other.m_settings.end());
888         m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
889 }
890
891
892 void Settings::clearNoLock()
893 {
894         m_settings.clear();
895         m_defaults.clear();
896 }
897
898
899 void Settings::registerChangedCallback(std::string name,
900         setting_changed_callback cbf)
901 {
902         m_callbacks[name].push_back(cbf);
903 }
904
905
906 void Settings::doCallbacks(const std::string name)
907 {
908         std::vector<setting_changed_callback> tempvector;
909         {
910                 JMutexAutoLock lock(m_mutex);
911                 if (m_callbacks.find(name) != m_callbacks.end())
912                 {
913                         tempvector = m_callbacks[name];
914                 }
915         }
916
917         for (std::vector<setting_changed_callback>::iterator iter = tempvector.begin();
918                         iter != tempvector.end(); iter ++)
919         {
920                 (*iter)(name);
921         }
922 }