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