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