Oolite
Loading...
Searching...
No Matches
OOJSStation.m
Go to the documentation of this file.
1/*
2OOJSStation.m (QuickJS-ng)
3
4Oolite
5Copyright (C) 2004-2013 Giles C Williams and contributors
6
7This program is free software; you can redistribute it and/or
8modify it under the terms of the GNU General Public License
9as published by the Free Software Foundation; either version 2
10of the License, or (at your option) any later version.
11
12This program is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with this program; if not, write to the Free Software
19Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20MA 02110-1301, USA.
21
22 */
23
24#import "OOJSStation.h"
26#import "OOJSEntity.h"
28#import "OOJSPlayer.h"
29#import "OOJSShip.h"
32#import "StationEntity.h"
33
34#import "GameController.h"
36#import "OOConstToString.h"
37#import "OOEquipmentType.h"
38#import "OOShipRegistry.h"
39
40static JSClassID sStationClassID;
41
42static BOOL JSStationGetStationEntity(JSContext* context, JSValueConst stationObj, StationEntity** outEntity);
43
46
67
68static JSClassDef sStationClass = {
69 .class_name = "Station",
70 .finalizer = OOJSObjectWrapperFinalize,
71};
72
73enum {
74 // Property IDs
80 kStation_dockedContractors, // miners and scavengers.
87 kStation_isMainStation, // Is [UNIVERSE station], boolean, read-only
93};
94
95static const JSCFunctionListEntry sStationProperties[] = {
96 // JS name, getter, setter, ID
115};
116
117static const JSCFunctionListEntry sStationMethods[] = {
118 // JS name, min args, function
119 JS_CFUNC_DEF("abortAllDockings", 0, StationAbortAllDockings),
120 JS_CFUNC_DEF("abortDockingForShip", 1, StationAbortDockingForShip),
121 JS_CFUNC_DEF("canDockShip", 1, StationCanDockShip),
122 JS_CFUNC_DEF("dockPlayer", 0, StationDockPlayer),
123 JS_CFUNC_DEF("increaseAlertLevel", 0, StationIncreaseAlertLevel),
124 JS_CFUNC_DEF("decreaseAlertLevel", 0, StationDecreaseAlertLevel),
125 JS_CFUNC_DEF("launchDefenseShip", 0, StationLaunchDefenseShip),
126 JS_CFUNC_DEF("launchEscort", 0, StationLaunchEscort),
127 JS_CFUNC_DEF("launchMiner", 0, StationLaunchMiner),
128 JS_CFUNC_DEF("launchPatrol", 0, StationLaunchPatrol),
129 JS_CFUNC_DEF("launchPirateShip", 0, StationLaunchPirateShip),
130 JS_CFUNC_DEF("launchPolice", 0, StationLaunchPolice),
131 JS_CFUNC_DEF("launchScavenger", 0, StationLaunchScavenger),
132 JS_CFUNC_DEF("launchShipWithRole", 1, StationLaunchShipWithRole),
133 JS_CFUNC_DEF("launchShuttle", 0, StationLaunchShuttle),
134 JS_CFUNC_DEF("setInterface", 0, StationSetInterface),
135 JS_CFUNC_DEF("setMarketPrice", 2, StationSetMarketPrice),
136 JS_CFUNC_DEF("setMarketQuantity", 2, StationSetMarketQuantity),
137 JS_CFUNC_DEF("addShipToShipyard", 1, StationAddShipToShipyard),
138 JS_CFUNC_DEF("removeShipFromShipyard", 1, StationRemoveShipFromShipyard),
139};
140
141void InitOOJSStation(JSContext* context, JSValueConst global)
142{
144
145 JSValue parentPrototype = JS_GetClassProto(context, JSShipClassID());
146 NSCAssert(JS_IsObject(parentPrototype), @"Ship must be initialized before Station.");
147 OOJSInitClass(context, global, sStationClassID, parentPrototype, OOJSUnconstructableConstruct, 0,
149 JS_FreeValue(context, parentPrototype);
150
153}
154
155JSClassID JSStationClassID(void)
156{
157 return sStationClassID;
158}
159
160/* As in the SpiderMonkey version, these return NO without an exception for
161 stale references (nil entity) and for entities of the wrong native class;
162 OOJSEntityGetEntity() throws if the object is not an Entity at all.
163*/
164static BOOL JSStationGetStationEntity(JSContext* context, JSValueConst stationObj, StationEntity** outEntity)
165{
167
168 BOOL result;
169 Entity* entity = nil;
170
171 if (outEntity == NULL)
172 return NO;
173 *outEntity = nil;
174
175 result = OOJSEntityGetEntity(context, stationObj, &entity);
176 if (!result)
177 return NO;
178
179 if (![entity isKindOfClass:[StationEntity class]])
180 return NO;
181
182 *outEntity = (StationEntity*)entity;
183 return YES;
184
186}
187
188static BOOL JSStationGetShipEntity(JSContext* context, JSValueConst shipObj, ShipEntity** outEntity)
189{
191
192 BOOL result;
193 Entity* entity = nil;
194
195 if (outEntity == NULL)
196 return NO;
197 *outEntity = nil;
198
199 result = OOJSEntityGetEntity(context, shipObj, &entity);
200 if (!result)
201 return NO;
202
203 if (![entity isKindOfClass:[ShipEntity class]])
204 return NO;
205
206 *outEntity = (ShipEntity*)entity;
207 return YES;
208
210}
211
212/* The SpiderMonkey methods treated a failed lookup of this as a no-op (a
213 stale reference). If the lookup failed because this is not an Entity, an
214 error is pending, and QuickJS natives must not return normally with an
215 exception pending.
216*/
217#define GET_THIS_STATION(THISENT) \
218 do { \
219 if (!JSStationGetStationEntity(context, OOJS_THIS, &THISENT)) { \
220 if (JS_HasException(context)) \
221 return JS_EXCEPTION; \
222 OOJS_RETURN_VOID; /* stale reference, no-op */ \
223 } \
224 } while (0)
225
226@implementation StationEntity (OOJavaScriptExtensions)
227
228- (JSClassID)oo_jsClassID
229{
230 return sStationClassID;
231}
232
233- (NSString*)oo_jsClassName
234{
235 return @"Station";
236}
237
238@end
239
241{
242 OOJS_NATIVE_ENTER(context)
243
244 StationEntity* entity = nil;
245
246 if (!JSStationGetStationEntity(context, this, &entity))
247 return OOJSNativeFailure(context);
248 if (entity == nil) {
249 return JS_UNDEFINED;
250 }
251
252 switch (magic) {
254 return OOJSValueFromBOOL(entity == [UNIVERSE station]);
255
257 return OOJSValueFromBOOL([entity hasNPCTraffic]);
258
260 return OOJSValueFromBOOL([entity hasShipyard]);
261
263 return JS_NewInt32(context, [entity alertLevel]);
264
265 case kStation_allegiance: {
266 NSString* result = [entity allegiance];
267 return OOJSValueFromNativeObject(context, result);
268 }
269
271 return OOJSValueFromBOOL([entity requiresDockingClearance]);
272
273 case kStation_roll:
274 // same as in ship definition, but this time read/write below
275 return JS_NewNumber(context, [entity flightRoll]);
276
278 return OOJSValueFromBOOL([entity allowsFastDocking]);
279
281 return OOJSValueFromBOOL([entity allowsAutoDocking]);
282
284 return JS_NewInt32(context, [entity countOfDockedContractors]);
285
287 return JS_NewInt32(context, [entity countOfDockedPolice]);
288
290 return JS_NewInt32(context, [entity countOfDockedDefenders]);
291
293 return JS_NewInt32(context, (int32_t)[entity equivalentTechLevel]);
294
296 return JS_NewNumber(context, [entity equipmentPriceFactor]);
297
299 return OOJSValueFromBOOL([entity suppressArrivalReports]);
300
302 return OOJSValueFromBOOL([entity hasBreakPattern]);
303
304 case kStation_shipyard: {
305 if (![entity hasShipyard]) {
306 // return null if station has no shipyard
307 return OOJSValueFromNativeObject(context, nil);
308 } else {
309 if ([entity localShipyard] == nil)
310 [entity generateShipyard];
311 NSMutableArray* shipyard = [entity localShipyard];
312 return OOJSValueFromNativeObject(context, shipyard);
313 }
314 }
315
316 case kStation_market: {
317 NSDictionary* market = [entity localMarketForScripting];
318 return OOJSValueFromNativeObject(context, market);
319 }
320
321 default:
323 return OOJSNativeFailure(context);
324 }
325
327}
328
330{
331 OOJS_NATIVE_ENTER(context)
332
333 StationEntity* entity = nil;
334 int bValue;
335 int32_t iValue;
336 double fValue;
337 NSString* sValue = nil;
338
339 if (!JSStationGetStationEntity(context, this, &entity))
340 return OOJSNativeFailure(context);
341 if (entity == nil)
342 return JS_UNDEFINED;
343
344 switch (magic) {
346 if ((bValue = JS_ToBool(context, value)) >= 0) {
347 [entity setHasNPCTraffic:bValue];
348 return JS_UNDEFINED;
349 }
350 break;
351
353 if (OOJSValueToInt32(context, value, &iValue)) {
354 [entity setAlertLevel:iValue signallingScript:NO]; // Performs range checking
355 return JS_UNDEFINED;
356 }
357 break;
358
360 sValue = OOStringFromJSValue(context, value);
361 if (sValue != nil) {
362 [entity setAllegiance:sValue];
363 return JS_UNDEFINED;
364 }
365 break;
366
368 if ((bValue = JS_ToBool(context, value)) >= 0) {
369 [entity setRequiresDockingClearance:bValue];
370 return JS_UNDEFINED;
371 }
372 break;
373
374 case kStation_roll:
375 if (JS_ToFloat64(context, &fValue, value) == 0) {
376 /* if (fValue < -2.0) fValue = -2.0;
377 if (fValue > 2.0) fValue = 2.0; // clamping to -2.0...2.0 gives us ±M_PI actual maximum rotation
378 [entity setRoll:fValue]; */
379 // use setRawRoll to make the units here equal to those in kShip_roll
380 if (fValue < -M_PI)
381 fValue = -M_PI;
382 else if (fValue > M_PI)
383 fValue = M_PI;
384 [entity setRawRoll:fValue];
385 return JS_UNDEFINED;
386 }
387 break;
388
390 if ((bValue = JS_ToBool(context, value)) >= 0) {
391 [entity setAllowsFastDocking:bValue];
392 return JS_UNDEFINED;
393 }
394 break;
395
397 if ((bValue = JS_ToBool(context, value)) >= 0) {
398 [entity setAllowsAutoDocking:bValue];
399 return JS_UNDEFINED;
400 }
401 break;
402
404 if ((bValue = JS_ToBool(context, value)) >= 0) {
405 [entity setSuppressArrivalReports:bValue];
406 return JS_UNDEFINED;
407 }
408 break;
409
411 if ((bValue = JS_ToBool(context, value)) >= 0) {
412 [entity setHasBreakPattern:bValue];
413 return JS_UNDEFINED;
414 }
415 break;
416
417 default:
419 return OOJSNativeFailure(context);
420 }
421
423 return OOJSNativeFailure(context);
424
426}
427
428// *** Methods ***
429
431{
432 OOJS_NATIVE_ENTER(context)
433
434 StationEntity* station = nil;
435 JSStationGetStationEntity(context, OOJS_THIS, &station);
436 // SpiderMonkey tolerated returning normally with an error pending; QuickJS does not.
437 if (JS_HasException(context))
438 return JS_EXCEPTION;
439 [station abortAllDockings];
440
442
444}
445
447{
448 OOJS_NATIVE_ENTER(context)
449
450 StationEntity* station = nil;
451 JSStationGetStationEntity(context, OOJS_THIS, &station);
452 if (JS_HasException(context))
453 return JS_EXCEPTION;
454 if (argc == 0) {
455 OOJSReportBadArguments(context, @"Station", @"abortDockingForShip", MIN(argc, 1), OOJS_ARGV, nil, @"ship in docking queue");
456 return OOJSNativeFailure(context);
457 }
458 // (null was an object to SpiderMonkey, but passing it was not meaningful; it now fails like other non-objects.)
459 if (JS_IsNull(OOJS_ARGV[0]) || !JS_IsObject(OOJS_ARGV[0]))
460 return OOJSNativeFailure(context);
461 ShipEntity* ship = nil;
462 JSStationGetShipEntity(context, OOJS_ARGV[0], &ship);
463 if (JS_HasException(context))
464 return JS_EXCEPTION;
465 if (ship != nil) {
466 [station abortDockingForShip:ship];
467 }
468
470
472}
473
474// canDockShip(shipEntity) : boolean
475// Proposed by phkb (Nick Rogers) 20161206
477{
478 OOJS_NATIVE_ENTER(context)
479
480 BOOL result = YES;
481 ShipEntity* shipToCheck = nil;
482
483 if (argc > 0) {
484 if (JS_IsNull(OOJS_ARGV[0]) || !JS_IsObject(OOJS_ARGV[0]) || !JSStationGetShipEntity(context, OOJS_ARGV[0], &shipToCheck)) {
485 return OOJSNativeFailure(context);
486 }
487 }
488 if (EXPECT_NOT(shipToCheck == nil)) {
489 OOJSReportBadArguments(context, @"Station", @"canDockShip", MIN(argc, 1), OOJS_ARGV, nil, @"shipEntity");
490 return OOJSNativeFailure(context);
491 }
492
493 StationEntity* station = nil;
494 GET_THIS_STATION(station);
495
497 result = [station fitsInDock:shipToCheck andLogNoFit:NO];
499
500 OOJS_RETURN_BOOL(result);
502}
503
504// dockPlayer()
505// Proposed and written by Frame 20090729
507{
508 OOJS_NATIVE_ENTER(context)
509
511 GameController* gameController = [UNIVERSE gameController];
512
513 if (EXPECT_NOT([gameController isGamePaused])) {
514 /* Station.dockPlayer() was executed while the game was in pause.
515 Do we want to return an error or just unpause and continue?
516 I think unpausing is the sensible thing to do here - Nikos 20110208
517 */
518 [gameController setGamePaused:NO];
519 }
520
521 if (EXPECT(![player isDocked])) {
522 StationEntity* stationForDockingPlayer = nil;
523 JSStationGetStationEntity(context, OOJS_THIS, &stationForDockingPlayer);
524 // SpiderMonkey tolerated returning normally with an error pending; QuickJS does not.
525 if (JS_HasException(context))
526 return JS_EXCEPTION;
527 [player setDockingClearanceStatus:DOCKING_CLEARANCE_STATUS_GRANTED];
528 [player safeAllMissiles];
529 [UNIVERSE setViewDirection:VIEW_FORWARD];
530 [player enterDock:stationForDockingPlayer];
531 }
533
535}
536
538{
539 OOJS_NATIVE_ENTER(context)
540 StationEntity* station = nil;
541
542 GET_THIS_STATION(station);
543
545 if ([station alertCondition] < 3) {
546 [station increaseAlertLevel];
547 }
551}
552
554{
555 OOJS_NATIVE_ENTER(context)
556 StationEntity* station = nil;
557
558 GET_THIS_STATION(station);
559
561 if ([station alertCondition] > 1) {
562 [station decreaseAlertLevel];
563 }
567}
568
569// launchShipWithRole(role : String [, abortAllDockings : boolean]) : shipEntity
571{
572 OOJS_NATIVE_ENTER(context)
573
574 NSString* shipRole = nil;
575 StationEntity* station = nil;
576 ShipEntity* result = nil;
577 BOOL abortAllDockings = NO;
578
579 GET_THIS_STATION(station);
580
581 if (argc > 0)
582 shipRole = OOStringFromJSValue(context, OOJS_ARGV[0]);
583 if (EXPECT_NOT(shipRole == nil)) {
584 OOJSReportBadArguments(context, @"Station", @"launchShipWithRole", MIN(argc, 1), OOJS_ARGV, nil, @"string (role)");
585 return OOJSNativeFailure(context);
586 }
587
588 if (argc > 1)
589 abortAllDockings = JS_ToBool(context, OOJS_ARGV[1]) > 0;
590
592 result = [station launchIndependentShip:shipRole];
593 if (abortAllDockings)
594 [station abortAllDockings];
596
597 OOJS_RETURN_OBJECT(result);
599}
600
602{
603 OOJS_NATIVE_ENTER(context)
604
605 StationEntity* station = nil;
606 GET_THIS_STATION(station);
607
608 ShipEntity* launched = nil;
610 launched = [station launchDefenseShip];
612 OOJS_RETURN_OBJECT(launched);
613
615}
616
618{
619 OOJS_NATIVE_ENTER(context)
620
621 StationEntity* station = nil;
622 GET_THIS_STATION(station);
623
624 ShipEntity* launched = nil;
626 launched = [station launchEscort];
628 OOJS_RETURN_OBJECT(launched);
629
631}
632
634{
635 OOJS_NATIVE_ENTER(context)
636
637 StationEntity* station = nil;
638 GET_THIS_STATION(station);
639
640 ShipEntity* launched = nil;
642 launched = [station launchScavenger];
644 OOJS_RETURN_OBJECT(launched);
645
647}
648
650{
651 OOJS_NATIVE_ENTER(context)
652
653 StationEntity* station = nil;
654 GET_THIS_STATION(station);
655
656 ShipEntity* launched = nil;
658 launched = [station launchMiner];
660 OOJS_RETURN_OBJECT(launched);
662}
663
665{
666 OOJS_NATIVE_ENTER(context)
667
668 StationEntity* station = nil;
669 GET_THIS_STATION(station);
670
671 ShipEntity* launched = nil;
673 launched = [station launchPirateShip];
675 OOJS_RETURN_OBJECT(launched);
676
678}
679
681{
682 OOJS_NATIVE_ENTER(context)
683
684 StationEntity* station = nil;
685 GET_THIS_STATION(station);
686
687 ShipEntity* launched = nil;
689 launched = [station launchShuttle];
691 OOJS_RETURN_OBJECT(launched);
693}
694
696{
697 OOJS_NATIVE_ENTER(context)
698
699 StationEntity* station = nil;
700 GET_THIS_STATION(station);
701
702 ShipEntity* launched = nil;
704 launched = [station launchPatrol];
706 OOJS_RETURN_OBJECT(launched);
708}
709
711{
712 OOJS_NATIVE_ENTER(context)
713
714 StationEntity* station = nil;
715 GET_THIS_STATION(station);
716
717 NSArray* launched = nil;
719 launched = [station launchPolice];
721 OOJS_RETURN_OBJECT(launched);
723}
724
725// Get a property of a definition object. As before, a failed get is treated like a missing property.
726static JSValue GetParam(JSContext* context, JSValueConst object, const char* key)
727{
728 JSValue value = JS_GetPropertyStr(context, object, key);
729 if (JS_IsException(value)) {
731 return JS_UNDEFINED;
732 }
733 return value;
734}
735
737{
738 OOJS_NATIVE_ENTER(context)
739
740 StationEntity* station = nil;
741 GET_THIS_STATION(station);
742
743 if (argc < 1) {
744 OOJSReportBadArguments(context, @"Station", @"setInterface", MIN(argc, 1), OOJS_ARGV, NULL, @"key [, definition]");
745 return OOJSNativeFailure(context);
746 }
747 NSString* key = OOStringFromJSValue(context, OOJS_ARGV[0]);
748
749 if (argc < 2 || JS_IsNull(OOJS_ARGV[1])) {
750 [station setInterfaceDefinition:nil forKey:key];
752 }
753
754 JSValue value = JS_UNDEFINED;
755 JSValue callback = JS_UNDEFINED;
756 JSValue params = JS_UNDEFINED;
757 NSString* errorDescription = nil;
758
759 NSString* title = nil;
760 NSString* summary = nil;
761 NSString* category = nil;
762
763 // SpiderMonkey's JS_ValueToObject() boxed primitives. (It gave no object for undefined, which then could not work; treat it as invalid.)
764 if (!JS_IsUndefined(OOJS_ARGV[1])) {
765 params = JS_ToObject(context, OOJS_ARGV[1]);
766 if (JS_IsException(params)) {
767 JS_FreeValue(context, JS_GetException(context));
768 params = JS_UNDEFINED;
769 }
770 }
771 if (!JS_IsObject(params)) {
772 errorDescription = @"key [, definition]";
773 goto fail;
774 }
775
776 // get and validate title
777 value = GetParam(context, params, "title");
778 if (JS_IsUndefined(value)) {
779 errorDescription = @"key [, definition]; if definition is set, it must have a 'title' property.";
780 goto fail;
781 }
782 title = OOStringFromJSValue(context, value);
783 JS_FreeValue(context, value);
784 value = JS_UNDEFINED;
785 if (title == nil || [title length] == 0) {
786 errorDescription = @"key [, definition]; if definition is set, 'title' property must be a non-empty string.";
787 goto fail;
788 }
789
790 // get category with default
791 value = GetParam(context, params, "category");
792 if (JS_IsUndefined(value)) {
793 category = [NSString stringWithString:DESC(@"interfaces-category-uncategorised")];
794 } else {
795 category = OOStringFromJSValue(context, value);
796 if (category == nil || [category length] == 0) {
797 category = [NSString stringWithString:DESC(@"interfaces-category-uncategorised")];
798 }
799 }
800 JS_FreeValue(context, value);
801 value = JS_UNDEFINED;
802
803 // get and validate summary
804 value = GetParam(context, params, "summary");
805 if (JS_IsUndefined(value)) {
806 errorDescription = @"key [, definition]; if definition is set, it must have a 'summary' property.";
807 goto fail;
808 }
809 summary = OOStringFromJSValue(context, value);
810 JS_FreeValue(context, value);
811 value = JS_UNDEFINED;
812 if (summary == nil || [summary length] == 0) {
813 errorDescription = @"key [, definition]; if definition is set, 'summary' property must be a non-empty string.";
814 goto fail;
815 }
816
817 // get and validate callback
818 callback = GetParam(context, params, "callback");
819 if (JS_IsUndefined(callback)) {
820 errorDescription = @"key [, definition]; if definition is set, it must have a 'callback' property.";
821 goto fail;
822 }
823 if (!OOJSValueIsFunction(context, callback)) {
824 errorDescription = @"key [, definition]; 'callback' property must be a function.";
825 goto fail;
826 }
827
828 OOJSInterfaceDefinition* definition = [[OOJSInterfaceDefinition alloc] init];
829 [definition setTitle:title];
830 [definition setCategory:category];
831 [definition setSummary:summary];
832 [definition setCallback:callback]; // Takes its own reference.
833 JS_FreeValue(context, callback);
834
835 // get callback 'this'
836 value = GetParam(context, params, "cbThis");
837 if (!JS_IsUndefined(value)) {
838 // As with SpiderMonkey's JS_ValueToObject(), null gives no object; primitives are boxed.
839 if (!JS_IsNull(value)) {
840 JSValue callbackThis = JS_ToObject(context, value);
841 if (JS_IsException(callbackThis)) {
842 JS_FreeValue(context, JS_GetException(context));
843 } else {
844 [definition setCallbackThis:callbackThis]; // Takes its own reference.
845 }
846 JS_FreeValue(context, callbackThis);
847 }
848 // can do .bind(this) for callback instead
849 }
850 JS_FreeValue(context, value);
851 JS_FreeValue(context, params);
852
853 [station setInterfaceDefinition:definition forKey:key];
854
855 [definition release];
856
858
859fail:
860 JS_FreeValue(context, callback);
861 JS_FreeValue(context, value);
862 JS_FreeValue(context, params);
863 OOJSReportBadArguments(context, @"Station", @"setInterface", MIN(argc, 1), OOJS_ARGV, NULL, errorDescription);
864 return OOJSNativeFailure(context);
865
867}
868
870{
871 OOJS_NATIVE_ENTER(context)
872
873 StationEntity* station = nil;
874 GET_THIS_STATION(station);
875
876 if (argc < 2) {
877 OOJSReportBadArguments(context, @"Station", @"setMarketPrice", MIN(argc, 2), OOJS_ARGV, NULL, @"commodity, credits");
878 return OOJSNativeFailure(context);
879 }
880
881 OOCommodityType commodity = OOStringFromJSValue(context, OOJS_ARGV[0]);
882 if (EXPECT_NOT(![[UNIVERSE commodities] goodDefined:commodity])) {
883 OOJSReportBadArguments(context, @"Station", @"setMarketPrice", MIN(argc, 2), OOJS_ARGV, NULL, @"Unrecognised commodity type");
884 return OOJSNativeFailure(context);
885 }
886
887 int32_t price;
888 BOOL gotPrice = OOJSValueToInt32(context, OOJS_ARGV[1], &price);
889 if (EXPECT_NOT(!gotPrice || price < 0)) {
890 OOJSReportBadArguments(context, @"Station", @"setMarketPrice", MIN(argc, 2), OOJS_ARGV, NULL, @"Price must be at least 0 decicredits");
891 return OOJSNativeFailure(context);
892 }
893
894 [station setPrice:(NSUInteger)price forCommodity:commodity];
895
896 if (station == [PLAYER dockedStation] && [PLAYER guiScreen] == GUI_SCREEN_MARKET) {
897 [PLAYER setGuiToMarketScreen]; // refresh screen
898 }
899
900 OOJS_RETURN_BOOL(YES);
901
903}
904
906{
907 OOJS_NATIVE_ENTER(context)
908
909 StationEntity* station = nil;
910 GET_THIS_STATION(station);
911
912 if (argc < 2) {
913 OOJSReportBadArguments(context, @"Station", @"setMarketQuantity", MIN(argc, 2), OOJS_ARGV, NULL, @"commodity, units");
914 return OOJSNativeFailure(context);
915 }
916
917 OOCommodityType commodity = OOStringFromJSValue(context, OOJS_ARGV[0]);
918 if (EXPECT_NOT(![[UNIVERSE commodities] goodDefined:commodity])) {
919 OOJSReportBadArguments(context, @"Station", @"setMarketQuantity", MIN(argc, 2), OOJS_ARGV, NULL, @"Unrecognised commodity type");
920 return OOJSNativeFailure(context);
921 }
922
923 int32_t quantity;
924 BOOL gotQuantity = OOJSValueToInt32(context, OOJS_ARGV[1], &quantity);
925 if (EXPECT_NOT(!gotQuantity || quantity < 0 || (OOCargoQuantity)quantity > [[station localMarket] capacityForGood:commodity])) {
926 OOJSReportBadArguments(context, @"Station", @"setMarketQuantity", MIN(argc, 2), OOJS_ARGV, NULL, @"Quantity must be between 0 and the station market capacity");
927 return OOJSNativeFailure(context);
928 }
929
930 [station setQuantity:(OOCargoQuantity)quantity forCommodity:commodity];
931
932 if (station == [PLAYER dockedStation] && [PLAYER guiScreen] == GUI_SCREEN_MARKET) {
933 [PLAYER setGuiToMarketScreen]; // refresh screen
934 }
935
936 OOJS_RETURN_BOOL(YES);
937
939}
940
942{
943 OOJS_NATIVE_ENTER(context)
944
945 StationEntity* station = nil;
946 GET_THIS_STATION(station);
947
948 /* SpiderMonkey's JS_ValueToObject() accepted primitives (boxing them) and
949 undefined, but the definition was then read from argv[0] as an object
950 regardless, so only objects (and null) ever worked. Anything else is
951 now rejected as bad arguments.
952 */
953 if (argc != 1 || (!JS_IsNull(OOJS_ARGV[0]) && !JS_IsObject(OOJS_ARGV[0]))) {
954 OOJSReportBadArguments(context, @"Station", @"addShipToShipyard", MIN(argc, 1), OOJS_ARGV, NULL, @"shipyard item definition");
955 return OOJSNativeFailure(context);
956 }
957
958 // make sure the station has a shipyard
959 if (![station hasShipyard]) {
960 OOJSReportWarningForCaller(context, @"Station", @"removeShipFromShipyard", @"Station does not have shipyard.");
961 return OOJSNativeFailure(context);
962 }
963 // make sure the shipyard has been generated
964 if (![station localShipyard])
965 [station generateShipyard];
966 NSMutableArray* shipyard = [station localShipyard];
967
968 if (JS_IsNull(OOJS_ARGV[0]))
969 OOJS_RETURN_VOID; // OK, do nothing for null ship.
970
971 NSMutableDictionary* result = [NSMutableDictionary dictionary];
972 NSDictionary* shipyardDefinition = OOJSNativeObjectFromJSObject(context, OOJS_ARGV[0]);
973 // validate each element of the dictionary
974 if (!shipyardDefinition) {
975 OOJSReportBadArguments(context, @"Station", @"addShipToShipyard", MIN(argc, 1), OOJS_ARGV, nil, @"valid dictionary object");
976 return OOJSNativeFailure(context);
977 }
978 if (![shipyardDefinition objectForKey:KEY_SHORT_DESCRIPTION]) {
979 OOJSReportBadArguments(context, @"Station", @"addShipToShipyard", MIN(argc, 1), OOJS_ARGV, nil, @"'short_description' in dictionary");
980 return OOJSNativeFailure(context);
981 }
982 [result setObject:[shipyardDefinition oo_stringForKey:@"short_description"] forKey:KEY_SHORT_DESCRIPTION];
983 if (![shipyardDefinition objectForKey:SHIPYARD_KEY_SHIPDATA_KEY]) {
984 OOJSReportBadArguments(context, @"Station", @"addShipToShipyard", MIN(argc, 1), OOJS_ARGV, nil, @"'shipdata_key' in dictionary");
985 return OOJSNativeFailure(context);
986 }
987 // get the shipInfo and shipyardInfo for this key
988 NSString* shipKey = [shipyardDefinition oo_stringForKey:SHIPYARD_KEY_SHIPDATA_KEY defaultValue:nil];
990 NSMutableDictionary* shipInfo = [NSMutableDictionary dictionaryWithDictionary:[registry shipInfoForKey:shipKey]];
991 NSDictionary* shipyardInfo = [registry shipyardInfoForKey:shipKey];
992 if (!shipInfo) {
993 OOJSReportWarningForCaller(context, @"Station", @"addShipToShipyard", @"Invalid shipdata_key provided.");
994 return OOJSNativeFailure(context);
995 }
996 // make sure the ship is a player ship
997 if ([[shipInfo oo_stringForKey:@"roles"] rangeOfString:@"player"].location == NSNotFound) {
998 OOJSReportWarningForCaller(context, @"Station", @"addShipToShipyard", @"shipdata_key not suitable for player role.");
999 return OOJSNativeFailure(context);
1000 }
1001 if (!shipyardInfo) {
1002 OOJSReportWarningForCaller(context, @"Station", @"addShipToShipyard", @"No shipyard information found for shipdata_key.");
1003 return OOJSNativeFailure(context);
1004 }
1005 // ok, feel pretty safe to include this ship now
1006 [result setObject:shipKey forKey:SHIPYARD_KEY_SHIPDATA_KEY];
1007
1008 // add an ID
1009 Random_Seed ship_seed = [UNIVERSE marketSeed];
1010 int superRand1 = ship_seed.a * 0x10000 + ship_seed.c * 0x100 + ship_seed.e;
1011 uint32_t superRand2 = ship_seed.b * 0x10000 + ship_seed.d * 0x100 + ship_seed.f;
1012 superRand2 &= Ranrot();
1013 NSString* shipID = [NSString stringWithFormat:@"%06x-%06x", superRand1, superRand2];
1014 [result setObject:shipID forKey:SHIPYARD_KEY_ID];
1015
1016 if (![shipyardDefinition objectForKey:SHIPYARD_KEY_PRICE]) {
1017 // if not provided, get the price from the registry
1018 OOCreditsQuantity price = [shipyardInfo oo_unsignedIntForKey:KEY_PRICE];
1019 [result setObject:[NSNumber numberWithUnsignedLongLong:price] forKey:SHIPYARD_KEY_PRICE];
1020 } else {
1021 OOCreditsQuantity price = [shipyardDefinition oo_unsignedIntForKey:SHIPYARD_KEY_PRICE];
1022 if (price > 0) {
1023 [result setObject:[NSNumber numberWithUnsignedLongLong:price] forKey:SHIPYARD_KEY_PRICE];
1024 } else {
1025 OOJSReportBadArguments(context, @"Station", @"addShipToShipyard", MIN(argc, 1), OOJS_ARGV, nil, @"'price' in dictionary");
1026 return OOJSNativeFailure(context);
1027 }
1028 }
1029
1030 if (![shipyardDefinition objectForKey:SHIPYARD_KEY_PERSONALITY]) {
1031 // default to 0 if not supplied
1032 [result setObject:[NSNumber numberWithUnsignedInt:0] forKey:SHIPYARD_KEY_PERSONALITY];
1033 } else {
1034 [result setObject:[NSNumber numberWithUnsignedLongLong:[shipyardDefinition oo_unsignedIntForKey:SHIPYARD_KEY_PERSONALITY]] forKey:SHIPYARD_KEY_PERSONALITY];
1035 }
1036
1037 NSArray* extras = [shipyardDefinition oo_arrayForKey:KEY_EQUIPMENT_EXTRAS];
1038 if (!extras) {
1039 // pick up defaults if extras not supplied
1040 extras = [NSArray arrayWithArray:[[shipyardInfo oo_dictionaryForKey:KEY_STANDARD_EQUIPMENT] oo_arrayForKey:KEY_EQUIPMENT_EXTRAS]];
1041 }
1042 if ([extras count] > 0) {
1043 // go looking for lasers and add them directly to our shipInfo
1044 NSString* fwdWeaponString = [[shipyardInfo oo_dictionaryForKey:KEY_STANDARD_EQUIPMENT] oo_stringForKey:KEY_EQUIPMENT_FORWARD_WEAPON];
1045 NSString* aftWeaponString = [[shipyardInfo oo_dictionaryForKey:KEY_STANDARD_EQUIPMENT] oo_stringForKey:KEY_EQUIPMENT_AFT_WEAPON];
1046 OOWeaponFacingSet availableFacings = [shipyardInfo oo_unsignedIntForKey:KEY_WEAPON_FACINGS defaultValue:VALID_WEAPON_FACINGS] & VALID_WEAPON_FACINGS;
1047
1048 OOWeaponType fwdWeapon = OOWeaponTypeFromEquipmentIdentifierSloppy(fwdWeaponString);
1049 OOWeaponType aftWeapon = OOWeaponTypeFromEquipmentIdentifierSloppy(aftWeaponString);
1050
1051 unsigned int i;
1052 NSString* equipmentKey = nil;
1053 for (i = 0; i < [extras count]; i++) {
1054 equipmentKey = [extras oo_stringAtIndex:i];
1055 if ([equipmentKey hasPrefix:@"EQ_WEAPON"]) {
1057 // fit best weapon forward
1058 if (availableFacings & WEAPON_FACING_FORWARD && [new_weapon weaponThreatAssessment] > [fwdWeapon weaponThreatAssessment]) {
1059 // again remember to divide price by 10 to get credits from tenths of credit
1060 fwdWeaponString = equipmentKey;
1061 fwdWeapon = new_weapon;
1062 [shipInfo setObject:fwdWeaponString forKey:KEY_EQUIPMENT_FORWARD_WEAPON];
1063 } else {
1064 // if less good than current forward, try fitting is to rear
1065 if (availableFacings & WEAPON_FACING_AFT && (isWeaponNone(aftWeapon) || [new_weapon weaponThreatAssessment] > [aftWeapon weaponThreatAssessment])) {
1066 aftWeaponString = equipmentKey;
1067 aftWeapon = new_weapon;
1068 [shipInfo setObject:aftWeaponString forKey:KEY_EQUIPMENT_AFT_WEAPON];
1069 }
1070 }
1071 }
1072 }
1073 }
1074 // add the extras
1075 [result setObject:extras forKey:KEY_EQUIPMENT_EXTRAS];
1076 // add the ship spec
1077 [result setObject:shipInfo forKey:SHIPYARD_KEY_SHIP];
1078 // add it to the station's shipyard
1079 [shipyard addObject:result];
1080
1081 // refresh the screen if the shipyard is currently being displayed
1082 if (station == [PLAYER dockedStation] && [PLAYER guiScreen] == GUI_SCREEN_SHIPYARD) {
1083 [PLAYER setGuiToShipyardScreen:0];
1084 }
1085
1086 OOJS_RETURN_BOOL(YES);
1087
1089}
1090
1092{
1093 OOJS_NATIVE_ENTER(context)
1094
1095 StationEntity* station = nil;
1096 GET_THIS_STATION(station);
1097
1098 // make sure the station has a shipyard
1099 if (![station hasShipyard]) {
1100 OOJSReportWarningForCaller(context, @"Station", @"removeShipFromShipyard", @"Station does not have shipyard.");
1101 return OOJSNativeFailure(context);
1102 }
1103 // make sure the shipyard has been generated
1104 if (![station localShipyard])
1105 [station generateShipyard];
1106 NSMutableArray* shipyard = [station localShipyard];
1107
1108 int32_t shipIndex = -1;
1109 BOOL gotIndex = YES;
1110 gotIndex = OOJSValueToInt32(context, OOJS_ARGV[0], &shipIndex); // argv[0] is undefined if argc is 0 (min args 1).
1111
1112 if (argc != 1 || (!JS_IsNull(OOJS_ARGV[0]) && !gotIndex) || shipIndex < 0 || (shipIndex + 1) > [shipyard count]) {
1113 OOJSReportBadArguments(context, @"Station", @"removeShipFromShipyard", MIN(argc, 1), OOJS_ARGV, NULL, @"valid ship index");
1114 return OOJSNativeFailure(context);
1115 }
1116
1117 [shipyard removeObjectAtIndex:shipIndex];
1118
1119 // refresh the screen if the shipyard is currently being displayed
1120 if (station == [PLAYER dockedStation] && [PLAYER guiScreen] == GUI_SCREEN_SHIPYARD) {
1121 [PLAYER setGuiToShipyardScreen:0];
1122 }
1123
1124 OOJS_RETURN_BOOL(YES);
1125
1127}
#define EXPECT_NOT(x)
#define EXPECT(x)
#define OOJS_PROFILE_EXIT
#define OOJS_END_FULL_NATIVE
#define OOJS_BEGIN_FULL_NATIVE(context)
#define OOJS_NATIVE_ENTER(cx)
#define OOJS_NATIVE_EXIT
#define OOJS_PROFILE_ENTER
PlayerEntity * OOPlayerForScripting(void)
Definition OOJSPlayer.m:175
static JSBool StationIncreaseAlertLevel(JSContext *context, uintN argc, jsval *vp)
static JSBool StationLaunchPolice(JSContext *context, uintN argc, jsval *vp)
static JSBool StationSetMarketQuantity(JSContext *context, uintN argc, jsval *vp)
static JSBool StationDecreaseAlertLevel(JSContext *context, uintN argc, jsval *vp)
static JSClass sStationClass
Definition OOJSStation.m:66
static JSBool StationLaunchShuttle(JSContext *context, uintN argc, jsval *vp)
static JSBool StationLaunchMiner(JSContext *context, uintN argc, jsval *vp)
static JSBool StationLaunchShipWithRole(JSContext *context, uintN argc, jsval *vp)
static JSBool StationRemoveShipFromShipyard(JSContext *context, uintN argc, jsval *vp)
static BOOL JSStationGetStationEntity(JSContext *context, JSObject *stationObj, StationEntity **outEntity)
static JSBool StationLaunchDefenseShip(JSContext *context, uintN argc, jsval *vp)
static BOOL JSStationGetShipEntity(JSContext *context, JSObject *shipObj, ShipEntity **outEntity)
static JSBool StationSetInterface(JSContext *context, uintN argc, jsval *vp)
static JSBool StationGetProperty(JSContext *context, JSObject *this, jsid propID, jsval *value)
void InitOOJSStation(JSContext *context, JSObject *global)
static JSBool StationSetMarketPrice(JSContext *context, uintN argc, jsval *vp)
static JSBool StationAbortDockingForShip(JSContext *context, uintN argc, jsval *vp)
static JSBool StationLaunchPirateShip(JSContext *context, uintN argc, jsval *vp)
static JSBool StationAddShipToShipyard(JSContext *context, uintN argc, jsval *vp)
static JSBool StationCanDockShip(JSContext *context, uintN argc, jsval *vp)
static JSBool StationDockPlayer(JSContext *context, uintN argc, jsval *vp)
@ kStation_isMainStation
Definition OOJSStation.m:95
@ kStation_equivalentTechLevel
Definition OOJSStation.m:92
@ kStation_hasShipyard
Definition OOJSStation.m:94
@ kStation_dockedPolice
Definition OOJSStation.m:90
@ kStation_hasNPCTraffic
Definition OOJSStation.m:93
@ kStation_allowsAutoDocking
Definition OOJSStation.m:85
@ kStation_allegiance
Definition OOJSStation.m:84
@ kStation_equipmentPriceFactor
Definition OOJSStation.m:91
@ kStation_shipyard
@ kStation_alertCondition
Definition OOJSStation.m:83
@ kStation_market
Definition OOJSStation.m:96
@ kStation_allowsFastDocking
Definition OOJSStation.m:86
@ kStation_dockedDefenders
Definition OOJSStation.m:89
@ kStation_roll
Definition OOJSStation.m:98
@ kStation_breakPattern
Definition OOJSStation.m:87
@ kStation_requiresDockingClearance
Definition OOJSStation.m:97
@ kStation_dockedContractors
Definition OOJSStation.m:88
@ kStation_suppressArrivalReports
Definition OOJSStation.m:99
static JSPropertySpec sStationProperties[]
static JSFunctionSpec sStationMethods[]
static JSBool StationLaunchScavenger(JSContext *context, uintN argc, jsval *vp)
static JSBool StationLaunchEscort(JSContext *context, uintN argc, jsval *vp)
static JSBool StationSetProperty(JSContext *context, JSObject *this, jsid propID, JSBool strict, jsval *value)
static JSBool StationAbortAllDockings(JSContext *context, uintN argc, jsval *vp)
static JSBool StationLaunchPatrol(JSContext *context, uintN argc, jsval *vp)
#define OOJS_THIS
void OOJSRegisterObjectConverter(JSClass *theClass, OOJSClassConverterCallback converter)
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
id OOJSNativeObjectFromJSObject(JSContext *context, JSObject *object)
void OOJSObjectWrapperFinalize(JSContext *context, JSObject *this)
#define OOJS_RETURN_OBJECT(o)
void OOJSReportBadPropertySelector(JSContext *context, JSObject *thisObj, jsid propID, JSPropertySpec *propertySpec)
void OOJSReportWarningForCaller(JSContext *context, NSString *scriptClass, NSString *function, NSString *format,...)
#define OOJS_RETURN_BOOL(v)
OOINLINE BOOL OOJSValueToInt32(JSContext *context, jsval value, int32_t *outValue)
NSString * OOStringFromJSValue(JSContext *context, jsval value)
JSBool OOJSUnconstructableConstruct(JSContext *context, uintN argc, jsval *vp)
OOINLINE BOOL OOJSValueIsFunction(JSContext *context, jsval value)
void OOJSRegisterSubclass(JSClass *subclass, JSClass *superclass)
OOINLINE void OOJSReportPendingException(JSContext *context)
#define OOJS_ARGV
OOINLINE jsval OOJSValueFromBOOL(int b) INLINE_CONST_FUNC
void OOJSReportBadPropertyValue(JSContext *context, JSObject *thisObj, jsid propID, JSPropertySpec *propertySpec, jsval value)
id OOJSBasicPrivateObjectConverter(JSContext *context, JSObject *object)
void OOJSReportBadArguments(JSContext *context, NSString *scriptClass, NSString *function, uintN argc, jsval *argv, NSString *message, NSString *expectedArgsDescription)
#define OOJS_RETURN_VOID
#define MIN(A, B)
Definition OOMaths.h:91
#define M_PI
Definition OOMaths.h:54
unsigned count
return nil
uint8_t OOWeaponFacingSet
Definition OOTypes.h:204
NSString * OOCommodityType
Definition OOTypes.h:97
uint64_t OOCreditsQuantity
Definition OOTypes.h:160
#define VALID_WEAPON_FACINGS
Definition OOTypes.h:206
uint32_t OOCargoQuantity
Definition OOTypes.h:155
@ WEAPON_FACING_FORWARD
Definition OOTypes.h:196
@ WEAPON_FACING_AFT
Definition OOTypes.h:197
#define PLAYER
static JSValue GetParam(JSContext *context, JSValueConst object, const char *key)
Definition OOJSGlobal.m:411
JSClassID JSShipClassID(void)
Definition OOJSShip.m:576
#define GET_THIS_STATION(THISENT)
JSClassID JSStationClassID(void)
static JSClassID sStationClassID
Definition OOJSStation.m:40
#define OOJS_PROPERTY_RW(name, getter, setter, magic)
JSValue OOJSNativeFailure(JSContext *context)
JSClassID OOJSRegisterClass(JSClassID *ioClassID, const JSClassDef *classDef)
Definition OOJSClasses.m:61
#define OOJS_SETTER_ARGS
#define OOJS_PROPERTY_RO(name, getter, magic)
JSValueConst OOJSInitClass(JSContext *context, JSValueConst global, JSClassID classID, JSValueConst parentPrototype, JSCFunction *constructor, int constructorArgCount, const JSCFunctionListEntry *properties, size_t propertyCount, const JSCFunctionListEntry *methods, size_t methodCount, const JSCFunctionListEntry *staticMethods, size_t staticMethodCount)
#define OOJS_GETTER_ARGS
#define OOJS_NATIVE_ARGS
#define OOJS_COUNT(array)
OOEquipmentType * OOWeaponType
Definition ShipEntity.h:164
BOOL isWeaponNone(OOWeaponType weapon)
OOWeaponType OOWeaponTypeFromEquipmentIdentifierSloppy(NSString *string) PURE_FUNC
#define KEY_SHORT_DESCRIPTION
Definition Universe.h:120
#define UNIVERSE
Definition Universe.h:827
#define SHIPYARD_KEY_PRICE
Definition Universe.h:140
#define SHIPYARD_KEY_PERSONALITY
Definition Universe.h:141
#define SHIPYARD_KEY_SHIPDATA_KEY
Definition Universe.h:138
void setGamePaused:(BOOL value)
void setSummary:(NSString *summary)
void setCategory:(NSString *category)
void setCallbackThis:(JSObject *callbackthis)
NSDictionary * shipyardInfoForKey:(NSString *key)
OOShipRegistry * sharedRegistry()
NSDictionary * shipInfoForKey:(NSString *key)
void setDockingClearanceStatus:(OODockingClearanceStatus newValue)
void enterDock:(StationEntity *station)
void setRawRoll:(double amount)
void setQuantity:forCommodity:(OOCargoQuantity quantity,[forCommodity] OOCommodityType commodity)
NSArray * launchPolice()
ShipEntity * launchMiner()
ShipEntity * launchScavenger()
void setHasNPCTraffic:(BOOL flag)
void setAllowsFastDocking:(BOOL newValue)
ShipEntity * launchIndependentShip:(NSString *role)
ShipEntity * launchDefenseShip()
ShipEntity * launchPirateShip()
void setAlertLevel:signallingScript:(OOStationAlertLevel level,[signallingScript] BOOL signallingScript)
ShipEntity * launchShuttle()
NSMutableArray * localShipyard
ShipEntity * launchPatrol()
void setSuppressArrivalReports:(BOOL newValue)
void setRequiresDockingClearance:(BOOL newValue)
void setAllowsAutoDocking:(BOOL newValue)
NSDictionary * localMarketForScripting()
void setInterfaceDefinition:forKey:(OOJSInterfaceDefinition *definition,[forKey] NSString *key)
NSString * allegiance
void setHasBreakPattern:(BOOL newValue)
BOOL fitsInDock:andLogNoFit:(ShipEntity *ship,[andLogNoFit] BOOL logNoFit)
ShipEntity * launchEscort()
void setPrice:forCommodity:(OOCreditsQuantity price,[forCommodity] OOCommodityType commodity)
void setAllegiance:(NSString *newAllegiance)
void abortDockingForShip:(ShipEntity *ship)
unsigned Ranrot(void)