]> git.mxchange.org Git - city.git/blob
a3b7fda6d3d8c89e81aec483675c96696ec2ce5f
[city.git] /
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\City\Database\Frontend\Sections;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Database\Frontend\BaseDatabaseFrontend;
8 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
9 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
10 use Org\Mxchange\CoreFramework\Registry\Registerable;
11
12 // Import SPL stuff
13 use \InvalidArgumentException;
14
15 /**
16  * A database frontend for city sections. Sections are the smalles entity of a
17  * city. They can be connected with each other and form a lot. Therefore only
18  * sections of same type (and sub type) can be linked combined, else you will
19  * something really strange, a residential building with some industry parts
20  * for example is not possible in real world.
21  *
22  * Sure you can have a small shop (commercial) on ground level and some
23  * residentials on higher levels. This city simulation does support such
24  * creations as the levels (Z axis) is different.
25  *
26  * @author              Roland Haeder <webmaster@shipsimu.org>
27  * @version             0.0.0
28  * @copyright   Copyright (c) 2015 - 2023 City Developer Team
29  * @license             GNU GPL 3.0 or any newer version
30  * @link                http://www.shipsimu.org
31  *
32  * This program is free software: you can redistribute it and/or modify
33  * it under the terms of the GNU General Public License as published by
34  * the Free Software Foundation, either version 3 of the License, or
35  * (at your option) any later version.
36  *
37  * This program is distributed in the hope that it will be useful,
38  * but WITHOUT ANY WARRANTY; without even the implied warranty of
39  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
40  * GNU General Public License for more details.
41  *
42  * You should have received a copy of the GNU General Public License
43  * along with this program. If not, see <http://www.gnu.org/licenses/>.
44  */
45 class CitySectionsDatabaseFrontend extends BaseDatabaseFrontend implements CitySectionsFrontend, Registerable {
46         // Constants for database table names
47         const DB_TABLE_CITY_SECTIONS           = 'city_sections';
48
49         // Entry id
50         const DB_COLUMN_ENTRY_ID               = 'entry_id';
51
52         // Section id, an referenced city id and lot id
53         const DB_COLUMN_SECTION_ID             = 'city_section_id';
54         const DB_COLUMN_CITY_ID                = 'city_id';
55
56         /*
57          * Lot id, the lot id is only set if the player has "aquired" the sections
58          * and has created a lot based on these sections.
59          */
60         const DB_COLUMN_LOT_ID                 = 'lot_id';
61
62         // Section and sub type (e.g. residential, hut)
63         const DB_COLUMN_SECTION_TYPE           = 'section_type';
64         const DB_COLUMN_SECTION_SUB_TYPE       = 'section_sub_type';
65
66         // X-Y-Z position
67         const DB_COLUMN_SECTION_POSITION_X     = 'section_position_x';
68         const DB_COLUMN_SECTION_POSITION_Y     = 'section_position_y';
69         const DB_COLUMN_SECTION_POSITION_Z     = 'section_position_z';
70
71         // Connected neigbouring sections
72         const DB_COLUMN_SECTION_NEIGHBOUR_WEST_ID  = 'section_neighbour_west_id';
73         const DB_COLUMN_SECTION_NEIGHBOUR_EAST_ID  = 'section_neighbour_east_id';
74         const DB_COLUMN_SECTION_NEIGHBOUR_NORTH_ID = 'section_neighbour_north_id';
75         const DB_COLUMN_SECTION_NEIGHBOUR_SOUTH_ID = 'section_neighbour_south_id';
76         const DB_COLUMN_SECTION_NEIGHBOUR_UP_ID    = 'section_neighbour_up_id';
77         const DB_COLUMN_SECTION_NEIGHBOUR_DOWN_ID  = 'section_neighbour_down_id';
78
79         // Other settings:
80         // Reserved section (see documentation)
81         const DB_COLUMN_SECTION_RESERVED       = 'section_reserved';
82
83         // Section types
84         // @TODO "water" is not yet supported and may end up in a very random land.
85         const SECTION_TYPE_WATER      = 'water';
86         const SECTION_TYPE_EMPTY_LAND = 'land';
87         const SECTION_TYPE_AIR        = 'air';
88
89         // Sub sections
90         // @TODO All types of water are not supported yet.
91         const SECTION_SUB_TYPE_GRASS = 'grass';
92         const SECTION_SUB_TYPE_AIR   = 'air';
93
94         // Reserved flag
95         const IS_NOT_RESERVED = 0;
96         const IS_RESERVED     = 1;
97
98         /**
99          * Protected constructor
100          *
101          * @return      void
102          */
103         protected function __construct () {
104                 // Call parent constructor
105                 parent::__construct(__CLASS__);
106         }
107
108         /**
109          * Creates an instance of this database frontend by a provided user class
110          *
111          * @return      $frontendInstance       An instance of the created frontend class
112          */
113         public static final function createCitySectionsDatabaseFrontend () {
114                 // Get a new instance
115                 $frontendInstance = new CitySectionsDatabaseFrontend();
116
117                 // Set (primary!) table name
118                 $frontendInstance->setTableName(self::DB_TABLE_CITY_SECTIONS);
119
120                 // Return the instance
121                 return $frontendInstance;
122         }
123
124         /**
125          * Checks if the given city id is found in sections table
126          *
127          * @param       $cityId         City id to check
128          * @return      $isFound        Whether the city id is found
129          * @throws      InvalidArgumentException        If a parameter as an invalid value
130          */
131         public function ifCityHasSections (int $cityId) {
132                 // Check parameter
133                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->traceMessage(sprintf('CITY-SECTIONS-DATABASE-FRONTEND: cityId=%d - CALLED!', $cityId));
134                 if ($cityId < 1) {
135                         // Throw IAE
136                         throw new InvalidArgumentException(sprintf('cityId=%d is not a valid id', $cityId), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
137                 }
138
139                 // Get search instance
140                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
141
142                 // Search for 'city_id'
143                 $searchInstance->addCriteria(self::DB_COLUMN_CITY_ID, $cityId);
144
145                 /*
146                  * Only one entry is enough to find, else this query could run very
147                  * long on large maps.
148                  */
149                 $searchInstance->setLimit(1);
150
151                 // Execute it on database instance
152                 $resultInstance = $this->doSelectByCriteria($searchInstance);
153
154                 // Check if there is one entry
155                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugMessage(sprintf('CITY-SECTIONS-DATABASE-FRONTEND: resultInstance=%s', $resultInstance->__toString()));
156                 $isFound = $resultInstance->next();
157
158                 // Return result
159                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->traceMessage(sprintf('CITY-SECTIONS-DATABASE-FRONTEND: isFound=%d - EXIT!', intval($isFound)));
160                 return $isFound;
161         }
162
163         /**
164          * Expands the sections table with initial data for given city id
165          *
166          * @param       $cityId         City id to check
167          * @return      $ids            Sections ids from initial expansion
168          * @throws      InvalidArgumentException        If a parameter as an invalid value
169          * @throws      BadMethodCallException  If the city has already sections but this method was invoked
170          * @todo        Add handling of water types to make a more cooler map
171          */
172         public function doInitialCityExpansion (int $cityId) {
173                 // Check parameter
174                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->traceMessage(sprintf('CITY-SECTIONS-DATABASE-FRONTEND: cityId=%d - CALLED!', $cityId));
175                 if ($cityId < 1) {
176                         // Throw IAE
177                         throw new InvalidArgumentException(sprintf('cityId=%d is not a valid id', $cityId), FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
178                 } elseif ($this->ifCityHasSections($cityId)) {
179                         // Already has sections
180                         throw new BadMethodCallException(sprintf('cityId=%d has already sections', $cityId), FrameworkInterface::EXCEPTION_BAD_METHOD_CALL);
181                 }
182
183                 /*
184                  * "Cache" max "radius" for initial city expansion. It is not a real
185                  * radius but more a max expansion area (expand +- half of "radius"
186                  * from 0/0). The "zero point" is always calculated in.
187                  *
188                  * This gives a maxium initial area calculated as follows:
189                  *
190                  * totalInitialSections = (radius + 1) * (radius + 1)
191                  */
192                 $radius = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('city_max_initial_xy_expansion_radius');
193
194                 // Max up and down ...
195                 $maxUp   = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('city_max_initial_up_expansion');
196                 $maxDown = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('city_max_initial_down_expansion');
197
198                 // Calculate total sections
199                 $totalSections = (($radius + 1) * ($radius + 1) * $maxUp * ($maxDown + 1));
200
201                 // Get data set instance
202                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugMessage(sprintf('CITY-SECTIONS-DATABASE-FRONTEND: radius=%d,maxUp=%d,maxDown=%d,totalSections=%d', $radius, $maxUp, $maxDown, $totalSections));
203                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_CITY_SECTIONS));
204
205                 // Add values for "zero point"
206                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_ID                , 1);
207                 $dataSetInstance->addCriteria(self::DB_COLUMN_CITY_ID                   , $cityId);
208                 $dataSetInstance->addCriteria(self::DB_COLUMN_LOT_ID                    , 0);
209                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_TYPE              , self::SECTION_TYPE_AIR);
210                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_SUB_TYPE          , self::SECTION_SUB_TYPE_AIR);
211                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_POSITION_X        , 0);
212                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_POSITION_Y        , 0);
213                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_POSITION_Z        , 0);
214                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_NEIGHBOUR_NORTH_ID, 0);
215                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_NEIGHBOUR_SOUTH_ID, 0);
216                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_NEIGHBOUR_WEST_ID , 0);
217                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_NEIGHBOUR_EAST_ID , 0);
218                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_NEIGHBOUR_UP_ID   , 0);
219                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_NEIGHBOUR_DOWN_ID , 0);
220                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_RESERVED          , self::IS_NOT_RESERVED);
221
222                 // Set primary key to 'city_id'/'section_id'
223                 $dataSetInstance->setPrimaryKeyCombined([self::DB_COLUMN_CITY_ID, self::DB_COLUMN_SECTION_ID]);
224
225                 // Entry id for counting each entry
226                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_ENTRY_ID);
227
228                 // Add "zero point"
229                 $this->queryInsertDataSet($dataSetInstance);
230
231                 // Set section id to 2 as 1 is already initialized + init array
232                 $sections = [];
233
234                 // Output message to ask for user's patience ...
235                 self::createDebugInstance(__CLASS__)->debugMessage(sprintf('CITY-SECTIONS-DATABASE-FRONTEND: Writing %d sections for city %d ... (this may takes some time)', $totalSections, $cityId));
236
237                 // Expand half of it to north/south (north=positive, south=negative)
238                 for ($north = 1; $north < round($radius / 2); $north++) {
239                         // Expand half of it to west/east (west=positive, east=negative)
240                         for ($west = 1; $west < round($radius / 2); $west++) {
241                                 // Expand up/down (including "zero point")
242                                 for ($z = $maxDown; $z < ($maxUp + 1); $z++) {
243                                         // Fill array up with south/east/down ids
244                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugMessage('[' . __METHOD__ . ':' . __LINE__ . ']: north=' . $north . ',west=' . $west . ',z=' . $z);
245                                         $sections[($north * -1)][($west * -1)][$z]['type'] = self::SECTION_TYPE_EMPTY_LAND;
246                                         $sections[($north * -1)][($west * -1)][$z]['sub']  = self::SECTION_SUB_TYPE_GRASS;
247
248                                         // Fill up array with north/west/up ids (only air)
249                                         $sections[$north][$west][$z]['type'] = self::SECTION_TYPE_AIR;
250                                         $sections[$north][$west][$z]['sub']  = self::SECTION_SUB_TYPE_AIR;
251                                 }
252                         }
253                 }
254
255                 // Init section id with 2 as 1 is the "zero point"
256                 $sectionId = 2;
257
258                 // Loop through whole array again for writing it to database: north/south
259                 foreach ($sections as $x => $sectionX) {
260                         // Loop through west/east values
261                         foreach ($sectionX as $y => $sectionY) {
262                                 // Loop through up/down values
263                                 foreach ($sectionY as $z => $sectionData) {
264                                         // Set all coordinates for positive directions
265                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugMessage('[' . __METHOD__ . ':' . __LINE__ . ']: x=' . $x . ',y=' . $y . ',z=' . $z . ',sectionId=' . $sectionId);
266                                         $dataSetInstance->setCriteria(self::DB_COLUMN_SECTION_ID        , $sectionId);
267                                         $dataSetInstance->setCriteria(self::DB_COLUMN_SECTION_POSITION_X, $x);
268                                         $dataSetInstance->setCriteria(self::DB_COLUMN_SECTION_POSITION_Y, $y);
269                                         $dataSetInstance->setCriteria(self::DB_COLUMN_SECTION_POSITION_Z, $z);
270                                         $dataSetInstance->setCriteria(self::DB_COLUMN_SECTION_TYPE      , $sectionData['type']);
271                                         $dataSetInstance->setCriteria(self::DB_COLUMN_SECTION_SUB_TYPE  , $sectionData['sub']);
272
273                                         // Add value to database
274                                         $this->queryInsertDataSet($dataSetInstance);
275
276                                         // Count id up
277                                         $sectionId++;
278                                 }
279
280                                 // Debug message
281                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugMessage('[' . __METHOD__ . ':' . __LINE__ . ']: x=' . $x . ',y=' . $y . ' has been written.');
282                         }
283
284                         // Debug message
285                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugMessage('[' . __METHOD__ . ':' . __LINE__ . ']: x=' . $x . ' has been written.');
286                 }
287
288                 // Thank you for waiting! :-)
289                 self::createDebugInstance(__CLASS__)->debugMessage(sprintf('A total of %d sections has been written for city id %s', $totalSections, $cityId));
290         }
291 }