blib/lib/Games/RolePlay/MapGen/Editor.pm untested

filter: Statementstmt 0.0% 0 / 1392 Branchbran 0.0% 0 / 394 Conditioncond 0.0% 0 / 166 MC/DCmcdc 0.0% 0 / 103 Subroutinesub 0.0% 0 / 73 Podpod 0.0% 0 / 45 totaltotal 0.0% 0 / 2173 CC 198 SCAR 51.4
CC
198
Cov
0%
_build_rccm
702.0
new
420.0
marea_button_release_event
380.0
CRAP 170.8
1 # vi:filetype=perl:
2  
3 package Games::RolePlay::MapGen::Editor;
4  
5 # NOTE: I'm aware this is monolithic and heinous, please don't judge me. I
6 # intend to split this up into manageable chunks (aka modules) later. I'm new
7 # to GUI code and I'm surprised how big it gets.
8 #
9 # -Paul
10  
11 use common::sense;
12 use GD;
13 use Glib qw(TRUE FALSE);
14 use Gtk2 -init; # -init tells import to ->init() your app
15 use Gtk2::Ex::Simple::Menu;
16 use Gtk2::Ex::Dialogs::ErrorMsg;
17 use Gtk2::Ex::Dialogs::Question;
18 use Gtk2::Ex::PodViewer;
19 use Gtk2::SimpleList;
20 use Games::RolePlay::MapGen;
21 use File::HomeDir;
22 use File::Spec;
23 use DB_File;
24 use Storable qw(freeze thaw);
25 use Data::Dump qw(dump);
26 use POSIX qw(ceil);
27 use MIME::Base64;
28  
29 use POE::Component::Server::HTTP;
30 use POE::Kernel {loop => "Glib"};
31 use HTTP::Status;
32 use CGI qw(escapeHTML);
33  
34 use Games::RolePlay::MapGen::MapQueue::Object;
35 use Games::RolePlay::MapGen::MapQueue;
36 use Games::RolePlay::MapGen::Editor::_MForm qw(make_form $default_restore_defaults);
37 use Games::RolePlay::MapGen::Tools qw( roll choice _door _group );
38  
39 use version; our $VERSION = qv("1.0.0");
40  
41 our $DEFAULT_GENERATOR = 'Basic';
42 our @GENERATORS = (qw( Basic Blank OneBigRoom Perfect SparseAndLoops ));
43 our @GENERATOR_PLUGINS = (qw( BasicDoors FiveSplit ));
44 our @DEFAULT_GENERATOR_PLUGINS = (qw( BasicDoors ));
45 our @FILTERS = (qw( BasicDoors FiveSplit ClearDoors ));
46  
47 use vars qw($x); # like our, but at compile time so these constants work
48 use constant {
49 # the per-object index constants {{{
50 MAP => $x++, # the Games::RolePlay::MapGen object, the actual map arrays are in [MAP]{_the_map}
51 MQ => $x++, # the Games::RolePlay::MapGen::MapQueue object
52 WINDOW => $x++, # the Gtk2 window (Gtk2::Window)
53 MENU => $x++, # the main menubar (Gtk2::Ex::Simple::Menu)
54 MAREA => $x++, # the map area Gtk2::Image
55 VP_DIM => $x++, # the current dimensions (changes on resizes and things) of the Gtk2::Viewport holding the [MAREA]
56 SETTINGS => $x++, # a tied DB_File hashref full of settings
57 FNAME => $x++, # the current file name or undef
58 STAT => $x++, # the statusbar (Gtk2::Statusbar)
59 MP => $x++, # the current map pixbufs, cell size, and pixbuf dimensions
60 RCCM => $x++, # the right click context menus (there are two: [RCCM][0] for tiles and [RCCM][1] for closures)
61 O_LT => $x++, # the tile location currently moused-overed, O_ is for old, during the motion-notify, O_LT is the
62 # old location and LT is the new one, although, LT isn't a constant
63 SEL_S => $x++, # the selection start, set to O_LT when a button is pressed
64 SEL_E => $x++, # set to the end of the selection being dragged during the selection handler. really only used in
65 # the button release event to (possibly) select a single square when shift-clicking
66 SEL_W => $x++, # the currently "working" select rectangle, used to pop the end of SELECTION while *still* dragging
67 SELECTION => $x++, # the current selection rectangles [ [x1,y1,x2,y2], [...], ... ]
68 S_ARG => $x++, # the status-bar arguments: the current tile location (LT), tile type, and door info
69 # [\@lt, $tile->{type}, undef]; $sarg->[1] (type) is replaced with [$g->name, $g->desc] when
70 # $tile has a group... door info starts out as undef and changes to [dir=>desc] when there is a door
71 # moused-overed. Perhaps the best way to describe it is this huge block of examples:
72 # [[11, 9, "corridor"], undef, undef]
73 # [[12, 9, "corridor"], undef, ["s", ["wall"]]]
74 # [[6, 4, "room"], ["Room #1", "(4, 3) 10x8"], undef]
75 # [[6, 3, "room"], ["Room #1", "(4, 3) 10x8"], ["w", ["opening"]]]
76 # [[5, 5], ["Room #1", "(4, 3) 10x8"], undef]
77 # [[5, 5], ["Room #1", "(4, 3) 10x8"], ["e", ["opening"]]]
78 # [[6, 5, "room"], ["Room #1", "(4, 3) 10x8"], undef]
79 # [[6, 6, "room"], ["Room #1", "(4, 3) 10x8"], undef]
80 # [[6, 6], ["Room #1", "(4, 3) 10x8"], ["s", ["opening"]]]
81 # [[6, 7, "room"], ["Room #1", "(4, 3) 10x8"], ["n", ["opening"]]]
82 # [[6, 7], ["Room #1", "(4, 3) 10x8"], undef]
83 # [[6, 7], ["Room #1", "(4, 3) 10x8"], ["s", ["wall"]]]
84 # [[6, 8, "corridor"], undef, ["n", ["wall"]]]
85 # [[7, 8], undef, ["n", ["ordinary", "door"]]]
86 # [ [7, 7, "room"], ["Room #1", "(4, 3) 10x8"], ["s", ["ordinary", "door"]], ]
87 O_DR => $x++, # door info, [dir => desc], called O_DR since it's the "old" door. really only used to invoke a
88 # reddraw of the cursors when there *was* a door (O_DR) and there *nolonger* is one
89 SERVER => $x++, # the map server (if applicable) [port, PoCo::HTTPD]
90 # }}}
91 };
92  
93 1;
94  
95 # new {{{
96 sub new {
97 my $class = shift;
98 my $this = bless [], $class;
99  
100 my $fname = "GRM Editor";
101 unless( File::Spec->case_tolerant ) {
102 $fname = lc $fname;
103 $fname =~ s/ /_/g;
104 substr($fname,0,0) = ".";
105 }
106  
107 my @homedir = File::HomeDir->my_home;
108 push @homedir, "Application Data" if "@homedir" =~ m/Documents and Settings/i;
109  
110 $fname = File::Spec->catfile(@homedir, $fname);
111  
112 # warn "fname=$fname";
113 my %o; tie %o, DB_File => $fname or die $!;
114  
115 $o{REMEMBER_SP} = 1 unless defined $o{REMEMBER_SP};
116  
117 $this->[SETTINGS] = \%o;
118  
119 my $vbox = new Gtk2::VBox;
120 my $window = $this->[WINDOW] = new Gtk2::Window("toplevel");
121 $window->signal_connect( delete_event => sub { $this->quit } );
122 $window->set_size_request(700,475);
123 $window->set_position('center');
124 $window->add($vbox);
125 $window->set_title("GRM Editor");
126  
127 my $menu_tree = [
128 _File => {
129 item_type => '<Branch>',
130 children => [
131 'Generate _New Map' => {
132 item_type => '<StockItem>',
133 callback => sub { $this->generate },
134 accelerator => '<ctrl>N',
135 extra_data => 'gtk-new',
136 },
137 _Open => {
138 item_type => '<StockItem>',
139 callback => sub { $this->open_file },
140 accelerator => '<ctrl>O',
141 extra_data => 'gtk-open',
142 },
143 _Save => {
144 item_type => '<StockItem>',
145 callback => sub { $this->save_file },
146 accelerator => '<ctrl>S',
147 extra_data => 'gtk-save',
148 },
149 'Save As...' => {
150 item_type => '<StockItem>',
151 callback => sub { $this->save_file_as },
152 extra_data => 'gtk-save-as',
153 },
154 '_Export' => {
155 item_type => '<Branch>',
156 children => [
157 "_Image..." => {
158 callback => sub { $this->save_image_as },
159 },
160 "_Text File..." => {
161 callback => sub { $this->save_text_as },
162 },
163 ],
164 },
165 _Close => {
166 item_type => '<StockItem>',
167 callback => sub { $this->blank_map },
168 accelerator => '<ctrl>W',
169 extra_data => 'gtk-close',
170 },
171 _Quit => {
172 item_type => '<StockItem>',
173 callback => sub { $this->quit },
174 accelerator => '<ctrl>Q',
175 extra_data => 'gtk-quit',
176 },
177 ],
178 },
179 _Edit => {
180 item_type => '<Branch>',
181 children => [
182 '_Redraw' => {
183 callback => sub { warn "forced redraw"; $this->draw_map; $this->draw_map_w_cursor },
184 accelerator => '<ctrl>R',
185 },
186 'R_ender Settings'=> {
187 callback => sub { $this->render_settings },
188 },
189 'Server _Settings'=> {
190 callback => sub { $this->server_settings },
191 accelerator => '<ctrl>T',
192 },
193 Separator => {
194 item_type => '<Separator>',
195 },
196 _Preferences => {
197 item_type => '<StockItem>',
198 callback => sub { $this->preferences },
199 accelerator => '<ctrl>P',
200 extra_data => 'gtk-preferences',
201 },
202 ],
203 },
204 _Help => {
205 item_type => '<LastBranch>',
206 children => [
207 _Help => {
208 item_type => '<StockItem>',
209 callback => sub { $this->help },
210 extra_data => 'gtk-help',
211 },
212 _About => {
213 item_type => '<StockItem>',
214 callback => sub { $this->about },
215 extra_data => 'gtk-about',
216 },
217 ],
218 },
219 ];
220  
221 my $menu = $this->[MENU] = Gtk2::Ex::Simple::Menu->new (
222 menu_tree => $menu_tree,
223 default_callback => sub { $this->unknown_menu_callback },
224 );
225  
226 $vbox->pack_start($menu->{widget}, 0,0,0);
227 $window->add_accel_group($menu->{accel_group});
228  
229 my $marea = $this->[MAREA] = new Gtk2::Image;
230 my $scwin = Gtk2::ScrolledWindow->new;
231 my $vp = Gtk2::Viewport->new(undef,undef);
232 my $al = Gtk2::Alignment->new(0.5,0.5,0,0);
233 my $eb = Gtk2::EventBox->new;
234  
235 $eb->set_has_tooltip(TRUE);
236 $eb->signal_connect( query_tooltip => sub {
237 my ($widget, $x, $y, $keyboard_mode, $tooltip) = @_;
238  
239 my @cs = split('x', $this->[MAP]{cell_size});
240 my @tc = (int($x/$cs[0]), int($y/$cs[1]));
241  
242 return FALSE unless $this->[MQ]->_check_loc(\@tc);
243  
244 my @o = $this->[MQ]->objects_at_location(@tc);
245  
246 return FALSE unless @o;
247  
248 $tooltip->set_text(
249 join("\n",
250 map { my $d = $_->[0]->desc; my $v = ($_->[1]=~ s/(\d+)$/ $1/ ? $_->[1] : "living"); "$v: $d" }
251 sort {$a->[-1] <=> $b->[-1] || $a->[1] cmp $b->[1] }
252 map {my $x= [$_, $_->attr('var')]; push @$x, ($x->[1]=~m/^l/?0:1); $x} @o) );
253  
254 return TRUE;
255 });
256  
257 # This is so we can later determin the size of the viewport.
258 $this->[VP_DIM] = my $dim = [];
259 $vp->signal_connect( size_allocate => sub { my $r = $_[1]; $dim->[0] = $r->width; $dim->[1] = $r->height; 0; });
260  
261 my $sb = $this->[STAT] = new Gtk2::Statusbar; $sb->push(1,'');
262  
263 my $s_up = sub {
264 $sb->pop(1); return unless @_;
265  
266 if( not ref $_[0] ) {
267 my @c = caller;
268 warn "caller=(@c)";
269 }
270  
271 # @_ is just like $this->[S_ARG], but (stuff) instead of [stuff]
272  
273 my $loc = shift; # so this is (x,y), not a tile object from the actual map
274 my $type = pop @$loc if @$loc == 3;
275 my $group = shift;
276 my $door = shift;
277 my $txt = '';
278  
279 if( $loc ) {
280 $txt .= "tile: " . ($type ? "$type " : ''). sprintf('[%d,%d]', @$loc);
281 $txt .= ":$door->[0] (@{$door->[1]})" if $door;
282 $txt .= " \x{2014} group: @$group" if $group;
283  
284 } else {
285 $loc = $group = $door = undef;
286 }
287  
288 $sb->push(1, $txt);
289 };
290  
291 $this->[O_LT]=[];
292  
293 my $bpe = 0;
294  
295 $eb->add_events([qw(leave-notify-mask pointer-motion-mask pointer-motion-hint-mask)]);
296 $eb->signal_connect( motion_notify_event => sub { $this->marea_motion_notify_event($s_up, @_); 0; });
297 $eb->signal_connect( leave_notify_event => sub {
298 if( $bpe ) {
299 $bpe = 0; # bpe prevents the leave_notify once
300  
301 } else {
302 @{$this->[O_LT]} = (); $s_up->(); $this->draw_map_w_cursor;
303 }
304 });
305  
306 $eb->signal_connect( button_release_event => sub {
307 my ($widget, $event) = @_;
308  
309 return FALSE if $event->button == 3;
310 $this->marea_button_release_event(@_);
311 });
312  
313 $eb->signal_connect ( button_press_event => sub {
314 my ($widget, $event) = @_;
315  
316 if( $event->button == 3 ) {
317 $bpe = 1; # bpe prevents the leave_notify_event once
318 $this->right_click_map($event);
319  
320 } else {
321 $this->marea_button_press_event(@_);
322 $this->double_click_map(@_)
323 if $event->type eq '2button-press';
324  
325 # tried using >= and * (see Glib under flags), but this
326 # seems to return boring strings
327 }
328  
329 return FALSE; # returning true prevents other events from firing
330 });
331  
332 $scwin->set_policy('automatic', 'automatic');
333 $scwin->add($vp);
334 $al->add($eb);
335 $vp->add($al);
336 $eb->add($marea);
337 $vbox->pack_start($scwin,1,1,0);
338 $vbox->pack_end($sb,0,0,0);
339  
340 if( $ARGV[0] and -f $ARGV[0] ) {
341 $this->read_file( $this->[SETTINGS]{LAST_FNAME} = $ARGV[0] );
342 }
343 $this->draw_map;
344  
345 return $this;
346 }
347 # }}}
348 # error {{{
349 sub error {
350 my $this = shift;
351 my $error = shift;
352  
353 # The Ex dialogs use Pango Markup Language... pffft
354 $error = Glib::Markup::escape_text( $error );
355  
356 Gtk2::Ex::Dialogs::ErrorMsg->new_and_run( parent_window=>$this->[WINDOW], text=>$error );
357 }
358 # }}}
359  
360 # FILE MANIPULATION
361 # open_file {{{
362 sub open_file {
363 my $this = shift;
364  
365 my $file_chooser =
366 Gtk2::FileChooserDialog->new ('Open a Map File',
367 $this->[WINDOW], 'open', 'gtk-cancel' => 'cancel', 'gtk-ok' => 'ok');
368  
369 $file_chooser->set_default_response('ok');
370  
371 if( $file_chooser->run eq 'ok' ) {
372 my $filename = $file_chooser->get_filename;
373  
374 $file_chooser->destroy;
375 $this->read_file($filename);
376 return;
377 }
378  
379 $file_chooser->destroy;
380 }
381 # }}}
382 # save_file {{{
383 sub save_file {
384 my $this = shift;
385  
386 unless( $this->[FNAME] ) {
387 $this->save_file_as;
388 return;
389 }
390  
391 my $file = $this->[FNAME];
392 my $pulser = $this->pulser( "Saving $file ...", "File I/O", 175 );
393 my $map = $this->[MAP];
394 my %mqo = (map {("@{$_->[0]}" => $_->[1])} $this->[MQ]->objects_with_locations);
395 eval {
396 $map->set_exporter( "XML" );
397 $map->export( fname => $this->[FNAME], t_cb => sub {
398 my (($x,$y), $h) = @_;
399  
400 local $" = ",";
401  
402 for my $o (@{$mqo{"$x $y"}}) {
403 push @{$h->{contents}{item}}, {
404 name=> $o->{v}, unique => ($o->{u}?'true':'false'), qty=> $o->{q}, ($o->{c} ? (id=>$o->{c}) :()),
405 attr=>[
406 map { {name=>$_->[0], value=>(ref($_->[1]) ? "@{$_->[1]}" : $_->[1])} }
407 map { [$_, $o->{a}{$_}] }
408 keys %{$o->{a}}
409 ],
410 };
411 }
412  
413 $pulser->();
414 });
415 };
416 $this->error($@) if $@;
417 $pulser->('destroy');
418 }
419 # }}}
420 # save_file_as {{{
421 sub save_file_as {
422 my $this = shift;
423  
424 my $file_chooser =
425 Gtk2::FileChooserDialog->new ('Save a Map File',
426 $this->[WINDOW], 'save', 'gtk-cancel' => 'cancel', 'gtk-ok' => 'ok');
427  
428 $file_chooser->set_default_response('ok');
429  
430 if ('ok' eq $file_chooser->run) {
431 my $fname = $file_chooser->get_filename;
432 $fname .= ".xml" unless $fname =~ m/\.xml\z/i;
433  
434 $this->[FNAME] = $fname;
435 $this->[WINDOW]->set_title("GRM Editor: $fname");
436  
437  
438 $file_chooser->destroy;
439 $this->save_file;
440  
441 return;
442 }
443  
444 $file_chooser->destroy;
445 }
446 # }}}
447 # save_image_as {{{
448 sub save_image_as {
449 my $this = shift;
450  
451 my $file_chooser =
452 Gtk2::FileChooserDialog->new ('Save a Map Image',
453 $this->[WINDOW], 'save', 'gtk-cancel' => 'cancel', 'gtk-ok' => 'ok');
454  
455 $file_chooser->set_default_response('ok');
456  
457 if ('ok' eq $file_chooser->run) {
458 my $fname = $file_chooser->get_filename;
459 $fname .= ".png" unless $fname =~ m/\.png\z/i;
460  
461 $file_chooser->destroy;
462  
463 my $pulser = $this->pulser( "Saving $fname ...", "File I/O", 150 );
464 my $map = $this->[MAP];
465 eval {
466 $map->set_exporter( "PNG" );
467 $map->export( fname => $fname, t_cb => $pulser );
468 };
469 $this->error($@) if $@;
470 $pulser->('destroy');
471  
472 return;
473 }
474  
475 $file_chooser->destroy;
476 }
477 # }}}
478 # save_text_as {{{
479 sub save_text_as {
480 my $this = shift;
481  
482 my $file_chooser =
483 Gtk2::FileChooserDialog->new ('Save a Map Image',
484 $this->[WINDOW], 'save', 'gtk-cancel' => 'cancel', 'gtk-ok' => 'ok');
485  
486 $file_chooser->set_default_response('ok');
487  
488 if ('ok' eq $file_chooser->run) {
489 my $fname = $file_chooser->get_filename;
490 $fname .= ".txt" unless $fname =~ m/\.txt\z/i;
491  
492 $file_chooser->destroy;
493  
494 my $pulser = $this->pulser( "Saving $fname ...", "File I/O", 75 );
495 my $map = $this->[MAP];
496 eval {
497 $map->set_exporter( "Text" );
498 $map->export( fname=>$fname, nocolor=>1 );
499 };
500 $this->error($@) if $@;
501 $pulser->('destroy');
502  
503 return;
504 }
505  
506 $file_chooser->destroy;
507 }
508 # }}}
509 # read_file (aka load_file) {{{
510 sub read_file {
511 my $this = shift;
512 my $file = shift;
513  
514 my $pulser = $this->pulser( "Reading $file ...", "File I/O" );
515 eval {
516 my %mqo;
517 $this->[MAP] = my $map = Games::RolePlay::MapGen->import_xml( $file, t_cb => sub {
518 if( my ($x,$y, $txp) = @_ ) {
519  
520 my $items = $txp->find('contents/item');
521 for my $item ($items->get_nodelist) {
522 my $name = $item->findvalue( '@name' )->value;
523 my $uniq = $item->findvalue( '@unique' )->value;
524 my $qty = $item->findvalue( '@qty' )->value;
525 my $id = $item->findvalue( '@id' )->value;
526  
527 my $attrs = $item->find('attr');
528 my %a;
529 for my $attr ($attrs->get_nodelist) {
530 my $var = $attr->findvalue( '@name' )->value;
531 my $val = $attr->findvalue( '@value' )->value;
532  
533 $a{$var} = $val;
534 }
535  
536 my $ob = new Games::RolePlay::MapGen::MapQueue::Object($name);
537 $ob->nonunique($id) unless $uniq and $uniq eq "true";
538 $ob->quantity($qty) if $qty;
539  
540 for my $k (keys %a) {
541 my $v = $a{$k};
542 $v = [ split ",", $v ] if $k eq "color";
543  
544 $ob->attr($k => $v);
545 }
546  
547 push @{$mqo{$x}{$y}}, $ob;
548 }
549 }
550  
551 $pulser->();
552 });
553  
554 $this->[MQ] = my $mq = new Games::RolePlay::MapGen::MapQueue( $map );
555 for my $x (keys %mqo) {
556 for my $y (keys %{ $mqo{$x} }) {
557 for my $o (@{$mqo{$x}{$y}}) {
558 $mq->replace( $o => ($x,$y) );
559 }} }
560 };
561 $this->error($@) if $@;
562 $pulser->('destroy');
563  
564 $this->[FNAME] = $file;
565 $this->[WINDOW]->set_title("GRM Editor: $file");
566 $this->draw_map;
567 }
568 # }}}
569 # pulser {{{
570 sub pulser {
571 my $this = shift;
572 my $op1 = shift || "Doing something";
573 my $op2 = shift || "Something";
574 my $cnt = shift || 25;
575  
576 my $dialog = new Gtk2::Dialog;
577 my $label = new Gtk2::Label($op1);
578 my $prog = new Gtk2::ProgressBar;
579  
580 $dialog->set_title($op2);
581 $dialog->vbox->pack_start( $label, TRUE, TRUE, 0 );
582 $dialog->vbox->pack_start( $prog, TRUE, TRUE, 0 );
583 $dialog->show_all;
584  
585 # NOTE: I'm not sure all these main_interations are necessary as written,
586 # but certainly just doing one isn't enough for some reason.
587 Gtk2->main_iteration while Gtk2->events_pending;
588 $prog->pulse;
589 Gtk2->main_iteration while Gtk2->events_pending;
590 Gtk2->main_iteration while Gtk2->events_pending;
591  
592 my $x = 0;
593 return sub {
594 if( ++$x >= $cnt ) {
595 Gtk2->main_iteration while Gtk2->events_pending;
596 $prog->pulse;
597 Gtk2->main_iteration while Gtk2->events_pending;
598 $x = 0;
599 }
600  
601 if( @_ and $_[0] eq "destroy" ) {
602 $dialog->destroy;
603 }
604 };
605 }
606 # }}}
607  
608 # DRAWING
609 # draw_mapqueue_objects {{{
610 sub draw_mapqueue_objects {
611 my ($this, $image) = @_;
612  
613 my $outline = $image->colorAllocate(0, 0, 0);
614  
615 my @cs = split('x', $this->[MAP]{cell_size});
616 my @hs = map {$_ / 2.555555555555} @cs; # humanoid size
617 my @of = map {int($_/2)} @cs; # humanoid offset
618 my @is = map {$_ / 3.285714} @cs; # item size
619 my @if = map {$_ / 4.6} @cs; # item offset
620  
621 my %colors;
622  
623 for my $owl ($this->[MQ]->objects_with_locations) {
624 my ($x, $y, @o) = map {@$_} @$owl;
625  
626 $x = $cs[0]*$x + $of[0];
627 $y = $cs[1]*$y + $of[1];
628  
629 for my $o (@o) {
630 my $var = $o->attr('var');
631 my $col = $o->attr('color');
632 my $icl = $colors{"@$col"};
633  
634 unless( defined $icl ) {
635 $icl = $colors{"@$col"} = $image->colorAllocate(@$col);
636 }
637  
638 if( $var =~ m/^l/ ) {
639 $image->filledEllipse ( $x, $y, @hs, $icl );
640 $image->ellipse ( $x, $y, @hs, $outline );
641  
642 } elsif( my ($in) = $var =~ m/item(\d+)/ ) {
643 my $c = 2*3.1415926 * ($in/8);
644 my $ax = $x + $if[0] * cos $c;
645 my $ay = $y + $if[1] * sin $c;
646  
647 $image->filledEllipse ( $ax, $ay, @is, $icl );
648 $image->ellipse ( $ax, $ay, @is, $outline );
649 }
650 }
651 }
652 }
653 # }}}
654 # draw_map (initial draw after a new mapload, sets up the MP pixbufs, etc) {{{
655 sub draw_map {
656 my $this = shift;
657  
658 my $map = $this->[MAP];
659 $map = $this->[MAP] = $this->blank_map unless $map;
660  
661 # clear out any selections or cursors that probably nolonger apply
662 $this->[SEL_S] = $this->[SEL_E] = $this->[SELECTION] = $this->[O_DR] = $this->[S_ARG] = undef;
663 @{$this->[O_LT]}=(); # this clears the pointer whole-tile highlight
664  
665 $map->set_exporter( "PNG" );
666 my $image = $map->export( -retonly );
667  
668 $this->draw_mapqueue_objects( $image );
669  
670 my $loader = Gtk2::Gdk::PixbufLoader->new;
671 $loader->write($image->png);
672 $loader->close;
673  
674 my @cs = split('x', $this->[MAP]{cell_size});
675 my $gd = new GD::Image(map {$_-1} @cs);
676 my $g1 = $gd->colorAllocateAlpha(0x00, 0xbb, 0x00, 0.5*127);
677 my $g2 = $gd->colorAllocateAlpha(0x00, 0xff, 0x00, 0.7*127);
678 my @wh = $gd->getBounds;
679  
680 $gd->filledRectangle( 2,2 => (map {$_-4} @cs), $g2 );
681  
682 my $cursor = Gtk2::Gdk::PixbufLoader->new;
683 $cursor->write($gd->png);
684 $cursor->close;
685  
686 $this->[MP] = [ $loader->get_pixbuf, $cursor->get_pixbuf, @cs, @wh ];
687 $this->draw_map_w_cursor;
688 }
689 # }}}
690 # draw_map_w_cursor {{{
691 sub draw_map_w_cursor {
692 my $this = shift;
693 my $pb = $this->[MP][0];
694  
695 if( my @o = (@{ $this->[O_LT] }) ) {
696 my ($cb, ($cx,$cy), ($dw,$dh) ) = @{$this->[MP]}[1 .. $#{$this->[MP]}];
697 my @ul = ($cx*$o[0]+1, $cy*$o[1]+1);
698  
699 my @pm = $pb->render_pixmap_and_mask(0);
700  
701 $cb->render_to_drawable_alpha($pm[0], 0,0, @ul, $dw,$dh, full=>255, max=>0,0);
702  
703 my ($gc, $cm);
704 if( my $s2 = @{$this->[S_ARG]}[2] ) {
705 my $cc = Gtk2::Gdk::Color->new( map {65535*($_/0xff)} (0x00, 0xff, 0x00) );
706  
707 $gc = Gtk2::Gdk::GC->new($pm[0]);
708 ($cm = $gc->get_colormap)->alloc_color($cc, 0, 0);
709 $gc->set_foreground($cc);
710  
711 my $d = $s2->[0];
712 if( $d eq 'n' ) {
713 $pm[0]->draw_rectangle($gc, 1, $ul[0]+4,$ul[1]-2, $cx-9, 3);
714  
715 } elsif( $d eq 's' ) {
716 $pm[0]->draw_rectangle($gc, 1, $ul[0]+4,$ul[1]+$cy-2, $cx-9, 3);
717  
718 } elsif( $d eq 'w' ) {
719 $pm[0]->draw_rectangle($gc, 1, $ul[0]-2,$ul[1]+4, 3, $cy-9);
720  
721 } elsif( $d eq 'e' ) {
722 $pm[0]->draw_rectangle($gc, 1, $ul[0]+$cx-2,$ul[1]+4, 3, $cy-9);
723 }
724  
725 }
726  
727 if( my $sel = $this->[SELECTION] ) {
728 my $sc = Gtk2::Gdk::Color->new( map {65535*($_/0xff)} (0x00, 0xff, 0x00) );
729 unless( $gc and $cm ) {
730 $gc = Gtk2::Gdk::GC->new($pm[0]);
731 ($cm = $gc->get_colormap);
732 }
733  
734 for my $s (@$sel) {
735 # NOTE: when we have more than one selection area, we'll
736 # probably want to prevent drawing the overlapping part of the
737 # rectangles.
738  
739 $cm->alloc_color($sc, 0, 0);
740 $gc->set_foreground($sc);
741  
742 my @s = ($cx*$s->[0], $cy*$s->[1]);
743 my @e = ($cx*(1+$s->[2]-$s->[0]),$cy*(1+$s->[3]-$s->[1]));
744  
745 $pm[0]->draw_rectangle($gc, 0, @s, @e);
746 }
747 }
748  
749 $this->[MAREA]->set_from_pixmap(@pm);
750 return;
751 }
752  
753 $this->[MAREA]->set_from_pixbuf($pb);
754 }
755 # }}}
756 # double_click_map {{{
757 sub double_click_map {
758 my ($this, $widget, $event) = @_;
759  
760 # For some reason, double clicking trips a selection.
761 # rather than carefully figuring that out, we'll just clear it.
762 $this->[SEL_S] = $this->[SEL_E] = $this->[SELECTION] = undef;
763  
764 my @o_lt = @{$this->[O_LT]};
765 my $tile = $this->[MAP]{_the_map}[ $o_lt[1] ][ $o_lt[0] ];
766 return unless defined $tile->{type};
767  
768 if( my $s2 = @{$this->[S_ARG]}[2] ) {
769 my $d = $s2->[0];
770 my $od = $tile->{od}{$d};
771  
772 if( ref $od ) {
773 $this->closure_door_properties( [$tile, $d] );
774  
775 } else {
776 goto PFFT;
777 }
778  
779 } else {
780 PFFT: $this->edit_items_at_location( $tile, @o_lt );
781 }
782 }
783 # }}}
784 # edit_items_at_location {{{
785 sub edit_items_at_location {
786 my ($this, $tile, $x,$y ) = @_;
787  
788 my $options = [[ # column 1
789 { mnemonic => "_Living: ",
790 type => "text",
791 desc => "the name of the living you wish to add to the map",
792 name => 'lname',
793 default => '' },
794  
795 (map(
796 { mnemonic => "Item #_$_: ",
797 type => "text",
798 desc => "the name of an item at this location",
799 name => "item$_",
800 default => '' }, 1 .. 8)),
801 ],[
802 { mnemonic => "unique: ",
803 type => "bool",
804 desc => "whether this living is uniquely named",
805 name => 'ulname',
806 disable => { lname => sub { $_[0] =~ m/^(.+?)\s*\#\s*(\d+)\s*$/ } },
807 default => 1 },
808  
809 (map(
810 { mnemonic => "unique: ",
811 type => "bool",
812 desc => "whether this living is uniquely named",
813 name => "uitem$_",
814 disable => { "item$_" => sub { $_[0] =~ m/^(.+?)\s*\#\s*(\d+)\s*$/ } },
815 default => 0 }, 1 .. 8)),
816 ],[
817 { mnemonic => "color: ",
818 type => "color",
819 desc => "the color of the living marker",
820 name => 'clname',
821 default => '#6464ff' },
822  
823 (map(
824 { mnemonic => "color: ",
825 type => "color",
826 desc => "the color of the item #$_ marker",
827 name => "citem$_",
828 default => '#ffff00' }, 1 .. 8)),
829 ]];
830  
831 my $i = {};
832 my %o_i;
833 for my $o ($this->[MQ]->objects_at_location($x,$y)) {
834 my $k = $o->attr('var');
835 my $c = $o->attr('color');
836 my $C = sprintf('#%02x%02x%02x', @$c);
837  
838 push @{$o_i{$k}}, $o;
839 $i->{$k} = $o->desc;
840 $i->{'c' . $k} = $C;
841 }
842  
843 my ($result, $o) = make_form($this->[WINDOW], $i, $options, "Objects at Location");
844 if( $result eq "ok" ) {
845  
846 for my $k (grep {!m/^[uc]/} sort keys %$o) {
847 if( my $k = delete $o_i{$k} ) {
848 $this->[MQ]->remove( $_ ) for @$k;
849 }
850  
851 my $v = $o->{$k};
852 next unless $v =~ m/[\w\d]/;
853 $v =~ s/^\s+//;
854 $v =~ s/\s+$//;
855  
856 my ($n, $c) = $v =~ m/^(.+?)\s*\#\s*(\d+)\s*$/;
857  
858 $n = $v unless defined $n;
859  
860 my $color = $o->{'c'.$k};
861 my $unique = $o->{'u'.$k};
862 my $qty = $1 if $n =~ s/\s*\(\s*(\d+)\s*\)\s*$//;
863  
864 my $ob = new Games::RolePlay::MapGen::MapQueue::Object($n||$v);
865 $ob->quantity($qty) if defined $qty;
866 $ob->attr(var => $k);
867 $ob->attr(color => [ map { hex $_ } $color =~ m/([\d\w]{2})/g ]);
868  
869 if( $c ) {
870 $ob->nonunique($c);
871  
872 } elsif( not $unique ) {
873 $ob->nonunique;
874 }
875  
876 $this->[MQ]->replace( $ob => $x,$y );
877 }
878  
879 $this->draw_map; # draw the map from scratch with the new objects
880 }
881 }
882 # }}}
883 # marea_button_press_event {{{
884 sub marea_button_press_event {
885 my ($this, $ebox, $ebut) = @_;
886  
887 my @o_lt = @{ $this->[O_LT] };
888  
889 $this->[SEL_S] = \@o_lt if @o_lt == 2;
890 }
891 # }}}
892 # marea_button_release_event {{{
893 sub marea_button_release_event {
894 my ($this, $ebox, $ebut) = @_;
895  
896 unless( $this->[SEL_E] ) {
897 my @state = $ebut->device->get_state( $this->[MAREA]->get_parent_window );
898 my $shift = $state[0] * 'shift-mask'; # see Glib under flags for reasons this makes sense
899 if( $shift ) {
900 # NOTE: pretend we just selected this one tile with motion, so it adds to the current selection:
901 $this->marea_selection_handler( $this->[O_LT], $this->[O_LT], $ebut );
902  
903 } else {
904 $this->draw_map_w_cursor if delete $this->[SELECTION];
905 }
906 }
907  
908 delete $this->[SEL_S];
909 delete $this->[SEL_E];
910 delete $this->[SEL_W];
911  
912 if( my $s = $this->[SELECTION] ) {
913 # NOTE: combine any rectangles that are combinable
914  
915 POINTLESS: {
916 for my $j (0 .. $#$s) { my $l = $s->[$j];
917 for my $i (0 .. $#$s) { my $r = $s->[$i];
918 next if $i == $j;
919  
920 if( $r->[0]>=$l->[0] and $r->[2]<=$l->[2] ) {
921 if( $r->[1]>=$l->[1] and $r->[3]<=$l->[3] ) {
922 splice @$s, $i, 1;
923 redo POINTLESS;
924 }}
925 }}
926 }
927  
928 CONTIGUOUS: {
929 for my $j (0 .. $#$s) { my $l = $s->[$j];
930 for my $i (0 .. $#$s) { my $r = $s->[$i];
931 next if $i == $j;
932  
933 if( $r->[0]==$l->[0] and $r->[2]==$l->[2] ) {
934 my ($max_min, $min_max) = $l->[1]<$r->[1] ? ($l->[3],$r->[1]) : ($r->[3],$l->[1]);
935  
936 if( $max_min >= $min_max-1 ) {
937 my $min = $r->[1]; $min = $l->[1] if $l->[1] < $min;
938 my $max = $r->[3]; $max = $l->[3] if $l->[3] > $max;
939  
940 splice @$s, $i, 1, [ $l->[0], $min, $l->[2], $max ];
941 splice @$s, $j, 1;
942  
943 goto CONTIGUOUS;
944 }
945 }
946  
947 if( $r->[1]==$l->[1] and $r->[3]==$l->[3] ) {
948 my ($max_min, $min_max) = $l->[0]<$r->[0] ? ($l->[2],$r->[0]) : ($r->[2],$l->[0]);
949  
950 if( $max_min >= $min_max-1 ) {
951 my $min = $r->[0]; $min = $l->[0] if $l->[0] < $min;
952 my $max = $r->[2]; $max = $l->[2] if $l->[2] > $max;
953  
954 splice @$s, $i, 1, [ $min, $l->[1], $max, $l->[3] ];
955 splice @$s, $j, 1;
956  
957 goto CONTIGUOUS;
958 }
959 }
960  
961 }}
962 }
963 }
964 }
965 # }}}
966 # marea_selection_handler {{{
967 sub marea_selection_handler {
968 my ($this, $o_lt, $lt, $event) = @_;
969 my $s_sel = $this->[SEL_S];
970  
971 my @state = $event->device->get_state( $this->[MAREA]->get_parent_window );
972 my $shift = $state[0] * 'shift-mask'; # see Glib under flgas for reasons this makes sense
973  
974 $this->[SEL_E] = $lt;
975  
976 # 1. TODO: if we're holding control, we should subtract rectangles
977 # 2. if we're hodling shift, we should add rectangles
978  
979 my $a = [@$s_sel, @$lt];
980 my $w = $this->[SEL_W];
981 $this->[SEL_W] = $a;
982  
983 ($a->[0],$a->[2]) = ($a->[2],$a->[0]) if $a->[2] < $a->[0];
984 ($a->[1],$a->[3]) = ($a->[3],$a->[1]) if $a->[3] < $a->[1];
985  
986 if( $shift and (my $s = $this->[SELECTION]) ) {
987 # NOTE: we don't combine any selections that form contiguous
988 # rectangles here since at least one could change shape, destroying
989 # the reasons for combining them. We do it in the button release
990 # instead.
991  
992 # If we're already working on a selection, take it back off the stack:
993 pop @$s if $w and $w == $s->[-1];
994 push @$s, $a;
995  
996 } else {
997 $this->[SELECTION] = [$a];
998 }
999 }
1000 # }}}
1001 # marea_motion_notify_event {{{
1002 sub marea_motion_notify_event {
1003 my ($this,$s_up,$eb,$em) = @_;
1004  
1005 my ($x, $y) = ($em->x, $em->y);
1006 my @cs = split 'x', $this->[MAP]{cell_size};
1007 my @lt = (int($x/$cs[0]), int($y/$cs[1]));
1008 my @bb = split 'x', $this->[MAP]{bounding_box};
1009  
1010 $lt[0] = $bb[0]-1 if $lt[0]>=$bb[0];
1011 $lt[1] = $bb[1]-1 if $lt[1]>=$bb[1];
1012  
1013 my $tile = $this->[MAP]{_the_map}[ $lt[1] ][ $lt[0] ];
1014 my $go = 0;
1015  
1016 my $o_lt = $this->[O_LT];
1017 my $s_arg = $this->[S_ARG];
1018 if( @$o_lt!=2 or ($lt[0] != $o_lt->[0] or $lt[1] != $o_lt->[1]) ) {
1019 $this->marea_selection_handler([@$o_lt], [@lt], $em) if $this->[SEL_S];
1020  
1021 @$o_lt = @lt;
1022  
1023 my @s_arg = ([@lt, $tile->{type}]);
1024 $s_arg = $this->[S_ARG] = \@s_arg;
1025  
1026 $this->[O_DR] = $s_arg->[2] = undef;
1027  
1028 if( my $g = $tile->{group} ) {
1029 $s_arg->[1] = [$g->name, $g->desc];
1030 }
1031  
1032 $go = 1;
1033 }
1034
1035 my $d_x1 = ($x - $cs[0]*$lt[0]);
1036 my $d_x2 = ($cs[0]*($lt[0]+1) - $x);
1037 my $d_y1 = ($y - $cs[1]*$lt[1]);
1038 my $d_y2 = ($cs[1]*($lt[1]+1) - $y);
1039  
1040 my $X = ((my $x1 = $d_x1<=2) or (my $x2 = $d_x2<=2));
1041 my $Y = ((my $y1 = $d_y1<=2) or (my $y2 = $d_y2<=2));
1042  
1043 my $dr;
1044 my $o_dr = $this->[O_DR];
1045 if( $X and not $Y ) {
1046 if( $x1 ) {
1047 goto SKIP_DR if $o_dr and $o_dr->[0] eq "w";
1048 $this->[O_DR] = $dr = [w => $this->_od_desc($tile->{od}{w})];
1049  
1050 } else {
1051 goto SKIP_DR if $o_dr and $o_dr->[0] eq "e";
1052 $this->[O_DR] = $dr = [e => $this->_od_desc($tile->{od}{e})];
1053 }
1054  
1055 } elsif( $Y and not $X ) {
1056 if( $y1 ) {
1057 goto SKIP_DR if $o_dr and $o_dr->[0] eq "n";
1058 $this->[O_DR] = $dr = [n => $this->_od_desc($tile->{od}{n})];
1059  
1060 } else {
1061 goto SKIP_DR if $o_dr and $o_dr->[0] eq "s";
1062 $this->[O_DR] = $dr = [s => $this->_od_desc($tile->{od}{s})];
1063 }
1064 }
1065  
1066 if( $dr ) {
1067 $go = 1;
1068 $s_arg->[2] = $dr;
1069  
1070 } elsif( $o_dr ) {
1071 $go = 1;
1072 $this->[O_DR] = $s_arg->[2] = undef;
1073 }
1074  
1075 SKIP_DR:
1076  
1077 if( $go ) {
1078 $this->draw_map_w_cursor;
1079 $s_up->(@$s_arg);
1080 }
1081 }
1082  
1083 sub _od_desc {
1084 my $that = $_[1];
1085  
1086 if( ref $that ) {
1087 my $r = [ grep {$that->{$_}} qw(locked stuck secret) ];
1088 push @$r, "ordinary" unless @$r;
1089 push @$r, "door";
1090  
1091 return $r;
1092 }
1093  
1094 return ['opening'] if $that;
1095 return ['wall'];
1096 }
1097 # }}}
1098  
1099 # EDITING COMMANDS
1100 # tileconvert_to_wall_tiles {{{
1101 sub tileconvert_to_wall_tiles {
1102 my $this = shift;
1103  
1104 # NOTE: The @_ passed to us is prefiltered by our {enable} from the context menu
1105  
1106 my $mq = $this->[MQ];
1107  
1108 for my $tile (@_) {
1109 $mq->remove( $_ ) for $mq->objects_at_location(@$tile{qw(x y)});
1110  
1111 delete $tile->{group};
1112 delete $tile->{type};
1113  
1114 for my $d (qw(n e s w)) {
1115 my $o = $Games::RolePlay::MapGen::opp{$d};
1116  
1117 if( my $n = $tile->{nb}{$d} ) {
1118 $tile->{od}{$d} = $n->{od}{$o} = 0;
1119 }
1120 }
1121 }
1122  
1123 $this->draw_map;
1124 }
1125 # }}}
1126 # tileconvert_to_corridor_tiles {{{
1127 sub tileconvert_to_corridor_tiles {
1128 my $this = shift;
1129  
1130 # NOTE: The @_ passed to us is prefiltered by our {enable} from the context menu
1131  
1132 for my $tile (@_) {
1133 $tile->{type} = "corridor";
1134  
1135 for my $d (qw(n e s w)) {
1136 my $o = $Games::RolePlay::MapGen::opp{$d};
1137  
1138 if( my $n = $tile->{nb}{$d} ) {
1139 my $t = $n->{type};
1140  
1141 # Arguably, this should use the map's door settings to drop doors
1142 # when appropriate... later maybe
1143  
1144 $tile->{od}{$d} = $n->{od}{$o} = 1 if $t and $t eq "corridor";
1145 }
1146 }
1147 }
1148  
1149 $this->draw_map;
1150 }
1151 # }}}
1152  
1153 # closureconvert_to_wall {{{
1154 sub closureconvert_to_wall {
1155 my $this = shift;
1156  
1157 for my $ca (@_) {
1158 my ($tile, $d) = @$ca;
1159 my $o = $Games::RolePlay::MapGen::opp{$d};
1160  
1161 $tile->{od}{$d} = $tile->{nb}{$d}{od}{$o} = 0;
1162 }
1163  
1164 $this->draw_map;
1165 }
1166 # }}}
1167 # closureconvert_to_opening {{{
1168 sub closureconvert_to_opening {
1169 my $this = shift;
1170  
1171 for my $ca (@_) {
1172 my ($tile, $d) = @$ca;
1173 my $o = $Games::RolePlay::MapGen::opp{$d};
1174  
1175 $tile->{od}{$d} = $tile->{nb}{$d}{od}{$o} = 1;
1176 }
1177  
1178 $this->draw_map;
1179 }
1180 # }}}
1181 # closureconvert_to_door {{{
1182 sub closureconvert_to_door {
1183 my $this = shift;
1184  
1185 my $minor_dirs = {
1186 n => [qw(e w)],
1187 s => [qw(e w)],
1188  
1189 e => [qw(n s)],
1190 w => [qw(n s)],
1191 };
1192  
1193 for my $ca (@_) {
1194 my ($t, $d) = @$ca;
1195 my $o = $Games::RolePlay::MapGen::opp{$d};
1196 my $n = $t->{nb}{$d};
1197  
1198 my ($ttype, $ntype) = ($t->{type}, $n->{type});
1199  
1200 if( $ttype eq "room" and $ntype eq "room" ) {
1201 $ntype = "corridor";
1202 }
1203  
1204 my $tkey = ( $t->{od}{$d} ? "open" : "closed" );
1205 $tkey .= "_" . join("_", reverse sort( $ttype, $ntype ));
1206 $tkey .= "_door_percent";
1207  
1208 my $chances = $this->[MAP]->{$tkey};
1209  
1210 # NOTE this really only comes up on blank maps before we've loaded the BasicDoors plugin
1211 $chances = {locked=>0, stuck=>0, secret=>0} unless defined $chances;
1212  
1213 $t->{od}{$d} = $n->{od}{$o} = &_door(
1214 (map {$_ => ((roll(1, 10000) <= $chances->{$_}*100) ? 1:0) } qw(locked stuck secret)),
1215  
1216 open_dir => {
1217 major => &choice( $d, $o ),
1218 minor => &choice( @{$minor_dirs->{$d}} ),
1219 },
1220 );
1221 }
1222  
1223 $this->draw_map;
1224 }
1225 # }}}
1226 # closure_door_properties {{{
1227 sub closure_door_properties {
1228 my $this = shift;
1229  
1230 my $c = 0;
1231 for my $ca (@_) {
1232 my $od = $ca->[0]{od}{$ca->[1]};
1233 my $i = { %$od };
1234  
1235 $i->{_open_dir_major} = $od->{open_dir}{major};
1236 $i->{_open_dir_minor} = $od->{open_dir}{minor};
1237  
1238 my $maj = [$ca->[1], $Games::RolePlay::MapGen::opp{$ca->[1]}];
1239 my $min = {
1240 n => [qw(e w)],
1241 s => [qw(e w)],
1242  
1243 e => [qw(n s)],
1244 w => [qw(n s)],
1245 }->{$maj->[0]};
1246  
1247 my $options = [[ # column 1
1248 { mnemonic => "_Open: ", type => "bool", desc => "is the door open?", name => 'open' },
1249 { mnemonic => "_Locked: ", type => "bool", desc => "is the door locked?", name => 'locked' },
1250 { mnemonic => "_Secret: ", type => "bool", desc => "is the door secret?", name => 'secret' },
1251 { mnemonic => "St_uck: ", type => "bool", desc => "is the door stuck?", name => 'stuck' },
1252 { mnemonic => "M_ajor Direction: ", type => "choice", choices => $maj, name => '_open_dir_major', desc => "The initial direction of the door swing.", },
1253 { mnemonic => "M_inor Direction: ", type => "choice", choices => $min, name => '_open_dir_minor', desc => "The final direction of the door swing.", },
1254 ]];
1255  
1256 my ($result, $o) = make_form($this->[WINDOW], $i, $options, "Door Properties");
1257 next unless $result eq "ok";
1258 $c ++;
1259 $od->{$_} = $o->{$_} for qw(open locked secret stuck);
1260 $od->{open_dir}{major} = $o->{_open_dir_major};
1261 $od->{open_dir}{minor} = $o->{_open_dir_minor};
1262 }
1263  
1264 $this->draw_map if $c;
1265 }
1266 # }}}
1267  
1268 # groupconvert_room_to_corridor {{{
1269 sub groupconvert_room_to_corridor {
1270 my $this = shift;
1271 my $group = shift;
1272 my $map = $this->[MAP]{_the_map};
1273  
1274 for my $tilel ($group->enumerate_tiles) {
1275 my $tile = $map->[ $tilel->[1] ][ $tilel->[0] ];
1276  
1277 warn "WARNING: this group seems to include tiles that aren't in the group"
1278 unless $group == delete $tile->{group};
1279  
1280 $tile->{type} = "corridor";
1281 }
1282  
1283 my $groups = $this->[MAP]{_the_groups};
1284 @$groups = grep {$_!=$group} @$groups;
1285 }
1286 # }}}
1287 # groupconvert_corridor_to_room {{{
1288 sub groupconvert_corridor_to_room {
1289 my $this = shift;
1290 my $map = $this->[MAP]{_the_map};
1291 my $groups = $this->[MAP]{_the_groups};
1292  
1293 my $rn = 0;
1294 for my $g (@$groups) {
1295 my $n = $g->name;
1296 my ($x) = $n =~ m/Room #(\d+)/;
1297  
1298 $rn = $x if $x > $rn;
1299 }
1300  
1301 $rn ++;
1302  
1303 my $group = &_group();
1304 $group->name( "Room #$rn" );
1305 $group->type( "room" );
1306  
1307 for my $s (@{ $this->[SELECTION] }) {
1308 my $loc = [@$s[0,1]];
1309 my $siz = [1+$s->[2]-$s->[0], 1+$s->[3]-$s->[1]];
1310  
1311 $group->add_rectangle( $loc, $siz );
1312 }
1313  
1314 push @$groups, $group;
1315  
1316 for my $tile (map {$map->[ $_->[1] ][ $_->[0] ]} $group->enumerate_tiles) {
1317 $tile->{group} = $group;
1318 $tile->{type} = "room";
1319 }
1320 }
1321 # }}}
1322  
1323 # _build_rccm {{{
1324 sub _build_rccm {
1325 my $this = shift;
1326 my $map = $this->[MAP]{_the_map};
1327  
1328 $this->[RCCM][0] = $this->_build_context_menu(
1329 'convert to w_all tile' => {
1330 enable => sub {
1331 grep { not $_->{group} and $_->{type} }
1332 map { $map->[ $_->[1] ][ $_->[0] ] }
1333 @_
1334 },
1335 activate => sub { $this->tileconvert_to_wall_tiles(@{$_[1]{result}}) },
1336 },
1337 'convert to _corridor tile' => {
1338 enable => sub {
1339 grep { not $_->{group} and not $_->{type} }
1340 map { $map->[ $_->[1] ][ $_->[0] ] }
1341 @_
1342 },
1343 activate => sub { $this->tileconvert_to_corridor_tiles(@{$_[1]{result}}) },
1344 },
1345 'convert room to corridor' => {
1346 enable => sub {
1347 my @g = grep { $_ }
1348 map { $map->[ $_->[1] ][ $_->[0] ]{group} }
1349 @_;
1350  
1351 return unless @g == @_;
1352  
1353 my %unique;
1354 @g = grep { my $r = 0; $unique{0+$_} = $r = 1 unless $unique{0+$_}; $r } @g;
1355  
1356 return unless @g == 1;
1357 @g;
1358 },
1359 activate => sub { $this->groupconvert_room_to_corridor(@{$_[1]{result}}) },
1360 },
1361 'convert selection to room' => {
1362 enable => sub {
1363 return unless $this->[SELECTION];
1364  
1365 my @a = grep { not $_->{group} and $_->{type} }
1366 map { $map->[ $_->[1] ][ $_->[0] ] }
1367 @_;
1368  
1369 @_ == @a ? 1 : 0 # we're not using the return value at all
1370 },
1371 activate => sub { $this->groupconvert_corridor_to_room(@{$this->[SELECTION]}) },
1372 },
1373 'convert _inside closures to openings' => {
1374 enable => sub {
1375 my $min_x = $_[0][0]; my $max_x = $_[0][0];
1376 my $min_y = $_[0][1]; my $max_y = $_[0][1];
1377  
1378 grep { my $od = $_->[0]{od}{ $_->[1] };
1379 $_->[0]{type} and $_->[0]{nb}{$_->[1]}{type} and (not($od) or ref($od)) }
1380 map { [ $map->[ $_->[1] ][ $_->[0] ], $_->[2] ] }
1381 grep {
1382 my $ret = 1;
1383 $ret = 0 if $_->[0] == $min_x and $_->[2] eq "w"; # this amounts to check if there exists a {nb}{d}
1384 $ret = 0 if $_->[0] == $max_x and $_->[2] eq "e";
1385 $ret = 0 if $_->[1] == $min_y and $_->[2] eq "n";
1386 $ret = 0 if $_->[1] == $max_y and $_->[2] eq "s";
1387 $ret;
1388 }
1389 map {
1390 my $l = $_;
1391  
1392 $min_x = $l->[0] if $l->[0] < $min_x; $max_x = $l->[0] if $l->[0] > $max_x;
1393 $min_y = $l->[1] if $l->[1] < $min_y; $max_y = $l->[1] if $l->[1] > $max_y;
1394  
1395 (map { [@$l, $_] } qw(n e s w))
1396 }
1397 @_
1398 },
1399 activate => sub { $this->closureconvert_to_opening(@{$_[1]{result}}) },
1400 },
1401 'convert _north edge of selection to walls' => {
1402 enable => sub {
1403 return unless $this->[SELECTION];
1404  
1405 my $min_y = $_[0][1];
1406  
1407 grep { $_->[0]{od}{ $_->[1] } } # this amounts to check if there exists an {nb}{d}
1408 map { [ $map->[ $_->[1] ][ $_->[0] ], $_->[2] ] }
1409 grep {
1410 my $ret = 0;
1411 $ret = 1 if $_->[1] == $min_y;
1412 $ret;
1413 }
1414 map {
1415 $min_y = $_->[1] if $_->[1] < $min_y;
1416  
1417 [@$_, 'n']
1418 }
1419 @_
1420 },
1421 activate => sub { $this->closureconvert_to_wall(@{$_[1]{result}}) },
1422 },
1423 'convert _east edge of selection to walls' => {
1424 enable => sub {
1425 return unless $this->[SELECTION];
1426  
1427 my $max_x = $_[0][0];
1428  
1429 grep { $_->[0]{od}{ $_->[1] } }
1430 map { [ $map->[ $_->[1] ][ $_->[0] ], $_->[2] ] }
1431 grep {
1432 my $ret = 0;
1433 $ret = 1 if $_->[0] == $max_x;
1434 $ret;
1435 }
1436 map {
1437 $max_x = $_->[0] if $_->[0] > $max_x;
1438  
1439 [@$_, 'e']
1440 }
1441 @_
1442 },
1443 activate => sub { $this->closureconvert_to_wall(@{$_[1]{result}}) },
1444 },
1445 'convert _south edge of selection to walls' => {
1446 enable => sub {
1447 return unless $this->[SELECTION];
1448  
1449 my $max_y = $_[0][1];
1450  
1451 grep { $_->[0]{od}{ $_->[1] } }
1452 map { [ $map->[ $_->[1] ][ $_->[0] ], $_->[2] ] }
1453 grep {
1454 my $ret = 0;
1455 $ret = 1 if $_->[1] == $max_y;
1456 $ret;
1457 }
1458 map {
1459 $max_y = $_->[1] if $_->[1] > $max_y;
1460  
1461 [@$_, 's']
1462 }
1463 @_
1464 },
1465 activate => sub { $this->closureconvert_to_wall(@{$_[1]{result}}) },
1466 },
1467 'convert _west edge of selection to walls' => {
1468 enable => sub {
1469 return unless $this->[SELECTION];
1470  
1471 my $min_x = $_[0][0];
1472  
1473 grep { $_->[0]{od}{ $_->[1] } }
1474 map { [ $map->[ $_->[1] ][ $_->[0] ], $_->[2] ] }
1475 grep {
1476 my $ret = 0;
1477 $ret = 1 if $_->[0] == $min_x;
1478 $ret;
1479 }
1480 map {
1481 $min_x = $_->[0] if $_->[0] < $min_x;
1482  
1483 [@$_, 'w']
1484 }
1485 @_
1486 },
1487 activate => sub { $this->closureconvert_to_wall(@{$_[1]{result}}) },
1488 },
1489 );
1490  
1491 # NOTE: I'm writing these to later take arrays of closures instead of just singles...
1492 # but for now, you can only select one closure at a time.
1493 $this->[RCCM][1] = $this->_build_context_menu(
1494 'convert to _wall' => {
1495 enable => sub {
1496 map { [ $_->[0], $_->[-1][-1] ] }
1497 grep { $_->[1] } # this amounts to checking if there exists an {nb}{d}
1498 map { my $t = $map->[ $_->[1] ][ $_->[0] ]; [ $t, $t->{od}{$_->[2]}, $t->{nb}{$_->[2]}, $_ ] }
1499 grep { @$_ == 3 }
1500 @_
1501 },
1502 activate => sub { $this->closureconvert_to_wall(@{$_[1]{result}}) },
1503 },
1504 'convert to _opening' => {
1505 enable => sub {
1506 map { [ $_->[0], $_->[-1][-1] ] }
1507 grep { $_->[1] and $_->[0]{type} and $_->[1]{type} and (not($_->[2]) or ref($_->[2])) }
1508 map { my $t = $map->[ $_->[1] ][ $_->[0] ]; [ $t, $t->{nb}{$_->[2]}, $t->{od}{$_->[2]}, $_ ] }
1509 grep { @$_ == 3 }
1510 @_
1511 },
1512 activate => sub { $this->closureconvert_to_opening(@{$_[1]{result}}) },
1513 },
1514 'convert to _door' => {
1515 enable => sub {
1516 map { [ $_->[0], $_->[-1][-1] ] }
1517 grep { $_->[1] and $_->[0]{type} and $_->[1]{type} and (not($_->[2]) or not ref($_->[2])) }
1518 map { my $t = $map->[ $_->[1] ][ $_->[0] ]; [ $t, $t->{nb}{$_->[2]}, $t->{od}{$_->[2]}, $_ ] }
1519 grep { @$_ == 3 }
1520 @_
1521 },
1522 activate => sub { $this->closureconvert_to_door(@{$_[1]{result}}) },
1523 },
1524 'door _properties' => {
1525 enable => sub {
1526 map { [ $_->[0], $_->[-1][-1] ] }
1527 grep { ref $_->[1] }
1528 map { my $t = $map->[ $_->[1] ][ $_->[0] ]; [ $t, $t->{od}{$_->[2]}, $_ ] }
1529 grep { @$_ == 3 }
1530 @_
1531 },
1532 activate => sub { $this->closure_door_properties(@{$_[1]{result}}) },
1533 },
1534 );
1535 }
1536 # }}}
1537 # _build_context_menu {{{
1538 sub _build_context_menu {
1539 my $this = shift;
1540 my $menu = new Gtk2::Menu->new;
1541  
1542 @_ = @{$_[0]} if ref $_[0];
1543  
1544 # TODO: this should become a module like _MForm.pm
1545  
1546 my @a;
1547 while( my($name, $opts) = splice @_, 0, 2 ) {
1548 my $item = Gtk2::MenuItem->new_with_mnemonic($name);
1549  
1550 push @a, sub { my @r = $opts->{enable}->(@_); $item->set_sensitive( $r[-1] ? 1 : 0 ); $opts->{result} = \@r; } if $opts->{enable};
1551 push @a, sub { my @r = $opts->{disable}->(@_); $item->set_sensitive( $r[-1] ? 0 : 1 ); $opts->{result} = \@r; } if $opts->{disable};
1552  
1553 $item->signal_connect( activate => $opts->{activate}, $opts ) if exists $opts->{activate};
1554 $menu->append( $item );
1555 }
1556  
1557 $menu->{_a} = \@a;
1558 $menu->show_all;
1559 $menu;
1560 }
1561 # }}}
1562 # right_click_map {{{
1563 sub right_click_map {
1564 my ($this, $event) = @_;
1565  
1566 my @a;
1567 if( my $s = $this->[SELECTION] ) {
1568 my %already;
1569 for my $r (@$s) {
1570 for my $x ($r->[0] .. $r->[2]) {
1571 for my $y ($r->[1] .. $r->[3]) {
1572 next if $already{$x,$y};
1573 $already{$x,$y} = push @a, [$x,$y];
1574 }}
1575 }
1576  
1577 } else {
1578 my @b;
1579 if( my @o = (@{ $this->[O_LT] }) ) {
1580 if( my $s2 = @{$this->[S_ARG]}[2] ) {
1581 @b = (@o, $s2->[0]);
1582  
1583 } else {
1584 @b = @o;
1585 }
1586  
1587 } else {
1588 return FALSE;
1589 }
1590 @a = (\@b);
1591 }
1592  
1593 $this->_build_rccm unless $this->[RCCM];
1594  
1595 my @menus = @{ $this->[RCCM] };
1596 my $menu = $menus[@{$a[0]}==3 ? 1:0];
1597  
1598 $_->(@a) for @{$menu->{_a}};
1599  
1600 $menu->popup(
1601 undef, # parent menu shell
1602 undef, # parent menu item
1603 undef, # menu pos func
1604 undef, # data
1605 $event->button,
1606 $event->time
1607 );
1608 }
1609 # }}}
1610  
1611 # OPTS AND PREFS
1612 # blank_map {{{
1613 sub blank_map {
1614 my $this = shift;
1615  
1616 # NOTE: This is just the blank map generator, it has no settings.
1617 # Later, we'll have a generate_map() that has all kinds of configuations options.
1618  
1619 $this->[FNAME] = undef;
1620 $this->[WINDOW]->set_title("GRM Editor");
1621  
1622 my $map = $this->[MAP] = new Games::RolePlay::MapGen({
1623 tile_size => 10,
1624 cell_size => "23x23",
1625 bounding_box => "25x25",
1626 });
1627  
1628 $this->[MQ] = new Games::RolePlay::MapGen::MapQueue( $map );
1629  
1630 $map->set_generator("Blank");
1631 $map->generate;
1632  
1633 $this->draw_map;
1634  
1635 $map;
1636 }
1637 # }}}
1638 # get_generate_opts {{{
1639 sub get_generate_opts {
1640 my $this = shift;
1641  
1642 my $i = $this->[SETTINGS]{GENERATE_OPTS};
1643 $i = thaw $i if $i;
1644 $i = {} unless $i;
1645  
1646 my $options = [[ # column 1
1647  
1648 { mnemonic => "_Tile Size: ",
1649 type => "text",
1650 desc => "The size of each tile (in Square Feet or Square Units or whatever)",
1651 name => 'tile_size',
1652 default => 10, # NOTE: fixes and matches must exist and must be arrrefs
1653 fixes => [sub { $_[0] =~ s/\s+//g }],
1654 matches => [qr/^\d+$/] },
1655  
1656 { mnemonic => "Cell Size: ",
1657 type => "text",
1658 desc => "The size of each tile in the image (in pixels)",
1659 name => 'cell_size',
1660 default => '23x23',
1661 fixes => [sub { $_[0] =~ s/\s+//g }],
1662 matches => [qr/^\d+x\d+$/] },
1663  
1664 { mnemonic => "Bounding Box: ",
1665 type => "text",
1666 desc => "The size of the whole map (in tiles)",
1667 name => 'bounding_box',
1668 default => '20x20',
1669 fixes => [sub { $_[0] =~ s/\s+//g }],
1670 matches => [qr/^\d+x\d+$/] },
1671  
1672 { mnemonic => "Number of Rooms: ",
1673 type => "text",
1674 desc => "The number of generated rooms, either a number or a roll (e.g., 2, 2d4, 2d4+2)",
1675 name => 'num_rooms',
1676 default => '2d4',
1677 disable => { generator => sub { $_[0] ne "Basic" } },
1678 fixes => [sub { $_[0] =~ s/\s+//g }],
1679 matches => [qr/^(?:\d+|\d+d\d+|\d+d\d+[+-]\d+)$/] },
1680  
1681 { mnemonic => "Min Room Size: ",
1682 type => "text",
1683 desc => "The minimum size of generated rooms (in tiles)",
1684 name => 'min_room_size',
1685 default => '2x2',
1686 disable => { generator => sub { $_[0] ne "Basic" } },
1687 fixes => [sub { $_[0] =~ s/\s+//g }],
1688 matches => [qr/^\d+x\d+$/] },
1689  
1690 { mnemonic => "Max Room Size: ",
1691 type => "text",
1692 desc => "The maximum size of generated rooms (in tiles)",
1693 name => 'max_room_size',
1694 default => '7x7',
1695 disable => { generator => sub { $_[0] ne "Basic" } },
1696 fixes => [sub { $_[0] =~ s/\s+//g }],
1697 matches => [qr/^\d+x\d+$/] },
1698  
1699 { mnemonic => "Open Room-Corridor: ",
1700 type => "text",
1701 desc => "The %-chance of a door occuring between a room tile and a corridor tile where there is already an opening. The percentages are listed as a four touple: door-chance, secret, stuck, locked (e.g., 95,2,25,50 means there's a 95% chance of dropping a door, but only 50% that it's locked if we do).",
1702 name => 'open_room_corridor_door_percent',
1703 default => '95, 2, 25, 50',
1704 disable => { generator_plugins => sub { (grep {$_ eq "BasicDoors"} @{$_[0]}) ? 0:1 } },
1705 convert => sub { my @a = split m/\D+/, $_[0]; { door=>$a[0], secret=>$a[1], stuck=>$a[2], locked=>$a[3] } },
1706 trevnoc => sub { join(", ", @{$_[0]}{qw( door secret stuck locked )}) },
1707 matches => [sub { (grep {$_ >= 0 and $_ <= 100} $_[0] =~ m/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)$/) == 4 }],
1708 fixes => [sub { $_[0] =~ s/[^\d,\s]+//g }], },
1709  
1710 { mnemonic => "Closed Room-Corridor: ",
1711 type => "text",
1712 desc => "The %-chance of a door occuring between a room tile and a corridor tile where there isn't an opening. The percentages are listed as a four touple: door-chance, secret, stuck, locked.",
1713 name => 'closed_room_corridor_door_percent',
1714 default => '5, 95, 10, 30',
1715 disable => { generator_plugins => sub { (grep {$_ eq "BasicDoors"} @{$_[0]}) ? 0:1 } },
1716 convert => sub { my @a = split m/\D+/, $_[0]; { door=>$a[0], secret=>$a[1], stuck=>$a[2], locked=>$a[3] } },
1717 trevnoc => sub { join(", ", @{$_[0]}{qw( door secret stuck locked )}) },
1718 matches => [sub { (grep {$_ >= 0 and $_ <= 100} $_[0] =~ m/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)$/) == 4 }],
1719 fixes => [sub { $_[0] =~ s/[^\d,\s]+//g }], },
1720  
1721 { mnemonic => "Open Corridor-Corridor: ",
1722 type => "text",
1723 desc => "The %-chance of a door occuring between a corridor tile and a corridor tile where there is already an opening. The percentages are listed as a four touple: door-chance, secret, stuck, locked.",
1724 name => 'open_corridor_corridor_door_percent',
1725 default => '1, 10, 25, 50',
1726 disable => { generator_plugins => sub { (grep {$_ eq "BasicDoors"} @{$_[0]}) ? 0:1 } },
1727 convert => sub { my @a = split m/\D+/, $_[0]; { door=>$a[0], secret=>$a[1], stuck=>$a[2], locked=>$a[3] } },
1728 trevnoc => sub { join(", ", @{$_[0]}{qw( door secret stuck locked )}) },
1729 matches => [sub { (grep {$_ >= 0 and $_ <= 100} $_[0] =~ m/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)$/) == 4 }],
1730 fixes => [sub { $_[0] =~ s/[^\d,\s]+//g }], },
1731  
1732 { mnemonic => "Closed Corridor-Corridor: ",
1733 type => "text",
1734 desc => "The %-chance of a door occuring between a corridor tile and a corridor tile where there isn't an opening. The percentages are listed as a four touple: door-chance, secret, stuck, locked.",
1735 name => 'closed_corridor_corridor_door_percent',
1736 default => '1, 95, 10, 30',
1737 disable => { generator_plugins => sub { (grep {$_ eq "BasicDoors"} @{$_[0]}) ? 0:1 } },
1738 convert => sub { my @a = split m/\D+/, $_[0]; { door=>$a[0], secret=>$a[1], stuck=>$a[2], locked=>$a[3] } },
1739 trevnoc => sub { join(", ", @{$_[0]}{qw( door secret stuck locked )}) },
1740 matches => [sub { (grep {$_ >= 0 and $_ <= 100} $_[0] =~ m/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)$/) == 4 }],
1741 fixes => [sub { $_[0] =~ s/[^\d,\s]+//g }], },
1742  
1743 { mnemonic => "Max Span: ",
1744 type => "text",
1745 desc => "The door dropper will close spans larger than a single tile in order to drop a door. This is the maximum sized span that it will close.",
1746 name => 'max_span',
1747 default => '50',
1748 disable => { generator_plugins => sub { (grep {$_ eq "BasicDoors"} @{$_[0]}) ? 0:1 } },
1749 fixes => [sub { $_[0] =~ s/\D+//g }], },
1750  
1751 ], [ # column 2
1752  
1753 { mnemonic => "_Generator: ",
1754 type => "choice",
1755 desc => "The generator used to create the map.",
1756 descs => {
1757 Basic => 'The basic generator uses perfect/sparseandloops to make a map and then drops rooms onto the result.',
1758 Perfect => 'The perfect maze generator James Buck designed.',
1759 SparseAndLoops => "Pretty much, this is same map generator on James Buck's site.",
1760 Blank => "Generates a boring blank map according to your selected bounding box.",
1761 OneBigRoom => "Generates a boring giant room the size of your bounding box.",
1762 },
1763 name => 'generator',
1764 default => $DEFAULT_GENERATOR,
1765 choices => [@GENERATORS] },
1766  
1767 { mnemonic => "Generator _Plugins: ", z=>3,
1768 type => "choices",
1769 desc => "The plugins you wish to use after the map is created.",
1770 descs => {
1771 BasicDoors => 'Adds doors using various strategies.',
1772 FiveSplit => 'Divides map tiles with tiles larger than 5 units square into tiles precisely 5 units square. E.g., if the tile size is set to 10, this will double the bounding box size of your map, but your hallways will be two tiles wide.',
1773 },
1774 name => 'generator_plugins',
1775 disable => { FiveSplit => {tile_size => sub { ($_[0]/5) =~ m/\./ }} },
1776 defaults => [@DEFAULT_GENERATOR_PLUGINS],
1777 choices => [@GENERATOR_PLUGINS] },
1778  
1779 { mnemonic => "_Sparseness: ",
1780 type => "text",
1781 desc => "The number of times to repeat the remove-dead-end-tile step in James Buck's generator algorithm.",
1782 name => 'sparseness',
1783 default => 10,
1784 disable => { generator => sub { not {Basic=>1, SparseAndLoops=>1}->{$_[0]} } },
1785 fixes => [sub { $_[0] =~ s/\s+//g }],
1786 matches => [qr/^(?:\d{1,2}|100)$/] },
1787  
1788 { mnemonic => "Same Way Percent:",
1789 type => "text",
1790 desc => "While digging out the perfect maze, this is the percent chance of digging in the same direction as last time each time we visit the node.",
1791 name => 'same_way_percent',
1792 default => 90,
1793 disable => { generator => sub { not {Basic=>1, Perfect=>1, SparseAndLoops=>1}->{$_[0]} } },
1794 fixes => [sub { $_[0] =~ s/\s+//g }],
1795 matches => [qr/^(?:\d{1,2}|100)$/] },
1796  
1797 { mnemonic => "Same Node Percent:",
1798 type => "text",
1799 desc => "While digging out the perfect maze, this is the percent chance of restarting the digging in the same place on each iteration.",
1800 name => 'same_node_percent',
1801 default => 30,
1802 disable => { generator => sub { not {Basic=>1, Perfect=>1, SparseAndLoops=>1}->{$_[0]} } },
1803 fixes => [sub { $_[0] =~ s/\s+//g }],
1804 matches => [qr/^(?:\d{1,2}|100)$/] },
1805  
1806 { mnemonic => "Remove Dead-End Percent:",
1807 type => "text",
1808 desc => "Like sparseness but tries harder to remove dead-end corridors completely.",
1809 name => 'remove_deadend_percent',
1810 default => 60,
1811 disable => { generator => sub { not {Basic=>1, SparseAndLoops=>1}->{$_[0]} } },
1812 fixes => [sub { $_[0] =~ s/\s+//g }],
1813 matches => [qr/^(?:\d{1,2}|100)$/] },
1814  
1815 ]];
1816  
1817 $this->modify_generate_opts_form if $this->can("modify_generate_opts_form");
1818  
1819 my $extra_buttons = [
1820 ['Defaults', $default_restore_defaults, 'Restore default options'],
1821 ['Auto BB', sub {
1822 my ($button, $reref) = @_;
1823 my $tile_size = $reref->{tile_size}[0]{extract} or warn "no code ref?";
1824 my $cell_size = $reref->{cell_size}[0]{extract} or warn "no code ref?";
1825 my $five_split = $reref->{generator_plugins}[0]{extract} or warn "no code ref?";
1826 my $vp_dim = $this->[VP_DIM];
1827  
1828 $button->signal_connect( clicked => sub {
1829 my $ts = $tile_size->();
1830 my $cs = [ split "x", $cell_size->() ];
1831 my $fs = grep {$_ eq "FiveSplit"} @{ $five_split->() };
1832  
1833 # warn dump({
1834 # ts => $ts,
1835 # cs => $cs,
1836 # fs => $fs,
1837 # vp => $vp_dim,
1838 # });
1839  
1840 my $m = ( $fs ? $ts/5 : 1 );
1841 my $x = int( $vp_dim->[0] / ($cs->[0]*$m) );
1842 my $y = int( $vp_dim->[1] / ($cs->[1]*$m) );
1843  
1844 $reref->{bounding_box}[1]->set_text( join("x", $x, $y) );
1845 });
1846 },
1847 'Generate a bounding box that will fit in the current window without scrolling.'
1848 ],
1849 ];
1850  
1851 my ($result, $o) = make_form($this->[WINDOW], $i, $options, "Generate Map", $extra_buttons);
1852 if( $result eq "ok" ) {
1853 # why?
1854 # $i->{$_} = $o->{$_} for keys %$o;
1855 # $this->[SETTINGS]{GENERATE_OPTS} = freeze $i;
1856  
1857 $this->[SETTINGS]{GENERATE_OPTS} = freeze $o;
1858 }
1859  
1860 return ($result, $o);
1861 }
1862 # }}}
1863 # generate {{{
1864 sub generate {
1865 my $this = shift;
1866  
1867 my ($result, $settings, $generator, @plugins) = $this->get_generate_opts;
1868  
1869 return unless $result eq "ok";
1870  
1871 $this->[FNAME] = undef;
1872 $this->[WINDOW]->set_title("GRM Editor");
1873  
1874 $generator = delete $settings->{generator};
1875 @plugins = @{ delete $settings->{generator_plugins} };
1876  
1877 my $map;
1878 REDO: {
1879 my $pulser = $this->pulser( "Generating Map...", "Generating", 150 );
1880 eval {
1881 $map = $this->[MAP] = new Games::RolePlay::MapGen;
1882 $map->set_generator($generator);
1883 $map->add_generator_plugin( $_ ) for @plugins;
1884 $map->generate( %$settings, t_cb => $pulser );
1885  
1886 $this->[MQ] = new Games::RolePlay::MapGen::MapQueue( $map );
1887 };
1888  
1889 $pulser->('destroy');
1890 if( $@ ) {
1891 $this->error($@);
1892 return $this->blank_map;
1893 }
1894  
1895 $this->draw_map;
1896 Gtk2->main_iteration while Gtk2->events_pending;
1897 Gtk2->main_iteration while Gtk2->events_pending;
1898 redo REDO if ask Gtk2::Ex::Dialogs::Question(text=>"Re-generate?", default_yes=>TRUE, parent_window=>$this->[WINDOW]);
1899 }
1900 $map;
1901 }
1902 # }}}
1903 # render_settings {{{
1904 sub render_settings {
1905 my $this = shift;
1906  
1907 my $options = [[
1908 { mnemonic => "Cell Size: ",
1909 type => "text",
1910 desc => "The size of each tile in the image (in pixels)",
1911 name => 'cell_size',
1912 default => '23x23',
1913 fixes => [sub { $_[0] =~ s/\s+//g }],
1914 matches => [qr/^\d+x\d+$/] },
1915 ]];
1916  
1917 my $i = $this->[SETTINGS]{GENERATE_OPTS};
1918 $i = thaw $i if $i;
1919 $i = {} unless $i;
1920  
1921 my ($result, $o) = make_form($this->[WINDOW], $i, $options, "Render Settings");
1922 return unless $result eq "ok";
1923  
1924 if($o->{cell_size} ne $i->{cell_size}) {
1925 $i->{cell_size} = $o->{cell_size};
1926 $this->[SETTINGS]{GENERATE_OPTS} = freeze $i; # here, we freeze $i because it has many more options than $o
1927 }
1928  
1929 if($o->{cell_size} ne $this->[MAP]{cell_size}) {
1930 $this->[MAP]{$_} = $i->{$_} = $o->{$_} for keys %$o;
1931 $this->draw_map;
1932 }
1933 }
1934 # }}}
1935 # server_settings {{{
1936 sub server_settings {
1937 my $this = shift;
1938  
1939 my $options = [[
1940 { mnemonic => "Enabled: ",
1941 type => "bool",
1942 desc => "Whether to listen.",
1943 name => 'listen',
1944 default => $this->[SERVER] ? 1:0,
1945 matches => [qr/^\d+$/] },
1946 { mnemonic => "Server Port: ",
1947 type => "text",
1948 desc => "The port on which your server runs.",
1949 name => 'port',
1950 default => '4000',
1951 matches => [qr/^\d+$/] },
1952  
1953 # TODO: We'll eventually want the bind port and default url as options
1954 ]];
1955  
1956 my $i = $this->[SETTINGS]{SERVER_OPTIONS};
1957 $i = thaw $i if $i;
1958 $i = {} unless $i;
1959  
1960 my ($result, $o) = make_form($this->[WINDOW], $i, $options, "Server Settings");
1961 return unless $result eq "ok";
1962  
1963 my $diff = 0;
1964 for my $k (keys %$o) {
1965 next if $k eq "listen";
1966 $diff ++ if $o->{$k} ne $i->{$k};
1967 }
1968 my $listen = delete $o->{'listen'};
1969  
1970 $this->[SETTINGS]{SERVER_OPTIONS} = freeze $o if $diff;
1971 $this->server_control($listen, $o);
1972 }
1973 # }}}
1974 # server_control {{{
1975 sub server_control {
1976 my ($this, $listen, $o) = @_;
1977  
1978 if( $listen ) {
1979 my $to_start = 1;
1980 if( my $s = $this->[SERVER] ) {
1981 if( $s->[0] ne $o->{port} ) {
1982 POE::Kernel->call($s->[0]{httpd}, "shutdown");
1983 $s->[1]->destroy;
1984 delete $this->[SERVER];
1985  
1986 } else {
1987 $to_start = 0;
1988 }
1989 }
1990  
1991 unless( eval "require Games::RolePlay::MapGen::Editor::_jQuery; 1" ) {
1992 warn "ERROR loading jquery: $@";
1993 return;
1994 }
1995  
1996 if( $to_start ) {
1997 my $s; $s = $this->[SERVER] = [
1998 POE::Component::Server::HTTP->new(
1999 Port => $o->{port},
2000 Headers => { Server => 'GRM Server' },
2001 ContentHandler => ({
2002 '/' => sub { $this->http_root_handler($s->[2], @_) },
2003 '/jquery/' => sub { $this->http_jquery_handler($s->[2], @_) },
2004 })
2005 ),
2006 my $w = Gtk2::Window->new('toplevel'),
2007 ];
2008 # $w->set_destroy_with_parent(TRUE);
2009 # $w->set_transient_for($this->[WINDOW]);
2010 $w->set_title("GRM Server");
2011 $w->set_size_request(500,200);
2012 $w->set_position('center');
2013 $w->add(my $vbox = Gtk2::VBox->new);
2014 $vbox->add(my $scwin = Gtk2::ScrolledWindow->new); # ($tv->get_focus_hadjustment, $tv->get_focus_vadjustment)
2015 $scwin->add(my $tv = Gtk2::TextView->new);
2016 $scwin->set_policy('automatic', 'automatic');
2017  
2018 $tv->set_editable(FALSE);
2019 $tv->set_wrap_mode("none");
2020 $tv->set_cursor_visible(FALSE);
2021  
2022 my $b = $tv->get_buffer;
2023 my $l = sub {
2024 my $ent = shift;
2025 $ent =~ s/[\r\n]/ /g;
2026 $ent =~ s/\s{2,}/ /g;
2027 $ent .= "\n";
2028  
2029 $tv->scroll_to_iter($b->get_end_iter, FALSE,FALSE, 0,0);
2030 Gtk2->main_iteration while Gtk2->events_pending;
2031 $b->insert($b->get_end_iter, localtime() . ": $ent");
2032 };
2033 push @$s, $l;
2034  
2035 $l->("server started on port $o->{port}");
2036  
2037 $w->signal_connect( delete_event => sub {
2038 POE::Kernel->call($s->[0]{httpd}, "shutdown");
2039 delete $this->[SERVER];
2040 FALSE; # this apparently can't return true
2041 });
2042  
2043 my $adder = sub {
2044 $vbox->add( my $hbox = Gtk2::HBox->new );
2045 $hbox->add( my $ul = Gtk2::Label->new("Username: ") );
2046 $hbox->add( my $ue = Gtk2::Entry->new );
2047 $hbox->add( my $pl = Gtk2::Label->new("Password: ") );
2048 $hbox->add( my $pe = Gtk2::Entry->new );
2049 $hbox->add( my $nl = Gtk2::Label->new("Map Name: ") );
2050 $hbox->add( my $ne = Gtk2::Entry->new );
2051  
2052 $ul->set_tooltip_text( "The users login name." );
2053 $pl->set_tooltip_text( "The users password (leave blank to accept any string)." );
2054 $nl->set_tooltip_text( "The name of a unique item on the map to connect with." );
2055 };
2056  
2057 $adder->();
2058  
2059 $w->show_all;
2060 }
2061  
2062 } else {
2063 if( my $s = $this->[SERVER] ) {
2064 POE::Kernel->call($s->[0]{httpd}, "shutdown");
2065 $s->[1]->destroy;
2066 delete $this->[SERVER];
2067 }
2068 }
2069 }
2070 # }}}
2071 # preferences {{{
2072 sub preferences {
2073 my $this = shift;
2074  
2075 my $i = {
2076 REMEMBER_SP => $this->[SETTINGS]{REMEMBER_SP},
2077 LOAD_LAST => $this->[SETTINGS]{LOAD_LAST},
2078 };
2079  
2080 my $options = [[
2081 { mnemonic => "Load Last: ",
2082 type => "bool",
2083 desc => "Re-load the last map when the GRM Editor opens?",
2084 name => 'LOAD_LAST',
2085 default => 0, },
2086  
2087 { mnemonic => "Remember Size: ",
2088 type => "bool",
2089 desc => "Remember the Size of your window from the last run?",
2090 name => 'REMEMBER_SP',
2091 default => 1 },
2092 ]];
2093  
2094 my ($result, $o) = make_form($this->[WINDOW], $i, $options, "Preferences");
2095 return unless $result eq "ok";
2096 $this->[SETTINGS]{$_} = $o->{$_} for keys %$o;
2097 }
2098 # }}}
2099  
2100 # SERVER FUNCTIONS
2101 # http_root_handler {{{
2102 sub http_root_handler {
2103 my ($this, $l, $request, $response) = @_;
2104  
2105 my $uri = $request->uri; # request is an HTTP::Request (and a little more)
2106 my $path = $uri->path; # uri is an URI object
2107  
2108 my @o = $this->[MQ]->objects;
2109 my $odump = escapeHTML(dump(\@o));
2110 my $auth = $request->header("authorization");
2111  
2112 $l->("request for $path" . ($auth ? " (auth: $auth)" : ""));
2113  
2114 my ($u, $p);
2115 if( my ($mime) = $auth =~ m/Basic\s*(.+)/ ) {
2116 if( (my @r = split(/:/, decode_base64($mime), 2)) == 2 ) {
2117 ($u, $p) = @r;
2118 }
2119 }
2120  
2121 if( 0 and ($u and $p) ) {
2122 $response->code(RC_OK);
2123 $response->header( content_type => "text/html" );
2124 $response->content(qq
2125 <html>
2126 <head><title>MapGen Server</title><script src='/jquery/'></script></head>
2127 <body>
2128 <p> Hi $u, you fetched $uri authenticated with $p.\n</p>
2129 <pre>$odump</pre>
2130 </body>
2131 </html>
2132 );
2133  
2134 } else {
2135 $response->code(401);
2136 $response->header( content_type => "text/html", www_authenticate => 'Basic realm="MapGen Server"' );
2137 $response->content(qq
2138 <html>
2139 <head><title>MapGen Server</title>
2140 <body>
2141 <p> 401 Authorization Required.
2142 <p> Who are you?
2143 </body>
2144 </html>
2145 );
2146 }
2147  
2148 return RC_OK;
2149 }
2150 # }}}
2151 # http_jquery_handler {{{
2152 sub http_jquery_handler {
2153 my ($this, $l, $request, $response) = @_;
2154  
2155 my $uri = $request->uri; # request is an HTTP::Request (and a little more)
2156 my $path = $uri->path; # uri is an URI object
2157  
2158 $l->("request for $path");
2159  
2160 $response->code(RC_OK);
2161 $response->header( content_type => "text/javascript" );
2162 $response->content( Games::RolePlay::MapGen::Editor::_jQuery::as_string() );
2163  
2164 return RC_OK;
2165 }
2166 # }}}
2167  
2168 # MISC
2169 # help {{{
2170 sub help {
2171 my $this = shift;
2172  
2173 my $search = Pod::Simple::Search->new;
2174 $search->inc(1);
2175  
2176 my $x = $search->find("Games::RolePlay::MapGen::Editor");
2177 my $s = { 'Games::RolePlay::MapGen::Editor' => $x };
2178  
2179 ## DEBUG ## warn "\e[33mINC=\e[m(\e[1;33m@INC\e[m) x=$x";
2180  
2181 my $viewer = Gtk2::Ex::PodViewer->new;
2182 $viewer->set_db($s); # cuz, do we really need to find THEM ALL?
2183 $viewer->load('Games::RolePlay::MapGen::Editor');
2184 $viewer->show; # see, it's a widget!
2185  
2186 my $vp = Gtk2::Viewport->new(undef,undef);
2187 $vp->add($viewer);
2188  
2189 my $scwin = Gtk2::ScrolledWindow->new;
2190 $scwin->set_policy('automatic', 'automatic');
2191 $scwin->add($vp);
2192  
2193 my $dialog = Gtk2::Dialog->new("GRM Editor Help", $this->[WINDOW], 'destroy-with-parent', 'gtk-ok' => 'ok');
2194 $dialog->vbox->add($scwin);
2195 $dialog->set_size_request(600,450);
2196 $dialog->set_default_response('ok');
2197 $dialog->show_all;
2198 $dialog->run;
2199 $dialog->destroy;
2200 }
2201 # }}}
2202 # about {{{
2203 sub about {
2204 my $this = shift;
2205  
2206 my $license = "LGPL -- attached to the GRM distribution";
2207 eval 'use Software::License::LGPL_2_1; $license = (Software::License::LGPL_2_1->new({holder=>"Paul Miller"}))->fulltext';
2208 warn "error loading license: $@" if $@;
2209  
2210 my $ver = $Games::RolePlay::MapGen::Editor::VERSION;
2211 my $mer = $Games::RolePlay::MapGen::VERSION;
2212  
2213 Gtk2->show_about_dialog($this->[WINDOW],
2214  
2215 'program-name' => "GRM Editor",
2216 license => $license,
2217 authors => ['Paul Miller <jettero@cpan.org>'],
2218 copyright => 'Copyright (c) 2008 Paul Miller',
2219 comments =>
2220 "This editor is version v$ver. It is part of the Games::RolePlay::MapGen (GRM)
2221 Distribution v$mer. You can use it in your own projrects with few
2222 restrictions. Use at your own risk. Designed for fun. Have fun.");
2223 }
2224 # }}}
2225 # unknown_menu_callback {{{
2226 sub unknown_menu_callback {
2227 my $this = shift;
2228  
2229 warn "unknown numeric callback: @_";
2230 }
2231 # }}}
2232 # quit {{{
2233 sub quit {
2234 my $this = shift;
2235  
2236 my ($w,$h) = $this->[WINDOW]->get_size;
2237 my ($x,$y) = $this->[WINDOW]->get_position;
2238  
2239 $this->[SETTINGS]{MAIN_SIZE_POS} = freeze [$w,$h,$x,$y];
2240 $this->[SETTINGS]{LAST_FNAME} = $this->[FNAME];
2241  
2242 Gtk2->main_quit;
2243 }
2244 # }}}
2245 # warning_handler {{{
2246 sub warning_handler {
2247 my $this = shift;
2248 my $err = shift;
2249  
2250 our $warnings_ignore;
2251 unless( $warnings_ignore ) {
2252 my @ignore = (
2253 qr(Use of uninitialized value in subtraction.*Glib.pm.*line),
2254 );
2255  
2256 $warnings_ignore = do { local $" = "|"; qr(@ignore) };
2257 }
2258  
2259 if( $err =~ m/(?:ERROR|WARNING)/ ) {
2260 $this->error($err);
2261  
2262 } elsif( $err =~ $warnings_ignore ) {
2263 # ignore
2264  
2265 } else {
2266 my ($package, $filename, $line, $subroutine, $hasargs,
2267 $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller 1;
2268  
2269 warn "$err at $filename line $line (in $subroutine)\n";
2270 }
2271 }
2272 # }}}
2273 # run {{{
2274 sub run {
2275 my $this = shift;
2276  
2277 local $SIG{__WARN__} = sub { $this->warning_handler(@_) };
2278  
2279 if( $this->[SETTINGS]{REMEMBER_SP} and my $sp = $this->[SETTINGS]{MAIN_SIZE_POS} ) {
2280 my ($w,$h,$x,$y) = @{thaw $sp};
2281  
2282 # warn "setting window params: ($w,$h,$x,$y)";
2283  
2284 $this->[WINDOW]->resize( $w,$h );
2285 # $this->[WINDOW]->set_position( $x,$y ); # TODO: this takes single scalars like "center" ... do we really want this anyway?
2286 }
2287  
2288 $this->[WINDOW]->show_all;
2289  
2290 if( $this->[SETTINGS]{LOAD_LAST} and my $f = $this->[SETTINGS]{LAST_FNAME} ) {
2291 $this->read_file($f) if -f $f;
2292 }
2293  
2294 # NOTE: is it smarter to let the POE::Kernel think it's finished and run
2295 # under Gtk2->main? or is it smarter to leave the Kernel running and never
2296 # call the Gtk2->main? Currently, we let the Kernel finish and run under
2297 # Gtk2. So, we create a session that doesn't do anything, letting the
2298 # session finish, so the POE->run returns and we fall through to the
2299 # Gtk2->main;
2300  
2301 POE::Session->create(inline_states=>{_start=>sub{}});
2302 POE::Kernel->run;
2303  
2304 if( "@ARGV" =~ m/server\s*(\d+)?/ ) {
2305 my $port = $1 || 4000;
2306  
2307 # NOTE: curiously, the above means we let the Kernel finish before we start the server session.
2308 $this->server_control(1, {port=>$port});
2309 }
2310  
2311 Gtk2->main;
2312 }
2313 # }}}