Fix single-frame lag in camera yaw/pitch, tune view bobbing and add wielded tool...
[oweals/minetest.git] / src / camera.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 "camera.h"
21 #include "debug.h"
22 #include "client.h"
23 #include "main.h" // for g_settings
24 #include "map.h"
25 #include "player.h"
26 #include "tile.h"
27 #include <cmath>
28
29 Camera::Camera(scene::ISceneManager* smgr, MapDrawControl& draw_control):
30         m_smgr(smgr),
31         m_playernode(NULL),
32         m_headnode(NULL),
33         m_cameranode(NULL),
34
35         m_wieldmgr(NULL),
36         m_wieldnode(NULL),
37
38         m_draw_control(draw_control),
39         m_viewing_range_min(5.0),
40         m_viewing_range_max(5.0),
41
42         m_camera_position(0,0,0),
43         m_camera_direction(0,0,0),
44
45         m_aspect(1.0),
46         m_fov_x(1.0),
47         m_fov_y(1.0),
48
49         m_wanted_frametime(0.0),
50         m_added_frametime(0),
51         m_added_frames(0),
52         m_range_old(0),
53         m_frametime_old(0),
54         m_frametime_counter(0),
55         m_time_per_range(30. / 50), // a sane default of 30ms per 50 nodes of range
56
57         m_view_bobbing_anim(0),
58         m_view_bobbing_state(0),
59         m_view_bobbing_speed(0),
60
61         m_digging_anim(0),
62         m_digging_button(-1)
63 {
64         //dstream<<__FUNCTION_NAME<<std::endl;
65
66         // note: making the camera node a child of the player node
67         // would lead to unexpected behaviour, so we don't do that.
68         m_playernode = smgr->addEmptySceneNode(smgr->getRootSceneNode());
69         m_headnode = smgr->addEmptySceneNode(m_playernode);
70         m_cameranode = smgr->addCameraSceneNode(smgr->getRootSceneNode());
71         m_cameranode->bindTargetAndRotation(true);
72
73         // This needs to be in its own scene manager. It is drawn after
74         // all other 3D scene nodes and before the GUI.
75         m_wieldmgr = smgr->createNewSceneManager();
76         m_wieldmgr->addCameraSceneNode();
77         m_wieldnode = new ExtrudedSpriteSceneNode(m_wieldmgr->getRootSceneNode(), m_wieldmgr);
78
79         updateSettings();
80 }
81
82 Camera::~Camera()
83 {
84         m_wieldmgr->drop();
85         m_wieldnode->drop();
86 }
87
88 bool Camera::successfullyCreated(std::wstring& error_message)
89 {
90         if (m_playernode == NULL)
91         {
92                 error_message = L"Failed to create the player scene node";
93                 return false;
94         }
95         if (m_headnode == NULL)
96         {
97                 error_message = L"Failed to create the head scene node";
98                 return false;
99         }
100         if (m_cameranode == NULL)
101         {
102                 error_message = L"Failed to create the camera scene node";
103                 return false;
104         }
105         if (m_wieldmgr == NULL)
106         {
107                 error_message = L"Failed to create the wielded item scene manager";
108                 return false;
109         }
110         if (m_wieldnode == NULL)
111         {
112                 error_message = L"Failed to create the wielded item scene node";
113                 return false;
114         }
115         return true;
116 }
117
118 // Returns the fractional part of x
119 inline f32 my_modf(f32 x)
120 {
121         double dummy;
122         return modf(x, &dummy);
123 }
124
125 void Camera::step(f32 dtime)
126 {
127         if (m_view_bobbing_state != 0)
128         {
129                 //f32 offset = dtime * m_view_bobbing_speed * 0.035;
130                 f32 offset = dtime * m_view_bobbing_speed * 0.030;
131                 if (m_view_bobbing_state == 2)
132                 {
133 #if 0
134                         // Animation is getting turned off
135                         if (m_view_bobbing_anim < 0.5)
136                                 m_view_bobbing_anim -= offset;
137                         else
138                                 m_view_bobbing_anim += offset;
139                         if (m_view_bobbing_anim <= 0 || m_view_bobbing_anim >= 1)
140                         {
141                                 m_view_bobbing_anim = 0;
142                                 m_view_bobbing_state = 0;
143                         }
144 #endif
145 #if 1
146                         // Animation is getting turned off
147                         if(m_view_bobbing_anim < 0.25){
148                                 m_view_bobbing_anim -= offset;
149                         } else if(m_view_bobbing_anim > 0.75){
150                                 m_view_bobbing_anim += offset;
151                         } if(m_view_bobbing_anim < 0.5){
152                                 m_view_bobbing_anim += offset;
153                                 if(m_view_bobbing_anim > 0.5)
154                                         m_view_bobbing_anim = 0.5;
155                         } else {
156                                 m_view_bobbing_anim -= offset;
157                                 if(m_view_bobbing_anim < 0.5)
158                                         m_view_bobbing_anim = 0.5;
159                         }
160                         if(m_view_bobbing_anim <= 0 || m_view_bobbing_anim >= 1 ||
161                                         fabs(m_view_bobbing_anim - 0.5) < 0.01)
162                         {
163                                 m_view_bobbing_anim = 0;
164                                 m_view_bobbing_state = 0;
165                         }
166 #endif
167                 }
168                 else
169                 {
170                         m_view_bobbing_anim = my_modf(m_view_bobbing_anim + offset);
171                 }
172         }
173
174         if (m_digging_button != -1)
175         {
176                 f32 offset = dtime * 3.5;
177                 m_digging_anim += offset;
178                 if (m_digging_anim >= 1)
179                 {
180                         m_digging_anim = 0;
181                         m_digging_button = -1;
182                 }
183         }
184 }
185
186 void Camera::update(LocalPlayer* player, f32 frametime, v2u32 screensize)
187 {
188         // Set player node transformation
189         m_playernode->setPosition(player->getPosition());
190         m_playernode->setRotation(v3f(0, -1 * player->getYaw(), 0));
191         m_playernode->updateAbsolutePosition();
192
193         // Set head node transformation
194         m_headnode->setPosition(player->getEyeOffset());
195         m_headnode->setRotation(v3f(player->getPitch(), 0, 0));
196         m_headnode->updateAbsolutePosition();
197
198         // Compute relative camera position and target
199         v3f rel_cam_pos = v3f(0,0,0);
200         v3f rel_cam_target = v3f(0,0,1);
201         v3f rel_cam_up = v3f(0,1,0);
202
203         if (m_view_bobbing_anim != 0)
204         {
205                 f32 bobfrac = my_modf(m_view_bobbing_anim * 2);
206                 f32 bobdir = (m_view_bobbing_anim < 0.5) ? 1.0 : -1.0;
207
208                 #if 1
209                 f32 bobknob = 1.2;
210                 f32 bobtmp = sin(pow(bobfrac, bobknob) * PI);
211                 f32 bobtmp2 = cos(pow(bobfrac, bobknob) * PI);
212
213                 v3f bobvec = v3f(
214                         0.3 * bobdir * sin(bobfrac * PI),
215                         -0.28 * bobtmp * bobtmp,
216                         0.);
217
218                 //rel_cam_pos += 0.2 * bobvec;
219                 //rel_cam_target += 0.03 * bobvec;
220                 //rel_cam_up.rotateXYBy(0.02 * bobdir * bobtmp * PI);
221                 float f = 1.0;
222                 rel_cam_pos += bobvec * f;
223                 //rel_cam_target += 0.995 * bobvec * f;
224                 rel_cam_target += bobvec * f;
225                 rel_cam_target.Z -= 0.005 * bobvec.Z * f;
226                 //rel_cam_target.X -= 0.005 * bobvec.X * f;
227                 //rel_cam_target.Y -= 0.005 * bobvec.Y * f;
228                 rel_cam_up.rotateXYBy(-0.03 * bobdir * bobtmp * PI * f);
229                 #else
230                 f32 angle_deg = 1 * bobdir * sin(bobfrac * PI);
231                 f32 angle_rad = angle_deg * PI / 180;
232                 f32 r = 0.05;
233                 v3f off = v3f(
234                         r * sin(angle_rad),
235                         r * (cos(angle_rad) - 1),
236                         0);
237                 rel_cam_pos += off;
238                 //rel_cam_target += off;
239                 rel_cam_up.rotateXYBy(angle_deg);
240                 #endif
241
242         }
243
244         // Compute absolute camera position and target
245         m_headnode->getAbsoluteTransformation().transformVect(m_camera_position, rel_cam_pos);
246         m_headnode->getAbsoluteTransformation().rotateVect(m_camera_direction, rel_cam_target - rel_cam_pos);
247
248         v3f abs_cam_up;
249         m_headnode->getAbsoluteTransformation().rotateVect(abs_cam_up, rel_cam_up);
250
251         // Set camera node transformation
252         m_cameranode->setPosition(m_camera_position);
253         m_cameranode->setUpVector(abs_cam_up);
254         // *100.0 helps in large map coordinates
255         m_cameranode->setTarget(m_camera_position + 100 * m_camera_direction);
256
257         // FOV and and aspect ratio
258         m_aspect = (f32)screensize.X / (f32) screensize.Y;
259         m_fov_x = 2 * atan(0.5 * m_aspect * tan(m_fov_y));
260         m_cameranode->setAspectRatio(m_aspect);
261         m_cameranode->setFOV(m_fov_y);
262         // Just so big a value that everything rendered is visible
263         // Some more allowance that m_viewing_range_max * BS because of active objects etc.
264         m_cameranode->setFarValue(m_viewing_range_max * BS * 10);
265
266         // Position the wielded item
267         v3f wield_position = v3f(45, -35, 65);
268         v3f wield_rotation = v3f(90, -90, -90);
269         if (m_digging_button != -1)
270         {
271                 f32 digfrac = m_digging_anim;
272                 wield_position.X -= 30 * sin(pow(digfrac, 0.8f) * PI);
273                 wield_position.Y += 15 * sin(digfrac * 2 * PI);
274                 wield_position.Z += 5 * digfrac;
275
276                 // Euler angles are PURE EVIL, so why not use quaternions?
277                 core::quaternion quat_begin(wield_rotation * core::DEGTORAD);
278                 core::quaternion quat_end(v3f(90, -10, -130) * core::DEGTORAD);
279                 core::quaternion quat_slerp;
280                 quat_slerp.slerp(quat_begin, quat_end, sin(digfrac * PI));
281                 quat_slerp.toEuler(wield_rotation);
282                 wield_rotation *= core::RADTODEG;
283         }
284         else {
285                 f32 bobfrac = my_modf(m_view_bobbing_anim);
286                 wield_position.X -= sin(bobfrac*PI*2.0) * 3.0;
287                 wield_position.Y += sin(my_modf(bobfrac*2.0)*PI) * 3.0;
288         }
289         m_wieldnode->setPosition(wield_position);
290         m_wieldnode->setRotation(wield_rotation);
291         m_wieldnode->updateLight(player->light);
292
293         // Render distance feedback loop
294         updateViewingRange(frametime);
295
296         // If the player seems to be walking on solid ground,
297         // view bobbing is enabled and free_move is off,
298         // start (or continue) the view bobbing animation.
299         v3f speed = player->getSpeed();
300         if ((hypot(speed.X, speed.Z) > BS) &&
301                 (player->touching_ground) &&
302                 (g_settings.getBool("view_bobbing") == true) &&
303                 (g_settings.getBool("free_move") == false))
304         {
305                 // Start animation
306                 m_view_bobbing_state = 1;
307                 m_view_bobbing_speed = MYMIN(speed.getLength(), 40);
308         }
309         else if (m_view_bobbing_state == 1)
310         {
311                 // Stop animation
312                 m_view_bobbing_state = 2;
313                 m_view_bobbing_speed = 60;
314         }
315 }
316
317 void Camera::updateViewingRange(f32 frametime_in)
318 {
319         if (m_draw_control.range_all)
320                 return;
321
322         m_added_frametime += frametime_in;
323         m_added_frames += 1;
324
325         // Actually this counter kind of sucks because frametime is busytime
326         m_frametime_counter -= frametime_in;
327         if (m_frametime_counter > 0)
328                 return;
329         m_frametime_counter = 0.2;
330
331         /*dstream<<__FUNCTION_NAME
332                         <<": Collected "<<m_added_frames<<" frames, total of "
333                         <<m_added_frametime<<"s."<<std::endl;
334
335         dstream<<"m_draw_control.blocks_drawn="
336                         <<m_draw_control.blocks_drawn
337                         <<", m_draw_control.blocks_would_have_drawn="
338                         <<m_draw_control.blocks_would_have_drawn
339                         <<std::endl;*/
340
341         m_draw_control.wanted_min_range = m_viewing_range_min;
342         m_draw_control.wanted_max_blocks = (1.5*m_draw_control.blocks_would_have_drawn)+1;
343         if (m_draw_control.wanted_max_blocks < 10)
344                 m_draw_control.wanted_max_blocks = 10;
345
346         f32 block_draw_ratio = 1.0;
347         if (m_draw_control.blocks_would_have_drawn != 0)
348         {
349                 block_draw_ratio = (f32)m_draw_control.blocks_drawn
350                         / (f32)m_draw_control.blocks_would_have_drawn;
351         }
352
353         // Calculate the average frametime in the case that all wanted
354         // blocks had been drawn
355         f32 frametime = m_added_frametime / m_added_frames / block_draw_ratio;
356
357         m_added_frametime = 0.0;
358         m_added_frames = 0;
359
360         f32 wanted_frametime_change = m_wanted_frametime - frametime;
361         //dstream<<"wanted_frametime_change="<<wanted_frametime_change<<std::endl;
362
363         // If needed frametime change is small, just return
364         if (fabs(wanted_frametime_change) < m_wanted_frametime*0.4)
365         {
366                 //dstream<<"ignoring small wanted_frametime_change"<<std::endl;
367                 return;
368         }
369
370         f32 range = m_draw_control.wanted_range;
371         f32 new_range = range;
372
373         f32 d_range = range - m_range_old;
374         f32 d_frametime = frametime - m_frametime_old;
375         if (d_range != 0)
376         {
377                 m_time_per_range = d_frametime / d_range;
378         }
379
380         // The minimum allowed calculated frametime-range derivative:
381         // Practically this sets the maximum speed of changing the range.
382         // The lower this value, the higher the maximum changing speed.
383         // A low value here results in wobbly range (0.001)
384         // A high value here results in slow changing range (0.0025)
385         // SUGG: This could be dynamically adjusted so that when
386         //       the camera is turning, this is lower
387         //f32 min_time_per_range = 0.0015;
388         f32 min_time_per_range = 0.0010;
389         //f32 min_time_per_range = 0.05 / range;
390         if(m_time_per_range < min_time_per_range)
391         {
392                 m_time_per_range = min_time_per_range;
393                 //dstream<<"m_time_per_range="<<m_time_per_range<<" (min)"<<std::endl;
394         }
395         else
396         {
397                 //dstream<<"m_time_per_range="<<m_time_per_range<<std::endl;
398         }
399
400         f32 wanted_range_change = wanted_frametime_change / m_time_per_range;
401         // Dampen the change a bit to kill oscillations
402         //wanted_range_change *= 0.9;
403         //wanted_range_change *= 0.75;
404         wanted_range_change *= 0.5;
405         //dstream<<"wanted_range_change="<<wanted_range_change<<std::endl;
406
407         // If needed range change is very small, just return
408         if(fabs(wanted_range_change) < 0.001)
409         {
410                 //dstream<<"ignoring small wanted_range_change"<<std::endl;
411                 return;
412         }
413
414         new_range += wanted_range_change;
415         
416         //f32 new_range_unclamped = new_range;
417         new_range = MYMAX(new_range, m_viewing_range_min);
418         new_range = MYMIN(new_range, m_viewing_range_max);
419         /*dstream<<"new_range="<<new_range_unclamped
420                         <<", clamped to "<<new_range<<std::endl;*/
421
422         m_draw_control.wanted_range = new_range;
423
424         m_range_old = new_range;
425         m_frametime_old = frametime;
426 }
427
428 void Camera::updateSettings()
429 {
430         m_viewing_range_min = g_settings.getS16("viewing_range_nodes_min");
431         m_viewing_range_min = MYMAX(5.0, m_viewing_range_min);
432
433         m_viewing_range_max = g_settings.getS16("viewing_range_nodes_max");
434         m_viewing_range_max = MYMAX(m_viewing_range_min, m_viewing_range_max);
435
436         f32 fov_degrees = g_settings.getFloat("fov");
437         fov_degrees = MYMAX(fov_degrees, 10.0);
438         fov_degrees = MYMIN(fov_degrees, 170.0);
439         m_fov_y = fov_degrees * PI / 180.0;
440
441         f32 wanted_fps = g_settings.getFloat("wanted_fps");
442         wanted_fps = MYMAX(wanted_fps, 1.0);
443         m_wanted_frametime = 1.0 / wanted_fps;
444 }
445
446 void Camera::wield(const InventoryItem* item)
447 {
448         if (item != NULL)
449         {
450                 bool isCube = false;
451
452                 // Try to make a MaterialItem cube.
453                 if (std::string(item->getName()) == "MaterialItem")
454                 {
455                         // A block-type material
456                         MaterialItem* mat_item = (MaterialItem*) item;
457                         content_t content = mat_item->getMaterial();
458                         if (content_features(content).solidness || content_features(content).visual_solidness)
459                         {
460                                 m_wieldnode->setCube(content_features(content).tiles);
461                                 m_wieldnode->setScale(v3f(30));
462                                 isCube = true;
463                         }
464                 }
465
466                 // If that failed, make an extruded sprite.
467                 if (!isCube)
468                 {
469                         m_wieldnode->setSprite(item->getImageRaw());
470                         m_wieldnode->setScale(v3f(40));
471                 }
472
473                 m_wieldnode->setVisible(true);
474         }
475         else
476         {
477                 // Bare hands
478                 m_wieldnode->setVisible(false);
479         }
480 }
481
482 void Camera::setDigging(s32 button)
483 {
484         if (m_digging_button == -1)
485                 m_digging_button = button;
486 }
487
488 void Camera::drawWieldedTool()
489 {
490         m_wieldmgr->getVideoDriver()->clearZBuffer();
491
492         scene::ICameraSceneNode* cam = m_wieldmgr->getActiveCamera();
493         cam->setAspectRatio(m_cameranode->getAspectRatio());
494         cam->setFOV(m_cameranode->getFOV());
495         cam->setNearValue(0.1);
496         cam->setFarValue(100);
497         m_wieldmgr->drawAll();
498 }
499
500
501 ExtrudedSpriteSceneNode::ExtrudedSpriteSceneNode(
502         scene::ISceneNode* parent,
503         scene::ISceneManager* mgr,
504         s32 id,
505         const v3f& position,
506         const v3f& rotation,
507         const v3f& scale
508 ):
509         ISceneNode(parent, mgr, id, position, rotation, scale)
510 {
511         m_meshnode = mgr->addMeshSceneNode(NULL, this, -1, v3f(0,0,0), v3f(0,0,0), v3f(1,1,1), true);
512         m_thickness = 0.1;
513         m_cubemesh = NULL;
514         m_is_cube = false;
515         m_light = LIGHT_MAX;
516 }
517
518 ExtrudedSpriteSceneNode::~ExtrudedSpriteSceneNode()
519 {
520         removeChild(m_meshnode);
521         if (m_cubemesh)
522                 m_cubemesh->drop();
523 }
524
525 void ExtrudedSpriteSceneNode::setSprite(video::ITexture* texture)
526 {
527         if (texture == NULL)
528         {
529                 m_meshnode->setVisible(false);
530                 return;
531         }
532
533         io::path name = getExtrudedName(texture);
534         scene::IMeshCache* cache = SceneManager->getMeshCache();
535         scene::IAnimatedMesh* mesh = cache->getMeshByName(name);
536         if (mesh != NULL)
537         {
538                 // Extruded texture has been found in cache.
539                 m_meshnode->setMesh(mesh);
540         }
541         else
542         {
543                 // Texture was not yet extruded, do it now and save in cache
544                 mesh = extrude(texture);
545                 if (mesh == NULL)
546                 {
547                         dstream << "Warning: failed to extrude sprite" << std::endl;
548                         m_meshnode->setVisible(false);
549                         return;
550                 }
551                 cache->addMesh(name, mesh);
552                 m_meshnode->setMesh(mesh);
553                 mesh->drop();
554         }
555
556         m_meshnode->setScale(v3f(1, 1, m_thickness));
557         m_meshnode->getMaterial(0).setTexture(0, texture);
558         m_meshnode->getMaterial(0).setFlag(video::EMF_LIGHTING, false);
559         m_meshnode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, false);
560         m_meshnode->getMaterial(0).MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
561         m_meshnode->setVisible(true);
562         m_is_cube = false;
563         updateLight(m_light);
564 }
565
566 void ExtrudedSpriteSceneNode::setCube(const TileSpec tiles[6])
567 {
568         if (m_cubemesh == NULL)
569                 m_cubemesh = createCubeMesh();
570
571         m_meshnode->setMesh(m_cubemesh);
572         m_meshnode->setScale(v3f(1));
573         for (int i = 0; i < 6; ++i)
574         {
575                 // Get the tile texture and atlas transformation
576                 video::ITexture* atlas = tiles[i].texture.atlas;
577                 v2f pos = tiles[i].texture.pos;
578                 v2f size = tiles[i].texture.size;
579
580                 // Set material flags and texture
581                 video::SMaterial& material = m_meshnode->getMaterial(i);
582                 material.setFlag(video::EMF_LIGHTING, false);
583                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
584                 tiles[i].applyMaterialOptions(material);
585                 material.setTexture(0, atlas);
586                 material.getTextureMatrix(0).setTextureTranslate(pos.X, pos.Y);
587                 material.getTextureMatrix(0).setTextureScale(size.X, size.Y);
588         }
589         m_meshnode->setVisible(true);
590         m_is_cube = true;
591         updateLight(m_light);
592 }
593
594 void ExtrudedSpriteSceneNode::updateLight(u8 light)
595 {
596         m_light = light;
597
598         u8 li = decode_light(light);
599         // Set brightness one lower than incoming light
600         diminish_light(li);
601         video::SColor color(255,li,li,li);
602         setMeshVerticesColor(m_meshnode->getMesh(), color);
603 }
604
605 void ExtrudedSpriteSceneNode::removeSpriteFromCache(video::ITexture* texture)
606 {
607         scene::IMeshCache* cache = SceneManager->getMeshCache();
608         scene::IAnimatedMesh* mesh = cache->getMeshByName(getExtrudedName(texture));
609         if (mesh != NULL)
610                 cache->removeMesh(mesh);
611 }
612
613 void ExtrudedSpriteSceneNode::setSpriteThickness(f32 thickness)
614 {
615         m_thickness = thickness;
616         if (!m_is_cube)
617                 m_meshnode->setScale(v3f(1, 1, thickness));
618 }
619
620 const core::aabbox3d<f32>& ExtrudedSpriteSceneNode::getBoundingBox() const
621 {
622         return m_meshnode->getBoundingBox();
623 }
624
625 void ExtrudedSpriteSceneNode::OnRegisterSceneNode()
626 {
627         if (IsVisible)
628                 SceneManager->registerNodeForRendering(this);
629         ISceneNode::OnRegisterSceneNode();
630 }
631
632 void ExtrudedSpriteSceneNode::render()
633 {
634         // do nothing
635 }
636
637 io::path ExtrudedSpriteSceneNode::getExtrudedName(video::ITexture* texture)
638 {
639         io::path path = texture->getName();
640         path.append("/[extruded]");
641         return path;
642 }
643
644 scene::IAnimatedMesh* ExtrudedSpriteSceneNode::extrudeARGB(u32 width, u32 height, u8* data)
645 {
646         const s32 argb_wstep = 4 * width;
647         const s32 alpha_threshold = 1;
648
649         scene::IMeshBuffer* buf = new scene::SMeshBuffer();
650         video::SColor c(255,255,255,255);
651
652         // Front and back
653         {
654                 video::S3DVertex vertices[8] =
655                 {
656                         video::S3DVertex(-0.5,-0.5,-0.5, 0,0,-1, c, 0,1),
657                         video::S3DVertex(-0.5,+0.5,-0.5, 0,0,-1, c, 0,0),
658                         video::S3DVertex(+0.5,+0.5,-0.5, 0,0,-1, c, 1,0),
659                         video::S3DVertex(+0.5,-0.5,-0.5, 0,0,-1, c, 1,1),
660                         video::S3DVertex(+0.5,-0.5,+0.5, 0,0,+1, c, 1,1),
661                         video::S3DVertex(+0.5,+0.5,+0.5, 0,0,+1, c, 1,0),
662                         video::S3DVertex(-0.5,+0.5,+0.5, 0,0,+1, c, 0,0),
663                         video::S3DVertex(-0.5,-0.5,+0.5, 0,0,+1, c, 0,1),
664                 };
665                 u16 indices[12] = {0,1,2,2,3,0,4,5,6,6,7,4};
666                 buf->append(vertices, 8, indices, 12);
667         }
668
669         // "Interior"
670         // (add faces where a solid pixel is next to a transparent one)
671         u8* solidity = new u8[(width+2) * (height+2)];
672         u32 wstep = width + 2;
673         for (u32 y = 0; y < height + 2; ++y)
674         {
675                 u8* scanline = solidity + y * wstep;
676                 if (y == 0 || y == height + 1)
677                 {
678                         for (u32 x = 0; x < width + 2; ++x)
679                                 scanline[x] = 0;
680                 }
681                 else
682                 {
683                         scanline[0] = 0;
684                         u8* argb_scanline = data + (y - 1) * argb_wstep;
685                         for (u32 x = 0; x < width; ++x)
686                                 scanline[x+1] = (argb_scanline[x*4+3] >= alpha_threshold);
687                         scanline[width + 1] = 0;
688                 }
689         }
690
691         // without this, there would be occasional "holes" in the mesh
692         f32 eps = 0.01;
693
694         for (u32 y = 0; y <= height; ++y)
695         {
696                 u8* scanline = solidity + y * wstep + 1;
697                 for (u32 x = 0; x <= width; ++x)
698                 {
699                         if (scanline[x] && !scanline[x + wstep])
700                         {
701                                 u32 xx = x + 1;
702                                 while (scanline[xx] && !scanline[xx + wstep])
703                                         ++xx;
704                                 f32 vx1 = (x - eps) / (f32) width - 0.5;
705                                 f32 vx2 = (xx + eps) / (f32) width - 0.5;
706                                 f32 vy = 0.5 - (y - eps) / (f32) height;
707                                 f32 tx1 = x / (f32) width;
708                                 f32 tx2 = xx / (f32) width;
709                                 f32 ty = (y - 0.5) / (f32) height;
710                                 video::S3DVertex vertices[8] =
711                                 {
712                                         video::S3DVertex(vx1,vy,-0.5, 0,-1,0, c, tx1,ty),
713                                         video::S3DVertex(vx2,vy,-0.5, 0,-1,0, c, tx2,ty),
714                                         video::S3DVertex(vx2,vy,+0.5, 0,-1,0, c, tx2,ty),
715                                         video::S3DVertex(vx1,vy,+0.5, 0,-1,0, c, tx1,ty),
716                                 };
717                                 u16 indices[6] = {0,1,2,2,3,0};
718                                 buf->append(vertices, 4, indices, 6);
719                                 x = xx - 1;
720                         }
721                         if (!scanline[x] && scanline[x + wstep])
722                         {
723                                 u32 xx = x + 1;
724                                 while (!scanline[xx] && scanline[xx + wstep])
725                                         ++xx;
726                                 f32 vx1 = (x - eps) / (f32) width - 0.5;
727                                 f32 vx2 = (xx + eps) / (f32) width - 0.5;
728                                 f32 vy = 0.5 - (y + eps) / (f32) height;
729                                 f32 tx1 = x / (f32) width;
730                                 f32 tx2 = xx / (f32) width;
731                                 f32 ty = (y + 0.5) / (f32) height;
732                                 video::S3DVertex vertices[8] =
733                                 {
734                                         video::S3DVertex(vx1,vy,-0.5, 0,1,0, c, tx1,ty),
735                                         video::S3DVertex(vx1,vy,+0.5, 0,1,0, c, tx1,ty),
736                                         video::S3DVertex(vx2,vy,+0.5, 0,1,0, c, tx2,ty),
737                                         video::S3DVertex(vx2,vy,-0.5, 0,1,0, c, tx2,ty),
738                                 };
739                                 u16 indices[6] = {0,1,2,2,3,0};
740                                 buf->append(vertices, 4, indices, 6);
741                                 x = xx - 1;
742                         }
743                 }
744         }
745
746         for (u32 x = 0; x <= width; ++x)
747         {
748                 u8* scancol = solidity + x + wstep;
749                 for (u32 y = 0; y <= height; ++y)
750                 {
751                         if (scancol[y * wstep] && !scancol[y * wstep + 1])
752                         {
753                                 u32 yy = y + 1;
754                                 while (scancol[yy * wstep] && !scancol[yy * wstep + 1])
755                                         ++yy;
756                                 f32 vx = (x - eps) / (f32) width - 0.5;
757                                 f32 vy1 = 0.5 - (y - eps) / (f32) height;
758                                 f32 vy2 = 0.5 - (yy + eps) / (f32) height;
759                                 f32 tx = (x - 0.5) / (f32) width;
760                                 f32 ty1 = y / (f32) height;
761                                 f32 ty2 = yy / (f32) height;
762                                 video::S3DVertex vertices[8] =
763                                 {
764                                         video::S3DVertex(vx,vy1,-0.5, 1,0,0, c, tx,ty1),
765                                         video::S3DVertex(vx,vy1,+0.5, 1,0,0, c, tx,ty1),
766                                         video::S3DVertex(vx,vy2,+0.5, 1,0,0, c, tx,ty2),
767                                         video::S3DVertex(vx,vy2,-0.5, 1,0,0, c, tx,ty2),
768                                 };
769                                 u16 indices[6] = {0,1,2,2,3,0};
770                                 buf->append(vertices, 4, indices, 6);
771                                 y = yy - 1;
772                         }
773                         if (!scancol[y * wstep] && scancol[y * wstep + 1])
774                         {
775                                 u32 yy = y + 1;
776                                 while (!scancol[yy * wstep] && scancol[yy * wstep + 1])
777                                         ++yy;
778                                 f32 vx = (x + eps) / (f32) width - 0.5;
779                                 f32 vy1 = 0.5 - (y - eps) / (f32) height;
780                                 f32 vy2 = 0.5 - (yy + eps) / (f32) height;
781                                 f32 tx = (x + 0.5) / (f32) width;
782                                 f32 ty1 = y / (f32) height;
783                                 f32 ty2 = yy / (f32) height;
784                                 video::S3DVertex vertices[8] =
785                                 {
786                                         video::S3DVertex(vx,vy1,-0.5, -1,0,0, c, tx,ty1),
787                                         video::S3DVertex(vx,vy2,-0.5, -1,0,0, c, tx,ty2),
788                                         video::S3DVertex(vx,vy2,+0.5, -1,0,0, c, tx,ty2),
789                                         video::S3DVertex(vx,vy1,+0.5, -1,0,0, c, tx,ty1),
790                                 };
791                                 u16 indices[6] = {0,1,2,2,3,0};
792                                 buf->append(vertices, 4, indices, 6);
793                                 y = yy - 1;
794                         }
795                 }
796         }
797
798         // Add to mesh
799         scene::SMesh* mesh = new scene::SMesh();
800         buf->recalculateBoundingBox();
801         mesh->addMeshBuffer(buf);
802         buf->drop();
803         mesh->recalculateBoundingBox();
804         scene::SAnimatedMesh* anim_mesh = new scene::SAnimatedMesh(mesh);
805         mesh->drop();
806         return anim_mesh;
807 }
808
809 scene::IAnimatedMesh* ExtrudedSpriteSceneNode::extrude(video::ITexture* texture)
810 {
811         scene::IAnimatedMesh* mesh = NULL;
812         core::dimension2d<u32> size = texture->getSize();
813         video::ECOLOR_FORMAT format = texture->getColorFormat();
814         if (format == video::ECF_A8R8G8B8)
815         {
816                 // Texture is in the correct color format, we can pass it
817                 // to extrudeARGB right away.
818                 void* data = texture->lock(true);
819                 if (data == NULL)
820                         return NULL;
821                 mesh = extrudeARGB(size.Width, size.Height, (u8*) data);
822                 texture->unlock();
823         }
824         else
825         {
826                 video::IVideoDriver* driver = SceneManager->getVideoDriver();
827
828                 video::IImage* img1 = driver->createImageFromData(format, size, texture->lock(true));
829                 if (img1 == NULL)
830                         return NULL;
831
832                 // img1 is in the texture's color format, convert to 8-bit ARGB
833                 video::IImage* img2 = driver->createImage(video::ECF_A8R8G8B8, size);
834                 if (img2 != NULL)
835                 {
836                         img1->copyTo(img2);
837                         img1->drop();
838
839                         mesh = extrudeARGB(size.Width, size.Height, (u8*) img2->lock());
840                         img2->unlock();
841                         img2->drop();
842                 }
843                 img1->drop();
844         }
845         return mesh;
846 }
847
848 scene::IMesh* ExtrudedSpriteSceneNode::createCubeMesh()
849 {
850         video::SColor c(255,255,255,255);
851         video::S3DVertex vertices[24] =
852         {
853                 // Up
854                 video::S3DVertex(-0.5,+0.5,-0.5, 0,1,0, c, 0,1),
855                 video::S3DVertex(-0.5,+0.5,+0.5, 0,1,0, c, 0,0),
856                 video::S3DVertex(+0.5,+0.5,+0.5, 0,1,0, c, 1,0),
857                 video::S3DVertex(+0.5,+0.5,-0.5, 0,1,0, c, 1,1),
858                 // Down
859                 video::S3DVertex(-0.5,-0.5,-0.5, 0,-1,0, c, 0,0),
860                 video::S3DVertex(+0.5,-0.5,-0.5, 0,-1,0, c, 1,0),
861                 video::S3DVertex(+0.5,-0.5,+0.5, 0,-1,0, c, 1,1),
862                 video::S3DVertex(-0.5,-0.5,+0.5, 0,-1,0, c, 0,1),
863                 // Right
864                 video::S3DVertex(+0.5,-0.5,-0.5, 1,0,0, c, 0,1),
865                 video::S3DVertex(+0.5,+0.5,-0.5, 1,0,0, c, 0,0),
866                 video::S3DVertex(+0.5,+0.5,+0.5, 1,0,0, c, 1,0),
867                 video::S3DVertex(+0.5,-0.5,+0.5, 1,0,0, c, 1,1),
868                 // Left
869                 video::S3DVertex(-0.5,-0.5,-0.5, -1,0,0, c, 1,1),
870                 video::S3DVertex(-0.5,-0.5,+0.5, -1,0,0, c, 0,1),
871                 video::S3DVertex(-0.5,+0.5,+0.5, -1,0,0, c, 0,0),
872                 video::S3DVertex(-0.5,+0.5,-0.5, -1,0,0, c, 1,0),
873                 // Back
874                 video::S3DVertex(-0.5,-0.5,+0.5, 0,0,1, c, 1,1),
875                 video::S3DVertex(+0.5,-0.5,+0.5, 0,0,1, c, 0,1),
876                 video::S3DVertex(+0.5,+0.5,+0.5, 0,0,1, c, 0,0),
877                 video::S3DVertex(-0.5,+0.5,+0.5, 0,0,1, c, 1,0),
878                 // Front
879                 video::S3DVertex(-0.5,-0.5,-0.5, 0,0,-1, c, 0,1),
880                 video::S3DVertex(-0.5,+0.5,-0.5, 0,0,-1, c, 0,0),
881                 video::S3DVertex(+0.5,+0.5,-0.5, 0,0,-1, c, 1,0),
882                 video::S3DVertex(+0.5,-0.5,-0.5, 0,0,-1, c, 1,1),
883         };
884
885         u16 indices[6] = {0,1,2,2,3,0};
886
887         scene::SMesh* mesh = new scene::SMesh();
888         for (u32 i=0; i<6; ++i)
889         {
890                 scene::IMeshBuffer* buf = new scene::SMeshBuffer();
891                 buf->append(vertices + 4 * i, 4, indices, 6);
892                 buf->recalculateBoundingBox();
893                 mesh->addMeshBuffer(buf);
894                 buf->drop();
895         }
896         mesh->recalculateBoundingBox();
897         return mesh;
898 }